// ──────────────────────────── Anagrafiche ────────────────────────────
const { useState: useStateA, useMemo: useMemoA } = React;

// Cache di sessione: preserva le modifiche durante la navigazione
const _anaCustomerEdits  = {};
const _anaSupplierEdits  = {};

// ─── Shared input/label CSS (prefisso _an_ per evitare collisioni nel bundle) ───
const _anIn = '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 _anLb = 'block text-[12px] font-semibold uppercase tracking-[0.04em] text-muted mb-1.5';

// ─── TierPill ───
const TierPill = ({ tier }) => {
  if (tier === 'Top Client') return <Pill tone="accent">★ Top Client</Pill>;
  if (tier === 'Privilege')  return <Pill tone="info">Privilege</Pill>;
  if (tier === 'Standard')   return <Pill tone="neutral">Standard</Pill>;
  return <Pill tone="neutral">{tier}</Pill>;
};

// ─── Initials avatar ───
const Initials = ({ name, size = 40 }) => {
  const init = (name || '?').split(' ').map(s => s[0]).join('').slice(0, 2);
  const fs = size <= 32 ? 11 : size <= 48 ? 13 : 18;
  return (
    <div className="rounded-full bg-[var(--bg-selected)] text-[var(--accent-blue)] font-semibold flex items-center justify-center shrink-0"
      style={{ width: size, height: size, fontSize: fs }}>
      {init}
    </div>
  );
};

// ─── Helper: costruisce la struttura locale editabile da un customer o supplier ───
const buildLocalData = (c) => ({
  personType: c.personType || (c.kind === 'Azienda' ? 'azienda' : 'fisica'),
  firstName:  c.firstName  || (c.kind !== 'Azienda' ? (c.name || '').split(' ')[0]              || '' : ''),
  lastName:   c.lastName   || (c.kind !== 'Azienda' ? (c.name || '').split(' ').slice(1).join(' ') || '' : ''),
  ragioneSociale: c.ragioneSociale || (c.kind === 'Azienda' ? c.name : ''),
  piva: c.piva || (c.fiscal?.vat  && c.fiscal.vat  !== '—' ? c.fiscal.vat  : '') || (c.vat || ''),
  cf:   c.cf   || (c.fiscal?.cf   && c.fiscal.cf   !== '—' ? c.fiscal.cf   : '') || '',
  sdi:  c.sdi  || c.fiscal?.sdi || '',
  email: c.email || '',
  addresses: c.addresses || (
    (c.fiscal?.address || c.city)
      ? [{ id: 'a0', label: 'Indirizzo', via: c.fiscal?.address || '', citta: c.city || '', cap: '', provincia: '', nazione: c.country || 'IT', principale: true }]
      : []
  ),
  phones: c.phones || (c.phone
    ? [{ id: 'p0', label: 'Mobile', numero: c.phone, principale: true }]
    : []
  ),
  paymentTermId: c.paymentTermId || null,
  adminData: c.adminData || { iban: '', banca: '', pagamento: c.kind === 'Azienda' || c.personType === 'azienda' ? 'bonifico' : 'contanti' },
});

// ─── Riga indirizzo nel form di modifica ───
const AnaAddrRow = ({ addr, onUpdate, onRemove, onSetPrimary }) => (
  <div className="p-4 rounded-xl mb-3 space-y-3" style={{ border: '0.5px solid var(--border-default)', background: 'var(--bg-sunken)' }}>
    <div className="grid grid-cols-[160px_1fr] gap-3">
      <div>
        <label className={_anLb}>Etichetta</label>
        <select value={addr.label} onChange={e => onUpdate('label', e.target.value)} className={_anIn}>
          {['Sede legale', 'Residenza', 'Spedizione', 'Fatturazione', 'Altro'].map(l => <option key={l}>{l}</option>)}
        </select>
      </div>
      <div>
        <label className={_anLb}>Via / Indirizzo</label>
        <input value={addr.via} onChange={e => onUpdate('via', e.target.value)} placeholder="es. Via Roma 1" className={_anIn}/>
      </div>
    </div>
    <div className="grid grid-cols-[1fr_100px_70px_100px] gap-3">
      <input value={addr.citta}     onChange={e => onUpdate('citta', e.target.value)}     placeholder="Città"    className={_anIn}/>
      <input value={addr.cap}       onChange={e => onUpdate('cap', e.target.value)}       placeholder="CAP"      className={_anIn}/>
      <input value={addr.provincia} onChange={e => onUpdate('provincia', e.target.value)} placeholder="Prov."    className={_anIn}/>
      <input value={addr.nazione}   onChange={e => onUpdate('nazione', e.target.value)}   placeholder="Nazione"  className={_anIn}/>
    </div>
    <div className="flex items-center justify-between">
      <label className="flex items-center gap-2.5 cursor-pointer">
        <input type="radio" checked={!!addr.principale} onChange={() => onSetPrimary()}
          className="w-4 h-4 accent-[var(--accent-blue)]"/>
        <span className="text-[13px] text-ink">Indirizzo principale</span>
        {addr.principale && <Pill tone="accent">Principale</Pill>}
      </label>
      <button onClick={onRemove}
        className="flex items-center gap-1.5 h-8 px-3 rounded-md text-[12.5px] text-muted hover:bg-[var(--danger-50)] hover:text-[var(--danger-700)] transition-colors duration-fast ease-standard focus-ring">
        <I.Trash size={13}/> Rimuovi
      </button>
    </div>
  </div>
);

// ─── Riga telefono nel form di modifica ───
const AnaPhoneRow = ({ ph, onUpdate, onRemove, onSetPrimary }) => (
  <div className="flex items-center gap-3 p-3 rounded-xl mb-2" style={{ border: '0.5px solid var(--border-default)', background: 'var(--bg-sunken)' }}>
    <select value={ph.label} onChange={e => onUpdate('label', e.target.value)}
      className="h-9 px-2 rounded-md border border-line bg-surface text-[13.5px] text-ink focus:border-strong focus:outline-none transition-all shrink-0" style={{ width: '110px' }}>
      {['Mobile', 'Ufficio', 'Fax', 'Altro'].map(l => <option key={l}>{l}</option>)}
    </select>
    <input value={ph.numero} onChange={e => onUpdate('numero', e.target.value)}
      placeholder="+39 000 000 0000" type="tel"
      className="flex-1 h-9 px-3 rounded-md border border-line bg-surface text-[14px] text-ink focus:border-strong focus:outline-none transition-all"/>
    <label className="flex items-center gap-2 cursor-pointer shrink-0">
      <input type="radio" checked={!!ph.principale} onChange={() => onSetPrimary()}
        className="w-4 h-4 accent-[var(--accent-blue)]"/>
      <span className="text-[12px] text-muted whitespace-nowrap">Principale</span>
    </label>
    <button onClick={onRemove}
      className="w-9 h-9 rounded-md flex items-center justify-center text-muted hover:bg-[var(--danger-50)] hover:text-[var(--danger-700)] transition-colors duration-fast ease-standard focus-ring shrink-0">
      <I.Trash size={13}/>
    </button>
  </div>
);

// ══════════════════════════════════════════════════════════════════════
//  Form di modifica anagrafica (usato da CustomerDetail e SupplierDetail)
// ══════════════════════════════════════════════════════════════════════
const AnaEditForm = ({ ld, isSupplier, onFieldChange, onSave, onCancel }) => {
  const terms = window.__BI_TERMINI__ || PAYMENT_TERMS;
  const isAzienda = ld.personType === 'azienda';

  // Address helpers
  const addAddr = () => onFieldChange('addresses', [...ld.addresses, { id: 'a' + Date.now(), label: 'Altro', via: '', citta: '', cap: '', provincia: '', nazione: 'IT', principale: ld.addresses.length === 0 }]);
  const updateAddr = (id, field, val) => onFieldChange('addresses', ld.addresses.map(a => a.id !== id ? a : { ...a, [field]: val }));
  const removeAddr = (id) => onFieldChange('addresses', ld.addresses.filter(a => a.id !== id));
  const setPrimAddr = (id) => onFieldChange('addresses', ld.addresses.map(a => ({ ...a, principale: a.id === id })));

  // Phone helpers
  const addPhone = () => onFieldChange('phones', [...ld.phones, { id: 'p' + Date.now(), label: 'Mobile', numero: '', principale: ld.phones.length === 0 }]);
  const updatePhone = (id, field, val) => onFieldChange('phones', ld.phones.map(p => p.id !== id ? p : { ...p, [field]: val }));
  const removePhone = (id) => onFieldChange('phones', ld.phones.filter(p => p.id !== id));
  const setPrimPhone = (id) => onFieldChange('phones', ld.phones.map(p => ({ ...p, principale: p.id === id })));

  const setAdmin = (key, val) => onFieldChange('adminData', { ...ld.adminData, [key]: val });

  return (
    <div className="px-7 py-6 max-w-[900px] space-y-5">
      {/* Tipo anagrafica (solo per clienti) */}
      {!isSupplier && (
        <Card title="Tipo anagrafica">
          <div className="flex gap-3">
            {[
              { id: 'fisica',  label: 'Persona fisica', icon: 'User'  },
              { id: 'azienda', label: 'Azienda',         icon: 'Globe' },
            ].map(t => {
              const Ico = I[t.icon];
              const active = ld.personType === t.id;
              return (
                <button key={t.id} type="button" onClick={() => onFieldChange('personType', t.id)}
                  className={`flex items-center gap-2.5 h-11 px-5 rounded-md border text-[14px] font-medium transition-all duration-fast ease-standard
                    ${active ? 'bg-[var(--bg-selected)] border-[var(--accent-blue)] text-[var(--accent-blue)]' : 'border-line bg-sunken text-muted hover:border-strong hover:text-ink'}`}>
                  <Ico size={16}/>
                  {t.label}
                </button>
              );
            })}
          </div>
        </Card>
      )}

      {/* Dati anagrafici */}
      <Card title={isAzienda || isSupplier ? 'Dati azienda' : 'Dati personali'}>
        {isAzienda || isSupplier ? (
          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-2">
              <label className={_anLb}>Ragione sociale</label>
              <input value={ld.ragioneSociale} onChange={e => onFieldChange('ragioneSociale', e.target.value)} className={_anIn}/>
            </div>
            <div>
              <label className={_anLb}>P.IVA</label>
              <input value={ld.piva} onChange={e => onFieldChange('piva', e.target.value)} placeholder="IT00000000000" className={_anIn}/>
            </div>
            <div>
              <label className={_anLb}>Codice fiscale</label>
              <input value={ld.cf} onChange={e => onFieldChange('cf', e.target.value)} className={_anIn}/>
            </div>
            <div>
              <label className={_anLb}>Codice SDI</label>
              <input value={ld.sdi} onChange={e => onFieldChange('sdi', e.target.value)} placeholder="es. A4707H7" className={_anIn}/>
            </div>
            <div>
              <label className={_anLb}>Email principale</label>
              <input type="email" value={ld.email} onChange={e => onFieldChange('email', e.target.value)} className={_anIn}/>
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className={_anLb}>Nome</label>
              <input value={ld.firstName} onChange={e => onFieldChange('firstName', e.target.value)} className={_anIn}/>
            </div>
            <div>
              <label className={_anLb}>Cognome</label>
              <input value={ld.lastName} onChange={e => onFieldChange('lastName', e.target.value)} className={_anIn}/>
            </div>
            <div>
              <label className={_anLb}>Codice fiscale</label>
              <input value={ld.cf} onChange={e => onFieldChange('cf', e.target.value)} className={_anIn}/>
            </div>
            <div className="col-span-3">
              <label className={_anLb}>Email principale</label>
              <input type="email" value={ld.email} onChange={e => onFieldChange('email', e.target.value)} className={_anIn}/>
            </div>
          </div>
        )}
      </Card>

      {/* Indirizzi */}
      <Card title="Indirizzi"
        action={<Btn variant="outline" size="sm" leading={<I.Plus size={13}/>} onClick={addAddr}>Aggiungi</Btn>}>
        {ld.addresses.length === 0
          ? <div className="text-[13.5px] text-muted py-2">Nessun indirizzo. Clicca "Aggiungi" per inserirne uno.</div>
          : ld.addresses.map(addr => (
            <AnaAddrRow key={addr.id} addr={addr}
              onUpdate={(f, v) => updateAddr(addr.id, f, v)}
              onRemove={() => removeAddr(addr.id)}
              onSetPrimary={() => setPrimAddr(addr.id)}/>
          ))
        }
      </Card>

      {/* Telefoni */}
      <Card title="Telefoni"
        action={<Btn variant="outline" size="sm" leading={<I.Plus size={13}/>} onClick={addPhone}>Aggiungi</Btn>}>
        {ld.phones.length === 0
          ? <div className="text-[13.5px] text-muted py-2">Nessun telefono. Clicca "Aggiungi" per inserirne uno.</div>
          : ld.phones.map(ph => (
            <AnaPhoneRow key={ph.id} ph={ph}
              onUpdate={(f, v) => updatePhone(ph.id, f, v)}
              onRemove={() => removePhone(ph.id)}
              onSetPrimary={() => setPrimPhone(ph.id)}/>
          ))
        }
      </Card>

      {/* Termini di pagamento */}
      <Card title="Termini e dati amministrativi">
        <div className="grid grid-cols-2 gap-5 mb-5">
          <div>
            <label className={_anLb}>Termini di pagamento</label>
            <select value={ld.paymentTermId || ''} onChange={e => onFieldChange('paymentTermId', e.target.value || null)} className={_anIn}>
              <option value="">— Nessuno —</option>
              {terms.map(t => <option key={t.id} value={t.id}>{t.desc}</option>)}
            </select>
          </div>
          <div>
            <label className={_anLb}>Modalità di pagamento</label>
            <select value={ld.adminData.pagamento} onChange={e => setAdmin('pagamento', e.target.value)} className={_anIn}>
              <option value="bonifico">Bonifico</option>
              <option value="contanti">Contanti</option>
              <option value="carta">Carta</option>
              <option value="assegno">Assegno</option>
            </select>
          </div>
        </div>
        <div className="grid grid-cols-2 gap-5">
          <div>
            <label className={_anLb}>IBAN</label>
            <input value={ld.adminData.iban} onChange={e => setAdmin('iban', e.target.value)} placeholder="IT00 X000 0000 0000 0000 0000 000" className={_anIn}/>
          </div>
          <div>
            <label className={_anLb}>Banca</label>
            <input value={ld.adminData.banca} onChange={e => setAdmin('banca', e.target.value)} placeholder="es. UniCredit" className={_anIn}/>
          </div>
        </div>
      </Card>

      {/* Azioni */}
      <div className="flex items-center justify-between bg-surface rounded-2xl p-4 shadow-soft">
        <Btn variant="outline" size="lg" onClick={onCancel}>Annulla</Btn>
        <button onClick={onSave}
          className="h-16 px-8 rounded-md bg-[var(--accent-blue)] text-[var(--text-inverse)] font-semibold text-[17px] flex items-center gap-3 hover:bg-[var(--accent-blue-hover)] active:bg-[var(--accent-blue-active)] transition-all duration-fast ease-standard shadow-soft">
          <I.Check size={20}/>
          Salva modifiche
        </button>
      </div>
    </div>
  );
};

// ══════════════════════════════════════════════════════════════════════
//  AnagraficheList
// ══════════════════════════════════════════════════════════════════════
const AnagraficheList = ({ onOpenCustomer, onOpenSupplier, role, onNew }) => {
  const isMagazziniere = role === 'Magazziniere';
  const [tab, setTab]   = useStateA(isMagazziniere ? 'fornitori' : 'clienti');
  const [q, setQ]       = useStateA('');
  const [tier, setTier] = useStateA('Tutti');
  const [kind, setKind] = useStateA('Tutti');

  const filteredCustomers = useMemoA(() => {
    const ql = q.trim().toLowerCase();
    return CUSTOMERS.filter(c => {
      if (tier !== 'Tutti' && c.tier !== tier) return false;
      if (kind !== 'Tutti' && c.kind !== kind) return false;
      if (ql && !(c.name.toLowerCase().includes(ql) || c.email.toLowerCase().includes(ql) || (c.phone || '').includes(ql) || c.id.toLowerCase().includes(ql))) return false;
      return true;
    });
  }, [q, tier, kind]);

  const filteredSuppliers = useMemoA(() => {
    const ql = q.trim().toLowerCase();
    return SUPPLIERS.filter(s => {
      if (ql && !(s.name.toLowerCase().includes(ql) || s.vat.toLowerCase().includes(ql) || s.cat.toLowerCase().includes(ql))) return false;
      return true;
    });
  }, [q]);

  return (
    <>
      <Topbar
        eyebrow={`Anagrafiche · ${STORE.name}`}
        title="Anagrafiche"
        right={<>
          <Btn variant="outline" size="md" leading={<I.ArrowD size={16}/>} onClick={() => {
            if (!window.__csv) return;
            if (tab === 'clienti') {
              window.__csv(
                'anagrafiche-clienti.csv',
                ['Cliente', 'ID', 'Tipo', 'Email', 'Telefono', 'Tier', 'Punti', 'Speso (12m)', 'Ultima visita'],
                filteredCustomers.map(c => [
                  c.name, c.id,
                  (c.personType === 'azienda' || c.kind === 'Azienda') ? 'Azienda' : 'Persona fisica',
                  c.email, c.phones?.[0]?.numero || c.phone || '—',
                  c.tier, c.points, fmtEur(c.spent), c.lastVisit,
                ])
              );
            } else {
              window.__csv(
                'anagrafiche-fornitori.csv',
                ['Fornitore', 'ID', 'Categoria', 'P.IVA', 'Sede', 'Referente', 'Telefono', 'Ultimo ordine', 'Aperto'],
                filteredSuppliers.map(s => [
                  s.name, s.id, s.cat, s.vat, s.city, s.contact,
                  s.phones?.[0]?.numero || s.phone || '—',
                  s.lastOrder, s.open > 0 ? fmtEur(s.open) : '—',
                ])
              );
            }
          }}>Esporta</Btn>
          <Btn variant="ink" size="md" leading={<I.Plus size={16}/>}
            onClick={() => { if (onNew) onNew(tab); }}>
            {tab === 'clienti' ? 'Nuovo cliente' : 'Nuovo fornitore'}
          </Btn>
        </>}
      />

      {!isMagazziniere && (
        <div className="px-7 hairline bg-paper">
          <div className="flex items-center gap-1">
            {[
              { id: 'clienti',   label: 'Clienti',   icon: 'User',  count: CUSTOMERS.length },
              { id: 'fornitori', label: 'Fornitori', icon: 'Truck', count: SUPPLIERS.length },
            ].map(t => {
              const Ico = I[t.icon];
              const active = tab === t.id;
              return (
                <button key={t.id} onClick={() => setTab(t.id)}
                  className={`flex items-center gap-2.5 h-11 px-4 text-[14px] font-medium transition-all duration-fast ease-standard border-b-2 -mb-px
                    ${active ? 'text-ink border-ink' : 'text-muted border-transparent hover:text-ink'}`}>
                  <Ico size={16}/>
                  {t.label}
                  <span className={`num text-[11px] px-1.5 py-0.5 rounded ${active ? 'bg-[var(--bg-selected)] text-[var(--accent-blue)]' : 'bg-line2 text-muted'}`}>{t.count}</span>
                </button>
              );
            })}
          </div>
        </div>
      )}

      <div className="px-7 py-5 space-y-4 max-w-[1400px]">
        {tab === 'clienti' && (
          <div className="grid grid-cols-4 gap-4">
            <KpiTile label="Clienti totali"  value={CUSTOMERS.length}                                           sub="anagrafiche attive"/>
            <KpiTile label="Top Client"      value={CUSTOMERS.filter(c => c.tier === 'Top Client').length}      sub="alto valore" tone="pos"/>
            <KpiTile label="Privilege"       value={CUSTOMERS.filter(c => c.tier === 'Privilege').length}       sub="fedeltà alta"/>
            <KpiTile label="Nuovi (90g)"     value={CUSTOMERS.filter(c => c.tags?.includes('Nuovo')).length}    sub="acquisiti di recente"/>
          </div>
        )}

        <div className="bg-surface rounded-2xl p-3.5 shadow-soft">
          <div className="flex flex-wrap items-center gap-2.5">
            <div className="relative flex-1 min-w-[260px]">
              <I.Search size={18} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-muted"/>
              <input value={q} onChange={e => setQ(e.target.value)}
                placeholder={tab === 'clienti' ? 'Cerca per nome, email, telefono o ID…' : 'Cerca fornitore, P.IVA o categoria…'}
                className="w-full h-11 pl-11 pr-4 rounded-md bg-sunken text-[14px] shadow-[inset_0_0_0_0.5px_var(--border-default)] focus:bg-surface focus:shadow-[var(--shadow-focus),inset_0_0_0_1px_var(--accent-blue)] transition-all duration-fast ease-standard"/>
            </div>
            {tab === 'clienti' && (
              <>
                <FilterSelect label="Tier" value={tier} onChange={setTier} options={['Tutti', 'Top Client', 'Privilege', 'Standard']}/>
                <FilterSelect label="Tipo" value={kind} onChange={setKind} options={['Tutti', 'Privato', 'Azienda']}/>
              </>
            )}
          </div>
        </div>

        {/* Tabella clienti */}
        {tab === 'clienti' && (
          <Card padded={false}>
            <table className="w-full text-[13.5px]">
              <thead>
                <tr className="text-left text-muted uppercase text-[11px] tracking-[0.08em] hairline">
                  <th className="px-5 py-3 font-medium">Cliente</th>
                  <th className="px-5 py-3 font-medium">Tipo</th>
                  <th className="px-5 py-3 font-medium">Contatti</th>
                  <th className="px-5 py-3 font-medium">Tier</th>
                  <th className="px-5 py-3 font-medium text-right">Punti</th>
                  <th className="px-5 py-3 font-medium text-right">Speso (12m)</th>
                  <th className="px-5 py-3 font-medium">Ultima visita</th>
                </tr>
              </thead>
              <tbody>
                {filteredCustomers.map(c => (
                  <tr key={c.id} onClick={() => onOpenCustomer(c.id)}
                    className="hover:bg-paper border-b border-line2 last:border-0 cursor-pointer">
                    <td className="px-5 py-3.5">
                      <div className="flex items-center gap-3">
                        <Initials name={c.name} size={36}/>
                        <div>
                          <div className="text-ink font-medium">{c.name}</div>
                          <div className="text-[11.5px] text-muted num">{c.id}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-5 py-3.5">
                      <Pill tone={c.personType === 'azienda' || c.kind === 'Azienda' ? 'info' : 'neutral'}>
                        {c.personType === 'azienda' || c.kind === 'Azienda' ? 'Azienda' : 'Persona fisica'}
                      </Pill>
                    </td>
                    <td className="px-5 py-3.5 text-muted">
                      <div className="truncate max-w-[200px]">{c.email}</div>
                      <div className="num text-[12px]">{c.phones?.[0]?.numero || c.phone || '—'}</div>
                    </td>
                    <td className="px-5 py-3.5"><TierPill tier={c.tier}/></td>
                    <td className="px-5 py-3.5 num text-ink text-right">{c.points.toLocaleString('it-IT')}</td>
                    <td className="px-5 py-3.5 num text-ink text-right font-medium">{fmtEur(c.spent)}</td>
                    <td className="px-5 py-3.5 text-ink">{c.lastVisit}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            {filteredCustomers.length === 0 && (
              <div className="py-16 text-center text-muted text-[14px]">Nessun cliente corrisponde ai filtri.</div>
            )}
          </Card>
        )}

        {/* Tabella fornitori */}
        {tab === 'fornitori' && (
          <Card padded={false}>
            <table className="w-full text-[13.5px]">
              <thead>
                <tr className="text-left text-muted uppercase text-[11px] tracking-[0.08em] hairline">
                  <th className="px-5 py-3 font-medium">Fornitore</th>
                  <th className="px-5 py-3 font-medium">Categoria</th>
                  <th className="px-5 py-3 font-medium">P.IVA</th>
                  <th className="px-5 py-3 font-medium">Sede</th>
                  <th className="px-5 py-3 font-medium">Contatti</th>
                  <th className="px-5 py-3 font-medium">Ultimo ordine</th>
                  <th className="px-5 py-3 font-medium text-right">Aperto</th>
                </tr>
              </thead>
              <tbody>
                {filteredSuppliers.map(s => (
                  <tr key={s.id} onClick={() => onOpenSupplier(s.id)}
                    className="hover:bg-paper border-b border-line2 last:border-0 cursor-pointer">
                    <td className="px-5 py-3.5">
                      <div className="flex items-center gap-3">
                        <div className="w-9 h-9 rounded-sm bg-line2 text-muted flex items-center justify-center">
                          <I.Truck size={16}/>
                        </div>
                        <div>
                          <div className="text-ink font-medium">{s.name}</div>
                          <div className="text-[11.5px] text-muted num">{s.id}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-5 py-3.5 text-ink">{s.cat}</td>
                    <td className="px-5 py-3.5 num text-muted">{s.vat}</td>
                    <td className="px-5 py-3.5 text-ink">{s.city}</td>
                    <td className="px-5 py-3.5 text-muted">
                      <div>{s.contact}</div>
                      <div className="num text-[12px]">{s.phones?.[0]?.numero || s.phone || '—'}</div>
                    </td>
                    <td className="px-5 py-3.5 text-ink">{s.lastOrder}</td>
                    <td className={`px-5 py-3.5 num text-right font-medium ${s.open > 0 ? 'text-warn' : 'text-muted'}`}>
                      {s.open > 0 ? fmtEur(s.open) : '—'}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        )}
      </div>
    </>
  );
};

// ══════════════════════════════════════════════════════════════════════
//  CustomerDetail
// ══════════════════════════════════════════════════════════════════════
const CustomerDetail = ({ customerId, onBack }) => {
  const c = CUSTOMERS.find(x => x.id === customerId);
  if (!c) return null;

  const [editing, setEditing] = useStateA(false);
  const [ld, setLd] = useStateA(() => _anaCustomerEdits[customerId] || buildLocalData(c));

  const setF = (key, val) => setLd(prev => ({ ...prev, [key]: val }));

  const terms     = window.__BI_TERMINI__ || PAYMENT_TERMS;
  const termLabel = ld.paymentTermId ? (terms.find(t => t.id === ld.paymentTermId)?.desc || '—') : '—';
  const isAzienda = ld.personType === 'azienda';

  const displayName  = isAzienda ? (ld.ragioneSociale || c.name) : ((ld.firstName && ld.lastName) ? `${ld.firstName} ${ld.lastName}` : c.name);
  const primaryPhone = ld.phones.find(p => p.principale)?.numero || c.phone || '—';
  const primaryAddr  = ld.addresses.find(a => a.principale);

  const handleSave = () => {
    _anaCustomerEdits[customerId] = { ...ld };
    if (window.__API__) window.__API__.mutate('/api/customers', { customer: { ...c, ...ld, name: displayName } }).then(()=>{ if (window.__toast) window.__toast('Cliente salvato', 'success'); }).catch(()=>{});
    setEditing(false);
  };
  const handleCancel = () => {
    setLd(_anaCustomerEdits[customerId] || buildLocalData(c));
    setEditing(false);
  };

  // Tag CRM: editor inline (aggiungi/rimuovi tag) con salvataggio
  const [tags, setTags] = useStateA(c.tags || []);
  const [addingTag, setAddingTag] = useStateA(false);
  const [tagInput, setTagInput] = useStateA('');
  const saveTags = (next) => {
    setTags(next);
    if (window.__API__) window.__API__.mutate('/api/customers', { customer: { ...c, ...ld, name: displayName, tags: next } })
      .then(() => { if (window.__toast) window.__toast('Tag aggiornati', 'success'); }).catch(() => {});
  };
  const addTag = () => {
    const t = tagInput.trim();
    if (!t) { setAddingTag(false); return; }
    if (!tags.includes(t)) saveTags([...tags, t]);
    setTagInput(''); setAddingTag(false);
  };
  const removeTag = (t) => saveTags(tags.filter(x => x !== t));

  return (
    <>
      <Topbar
        eyebrow={
          <span className="flex items-center gap-1.5">
            <button onClick={onBack} className="text-ink hover:underline">Anagrafiche</button>
            <I.ArrowR size={11} className="opacity-60"/>
            <span>Clienti</span>
          </span>
        }
        title={displayName}
        right={<>
          <Btn variant="outline" size="md" onClick={onBack}
            leading={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>}>
            Torna all'elenco
          </Btn>
          {!editing && <Btn variant="outline" size="md" leading={<I.Edit size={16}/>} onClick={() => setEditing(true)}>Modifica</Btn>}
          <Btn variant="ink" size="md" leading={<I.Cash size={16}/>}
            onClick={() => { if (window.__nav) window.__nav('pos'); else if (window.__toast) window.__toast('Apri la Cassa', 'info'); }}>Nuova vendita</Btn>
        </>}
      />

      {editing ? (
        <AnaEditForm
          ld={ld}
          isSupplier={false}
          onFieldChange={setF}
          onSave={handleSave}
          onCancel={handleCancel}
        />
      ) : (
        <div className="px-7 py-6 space-y-6 max-w-[1400px]">
          {/* Hero card */}
          <Card>
            <div className="flex items-start gap-5">
              <Initials name={displayName} size={72}/>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-3 mb-1 flex-wrap">
                  <h2 className="text-[24px] font-semibold tracking-tight text-ink">{displayName}</h2>
                  <TierPill tier={c.tier}/>
                  <Pill tone={isAzienda ? 'info' : 'neutral'}>{isAzienda ? 'Azienda' : 'Persona fisica'}</Pill>
                  {c.tags.map(t => <Pill key={t} tone="neutral">{t}</Pill>)}
                </div>
                <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[13.5px] text-muted">
                  <span className="num">{c.id}</span>
                  <span>·</span>
                  <span>{ld.email || c.email}</span>
                  <span>·</span>
                  <span className="num">{primaryPhone}</span>
                  {primaryAddr && <>
                    <span>·</span>
                    <span>{primaryAddr.citta}{primaryAddr.provincia ? ` (${primaryAddr.provincia})` : ''}</span>
                  </>}
                </div>
                <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-[12.5px] text-muted">
                  <span>Cliente dal <span className="text-ink font-medium">{c.since}</span></span>
                  {!isAzienda && c.birth && c.birth !== '—' && <>
                    <span>·</span>
                    <span>Nato il <span className="text-ink font-medium">{c.birth}</span></span>
                  </>}
                  <span>·</span>
                  <span>Ultima visita <span className="text-ink font-medium">{c.lastVisit}</span></span>
                </div>
              </div>
              <div className="text-right shrink-0">
                <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Punti fedeltà</div>
                <div className="num text-[36px] font-semibold text-ink leading-none mt-1">{c.points.toLocaleString('it-IT')}</div>
                <div className="text-[12px] text-muted mt-1">≈ {fmtEur(c.points * 0.05)} disponibili</div>
              </div>
            </div>
          </Card>

          {/* KPI strip */}
          <Card padded={false}>
            <div className="flex divide-x divide-line">
              <Stat label="Totale speso"    value={fmtEur(c.spent)}    subtle="negli ultimi 12 mesi"/>
              <Stat label="Acquisti"         value={c.orders}            subtle="documenti emessi"/>
              <Stat label="Scontrino medio" value={fmtEur(c.avgTicket)} subtle={`su ${c.orders} acquisti`}/>
              <Stat label="Punti maturati"  value={c.points.toLocaleString('it-IT')} subtle="programma fedeltà"/>
            </div>
          </Card>

          {/* Grid: history | right panel */}
          <div className="grid grid-cols-[1fr_380px] gap-6">
            {/* Storico acquisti */}
            <Card title="Storico acquisti" padded={false}
              action={
                <div className="flex items-center gap-2">
                  <Pill tone="neutral">{c.history.length} documenti</Pill>
                  <Btn variant="ghost" size="sm" trailing={<I.ArrowR size={14}/>}
                    onClick={() => {
                      if (window.__csv) window.__csv(
                        `storico-${c.id}.csv`,
                        ['Documento', 'Tipo', 'Data', 'Negozio', 'Importo'],
                        c.history.map(h => [h.id, h.type, h.date, STORES.find(s => s.id === h.store)?.name || h.store, fmtEur(h.total)])
                      );
                    }}>Vedi tutti</Btn>
                </div>
              }>
              <table className="w-full text-[13.5px]">
                <thead>
                  <tr className="text-left text-muted uppercase text-[11px] tracking-[0.08em] hairline">
                    <th className="px-5 py-3 font-medium">Documento</th>
                    <th className="px-5 py-3 font-medium">Tipo</th>
                    <th className="px-5 py-3 font-medium">Data</th>
                    <th className="px-5 py-3 font-medium">Negozio</th>
                    <th className="px-5 py-3 font-medium text-right">Importo</th>
                  </tr>
                </thead>
                <tbody>
                  {c.history.map(h => (
                    <tr key={h.id}
                      onClick={() => {
                        // apri la sezione Documenti (lì si trova/stampa il documento)
                        window.__DOC_FOCUS__ = h.id;
                        if (window.__nav) window.__nav('documenti');
                        else if (window.__toast) window.__toast(`${h.type} ${h.id} · vai in Documenti`, 'info');
                      }}
                      title="Apri in Documenti"
                      className="hover:bg-paper border-b border-line2 last:border-0 cursor-pointer">
                      <td className="px-5 py-3.5 num text-ink font-medium">{h.id}</td>
                      <td className="px-5 py-3.5">
                        <span className="inline-flex items-center gap-2">
                          <span className="text-ink">{h.type}</span>
                          {h.taxfree && <Pill tone="info"><I.Globe size={11}/> Tax-free</Pill>}
                        </span>
                      </td>
                      <td className="px-5 py-3.5 text-ink">{h.date}</td>
                      <td className="px-5 py-3.5 text-muted">{STORES.find(s => s.id === h.store)?.name}</td>
                      <td className={`px-5 py-3.5 num text-right font-medium ${h.total < 0 ? 'text-neg' : 'text-ink'}`}>{fmtEur(h.total)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </Card>

            {/* Pannello destro */}
            <div className="space-y-5">
              {/* CRM */}
              <Card title="Segmentazione CRM">
                <div className="space-y-4">
                  <div>
                    <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium mb-2">Tier fedeltà</div>
                    <TierPill tier={c.tier}/>
                  </div>
                  <div>
                    <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium mb-2">Tag e segmenti</div>
                    <div className="flex flex-wrap items-center gap-1.5">
                      {tags.map(t => (
                        <span key={t} className="group inline-flex items-center gap-1">
                          <Pill tone={t === 'VIP' || t === 'Top Client' ? 'accent' : t === 'Nuovo' ? 'pos' : 'neutral'}>{t}</Pill>
                          <button onClick={() => removeTag(t)} title="Rimuovi tag"
                            className="opacity-0 group-hover:opacity-100 transition-opacity text-muted hover:text-[var(--danger-500)] text-[12px] leading-none">×</button>
                        </span>
                      ))}
                      {addingTag ? (
                        <input autoFocus value={tagInput}
                          onChange={(e) => setTagInput(e.target.value)}
                          onKeyDown={(e) => { if (e.key === 'Enter') addTag(); if (e.key === 'Escape') { setTagInput(''); setAddingTag(false); } }}
                          onBlur={addTag}
                          placeholder="nuovo tag…"
                          className="h-6 px-2 rounded-full text-[11px] bg-surface text-ink focus:outline-none" style={{ border: '1px solid var(--border-strong)', width: 100 }}/>
                      ) : (
                        <button onClick={() => setAddingTag(true)}
                          className="h-6 px-2 rounded-full text-[11px] text-muted hover:border-strong hover:text-ink" style={{ border: '1px dashed var(--border-default)' }}>
                          + aggiungi
                        </button>
                      )}
                    </div>
                  </div>
                  <div>
                    <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium mb-2">Punteggio fedeltà</div>
                    <div className="flex items-baseline gap-2">
                      <span className="num text-[22px] font-semibold text-ink">{c.points.toLocaleString('it-IT')}</span>
                      <span className="text-[12.5px] text-muted">/ 20.000 al livello successivo</span>
                    </div>
                    <div className="mt-2 h-2 bg-line2 rounded-full overflow-hidden">
                      <div className="h-full bg-[var(--accent-blue)] rounded-full" style={{ width: `${Math.min(100, (c.points / 20000) * 100)}%` }}/>
                    </div>
                  </div>
                  <div className="pt-3 border-t border-line2 grid grid-cols-2 gap-3">
                    <KeyVal label="Frequenza" value={c.orders >= 10 ? 'Alta' : c.orders >= 4 ? 'Media' : 'Bassa'}/>
                    <KeyVal label="Valore" value={c.spent >= 20000 ? 'Alto' : c.spent >= 5000 ? 'Medio' : 'Standard'}/>
                  </div>
                </div>
              </Card>

              {/* Dati fiscali */}
              <Card title="Dati fiscali e pagamento">
                <div className="space-y-3.5">
                  {isAzienda ? (
                    <>
                      <KeyVal label="Ragione sociale" value={ld.ragioneSociale || c.fiscal?.name || '—'}/>
                      <div className="grid grid-cols-2 gap-3.5">
                        <KeyVal label="P.IVA" value={ld.piva || '—'} mono/>
                        <KeyVal label="Cod. fiscale" value={ld.cf || '—'} mono/>
                      </div>
                      {(ld.sdi || c.fiscal?.sdi) && (
                        <KeyVal label="Codice SDI" value={ld.sdi || c.fiscal?.sdi} mono/>
                      )}
                    </>
                  ) : (
                    <>
                      <div className="grid grid-cols-2 gap-3.5">
                        <KeyVal label="Nome" value={ld.firstName || c.name.split(' ')[0] || '—'}/>
                        <KeyVal label="Cognome" value={ld.lastName || c.name.split(' ').slice(1).join(' ') || '—'}/>
                      </div>
                      <KeyVal label="Codice fiscale" value={ld.cf || '—'} mono/>
                    </>
                  )}
                  <div className="pt-3 border-t border-line2 space-y-3">
                    <KeyVal label="Termini di pagamento" value={termLabel}/>
                    <div className="grid grid-cols-2 gap-3.5">
                      <KeyVal label="Modalità" value={ld.adminData.pagamento || '—'}/>
                      {ld.adminData.banca && <KeyVal label="Banca" value={ld.adminData.banca}/>}
                    </div>
                    {ld.adminData.iban && <KeyVal label="IBAN" value={ld.adminData.iban} mono/>}
                  </div>
                </div>
              </Card>
            </div>
          </div>

          {/* Indirizzi e contatti (full width) */}
          {(ld.addresses.length > 0 || ld.phones.length > 1) && (
            <Card title="Indirizzi e contatti">
              <div className="grid grid-cols-2 gap-6">
                <div>
                  <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium mb-3">Indirizzi</div>
                  <div className="space-y-3">
                    {ld.addresses.map(addr => (
                      <div key={addr.id} className="flex items-start gap-3">
                        <Pill tone={addr.principale ? 'accent' : 'neutral'}>{addr.label}</Pill>
                        <div className="text-[13.5px] text-ink leading-snug">
                          {[addr.via, addr.cap && addr.citta ? `${addr.cap} ${addr.citta}` : addr.citta, addr.provincia && `(${addr.provincia})`, addr.nazione !== 'IT' ? addr.nazione : null].filter(Boolean).join(', ')}
                        </div>
                      </div>
                    ))}
                    {ld.addresses.length === 0 && <span className="text-muted text-[13.5px]">{c.fiscal?.address || '—'}</span>}
                  </div>
                </div>
                <div>
                  <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium mb-3">Telefoni</div>
                  <div className="space-y-2">
                    {ld.phones.map(ph => (
                      <div key={ph.id} className="flex items-center gap-2">
                        <Pill tone="neutral">{ph.label}</Pill>
                        <span className="num text-[13.5px] text-ink">{ph.numero}</span>
                        {ph.principale && <Pill tone="accent">Principale</Pill>}
                      </div>
                    ))}
                    {ld.phones.length === 0 && <span className="text-muted text-[13.5px]">{c.phone || '—'}</span>}
                  </div>
                </div>
              </div>
            </Card>
          )}
        </div>
      )}
    </>
  );
};

// ══════════════════════════════════════════════════════════════════════
//  SupplierDetail
// ══════════════════════════════════════════════════════════════════════
const SupplierDetail = ({ supplierId, onBack }) => {
  const s = SUPPLIERS.find(x => x.id === supplierId);
  if (!s) return null;

  const [editing, setEditing] = useStateA(false);
  const [ld, setLd] = useStateA(() => _anaSupplierEdits[supplierId] || buildLocalData(s));

  const setF = (key, val) => setLd(prev => ({ ...prev, [key]: val }));

  const terms     = window.__BI_TERMINI__ || PAYMENT_TERMS;
  const termLabel = ld.paymentTermId ? (terms.find(t => t.id === ld.paymentTermId)?.desc || '—') : '—';
  const primaryPhone = ld.phones.find(p => p.principale)?.numero || s.phone || '—';

  const handleSave = () => {
    _anaSupplierEdits[supplierId] = { ...ld };
    if (window.__API__) window.__API__.mutate('/api/suppliers', { supplier: { ...s, ...ld } }).then(()=>{ if (window.__toast) window.__toast('Fornitore salvato', 'success'); }).catch(()=>{});
    setEditing(false);
  };
  const handleCancel = () => {
    setLd(_anaSupplierEdits[supplierId] || buildLocalData(s));
    setEditing(false);
  };

  return (
    <>
      <Topbar
        eyebrow={
          <span className="flex items-center gap-1.5">
            <button onClick={onBack} className="text-ink hover:underline">Anagrafiche</button>
            <I.ArrowR size={11} className="opacity-60"/>
            <span>Fornitori</span>
          </span>
        }
        title={ld.ragioneSociale || s.name}
        right={<>
          <Btn variant="outline" size="md" onClick={onBack}
            leading={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>}>
            Torna all'elenco
          </Btn>
          {!editing && <Btn variant="outline" size="md" leading={<I.Edit size={16}/>} onClick={() => setEditing(true)}>Modifica</Btn>}
          <Btn variant="ink" size="md" leading={<I.Receipt size={16}/>}
            onClick={() => { if (window.__nav) window.__nav('acquisti'); else if (window.__toast) window.__toast('Apri Acquisti', 'info'); }}>Nuovo ordine</Btn>
        </>}
      />

      {editing ? (
        <AnaEditForm
          ld={ld}
          isSupplier={true}
          onFieldChange={setF}
          onSave={handleSave}
          onCancel={handleCancel}
        />
      ) : (
        <div className="px-7 py-6 space-y-6 max-w-[1400px]">
          {/* Hero */}
          <Card>
            <div className="flex items-start gap-5">
              <div className="w-16 h-16 rounded-xl bg-line2 text-muted flex items-center justify-center shrink-0">
                <I.Truck size={28}/>
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-3 mb-1 flex-wrap">
                  <h2 className="text-[24px] font-semibold tracking-tight text-ink">{ld.ragioneSociale || s.name}</h2>
                  <Pill tone="info">{s.cat}</Pill>
                </div>
                <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[13.5px] text-muted">
                  <span className="num">{s.id}</span>
                  <span>·</span>
                  <span className="num">{ld.piva || s.vat}</span>
                  <span>·</span>
                  <span>{ld.email || s.email}</span>
                  <span>·</span>
                  <span className="num">{primaryPhone}</span>
                </div>
                <div className="mt-2 text-[12.5px] text-muted">
                  Referente: <span className="text-ink font-medium">{s.contact}</span>
                  <span className="mx-3">·</span>
                  Ultimo ordine: <span className="text-ink font-medium">{s.lastOrder}</span>
                </div>
              </div>
              {s.open > 0 && (
                <div className="text-right shrink-0">
                  <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium">Ordine aperto</div>
                  <div className="num text-[28px] font-semibold text-warn leading-none mt-1">{fmtEur(s.open)}</div>
                </div>
              )}
            </div>
          </Card>

          {/* Grid: fiscal | admin */}
          <div className="grid grid-cols-2 gap-6">
            {/* Dati fiscali */}
            <Card title="Dati fiscali">
              <div className="space-y-3.5">
                <KeyVal label="Ragione sociale" value={ld.ragioneSociale || s.name}/>
                <div className="grid grid-cols-2 gap-3.5">
                  <KeyVal label="P.IVA" value={ld.piva || s.vat || '—'} mono/>
                  <KeyVal label="Cod. fiscale" value={ld.cf || '—'} mono/>
                </div>
                {ld.sdi && <KeyVal label="Codice SDI" value={ld.sdi} mono/>}
                <div className="pt-3 border-t border-line2 space-y-3">
                  <KeyVal label="Termini di pagamento" value={termLabel}/>
                  <div className="grid grid-cols-2 gap-3.5">
                    <KeyVal label="Modalità" value={ld.adminData.pagamento || '—'}/>
                    {ld.adminData.banca && <KeyVal label="Banca" value={ld.adminData.banca}/>}
                  </div>
                  {ld.adminData.iban && <KeyVal label="IBAN" value={ld.adminData.iban} mono/>}
                </div>
              </div>
            </Card>

            {/* Indirizzi e contatti */}
            <Card title="Indirizzi e contatti">
              <div className="space-y-5">
                {ld.addresses.length > 0 ? (
                  <div>
                    <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium mb-3">Indirizzi</div>
                    <div className="space-y-3">
                      {ld.addresses.map(addr => (
                        <div key={addr.id} className="flex items-start gap-3">
                          <Pill tone={addr.principale ? 'accent' : 'neutral'}>{addr.label}</Pill>
                          <div className="text-[13.5px] text-ink leading-snug">
                            {[addr.via, addr.cap && addr.citta ? `${addr.cap} ${addr.citta}` : addr.citta, addr.provincia && `(${addr.provincia})`, addr.nazione !== 'IT' ? addr.nazione : null].filter(Boolean).join(', ')}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                ) : (
                  <KeyVal label="Sede" value={s.city || '—'}/>
                )}
                <div>
                  <div className="text-[11px] uppercase tracking-[0.08em] text-muted font-medium mb-3">Telefoni</div>
                  <div className="space-y-2">
                    {ld.phones.length > 0
                      ? ld.phones.map(ph => (
                        <div key={ph.id} className="flex items-center gap-2">
                          <Pill tone="neutral">{ph.label}</Pill>
                          <span className="num text-[13.5px] text-ink">{ph.numero}</span>
                          {ph.principale && <Pill tone="accent">Principale</Pill>}
                        </div>
                      ))
                      : <span className="text-muted text-[13.5px]">{s.phone || '—'}</span>
                    }
                  </div>
                </div>
              </div>
            </Card>
          </div>
        </div>
      )}
    </>
  );
};

// ══════════════════════════════════════════════════════════════════════
//  AnagraficheView — wrapper con routing interno fornitore
// ══════════════════════════════════════════════════════════════════════
// Creazione anagrafica da zero (cliente o fornitore): riusa il form vuoto.
const AnaCreate = ({ isSupplier, onDone }) => {
  const [ld, setLd] = useStateA(() => buildLocalData({}));
  const setF = (key, val) => setLd(prev => ({ ...prev, [key]: val }));
  const nameOf = (d) => isSupplier
    ? (d.ragioneSociale || '').trim()
    : (d.personType === 'azienda' ? (d.ragioneSociale || '').trim() : [d.firstName, d.lastName].filter(Boolean).join(' ').trim());
  const save = () => {
    const name = nameOf(ld);
    if (!name) { if (window.__toast) window.__toast(isSupplier ? 'Inserisci la ragione sociale' : 'Inserisci nome o ragione sociale', 'error'); return; }
    const endpoint = isSupplier ? '/api/suppliers' : '/api/customers';
    const phone = (ld.phones && ld.phones[0] && ld.phones[0].numero) || '';
    const addr0 = (ld.addresses && ld.addresses[0]) || {};
    const payload = isSupplier
      ? { supplier: { ...ld, name, phone, category: '—', orders: 0, lastOrder: '—', openValue: 0 } }
      : { customer: {
          ...ld, name, phone,
          kind: ld.personType === 'azienda' ? 'Azienda' : 'Privato',
          tier: 'Standard', tags: [], points: 0, spent: 0, orders: 0, avgTicket: 0,
          lastVisit: '—', since: new Date().getFullYear().toString(), history: [],
          city: addr0.citta || '', country: addr0.nazione || 'IT',
        } };
    if (window.__API__) {
      window.__API__.mutate(endpoint, payload)
        .then(() => { if (window.__toast) window.__toast(isSupplier ? 'Fornitore creato' : 'Cliente creato', 'success'); onDone(); })
        .catch(() => {});
    } else onDone();
  };
  return (
    <>
      <Topbar
        eyebrow="Anagrafiche"
        title={isSupplier ? 'Nuovo fornitore' : 'Nuovo cliente'}
        right={<Btn variant="outline" size="md" onClick={onDone}
          leading={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M15 6l-6 6 6 6"/></svg>}>
          Torna all'elenco</Btn>}
      />
      <AnaEditForm ld={ld} isSupplier={isSupplier} onFieldChange={setF} onSave={save} onCancel={onDone}/>
    </>
  );
};

const AnagraficheView = ({ customerId, onOpenCustomer, onBack, role }) => {
  const [supplierId, setSupplierId] = useStateA(null);
  const [creating, setCreating] = useStateA(null); // 'customer' | 'supplier' | null

  if (customerId) return <CustomerDetail customerId={customerId} onBack={onBack}/>;
  if (supplierId) return <SupplierDetail supplierId={supplierId} onBack={() => setSupplierId(null)}/>;
  if (creating) return <AnaCreate isSupplier={creating === 'supplier'} onDone={() => setCreating(null)}/>;
  return <AnagraficheList onOpenCustomer={onOpenCustomer} onOpenSupplier={setSupplierId} role={role}
    onNew={(tab) => setCreating(tab === 'clienti' ? 'customer' : 'supplier')}/>;
};

Object.assign(window, { AnagraficheView, TierPill, Initials });
