// --- Clienti — versione funzionale cablata all'API -----------------------

function ClientiScreen({ onOpen, openId, onBack }) {
  const [q, setQ] = useState('');
  const [filter, setFilter] = useState('all');
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState(null);
  const [clients, setClients] = useState([]);
  const [loading, setLoading] = useState(true);

  const load = () => {
    setLoading(true);
    (window.LibroAPI?.clients?.() || Promise.resolve([]))
      .then((list) => { setClients(list); setLoading(false); })
      .catch(() => setLoading(false));
  };
  useEffect(load, []);

  if (openId) return <ClienteDettaglio id={openId} onBack={onBack} onEdit={(c) => { setEditing(c); setShowForm(true); }} onDeleted={() => { onBack(); load(); }} onClose={() => setShowForm(false)} showForm={showForm} editing={editing} onSaved={() => { setShowForm(false); load(); }} />;

  const rows = clients.filter((c) => {
    if (filter === 'b2b' && c.type !== 'B2B') return false;
    if (filter === 'b2c' && c.type !== 'B2C') return false;
    if (q && !(c.name || '').toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  const counts = {
    all: clients.length,
    b2b: clients.filter((c) => c.type === 'B2B').length,
    b2c: clients.filter((c) => c.type === 'B2C').length,
  };

  const totalRevenue = clients.reduce((s, c) => s + (c.revenue_ytd || 0), 0);
  const top = [...clients].sort((a, b) => (b.revenue_ytd || 0) - (a.revenue_ytd || 0))[0];
  const totInvoices = clients.reduce((s, c) => s + (c.invoices_count || 0), 0);
  const avgTicket = totInvoices ? totalRevenue / totInvoices : 0;

  return (
    <>
      <Topbar crumbs={['Gestionale', 'Amministrazione', 'Clienti']} />
      <div className="content">
        <div className="page-head">
          <div>
            <h1 className="page-title">Clienti <em>{counts.all}</em></h1>
            <div className="page-sub">Rubrica — B2B · B2C · privati</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-accent btn-lg" onClick={() => { setEditing(null); setShowForm(true); }}>
              <Icon name="user-plus" size={15} /> Nuovo cliente
            </button>
          </div>
        </div>

        <div className="kpi-strip">
          {[
            { label: 'Clienti attivi', value: counts.all,   ic: 'users',       meta: `${counts.b2b} B2B · ${counts.b2c} B2C`, nonEuro: true },
            { label: 'Fatturato YTD',  value: totalRevenue, ic: 'trending-up', meta: 'anno in corso' },
            { label: 'Top cliente',    value: top?.revenue_ytd || 0, ic: 'crown', meta: top?.name || '—' },
            { label: 'Ticket medio',   value: Math.round(avgTicket), ic: 'calculator', meta: `su ${totInvoices} fatture` },
          ].map((k, i) => {
            const { intp, cent } = fmtEURSplit(k.value || 0);
            return (
              <div key={i} className="kpi">
                <div className="kpi-label"><Icon name={k.ic} size={12} stroke={2} />{k.label}</div>
                <div className="kpi-value">
                  {!k.nonEuro && <span style={{ color: 'var(--ink-3)', fontSize: 18, marginRight: 2, fontWeight: 400 }}>€</span>}
                  {k.nonEuro ? k.value : <>{intp}<span className="cent">,{cent}</span></>}
                </div>
                <div className="kpi-meta"><span>{k.meta}</span></div>
              </div>
            );
          })}
        </div>

        <div className="tabs">
          {[
            { id: 'all', l: 'Tutti', c: counts.all },
            { id: 'b2b', l: 'B2B', c: counts.b2b },
            { id: 'b2c', l: 'B2C · Privati', c: counts.b2c },
          ].map((t) => (
            <div key={t.id} className={`tab ${filter === t.id ? 'active' : ''}`} onClick={() => setFilter(t.id)}>
              {t.l}<span className="c">{t.c}</span>
            </div>
          ))}
        </div>

        <div className="filter-row">
          <div className="search-wrap">
            <Icon name="search" size={14} />
            <input className="input" placeholder="Cerca cliente…" value={q} onChange={(e) => setQ(e.target.value)} />
          </div>
        </div>

        <div className="table-wrap">
          <table className="invoices">
            <thead>
              <tr>
                <th>Cliente</th>
                <th style={{ width: 90 }}>Tipo</th>
                <th style={{ width: 180 }}>P.IVA / CF</th>
                <th style={{ width: 90, textAlign: 'right' }}>Fatture</th>
                <th style={{ width: 140, textAlign: 'right' }}>Fatturato YTD</th>
                <th style={{ width: 120 }}>Ultima</th>
              </tr>
            </thead>
            <tbody>
              {loading && <tr><td colSpan={6} style={{ textAlign: 'center', padding: 40, color: 'var(--ink-3)' }}>Caricamento…</td></tr>}
              {!loading && rows.length === 0 && (
                <tr><td colSpan={6} style={{ textAlign: 'center', padding: 40, color: 'var(--ink-3)' }}>
                  <Icon name="users" size={20} style={{ margin: '0 auto 8px' }} />
                  <div>Nessun cliente ancora</div>
                  <div style={{ marginTop: 10 }}><button className="btn btn-accent" onClick={() => { setEditing(null); setShowForm(true); }}><Icon name="user-plus" size={13} /> Aggiungi il primo</button></div>
                </td></tr>
              )}
              {!loading && rows.map((c) => (
                <tr key={c.id} onClick={() => onOpen(c.id)} style={{ cursor: 'pointer' }}>
                  <td>
                    <div className="client-cell">
                      <div className="client-mark">{c.short}</div>
                      <div>
                        <div className="client-name">{c.name}</div>
                        <div className="client-sub">{c.email || c.telefono || '—'}</div>
                      </div>
                    </div>
                  </td>
                  <td><span className={`badge ${c.type === 'B2B' ? 'b-accent' : 'b-gray'}`}>{c.type}</span></td>
                  <td className="mono" style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{c.p_iva || c.codice_fiscale || '—'}</td>
                  <td className="amount mono">{c.invoices_count || 0}</td>
                  <td className="amount total mono">
                    <span className="euro">€</span>
                    {new Intl.NumberFormat('it-IT', { minimumFractionDigits: 2 }).format(c.revenue_ytd || 0)}
                  </td>
                  <td className="mono" style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{c.last_invoice ? fmtDate(c.last_invoice) : '—'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {showForm && (
        <ClienteForm
          initial={editing}
          onClose={() => setShowForm(false)}
          onSaved={() => { setShowForm(false); load(); }}
        />
      )}
    </>
  );
}

// --- Form nuovo/modifica cliente -----------------------------------------
function ClienteForm({ initial, onClose, onSaved }) {
  const [isPriv, setIsPriv] = useState(initial ? !!initial.is_privato : false);
  const [f, setF] = useState({
    ragione_sociale: '', nome: '', cognome: '', p_iva: '', codice_fiscale: '',
    codice_destinatario: '0000000', pec: '', email: '', telefono: '',
    indirizzo: '', cap: '', comune: '', provincia: '', nazione: 'IT', note: '',
    ...(initial || {}),
  });
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState('');
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });

  const submit = async (e) => {
    e.preventDefault();
    setSaving(true); setErr('');
    try {
      const payload = { ...f, is_privato: isPriv ? 1 : 0 };
      if (initial?.id) await window.LibroAPI.updateClient(initial.id, payload);
      else await window.LibroAPI.createClient(payload);
      onSaved();
    } catch (ex) { setErr(ex.message); }
    finally { setSaving(false); }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <form className="modal" onClick={(e) => e.stopPropagation()} onSubmit={submit} style={{ width: 560 }}>
        <div className="modal-head">
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{initial?.id ? 'Modifica' : 'Nuovo'} cliente</div>
            <h2 style={{ fontFamily: 'Fraunces', fontSize: 20, fontWeight: 500, margin: '4px 0 0' }}>{initial?.name || 'Anagrafica'}</h2>
          </div>
          <button type="button" className="btn btn-ic btn-ghost" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div className="modal-body" style={{ maxHeight: '70vh', overflowY: 'auto' }}>
          {err && <div className="err" style={{ marginBottom: 12 }}><Icon name="alert-circle" size={14} /> <span>{err}</span></div>}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 16 }}>
            <div onClick={() => setIsPriv(false)} style={{ padding: '10px 12px', border: `1px solid ${!isPriv ? 'var(--accent)' : 'var(--rule)'}`, background: !isPriv ? 'var(--accent-wash)' : '#fff', borderRadius: 8, cursor: 'pointer' }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>🏢 B2B</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Azienda / professionista</div>
            </div>
            <div onClick={() => setIsPriv(true)} style={{ padding: '10px 12px', border: `1px solid ${isPriv ? 'var(--accent)' : 'var(--rule)'}`, background: isPriv ? 'var(--accent-wash)' : '#fff', borderRadius: 8, cursor: 'pointer' }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>👤 B2C</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Privato senza P.IVA</div>
            </div>
          </div>

          {!isPriv ? (
            <div className="field"><label className="label">Ragione sociale *</label><input className="input" value={f.ragione_sociale || ''} onChange={set('ragione_sociale')} required /></div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <div className="field"><label className="label">Nome *</label><input className="input" value={f.nome || ''} onChange={set('nome')} required /></div>
              <div className="field"><label className="label">Cognome *</label><input className="input" value={f.cognome || ''} onChange={set('cognome')} required /></div>
            </div>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <div className="field"><label className="label">P.IVA</label><input className="input" value={f.p_iva || ''} onChange={set('p_iva')} maxLength={11} /></div>
            <div className="field"><label className="label">Codice Fiscale</label><input className="input" value={f.codice_fiscale || ''} onChange={set('codice_fiscale')} /></div>
          </div>

          {!isPriv && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <div className="field"><label className="label">Codice SDI</label><input className="input" value={f.codice_destinatario || ''} onChange={set('codice_destinatario')} maxLength={7} placeholder="0000000" /></div>
              <div className="field"><label className="label">PEC</label><input className="input" value={f.pec || ''} onChange={set('pec')} type="email" /></div>
            </div>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <div className="field"><label className="label">Email</label><input className="input" value={f.email || ''} onChange={set('email')} type="email" /></div>
            <div className="field"><label className="label">Telefono</label><input className="input" value={f.telefono || ''} onChange={set('telefono')} /></div>
          </div>

          <div className="field"><label className="label">Indirizzo</label><input className="input" value={f.indirizzo || ''} onChange={set('indirizzo')} /></div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr 1fr', gap: 10 }}>
            <div className="field"><label className="label">CAP</label><input className="input" value={f.cap || ''} onChange={set('cap')} maxLength={5} /></div>
            <div className="field"><label className="label">Comune</label><input className="input" value={f.comune || ''} onChange={set('comune')} /></div>
            <div className="field"><label className="label">Prov.</label><input className="input" value={f.provincia || ''} onChange={set('provincia')} maxLength={2} /></div>
          </div>

          <div className="field"><label className="label">Note</label><textarea className="textarea" rows={3} value={f.note || ''} onChange={set('note')} /></div>
        </div>
        <div className="modal-foot">
          <button type="button" className="btn btn-ghost" onClick={onClose}>Annulla</button>
          <div style={{ flex: 1 }} />
          <button className="btn btn-accent" type="submit" disabled={saving}>{saving ? 'Salvataggio…' : (initial?.id ? 'Salva modifiche' : 'Crea cliente')}</button>
        </div>
      </form>
    </div>
  );
}

// --- Dettaglio cliente ----------------------------------------------------
function ClienteDettaglio({ id, onBack, onEdit, onDeleted, showForm, editing, onClose, onSaved }) {
  const [c, setC] = useState(null);
  const [err, setErr] = useState('');
  const [invoices, setInvoices] = useState([]);
  const [cStats, setCStats] = useState(null);
  useEffect(() => {
    (window.LibroAPI?.client?.(id) || Promise.reject(new Error('No API')))
      .then(setC).catch((e) => setErr(e.message));
    fetch(`/api/clients/${id}/invoices`, { credentials: 'include' }).then(r => r.json()).then(setInvoices).catch(() => {});
    fetch(`/api/clients/${id}/stats`, { credentials: 'include' }).then(r => r.json()).then(setCStats).catch(() => {});
  }, [id]);

  const destroy = async () => {
    if (!confirm('Eliminare questo cliente?')) return;
    try {
      await window.LibroAPI.deleteClient(id);
      onDeleted();
    } catch (e) { alert(e.message); }
  };

  if (err) return <div className="content"><div className="err">{err}</div><button className="btn btn-ghost" onClick={onBack}>← Indietro</button></div>;
  if (!c) return <div className="content" style={{ color: 'var(--ink-3)' }}>Caricamento…</div>;

  return (
    <>
      <Topbar crumbs={['Gestionale', 'Clienti', c.name]} />
      <div className="content">
        <div className="page-head">
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <button className="btn btn-ghost btn-ic" onClick={onBack}><Icon name="arrow-left" size={14} /></button>
            <div>
              <h1 className="page-title">{c.name}</h1>
              <div className="page-sub">{c.type} · {c.p_iva || c.codice_fiscale || '—'}</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-ghost" onClick={() => onEdit(c)}><Icon name="pencil" size={13} /> Modifica</button>
            <button className="btn btn-ghost" onClick={destroy}><Icon name="trash-2" size={13} /> Elimina</button>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <div className="card" style={{ background: '#fff', padding: 18, borderRadius: 10, border: '1px solid var(--rule)' }}>
            <div style={{ fontSize: 11, fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-3)', marginBottom: 10 }}>Anagrafica</div>
            <dl style={{ display: 'grid', gridTemplateColumns: '140px 1fr', rowGap: 8, fontSize: 13 }}>
              <dt style={{ color: 'var(--ink-3)' }}>P.IVA</dt><dd className="mono">{c.p_iva || '—'}</dd>
              <dt style={{ color: 'var(--ink-3)' }}>Cod. fiscale</dt><dd className="mono">{c.codice_fiscale || '—'}</dd>
              <dt style={{ color: 'var(--ink-3)' }}>SDI</dt><dd className="mono">{c.codice_destinatario || '—'}</dd>
              <dt style={{ color: 'var(--ink-3)' }}>PEC</dt><dd className="mono">{c.pec || '—'}</dd>
              <dt style={{ color: 'var(--ink-3)' }}>Email</dt><dd>{c.email || '—'}</dd>
              <dt style={{ color: 'var(--ink-3)' }}>Telefono</dt><dd>{c.telefono || '—'}</dd>
              <dt style={{ color: 'var(--ink-3)' }}>Indirizzo</dt><dd>{[c.indirizzo, c.cap, c.comune, c.provincia].filter(Boolean).join(', ') || '—'}</dd>
            </dl>
          </div>

          <div className="card" style={{ background: '#fff', padding: 18, borderRadius: 10, border: '1px solid var(--rule)' }}>
            <div style={{ fontSize: 11, fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-3)', marginBottom: 10 }}>Statistiche</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div>
                <div style={{ fontSize: 22, fontFamily: 'Fraunces', fontWeight: 500 }}>{c.invoices_count || 0}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Fatture emesse</div>
              </div>
              <div>
                <div style={{ fontSize: 22, fontFamily: 'Fraunces', fontWeight: 500 }}>€ {new Intl.NumberFormat('it-IT', { minimumFractionDigits: 2 }).format(c.revenue_ytd || 0)}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Fatturato YTD</div>
              </div>
            </div>
            {c.note && (
              <div style={{ marginTop: 18, padding: 12, background: 'var(--paper-2)', borderRadius: 6, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.55 }}>
                <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--ink-3)', marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Note</div>
                {c.note}
              </div>
            )}
          </div>
        </div>

        {/* Storico fatture */}
        <div className="card" style={{ background: '#fff', padding: 18, borderRadius: 10, border: '1px solid var(--rule)', marginTop: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
            <div style={{ fontSize: 11, fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-3)' }}>
              Fatture ({invoices.length})
            </div>
            {cStats && cStats.total > 0 && (
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
                Fatturato <span className="mono" style={{ color: 'var(--ink)' }}>€ {new Intl.NumberFormat('it-IT', { minimumFractionDigits: 2 }).format(cStats.fatturato_totale || 0)}</span>
                {' · '}Incassato <span className="mono" style={{ color: 'var(--green)' }}>€ {new Intl.NumberFormat('it-IT', { minimumFractionDigits: 2 }).format(cStats.incassato || 0)}</span>
                {cStats.da_incassare > 0 && <>{' · '}Da incassare <span className="mono" style={{ color: 'var(--amber)' }}>€ {new Intl.NumberFormat('it-IT', { minimumFractionDigits: 2 }).format(cStats.da_incassare)}</span></>}
              </div>
            )}
          </div>
          {invoices.length === 0 ? (
            <div style={{ padding: 30, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>Nessuna fattura per questo cliente</div>
          ) : (
            <table className="invoices">
              <thead>
                <tr>
                  <th>Numero</th>
                  <th style={{ width: 120 }}>Data</th>
                  <th style={{ width: 120 }}>Scadenza</th>
                  <th style={{ width: 90 }}>Tipo</th>
                  <th style={{ width: 140, textAlign: 'right' }}>Totale</th>
                  <th style={{ width: 110 }}>Stato</th>
                </tr>
              </thead>
              <tbody>
                {invoices.map((inv) => (
                  <tr key={inv.id} onClick={() => { location.hash = '#invoices/' + inv.id; }} style={{ cursor: 'pointer' }}>
                    <td className="mono">{inv.numero_completo}</td>
                    <td className="mono" style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{inv.data_emissione && fmtDate(inv.data_emissione)}</td>
                    <td className="mono" style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{inv.data_scadenza ? fmtDate(inv.data_scadenza) : '—'}</td>
                    <td><span className="type-chip">{({ fattura_sdi: 'Fattura', nota_credito: 'Nota cr.', ricevuta_privata: 'Ricevuta', proforma: 'Proforma' })[inv.doc_type] || inv.doc_type}</span></td>
                    <td className="amount total mono"><span className="euro">€</span>{new Intl.NumberFormat('it-IT', { minimumFractionDigits: 2 }).format(inv.totale_documento || 0)}</td>
                    <td>{(() => {
                      const st = STATUSES[inv.status === 'inviata_sdi' ? 'inviata' : inv.status] || STATUSES.bozza;
                      return <span className={`badge ${st.cls}`}><span className="badge-dot" style={{ background: st.dot }} />{st.label}</span>;
                    })()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
      {showForm && <ClienteForm initial={editing} onClose={onClose} onSaved={onSaved} />}
    </>
  );
}

window.ClientiScreen = ClientiScreen;
