// ──────────────────────── Gestione utenti — pannello laterale ────────────────────────
const { useState: useStateU } = React;

const ROLE_OPTIONS = ['Admin', 'Manager', 'Area Manager', 'Store Manager', 'Cassiere', 'Magazziniere'];
const STORE_REQUIRED_ROLES = ['Store Manager', 'Cassiere', 'Magazziniere'];

// Classe comune per gli input di testo/select nel pannello
const _inputCls = 'w-full h-11 px-3 rounded-md border border-line bg-surface text-[14px] text-ink focus:border-strong focus:outline-none transition-all duration-fast ease-standard';
const _labelCls = 'block text-[12px] font-semibold uppercase tracking-[0.04em] text-muted mb-1.5';

const UserManagementPanel = ({ session, operators, onClose, onUpdateOperators }) => {
  const isPrivileged = ['Admin', 'Manager'].includes(session?.op?.role);
  const isAdmin = session?.op?.role === 'Admin';
  const PRIVILEGED_ROLES = ['Admin', 'Manager', 'Area Manager']; // login diretto (username+password)

  // ── Logout (con comportamento per tipo di accesso) ──
  const isStore = session?.op?.kind === 'store';
  const cassaAperta = session?.fondo != null;
  const [logoutConfirm, setLogoutConfirm] = useStateU(null); // null | 'ask' | 'cassa'
  const doLogout = async () => { if (window.__API__) await window.__API__.logout(); window.location.reload(); };
  const onExit = () => { if (isStore && cassaAperta) setLogoutConfirm('cassa'); else setLogoutConfirm('ask'); };

  // ── Tabs e sub-view ──
  const [tab, setTab]         = useStateU('profile');
  const [subView, setSubView] = useStateU('list');   // 'list' | 'new' | 'edit'
  const [editTarget, setEditTarget] = useStateU(null);

  // ── Aree (per i selettori + creazione) ──
  const [areas, setAreas] = useStateU([]);
  React.useEffect(() => {
    if (window.__API__ && window.__API__.get) window.__API__.get('/api/areas').then(r => { if (r && r.ok) setAreas(r.areas); });
  }, []);
  // ── Form nuovo negozio / nuova area (Admin) ──
  const [stName, setStName] = useStateU(''); const [stCity, setStCity] = useStateU('');
  const [stUser, setStUser] = useStateU(''); const [stPass, setStPass] = useStateU(''); const [stArea, setStArea] = useStateU('');
  const [areaName, setAreaName] = useStateU('');

  // ── Liste configurabili (tendine) ──
  const LIST_DEFS = [
    { key: 'categorie', label: 'Categorie prodotto' },
    { key: 'stagioni', label: 'Stagioni' },
    { key: 'brand', label: 'Brand / Marche' },
    { key: 'causali', label: 'Causali magazzino' },
    { key: 'motivi_reso', label: 'Motivi reso' },
    { key: 'metodi_pagamento', label: 'Metodi di pagamento' },
    { key: 'termini_pagamento', label: 'Termini di pagamento' },
  ];
  const [lists, setLists] = useStateU(() => (window.LISTS ? JSON.parse(JSON.stringify(window.LISTS)) : {}));
  const [activeList, setActiveList] = useStateU('categorie');
  const [newVal, setNewVal] = useStateU('');
  const refreshLists = () => { if (window.LISTS) setLists(JSON.parse(JSON.stringify(window.LISTS))); };
  const addListItem = () => {
    const v = newVal.trim(); if (!v) return;
    window.__API__.mutate('/api/lists/item', { listKey: activeList, value: v })
      .then(() => { if (window.__toast) window.__toast('Voce aggiunta', 'success'); setNewVal(''); refreshLists(); }).catch(()=>{});
  };
  const idOf = (key, value) => `${key}:${String(value).toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/(^-|-$)/g,'').slice(0,32)}`;
  const delListItem = async (key, value) => {
    try { const r = await fetch('/api/lists/item/' + encodeURIComponent(idOf(key, value)), { method: 'DELETE', credentials: 'same-origin' }); if (!r.ok) throw 0;
      if (window.__BI_REFRESH__) await window.__BI_REFRESH__(); if (window.__toast) window.__toast('Voce eliminata', 'info'); refreshLists();
    } catch (e) { if (window.__toast) window.__toast('Eliminazione non riuscita', 'error'); }
  };
  const saveRename = async (key, value, next) => {
    if (!next.trim() || next.trim() === value) return;
    try { const r = await fetch('/api/lists/item/' + encodeURIComponent(idOf(key, value)), { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: next.trim() }) }); if (!r.ok) throw 0;
      if (window.__BI_REFRESH__) await window.__BI_REFRESH__(); if (window.__toast) window.__toast('Voce rinominata', 'success'); refreshLists();
    } catch (e) { if (window.__toast) window.__toast('Rinomina non riuscita', 'error'); }
  };
  const [renaming, setRenaming] = useStateU(null); // {key,value}
  const [renameVal, setRenameVal] = useStateU('');

  // ── Archivio dipendenti (licenziamento/dimissioni) ──
  const [archiving, setArchiving] = useStateU(null); // operatore in fase di archiviazione
  const [archReason, setArchReason] = useStateU('Licenziamento');
  const [archDate, setArchDate] = useStateU('');
  const ARCH_REASONS = ['Licenziamento', 'Dimissioni', 'Fine contratto', 'Altro'];
  const doArchive = () => {
    if (!archiving) return;
    const id = archiving.id, reason = archReason, date = archDate.trim();
    window.__API__.post('/api/operators/' + id + '/archive', { reason, date: date || undefined })
      .then(() => {
        if (window.__toast) window.__toast('Dipendente archiviato', 'success');
        onUpdateOperators(operators.map(o => o.id === id ? { ...o, active: false, archiveReason: reason, archivedAt: date || o.archivedAt } : o));
        setArchiving(null); setArchReason('Licenziamento'); setArchDate('');
      }).catch(() => {});
  };
  const doReactivate = (op) => {
    window.__API__.post('/api/operators/' + op.id + '/reactivate', {})
      .then(() => { if (window.__toast) window.__toast('Dipendente riattivato', 'success'); onUpdateOperators(operators.map(o => o.id === op.id ? { ...o, active: true, archiveReason: null, archivedAt: null } : o)); })
      .catch(() => {});
  };

  // ── Cambio PIN (profilo) ──
  const [pinCurrent, setPinCurrent] = useStateU('');
  const [pinNew,     setPinNew]     = useStateU('');
  const [pinConfirm, setPinConfirm] = useStateU('');
  const [pinMsg,     setPinMsg]     = useStateU(null); // { type:'ok'|'err', text }

  // ── Nuovo account ──
  const [newName,  setNewName]  = useStateU('');
  const [newRole,  setNewRole]  = useStateU('Cassiere');
  const [newStore, setNewStore] = useStateU(STORES[0]?.id || '');
  const [newPin,   setNewPin]   = useStateU('');
  const [newUser,  setNewUser]  = useStateU('');
  const [newPass,  setNewPass]  = useStateU('');
  const [newArea,  setNewArea]  = useStateU('');
  const [newErr,   setNewErr]   = useStateU('');

  // ── Modifica account ──
  const [editName,      setEditName]      = useStateU('');
  const [editRole,      setEditRole]      = useStateU('');
  const [editStore,     setEditStore]     = useStateU('');
  const [editActive,    setEditActive]    = useStateU(true);
  const [editMaggWrite, setEditMaggWrite] = useStateU(false);
  const [editPinReset,  setEditPinReset]  = useStateU('');
  const [editErr,       setEditErr]       = useStateU('');

  // Operatore corrente (con eventuali aggiornamenti dalla lista)
  const currentOp = operators.find(op => op.id === session.op.id) || session.op;

  // ── Handler: cambia PIN ──
  const handleChangePIN = () => {
    setPinMsg(null);
    if (!window.__API__ && (!pinCurrent || pinCurrent !== (currentOp.pin || '1234'))) {
      setPinMsg({ type: 'err', text: 'PIN attuale non corretto.' });
      return;
    }
    if (!/^\d{4,}$/.test(pinNew)) {
      setPinMsg({ type: 'err', text: 'Il nuovo PIN deve essere di almeno 4 cifre numeriche.' });
      return;
    }
    if (pinNew !== pinConfirm) {
      setPinMsg({ type: 'err', text: 'Il nuovo PIN e la conferma non coincidono.' });
      return;
    }
    if (window.__API__) {
      window.__API__.post('/api/operators/' + session.op.id + '/pin', { current: pinCurrent, next: pinNew })
        .then(() => { onUpdateOperators(operators.map(op => op.id === session.op.id ? { ...op, pin: pinNew } : op)); setPinCurrent(''); setPinNew(''); setPinConfirm(''); setPinMsg({ type: 'ok', text: 'PIN aggiornato con successo.' }); })
        .catch(() => setPinMsg({ type: 'err', text: 'PIN attuale non corretto.' }));
      return;
    }
    onUpdateOperators(operators.map(op => op.id === session.op.id ? { ...op, pin: pinNew } : op));
    setPinCurrent(''); setPinNew(''); setPinConfirm('');
    setPinMsg({ type: 'ok', text: 'PIN aggiornato con successo.' });
  };

  // ── Handler: crea account ──
  const handleNewAccount = () => {
    setNewErr('');
    const privileged = PRIVILEGED_ROLES.includes(newRole);
    if (!newName.trim())                                        { setNewErr('Il nome è obbligatorio.'); return; }
    if (STORE_REQUIRED_ROLES.includes(newRole) && !newStore)   { setNewErr('Il negozio è obbligatorio per questo ruolo.'); return; }
    if (!/^\d{4,}$/.test(newPin))                              { setNewErr('Il PIN deve essere di almeno 4 cifre numeriche.'); return; }
    if (privileged && (!newUser.trim() || newPass.length < 4)) { setNewErr('Per i ruoli con accesso diretto servono username e password (min. 4).'); return; }
    if (newRole === 'Area Manager' && !newArea)                { setNewErr('Scegli l’area per l’Area Manager.'); return; }
    const words    = newName.trim().split(/\s+/);
    const initials = words.map(w => w[0]).join('').slice(0, 2).toUpperCase();
    const storeId  = STORE_REQUIRED_ROLES.includes(newRole) ? newStore : null;
    const newOp = { id: 'op_' + Date.now(), name: newName.trim(), initials, role: newRole, storeId, pin: newPin, active: true, lastAccess: null, canMagazzinoWrite: false };
    if (window.__API__) window.__API__.post('/api/operators', {
      name: newOp.name, role: newOp.role, storeId: newOp.storeId, pin: newOp.pin,
      username: privileged ? newUser.trim() : undefined,
      password: privileged ? newPass : undefined,
      areaId: newRole === 'Area Manager' ? newArea : undefined,
    }).then(() => { if (window.__toast) window.__toast('Account creato', 'success'); }).catch(()=>{});
    onUpdateOperators([...operators, newOp]);
    setNewName(''); setNewRole('Cassiere'); setNewStore(STORES[0]?.id || ''); setNewPin(''); setNewUser(''); setNewPass(''); setNewArea('');
    setSubView('list');
  };

  // ── Handler: crea negozio / crea area (Admin) ──
  const handleNewStore = () => {
    setNewErr('');
    if (!stName.trim() || !stUser.trim() || stPass.length < 4) { setNewErr('Servono nome, username e password (min. 4) del negozio.'); return; }
    if (window.__API__) window.__API__.mutate('/api/stores', { name: stName.trim(), city: stCity.trim(), areaId: stArea || null, username: stUser.trim(), password: stPass })
      .then(() => { if (window.__toast) window.__toast('Negozio creato', 'success'); setStName(''); setStCity(''); setStUser(''); setStPass(''); setStArea(''); }).catch(()=>{});
  };
  const handleNewArea = () => {
    if (!areaName.trim()) return;
    if (window.__API__) window.__API__.post('/api/areas', { name: areaName.trim() })
      .then((r) => { if (r && r.ok) { setAreas(a => [...a, { id: r.id, name: areaName.trim() }]); if (window.__toast) window.__toast('Area creata', 'success'); setAreaName(''); } }).catch(()=>{});
  };

  // ── Handler: apri modifica ──
  const openEdit = (op) => {
    setEditTarget(op);
    setEditName(op.name);
    setEditRole(op.role);
    setEditStore(op.storeId || STORES[0]?.id || '');
    setEditActive(op.active !== false);
    setEditMaggWrite(!!op.canMagazzinoWrite);
    setEditPinReset('');
    setEditErr('');
    setSubView('edit');
  };

  // ── Handler: salva modifica ──
  const handleSaveEdit = () => {
    setEditErr('');
    if (!editName.trim())                                       { setEditErr('Il nome è obbligatorio.'); return; }
    if (STORE_REQUIRED_ROLES.includes(editRole) && !editStore)  { setEditErr('Il negozio è obbligatorio per questo ruolo.'); return; }
    if (editPinReset && !/^\d{4,}$/.test(editPinReset))         { setEditErr('Il PIN deve essere di almeno 4 cifre numeriche.'); return; }
    if (editTarget.id === session.op.id && !editActive)          { setEditErr('Non puoi disattivare il tuo stesso account.'); return; }
    const words    = editName.trim().split(/\s+/);
    const initials = words.map(w => w[0]).join('').slice(0, 2).toUpperCase();
    const storeId  = STORE_REQUIRED_ROLES.includes(editRole) ? editStore : null;
    if (window.__API__) window.__API__.post('/api/operators/' + editTarget.id, { name: editName.trim(), role: editRole, storeId, active: editActive, canMagazzinoWrite: editRole === 'Cassiere' ? editMaggWrite : false, pinReset: editPinReset || '' }).catch(()=>{});
    onUpdateOperators(operators.map(op => op.id !== editTarget.id ? op : {
      ...op,
      name: editName.trim(),
      initials,
      role: editRole,
      storeId,
      active: editActive,
      canMagazzinoWrite: editRole === 'Cassiere' ? editMaggWrite : false,
      ...(editPinReset ? { pin: editPinReset } : {}),
    }));
    setSubView('list');
  };

  // ── Componenti micro (senza stato, chiamati come funzioni) ──
  const renderBackBtn = (onClick) => (
    <button onClick={onClick}
      className="flex items-center gap-1.5 text-[13px] text-muted hover:text-ink transition-colors duration-fast ease-standard focus-ring rounded-md px-2 py-1 -ml-2 mb-3">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
      Indietro
    </button>
  );

  // Toggle iOS-style — dimensioni fisse inline per evitare dipendenza da spacing
  // Tailwind con CSS custom property (track 44×26, knob 20×20, padding 3px).
  const renderToggle = (value, onChange) => (
    <button
      onClick={() => onChange(!value)}
      className="focus-ring"
      style={{
        position: 'relative', flexShrink: 0, border: 'none', padding: 0, cursor: 'pointer',
        width: '44px', height: '26px', borderRadius: '13px',
        background: value ? 'var(--accent-blue)' : 'var(--border-strong)',
        transition: 'background 160ms cubic-bezier(0.32,0.72,0,1)',
      }}
    >
      <span style={{
        position: 'absolute',
        top: '3px',
        left: value ? '21px' : '3px',
        width: '20px', height: '20px', borderRadius: '50%',
        background: 'white',
        boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
        transition: 'left 160ms cubic-bezier(0.32,0.72,0,1)',
      }} />
    </button>
  );

  const renderField = (label, child) => (
    <div>
      <label className={_labelCls}>{label}</label>
      {child}
    </div>
  );

  // ── Tab: Il mio profilo ──
  const renderProfile = () => {
    const op        = currentOp;
    const storeName = op.storeId ? (STORES.find(s => s.id === op.storeId)?.name || op.storeId) : null;
    return (
      <div className="p-6 space-y-6">
        {/* Sessione / Esci */}
        <div className="flex items-center justify-between gap-4 flex-wrap p-4 rounded-2xl bg-surface shadow-sm">
          <div className="min-w-0">
            <div className="text-[14px] font-medium text-ink">{isStore ? ('Postazione · ' + (session?.op?.name || '')) : (session?.op?.name || op.name)}</div>
            <div className="text-[12.5px] text-muted">
              {isStore ? 'Account negozio' : (session?.op?.role || op.role)}
              {isStore && (cassaAperta ? ' · cassa aperta' : ' · cassa chiusa')}
            </div>
          </div>
          <Btn variant="danger" size="md" leading={<I.Lock size={16}/>} onClick={onExit}>Esci</Btn>
        </div>

        {logoutConfirm && (
          <div className="fixed inset-0 z-overlay flex items-center justify-center p-6"
            style={{ background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)' }}
            onClick={() => setLogoutConfirm(null)}>
            <div className="bg-surface rounded-2xl shadow-modal w-full max-w-[440px] p-6" onClick={e => e.stopPropagation()}>
              {logoutConfirm === 'cassa' ? (
                <>
                  <div className="flex items-center gap-2.5 mb-1">
                    <span className="w-9 h-9 rounded-md bg-[var(--warning-50)] text-[var(--warning-700)] flex items-center justify-center"><I.Wallet size={18}/></span>
                    <div className="text-[17px] font-semibold text-ink">Cassa ancora aperta</div>
                  </div>
                  <div className="text-[13.5px] text-muted mb-5 mt-1">Devi effettuare la <b>chiusura giornaliera</b> prima di uscire dalla postazione.</div>
                  <div className="flex justify-end gap-2">
                    <Btn variant="outline" size="md" onClick={() => setLogoutConfirm(null)}>Annulla</Btn>
                    <Btn variant="primary" size="md" leading={<I.EOD size={16}/>} onClick={() => { setLogoutConfirm(null); onClose && onClose(); if (window.__nav) window.__nav('eod'); }}>Vai alla chiusura</Btn>
                  </div>
                </>
              ) : (
                <>
                  <div className="text-[17px] font-semibold text-ink mb-1">{isStore ? 'Uscire dalla postazione?' : 'Vuoi uscire?'}</div>
                  <div className="text-[13.5px] text-muted mb-5">{isStore ? 'Tornerai alla schermata di accesso del negozio.' : 'Verrai disconnesso e tornerai al login.'}</div>
                  <div className="flex justify-end gap-2">
                    <Btn variant="outline" size="md" onClick={() => setLogoutConfirm(null)}>Annulla</Btn>
                    <Btn variant="danger" size="md" leading={<I.Lock size={16}/>} onClick={doLogout}>Esci</Btn>
                  </div>
                </>
              )}
            </div>
          </div>
        )}

        {/* Card info operatore */}
        <div className="flex items-center gap-4 p-4 bg-sunken rounded-2xl">
          <div className="w-14 h-14 rounded-2xl text-[var(--text-inverse)] flex items-center justify-center text-[20px] font-semibold shrink-0"
            style={{ background: 'linear-gradient(140deg, var(--accent-blue), var(--accent-indigo))' }}>
            {isStore ? <I.Store size={26}/> : op.initials}
          </div>
          <div className="min-w-0">
            <div className="text-[17px] font-semibold text-ink leading-tight">{op.name}</div>
            <div className="mt-1.5 flex items-center gap-2 flex-wrap">
              <Pill tone={ROLE_BADGE_TONE[op.role] || 'neutral'}>{op.role}</Pill>
              {storeName && <span className="text-[12px] text-muted">{storeName}</span>}
            </div>
          </div>
        </div>

        {/* Cambio PIN */}
        <div style={{ borderTop: '0.5px solid var(--border-subtle)', paddingTop: '20px' }}>
          <div className="text-[15px] font-semibold text-ink mb-4">Cambia PIN</div>
          <div className="space-y-3">
            {renderField('PIN attuale',
              <input type="password" inputMode="numeric" maxLength={8}
                value={pinCurrent} placeholder="••••"
                onChange={e => { setPinCurrent(e.target.value.replace(/\D/g, '')); setPinMsg(null); }}
                className={_inputCls}/>
            )}
            {renderField('Nuovo PIN',
              <input type="password" inputMode="numeric" maxLength={8}
                value={pinNew} placeholder="Min. 4 cifre"
                onChange={e => { setPinNew(e.target.value.replace(/\D/g, '')); setPinMsg(null); }}
                className={_inputCls}/>
            )}
            {renderField('Conferma nuovo PIN',
              <input type="password" inputMode="numeric" maxLength={8}
                value={pinConfirm} placeholder="••••"
                onChange={e => { setPinConfirm(e.target.value.replace(/\D/g, '')); setPinMsg(null); }}
                className={_inputCls}/>
            )}
            {pinMsg && (
              <div className={`text-[13px] px-3 py-2 rounded-lg ${pinMsg.type === 'ok' ? 'bg-[var(--success-50)] text-[var(--success-700)]' : 'bg-[var(--danger-50)] text-[var(--danger-700)]'}`}>
                {pinMsg.text}
              </div>
            )}
            <Btn variant="primary" size="lg" className="w-full"
              onClick={handleChangePIN}
              disabled={!pinCurrent || !pinNew || !pinConfirm}>
              Aggiorna PIN
            </Btn>
          </div>
        </div>
      </div>
    );
  };

  // ── Tab: Gestione account — lista ──
  const renderAccountRow = (op) => {
    const storeName = op.storeId ? (STORES.find(s => s.id === op.storeId)?.name || op.storeId) : null;
    return (
      <div key={op.id} className="flex items-center gap-3.5 px-4 py-3.5 rounded-xl bg-surface shadow-sm hover:shadow-md transition-shadow">
        <div className="w-10 h-10 rounded-full bg-[var(--accent-blue)] text-[var(--text-inverse)] flex items-center justify-center text-[13px] font-semibold shrink-0">{op.initials}</div>
        <div className="flex-1 min-w-0">
          <div className="text-[14.5px] font-semibold text-ink leading-tight truncate">{op.name}</div>
          <div className="flex items-center gap-2 mt-1">
            <Pill tone={ROLE_BADGE_TONE[op.role] || 'neutral'}>{op.role}</Pill>
            {storeName && <span className="text-[12px] text-muted truncate">{storeName}</span>}
          </div>
        </div>
        <div className="hidden md:block text-right shrink-0 mr-1">
          <div className="text-[10.5px] uppercase tracking-[0.05em] text-[var(--text-tertiary)]">Ultimo accesso</div>
          <div className="num text-[12px] text-muted">{op.lastAccess || '—'}</div>
        </div>
        <div className="shrink-0 flex items-center gap-1">
          <button onClick={() => openEdit(op)} className="focus-ring text-[12.5px] font-medium text-[var(--accent-blue)] hover:bg-[var(--bg-hover)] rounded-lg px-2.5 py-1.5">Modifica</button>
          {op.id !== session.op.id && (
            <button onClick={() => { setArchiving(op); setArchReason('Licenziamento'); setArchDate(''); }}
              className="focus-ring text-[12.5px] text-[var(--danger-700)] hover:bg-[var(--danger-50)] rounded-lg px-2.5 py-1.5">Archivia</button>
          )}
        </div>
      </div>
    );
  };

  const renderArchivedRow = (op) => (
    <div key={op.id} className="flex items-center gap-3.5 px-4 py-3 rounded-xl bg-sunken">
      <div className="w-10 h-10 rounded-full bg-[var(--gray-200)] text-[var(--text-secondary)] flex items-center justify-center text-[13px] font-semibold shrink-0">{op.initials}</div>
      <div className="flex-1 min-w-0">
        <div className="text-[14px] font-medium text-ink leading-tight truncate">{op.name}</div>
        <div className="text-[11.5px] text-muted mt-0.5">
          {op.role} · archiviato{op.archivedAt ? ' il ' + op.archivedAt : ''}{op.archiveReason ? ' · ' + op.archiveReason : ''}
        </div>
      </div>
      <button onClick={() => doReactivate(op)} className="focus-ring text-[12.5px] font-medium text-[var(--success-700)] hover:bg-[var(--success-50)] rounded-lg px-2.5 py-1.5 shrink-0">Riattiva</button>
    </div>
  );

  const renderAccountList = () => {
    const attivi = operators.filter(o => o.active !== false);
    const archiviati = operators.filter(o => o.active === false);
    return (
      <div className="p-5">
        <div className="flex items-center justify-between mb-4">
          <span className="text-[13px] text-muted"><span className="text-ink font-medium">{attivi.length}</span> attivi{archiviati.length ? ` · ${archiviati.length} archiviati` : ''}</span>
          <Btn variant="primary" size="sm" leading={<I.Plus size={14}/>} onClick={() => {
            setNewName(''); setNewRole('Cassiere'); setNewStore(STORES[0]?.id || ''); setNewPin(''); setNewErr('');
            setSubView('new');
          }}>Nuovo</Btn>
        </div>

        <div className="space-y-2">{attivi.map(renderAccountRow)}</div>

        {archiviati.length > 0 && (
          <>
            <div className="pt-6 pb-2 text-[11px] uppercase tracking-[0.06em] text-muted font-semibold">Archiviati</div>
            <div className="space-y-2">{archiviati.map(renderArchivedRow)}</div>
          </>
        )}

        {/* Modale archiviazione: motivo + data */}
        {archiving && (
          <div className="fixed inset-0 z-overlay flex items-center justify-center p-6"
            style={{ background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)' }} onClick={() => setArchiving(null)}>
            <div className="bg-surface rounded-2xl shadow-modal w-full max-w-[440px] p-6" onClick={e => e.stopPropagation()}>
              <div className="text-[17px] font-semibold text-ink mb-1">Archivia {archiving.name}</div>
              <div className="text-[13px] text-muted mb-5">Non comparirà più in cassa, timbrature e selettori. Resta nello storico e potrai riattivarlo.</div>
              <label className="block mb-3">
                <span className="text-[12px] text-muted">Motivo</span>
                <select className={_inputCls} value={archReason} onChange={e => setArchReason(e.target.value)}>
                  {ARCH_REASONS.map(r => <option key={r} value={r}>{r}</option>)}
                </select>
              </label>
              <label className="block mb-5">
                <span className="text-[12px] text-muted">Data (lascia vuoto = oggi)</span>
                <input className={_inputCls} value={archDate} onChange={e => setArchDate(e.target.value)} placeholder="GG/MM/AAAA"/>
              </label>
              <div className="flex justify-end gap-2">
                <Btn variant="outline" size="md" onClick={() => setArchiving(null)}>Annulla</Btn>
                <Btn variant="danger" size="md" leading={<I.Lock size={16}/>} onClick={doArchive}>Archivia</Btn>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  };

  // ── Tab: Gestione account — nuovo ──
  const renderNewAccount = () => (
    <div className="p-6 space-y-4">
      {renderBackBtn(() => setSubView('list'))}
      <div className="text-[16px] font-semibold text-ink">Nuovo account</div>
      {renderField('Nome completo',
        <input className={_inputCls} value={newName} placeholder="Nome Cognome"
          onChange={e => { setNewName(e.target.value); setNewErr(''); }}/>
      )}
      {renderField('Ruolo',
        <select className={_inputCls} value={newRole} onChange={e => { setNewRole(e.target.value); setNewErr(''); }}>
          {ROLE_OPTIONS.map(r => <option key={r} value={r}>{r}</option>)}
        </select>
      )}
      {STORE_REQUIRED_ROLES.includes(newRole) && renderField('Negozio di riferimento',
        <select className={_inputCls} value={newStore} onChange={e => { setNewStore(e.target.value); setNewErr(''); }}>
          {STORES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
        </select>
      )}
      {newRole === 'Area Manager' && renderField('Area di competenza',
        <select className={_inputCls} value={newArea} onChange={e => { setNewArea(e.target.value); setNewErr(''); }}>
          <option value="">— scegli area —</option>
          {areas.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
        </select>
      )}
      {PRIVILEGED_ROLES.includes(newRole) && (
        <>
          {renderField('Username (accesso diretto)',
            <input className={_inputCls} value={newUser} placeholder="es. mario.rossi" autoCapitalize="off"
              onChange={e => { setNewUser(e.target.value); setNewErr(''); }}/>
          )}
          {renderField('Password (accesso diretto)',
            <input type="password" className={_inputCls} value={newPass} placeholder="Min. 4 caratteri"
              onChange={e => { setNewPass(e.target.value); setNewErr(''); }}/>
          )}
        </>
      )}
      {renderField('PIN iniziale (per operare in negozio)',
        <input type="password" inputMode="numeric" maxLength={8}
          className={_inputCls} value={newPin} placeholder="Min. 4 cifre"
          onChange={e => { setNewPin(e.target.value.replace(/\D/g, '')); setNewErr(''); }}/>
      )}
      {newErr && (
        <div className="text-[13px] px-3 py-2 rounded-lg bg-[var(--danger-50)] text-[var(--danger-700)]">{newErr}</div>
      )}
      <Btn variant="primary" size="xl" className="w-full" onClick={handleNewAccount}>Crea account</Btn>
    </div>
  );

  // ── Tab: Gestione account — modifica ──
  const renderEditAccount = () => {
    if (!editTarget) return null;
    const isSelf = editTarget.id === session.op.id;
    return (
      <div className="p-6 space-y-4">
        {renderBackBtn(() => setSubView('list'))}
        <div className="text-[16px] font-semibold text-ink">Modifica account</div>
        {renderField('Nome completo',
          <input className={_inputCls} value={editName}
            onChange={e => { setEditName(e.target.value); setEditErr(''); }}/>
        )}
        {renderField('Ruolo',
          <select className={_inputCls} value={editRole} onChange={e => { setEditRole(e.target.value); setEditErr(''); }}>
            {ROLE_OPTIONS.map(r => <option key={r} value={r}>{r}</option>)}
          </select>
        )}
        {STORE_REQUIRED_ROLES.includes(editRole) && renderField('Negozio di riferimento',
          <select className={_inputCls} value={editStore} onChange={e => { setEditStore(e.target.value); setEditErr(''); }}>
            {STORES.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
        )}
        {editRole === 'Cassiere' && (
          <div className="flex items-center justify-between gap-4 p-3.5 bg-sunken rounded-xl">
            <div className="min-w-0">
              <div className="text-[14px] font-medium text-ink">Può gestire il magazzino</div>
              <div className="text-[12px] text-muted leading-snug mt-0.5">Accesso in scrittura alla sezione Magazzino</div>
            </div>
            {renderToggle(editMaggWrite, setEditMaggWrite)}
          </div>
        )}
        {renderField('Reset PIN (lascia vuoto per non cambiare)',
          <input type="password" inputMode="numeric" maxLength={8}
            className={_inputCls} value={editPinReset} placeholder="Nuovo PIN (min. 4 cifre)"
            onChange={e => { setEditPinReset(e.target.value.replace(/\D/g, '')); setEditErr(''); }}/>
        )}
        {!isSelf && (
          <div className="flex items-center justify-between gap-4 p-3.5 bg-sunken rounded-xl">
            <div className="min-w-0">
              <div className="text-[14px] font-medium text-ink">Account attivo</div>
              <div className="text-[12px] text-muted leading-snug mt-0.5">Gli account disattivati non appaiono al login</div>
            </div>
            {renderToggle(editActive, setEditActive)}
          </div>
        )}
        {editErr && (
          <div className="text-[13px] px-3 py-2 rounded-lg bg-[var(--danger-50)] text-[var(--danger-700)]">{editErr}</div>
        )}
        <Btn variant="primary" size="xl" className="w-full" onClick={handleSaveEdit}>Salva modifiche</Btn>
      </div>
    );
  };

  // ── Render principale ──
  return (
    <div>
      <Topbar
        eyebrow={STORE.name}
        title="Profilo e account"
        right={
          <Btn variant="outline" size="md" onClick={onClose}
            leading={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>}>
            Torna indietro
          </Btn>
        }
      />

      {/* Tabs — solo per Admin e Manager */}
      {isPrivileged && (
        <div className="flex px-7" style={{ borderBottom: '0.5px solid var(--border-subtle)' }}>
          {[
            { id: 'profile',  label: 'Il mio profilo' },
            { id: 'accounts', label: 'Gestione account' },
            { id: 'azienda',  label: 'Azienda' },
            ...(isAdmin ? [{ id: 'stores', label: 'Negozi e aree' }, { id: 'liste', label: 'Liste' }] : []),
          ].map(t => (
            <button key={t.id}
              onClick={() => { setTab(t.id); setSubView('list'); }}
              className={`relative h-11 px-4 text-[13.5px] font-medium transition-colors duration-fast ease-standard focus-ring ${tab === t.id ? 'text-[var(--accent-blue)]' : 'text-muted hover:text-ink'}`}
            >
              {t.label}
              {tab === t.id && (
                <span style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: '2px', background: 'var(--accent-blue)', borderRadius: '2px 2px 0 0' }}/>
              )}
            </button>
          ))}
        </div>
      )}

      {/* Impostazioni aziendali (a piena larghezza, fuori dal contenitore stretto) */}
      {tab === 'azienda' && isPrivileged && window.ImpostazioniContent && (
        <ImpostazioniContent withSession={false}/>
      )}

      {/* Contenuto */}
      <div className="max-w-[720px] mx-auto">
        {tab === 'profile'  && renderProfile()}
        {tab === 'accounts' && isPrivileged && (
          subView === 'list' ? renderAccountList() :
          subView === 'new'  ? renderNewAccount()  :
                               renderEditAccount()
        )}
        {tab === 'stores' && isAdmin && (
          <div className="p-6 space-y-6">
            {/* Negozi esistenti */}
            <div>
              <div className="text-[16px] font-semibold text-ink mb-2">Negozi</div>
              <div className="space-y-1.5 mb-4">
                {STORES.map(s => (
                  <div key={s.id} className="flex items-center justify-between px-3.5 py-2.5 rounded-lg bg-surface shadow-sm text-[13.5px]">
                    <span className="text-ink font-medium">{s.name}</span>
                    <span className="num text-muted text-[12px]">{s.id}</span>
                  </div>
                ))}
              </div>
              <div className="rounded-xl bg-paper p-4 space-y-3">
                <div className="text-[13px] font-semibold text-ink">Aggiungi negozio</div>
                <div className="grid grid-cols-2 gap-2.5">
                  <input className={_inputCls} value={stName} placeholder="Nome negozio" onChange={e => { setStName(e.target.value); setNewErr(''); }}/>
                  <input className={_inputCls} value={stCity} placeholder="Città" onChange={e => setStCity(e.target.value)}/>
                  <input className={_inputCls} value={stUser} placeholder="Username (login negozio)" autoCapitalize="off" onChange={e => { setStUser(e.target.value); setNewErr(''); }}/>
                  <input type="password" className={_inputCls} value={stPass} placeholder="Password (min. 4)" onChange={e => { setStPass(e.target.value); setNewErr(''); }}/>
                  <select className={_inputCls} value={stArea} onChange={e => setStArea(e.target.value)}>
                    <option value="">— area (opzionale) —</option>
                    {areas.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
                  </select>
                </div>
                <Btn variant="primary" size="md" onClick={handleNewStore}>Crea negozio</Btn>
              </div>
            </div>
            {/* Aree */}
            <div>
              <div className="text-[16px] font-semibold text-ink mb-2">Aree</div>
              <div className="flex flex-wrap gap-1.5 mb-3">
                {areas.map(a => <Pill key={a.id} tone="neutral">{a.name}</Pill>)}
                {areas.length === 0 && <span className="text-[12.5px] text-muted">Nessuna area.</span>}
              </div>
              <div className="flex gap-2">
                <input className={_inputCls} value={areaName} placeholder="Nome nuova area" onChange={e => setAreaName(e.target.value)}/>
                <Btn variant="outline" size="md" onClick={handleNewArea}>Aggiungi area</Btn>
              </div>
            </div>
            {newErr && <div className="text-[13px] px-3 py-2 rounded-lg bg-[var(--danger-50)] text-[var(--danger-700)]">{newErr}</div>}
          </div>
        )}

        {tab === 'liste' && isAdmin && (
          <div className="p-6">
            <div className="text-[16px] font-semibold text-ink mb-1">Liste e tendine</div>
            <div className="text-[12.5px] text-muted mb-4">Le voci qui compaiono nelle tendine del gestionale (catalogo, magazzino, pagamenti…).</div>
            <div className="grid grid-cols-1 md:grid-cols-[200px_minmax(0,1fr)] gap-5">
              {/* selettore lista */}
              <div className="space-y-1">
                {LIST_DEFS.map(d => (
                  <button key={d.key} onClick={() => { setActiveList(d.key); setRenaming(null); }}
                    className={`focus-ring w-full text-left px-3 py-2 rounded-lg text-[13px] transition-colors ${activeList === d.key ? 'bg-[var(--bg-selected)] text-[var(--accent-blue)] font-medium' : 'text-ink hover:bg-[var(--bg-hover)]'}`}>
                    {d.label} <span className="text-muted">· {(lists[d.key] || []).length}</span>
                  </button>
                ))}
              </div>
              {/* voci della lista attiva */}
              <div>
                <div className="rounded-xl bg-surface shadow-sm divide-y divide-line2 mb-3">
                  {(lists[activeList] || []).length === 0 && <div className="px-4 py-5 text-[13px] text-muted">Nessuna voce.</div>}
                  {(lists[activeList] || []).map(value => (
                    <div key={value} className="flex items-center justify-between px-4 py-2.5">
                      {renaming && renaming.key === activeList && renaming.value === value ? (
                        <div className="flex items-center gap-2 flex-1">
                          <input autoFocus className={_inputCls + ' h-9'} value={renameVal} onChange={e => setRenameVal(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') { saveRename(activeList, value, renameVal); setRenaming(null); } }}/>
                          <button onClick={() => { saveRename(activeList, value, renameVal); setRenaming(null); }} className="focus-ring text-[12.5px] font-medium text-[var(--accent-blue)]">Salva</button>
                          <button onClick={() => setRenaming(null)} className="focus-ring text-[12.5px] text-muted">Annulla</button>
                        </div>
                      ) : (
                        <>
                          <span className="text-[13.5px] text-ink">{value}</span>
                          <div className="flex items-center gap-3 shrink-0">
                            <button onClick={() => { setRenaming({ key: activeList, value }); setRenameVal(value); }} className="focus-ring text-[12.5px] text-[var(--accent-blue)] hover:underline">Rinomina</button>
                            <button onClick={() => delListItem(activeList, value)} className="focus-ring text-[12.5px] text-[var(--danger-700)] hover:underline">Elimina</button>
                          </div>
                        </>
                      )}
                    </div>
                  ))}
                </div>
                <div className="flex gap-2">
                  <input className={_inputCls} value={newVal} placeholder="Nuova voce…" onChange={e => setNewVal(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') addListItem(); }}/>
                  <Btn variant="primary" size="md" onClick={addListItem}>Aggiungi</Btn>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { UserManagementPanel });
