// --- Fattura: Wizard + Editor completamente cablati all'API -----------
const PAYMENT_METHODS = [
  { id: 'bonifico', label: 'Bonifico bancario', code: 'MP05' },
  { id: 'stripe',   label: 'Carta via Stripe',   code: 'MP08' },
  { id: 'paypal',   label: 'PayPal',             code: 'MP08' },
  { id: 'contanti', label: 'Contanti',           code: 'MP01' },
  { id: 'assegno',  label: 'Assegno',            code: 'MP02' },
  { id: 'rid',      label: 'Addebito SEPA',      code: 'MP10' },
];
const UNITS = ['pz', 'ore', 'gg', 'h', 'mese', 'forfait', 'km', 'kg', 'lt'];
const DOC_TYPES_API = { fattura: 'fattura_sdi', ricevuta: 'ricevuta_privata', 'nota-credito': 'nota_credito', proforma: 'proforma' };

function fmtEur(n) {
  return new Intl.NumberFormat('it-IT', { style: 'currency', currency: 'EUR', minimumFractionDigits: 2 }).format(Number(n) || 0);
}
function addDaysISO(iso, d) { const dt = new Date(iso); dt.setDate(dt.getDate() + d); return dt.toISOString().slice(0, 10); }

// --- Wizard nuova fattura (cablato) --------------------------------------
function WizardNuovaFattura({ onClose, onCreate }) {
  const [q, setQ] = useState('');
  const [pickId, setPickId] = useState(null);
  const [docType, setDocType] = useState('fattura');
  const [fromProjectMode, setFromProjectMode] = useState(false);
  const [projectId, setProjectId] = useState(null);
  const [clients, setClients] = useState([]);
  const [projects, setProjects] = useState([]);
  const [submitting, setSubmitting] = useState(false);
  const [err, setErr] = useState('');

  useEffect(() => {
    window.LibroAPI.clients().then(setClients).catch(() => {});
    fetch('/api/projects', { credentials: 'include' }).then(r => r.json()).then(setProjects).catch(() => {});
  }, []);

  const filtered = clients.filter(c => !q || (c.name || '').toLowerCase().includes(q.toLowerCase()));
  const canProceed = !submitting && ((fromProjectMode && projectId) || pickId !== null);

  const create = async () => {
    setSubmitting(true); setErr('');
    try {
      let inv;
      if (fromProjectMode && projectId) {
        inv = await window.LibroAPI._fromProject(projectId, { doc_type: DOC_TYPES_API[docType], client_id: pickId });
      } else {
        inv = await window.LibroAPI.createInvoice({
          doc_type: DOC_TYPES_API[docType], client_id: pickId,
          data_emissione: new Date().toISOString().slice(0, 10), items: [], status: 'bozza',
        });
      }
      onCreate({ id: inv.id, num: inv.numero_completo, clientId: pickId, docType });
    } catch (e) { setErr(e.message); }
    finally { setSubmitting(false); }
  };

  const docTypes = [
    { id: 'fattura',     label: 'Fattura elettronica', sub: 'Invio a SDI' },
    { id: 'proforma',    label: 'Proforma',            sub: 'Non ha valore fiscale' },
    { id: 'ricevuta',    label: 'Ricevuta',            sub: 'Per privati/occasionali' },
    { id: 'nota-credito',label: 'Nota di credito',     sub: 'Storno fattura emessa' },
  ];

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 560, maxHeight: '86vh', display: 'flex', flexDirection: 'column' }}>
        <div className="modal-head" style={{ padding: '18px 24px', borderBottom: '1px solid var(--rule-2)' }}>
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>Nuovo documento</div>
            <h2 style={{ fontFamily: 'Fraunces', fontSize: 22, fontWeight: 500, margin: 0, letterSpacing: '-0.02em' }}>Inizia una fattura</h2>
          </div>
          <button className="btn btn-ic btn-ghost" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div className="modal-body" style={{ padding: '20px 24px', flex: 1, overflowY: 'auto' }}>
          {err && <div className="err" style={{ marginBottom: 12 }}><Icon name="alert-circle" size={14} /> {err}</div>}

          <div className="label" style={{ marginBottom: 8 }}>Tipo documento</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 18 }}>
            {docTypes.map(t => (
              <div key={t.id} onClick={() => setDocType(t.id)} style={{
                padding: '10px 12px',
                border: '1px solid ' + (docType === t.id ? 'var(--accent)' : 'var(--rule)'),
                background: docType === t.id ? 'var(--accent-wash)' : '#fff',
                borderRadius: 8, cursor: 'pointer',
              }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{t.label}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{t.sub}</div>
              </div>
            ))}
          </div>

          <div className="label" style={{ marginBottom: 8, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span>Sorgente righe</span>
            <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, textTransform: 'none', cursor: 'pointer' }}>
              <input type="checkbox" checked={fromProjectMode} onChange={(e) => setFromProjectMode(e.target.checked)} />
              Da progetto (ore tracciate)
            </label>
          </div>
          {fromProjectMode && (
            <select className="input" style={{ marginBottom: 14 }} value={projectId || ''} onChange={(e) => setProjectId(Number(e.target.value) || null)}>
              <option value="">— seleziona progetto —</option>
              {projects.map(p => <option key={p.id} value={p.id}>{p.name}{p.hourly_rate ? ` (€${p.hourly_rate}/h)` : ' (no tariffa)'}</option>)}
            </select>
          )}

          <div className="label" style={{ marginBottom: 8 }}>Cliente</div>
          <div style={{ position: 'relative', marginBottom: 10 }}>
            <Icon name="search" size={14} style={{ position: 'absolute', left: 10, top: 10, color: 'var(--ink-3)' }} />
            <input className="input" placeholder="Cerca cliente o P.IVA…" value={q} onChange={e => setQ(e.target.value)} style={{ paddingLeft: 32 }} autoFocus />
          </div>
          <div style={{ maxHeight: 220, overflowY: 'auto', border: '1px solid var(--rule)', borderRadius: 8 }}>
            {filtered.map(c => (
              <div key={c.id} onClick={() => setPickId(c.id)} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
                borderBottom: '1px solid var(--rule-2)',
                background: pickId === c.id ? 'var(--accent-wash)' : 'transparent',
                cursor: 'pointer',
              }}>
                <div className="client-mark" style={{ width: 28, height: 28, fontSize: 11 }}>{c.short}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{c.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{c.type} {c.p_iva && `· ${c.p_iva}`}</div>
                </div>
                {pickId === c.id && <Icon name="check" size={14} stroke={2.5} style={{ color: 'var(--accent)' }} />}
              </div>
            ))}
            {filtered.length === 0 && (
              <div style={{ padding: 20, textAlign: 'center', color: 'var(--ink-3)', fontSize: 12.5 }}>Nessun cliente trovato</div>
            )}
          </div>
        </div>
        <div className="modal-foot" style={{ padding: '14px 24px', borderTop: '1px solid var(--rule-2)' }}>
          <button className="btn btn-ghost" onClick={onClose}>Annulla</button>
          <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>Tutto modificabile dopo</div>
          <button className="btn btn-accent" disabled={!canProceed} onClick={create}>
            {submitting ? 'Creazione…' : <>Apri editor <Icon name="arrow-right" size={13} /></>}
          </button>
        </div>
      </div>
    </div>
  );
}

// Extension API per "Da progetto"
if (window.LibroAPI) {
  window.LibroAPI._fromProject = (projectId, payload) =>
    fetch(`/api/invoices/from-project/${projectId}`, {
      method: 'POST', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    }).then(async (r) => {
      const j = await r.json();
      if (!r.ok) throw new Error(j.error || 'HTTP ' + r.status);
      return j;
    });
}

// --- Editor fattura cablato all'API --------------------------------------
function FatturaScreen({ invoiceNum, invoiceId, mode, onBack, initialClient, docType: initialDocType }) {
  const [inv, setInv] = useState(null);
  const [items, setItems] = useState([]);
  const [client, setClient] = useState(null);
  const [events, setEvents] = useState([]);
  const [payments, setPayments] = useState([]);
  const [paySummary, setPaySummary] = useState(null);
  const [showPayForm, setShowPayForm] = useState(false);
  const [saving, setSaving] = useState(false);
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState('');
  const [err, setErr] = useState('');

  const id = invoiceId || inv?.id;

  const loadPayments = async () => {
    if (!id) return;
    try {
      const data = await window.LibroAPI.payments(id);
      setPayments(data.payments || []);
      setPaySummary(data.summary || null);
    } catch {}
  };

  const load = async () => {
    try {
      const full = await window.LibroAPI.invoice(id);
      setInv(full);
      setItems(full.items || []);
      setClient(full.client || null);
      fetch(`/api/invoices/${id}/sdi-events`, { credentials: 'include' }).then(r => r.json()).then(setEvents).catch(() => {});
      loadPayments();
    } catch (e) { setErr(e.message); }
  };
  useEffect(() => { if (id) load(); }, [id]);

  if (!inv) return (
    <><Topbar crumbs={['Gestionale', 'Fatture', invoiceNum || '...']} />
    <div className="content" style={{ color: 'var(--ink-3)' }}>{err || 'Caricamento…'}</div></>);

  const readOnly = inv.status !== 'bozza';

  // Calcoli live
  const rowTotal = (r) => {
    const base = (Number(r.quantita) || 0) * (Number(r.prezzo_unitario) || 0);
    const imp = Math.round(base * (1 - (Number(r.sconto_pct) || 0) / 100) * 100) / 100;
    const iva = Math.round(imp * (Number(r.aliquota_iva) || 0) / 100 * 100) / 100;
    return { imponibile: imp, iva, totale: Math.round((imp + iva) * 100) / 100 };
  };
  const totImp = Math.round(items.reduce((s, r) => s + rowTotal(r).imponibile, 0) * 100) / 100;
  const totIva = Math.round(items.reduce((s, r) => s + rowTotal(r).iva, 0) * 100) / 100;
  const bollo = inv.bollo_euro || 0;
  // Se una riga rappresenta già il bollo (descrizione contiene "bollo"), non sommarlo di nuovo
  const bolloInRighe = items.some((r) => /bollo/i.test(r.descrizione || ''));
  const bolloAggiuntivo = bolloInRighe ? 0 : bollo;
  const totDocComputed = Math.round((totImp + totIva + bolloAggiuntivo) * 100) / 100;
  // Per fatture già emesse usa il totale canonico salvato in DB, altrimenti calcola dal vivo
  const totDoc = (inv.status !== 'bozza' && inv.totale_documento != null)
    ? inv.totale_documento
    : totDocComputed;

  const updateRow = (i, patch) => setItems(items.map((r, j) => j === i ? { ...r, ...patch } : r));
  const addRow = () => setItems([...items, { descrizione: '', unita_misura: 'ore', quantita: 1, prezzo_unitario: 0, sconto_pct: 0, aliquota_iva: inv.doc_type === 'ricevuta_privata' ? 0 : 22, natura_iva: null }]);
  const removeRow = (i) => setItems(items.filter((_, j) => j !== i));

  const save = async () => {
    setSaving(true); setErr('');
    try {
      const payload = {
        data_emissione: inv.data_emissione, data_scadenza: inv.data_scadenza,
        metodo_pagamento: inv.metodo_pagamento, causale: inv.causale, note: inv.note,
        items: items.map((r) => ({ ...r, ...rowTotal(r) })),
      };
      const updated = await window.LibroAPI.updateInvoice(id, payload);
      setInv(updated); setItems(updated.items || []);
      setMsg('✓ Salvato'); setTimeout(() => setMsg(''), 1500);
    } catch (e) { setErr(e.message); }
    finally { setSaving(false); }
  };

  const issue = async () => {
    if (!confirm('Emettere la fattura? Dopo non sarà più modificabile.')) return;
    setBusy(true);
    try { await save(); await window.LibroAPI.issueInvoice(id); await load(); setMsg('✓ Emessa'); }
    catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  const sendSDI = async () => {
    if (!confirm('Inviare a SDI via PEC?')) return;
    setBusy(true);
    try { const r = await window.LibroAPI.sendSDI(id); setMsg(`✓ Inviata: ${r.filename}`); await load(); }
    catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  const markPaid = () => setShowPayForm(true);

  const cancel = async () => {
    const motivo = prompt('Motivo annullamento (opzionale):');
    if (motivo === null) return;
    setBusy(true);
    try { await window.LibroAPI.cancelInvoice(id, motivo); await load(); setMsg('✓ Annullata'); }
    catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  const typeLabel = { fattura_sdi: 'Fattura elettronica', nota_credito: 'Nota di credito', ricevuta_privata: 'Ricevuta', proforma: 'Proforma' }[inv.doc_type] || 'Documento';

  return (
    <>
      <Topbar crumbs={['Gestionale', 'Fatture', inv.numero_completo]} />
      <div className="content" style={{ maxWidth: 1280 }}>

        {/* Action bar */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18, padding: '10px 14px', background: '#fff', border: '1px solid var(--rule)', borderRadius: 10, flexWrap: 'wrap' }}>
          <button className="btn btn-ghost" onClick={onBack}><Icon name="arrow-left" size={14} /> Fatture</button>
          <div style={{ height: 20, width: 1, background: 'var(--rule)' }} />
          <span className="badge" style={{ textTransform: 'uppercase', fontSize: 10 }}>{STATUSES[inv.status === 'inviata_sdi' ? 'inviata' : inv.status]?.label || inv.status}</span>
          <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>{typeLabel} · {inv.numero_completo}</span>
          <div style={{ flex: 1 }} />
          {err && <span style={{ fontSize: 12, color: 'var(--red)' }}>{err}</span>}
          {msg && <span style={{ fontSize: 12, color: 'var(--green)' }}>{msg}</span>}
          {!readOnly && <button className="btn btn-ghost" onClick={save} disabled={saving}><Icon name="save" size={13} /> {saving ? 'Salvo…' : 'Salva'}</button>}
          <button className="btn btn-ghost" onClick={() => window.LibroAPI.downloadXML(id)} disabled={inv.doc_type === 'ricevuta_privata' || inv.doc_type === 'proforma'}><Icon name="file-code-2" size={13} /> XML</button>
          <a className="btn btn-ghost" href={`/api/invoices/${id}/pdf`} target="_blank"><Icon name="file-down" size={13} /> PDF</a>
          {!readOnly && <button className="btn btn-accent" onClick={issue} disabled={busy || items.length === 0}><Icon name="check-circle-2" size={13} /> Emetti</button>}
          {(inv.status === 'emessa' || inv.status === 'inviata_sdi') && (inv.doc_type === 'fattura_sdi' || inv.doc_type === 'nota_credito') && (
            <button className="btn btn-accent" onClick={sendSDI} disabled={busy}><Icon name="send" size={13} /> Invia SDI</button>
          )}
          {(inv.status === 'emessa' || inv.status === 'inviata_sdi' || inv.status === 'scaduta') && (
            <button className="btn btn-ghost" onClick={markPaid} disabled={busy}><Icon name="banknote" size={13} /> Pagata</button>
          )}
          {inv.status !== 'pagata' && inv.status !== 'annullata' && inv.status !== 'bozza' && (
            <button className="btn btn-ghost" onClick={cancel} disabled={busy} style={{ color: 'var(--red)' }}><Icon name="ban" size={13} /> Annulla</button>
          )}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 24 }} className="fattura-layout">
          {/* Colonna sinistra: dati principali + righe */}
          <div>
            {/* Cliente + date */}
            <div className="card" style={{ background: '#fff', border: '1px solid var(--rule)', borderRadius: 10, padding: 16, marginBottom: 16 }}>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>Cliente</div>
              {client ? (
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div className="client-mark">{client.short}</div>
                  <div><div style={{ fontWeight: 500 }}>{client.name}</div><div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{client.type}</div></div>
                </div>
              ) : <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>Nessun cliente</div>}

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginTop: 14 }}>
                <div><div className="label">Data emissione</div>
                  <input type="date" className="input" disabled={readOnly} value={inv.data_emissione || ''} onChange={(e) => setInv({ ...inv, data_emissione: e.target.value })} />
                </div>
                <div><div className="label">Scadenza</div>
                  <input type="date" className="input" disabled={readOnly} value={inv.data_scadenza || ''} onChange={(e) => setInv({ ...inv, data_scadenza: e.target.value })} />
                </div>
                <div><div className="label">Numero</div>
                  <input className="input mono" value={inv.numero_completo} disabled />
                </div>
              </div>
              <div style={{ marginTop: 12 }}><div className="label">Causale</div>
                <input className="input" disabled={readOnly} value={inv.causale || ''} onChange={(e) => setInv({ ...inv, causale: e.target.value })} placeholder="es. Prestazione professionale" />
              </div>
            </div>

            {/* Righe */}
            <div className="card" style={{ background: '#fff', border: '1px solid var(--rule)', borderRadius: 10, padding: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Righe</div>
                {!readOnly && <button className="btn btn-ghost" onClick={addRow}><Icon name="plus" size={13} /> Aggiungi riga</button>}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '2fr 70px 50px 90px 70px 100px 30px', gap: 6, fontSize: 10, textTransform: 'uppercase', color: 'var(--ink-3)', letterSpacing: '0.06em', padding: '6px 0', borderBottom: '1px solid var(--rule-2)' }}>
                <div>Descrizione</div><div>Q.tà</div><div>UM</div><div>Prezzo</div><div>IVA%</div><div style={{ textAlign: 'right' }}>Totale</div><div></div>
              </div>
              {items.map((r, i) => {
                const calc = rowTotal(r);
                return (
                  <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 70px 50px 90px 70px 100px 30px', gap: 6, padding: '8px 0', borderBottom: '1px solid var(--rule-2)', alignItems: 'center' }}>
                    <input className="input" disabled={readOnly} value={r.descrizione || ''} onChange={(e) => updateRow(i, { descrizione: e.target.value })} />
                    <input className="input mono" disabled={readOnly} type="number" step="0.01" value={r.quantita} onChange={(e) => updateRow(i, { quantita: e.target.value })} style={{ textAlign: 'right' }} />
                    <select className="input" disabled={readOnly} value={r.unita_misura || 'pz'} onChange={(e) => updateRow(i, { unita_misura: e.target.value })}>
                      {UNITS.map(u => <option key={u}>{u}</option>)}
                    </select>
                    <input className="input mono" disabled={readOnly} type="number" step="0.01" value={r.prezzo_unitario} onChange={(e) => updateRow(i, { prezzo_unitario: e.target.value })} style={{ textAlign: 'right' }} />
                    <input className="input mono" disabled={readOnly} type="number" step="0.01" value={r.aliquota_iva} onChange={(e) => updateRow(i, { aliquota_iva: e.target.value })} style={{ textAlign: 'right' }} />
                    <div className="mono" style={{ textAlign: 'right', fontSize: 12, padding: '7px 0' }}>{fmtEur(calc.totale)}</div>
                    {!readOnly ? (
                      <button className="btn btn-ic btn-ghost" onClick={() => removeRow(i)}><Icon name="trash-2" size={12} /></button>
                    ) : <div />}
                  </div>
                );
              })}
              {items.length === 0 && (
                <div style={{ textAlign: 'center', padding: 30, color: 'var(--ink-3)', fontSize: 13 }}>
                  Nessuna riga. {!readOnly && <a onClick={addRow} style={{ cursor: 'pointer', color: 'var(--accent)' }}>Aggiungine una →</a>}
                </div>
              )}
            </div>
          </div>

          {/* Colonna destra: totali + pagamento + storico */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, position: 'sticky', top: 70, alignSelf: 'start' }}>
            <div className="card" style={{ background: '#fff', border: '1px solid var(--rule)', borderRadius: 10, padding: 16 }}>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10 }}>Totali</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '4px 0' }}>
                <span>Imponibile</span><span className="mono">{fmtEur(totImp)}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '4px 0' }}>
                <span>IVA</span><span className="mono">{fmtEur(totIva)}</span>
              </div>
              {bollo > 0 && (
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '4px 0', color: 'var(--amber)' }}>
                  <span>Bollo virtuale</span><span className="mono">{fmtEur(bollo)}</span>
                </div>
              )}
              <div style={{ borderTop: '1px solid var(--rule)', marginTop: 8, paddingTop: 8, display: 'flex', justifyContent: 'space-between', fontWeight: 700, fontSize: 15 }}>
                <span>Totale</span><span className="mono" style={{ color: 'var(--accent-ink)' }}>{fmtEur(totDoc)}</span>
              </div>
            </div>

            <div className="card" style={{ background: '#fff', border: '1px solid var(--rule)', borderRadius: 10, padding: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Pagamenti</div>
                {inv.status !== 'bozza' && inv.status !== 'annullata' && (
                  <button className="btn btn-ghost btn-sm" onClick={() => setShowPayForm(true)}><Icon name="plus" size={12} /> Registra</button>
                )}
              </div>

              <div className="label">Modalità default</div>
              <select className="input" disabled={readOnly} value={inv.metodo_pagamento || 'bonifico'} onChange={(e) => setInv({ ...inv, metodo_pagamento: e.target.value })}>
                {PAYMENT_METHODS.map(p => <option key={p.id} value={p.id}>{p.label}</option>)}
              </select>

              {paySummary && paySummary.total > 0 && (
                <div style={{ marginTop: 14 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-2)', marginBottom: 4 }}>
                    <span>Pagato</span><span className="mono">{fmtEur(paySummary.paid)} / {fmtEur(paySummary.total)}</span>
                  </div>
                  <div style={{ height: 6, background: 'var(--paper-2)', borderRadius: 99, overflow: 'hidden' }}>
                    <div style={{ width: Math.min(100, paySummary.paid / paySummary.total * 100) + '%', height: '100%', background: paySummary.remaining <= 0.01 ? 'var(--green)' : 'var(--accent)', transition: 'width 0.2s' }} />
                  </div>
                  {paySummary.remaining > 0.01 ? (
                    <div style={{ marginTop: 6, fontSize: 11, color: 'var(--amber)' }}>
                      Residuo: <span className="mono">{fmtEur(paySummary.remaining)}</span>
                    </div>
                  ) : (
                    <div style={{ marginTop: 8, padding: 6, background: 'rgba(46,139,87,0.08)', color: 'var(--green)', borderRadius: 4, fontSize: 12, textAlign: 'center' }}>
                      ✓ Saldata al 100%
                    </div>
                  )}
                </div>
              )}

              {payments.length > 0 && (
                <div style={{ marginTop: 12, borderTop: '1px solid var(--rule-2)', paddingTop: 10 }}>
                  {payments.map((p) => (
                    <div key={p.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12, padding: '5px 0' }}>
                      <div>
                        <div style={{ color: 'var(--ink-2)' }}>{fmtDate(p.payment_date)}{p.method ? ` · ${p.method}` : ''}</div>
                        {p.note && <div style={{ color: 'var(--ink-3)', fontSize: 11 }}>{p.note}</div>}
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span className="mono" style={{ color: 'var(--green)' }}>{fmtEur(p.amount)}</span>
                        <button className="ia" onClick={async () => { if (confirm('Rimuovere questo pagamento?')) { try { await window.LibroAPI.deletePayment(id, p.id); await loadPayments(); await load(); } catch (e) { alert(e.message); } } }} title="Rimuovi"><Icon name="trash-2" size={11} /></button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {events.length > 0 && (
              <div className="card" style={{ background: '#fff', border: '1px solid var(--rule)', borderRadius: 10, padding: 16 }}>
                <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10 }}>Storico SDI</div>
                {events.map((ev) => (
                  <div key={ev.id} style={{ fontSize: 12, padding: '6px 0', borderBottom: '1px solid var(--rule-2)' }}>
                    <div style={{ fontWeight: 500 }}>{ev.event_type} · {ev.summary}</div>
                    <div style={{ color: 'var(--ink-3)', fontSize: 11 }}>{fmtDate(ev.received_at)}</div>
                    {ev.error_desc && <div style={{ color: 'var(--red)', fontSize: 11 }}>{ev.error_desc}</div>}
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
      {showPayForm && (
        <PaymentFormModal
          invoice={inv}
          summary={paySummary}
          onClose={() => setShowPayForm(false)}
          onSaved={async () => { setShowPayForm(false); await load(); setMsg('✓ Pagamento registrato'); setTimeout(() => setMsg(''), 1500); }}
        />
      )}
    </>
  );
}

// --- Modale registra pagamento -----------------------------------------
function PaymentFormModal({ invoice, summary, onClose, onSaved }) {
  const remaining = summary ? summary.remaining : (invoice.totale_documento || 0) - (invoice.importo_pagato || 0);
  const [f, setF] = useState({
    amount: Math.max(0, remaining),
    payment_date: new Date().toISOString().slice(0, 10),
    method: invoice.metodo_pagamento || 'bonifico',
    reference: '',
    note: '',
  });
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState('');
  const set = (k) => (e) => setF({ ...f, [k]: e.target.type === 'number' ? parseFloat(e.target.value) : e.target.value });

  const submit = async (e) => {
    e.preventDefault();
    setSaving(true); setErr('');
    try {
      await window.LibroAPI.addPayment(invoice.id, f);
      onSaved();
    } catch (e) { setErr(e.message); }
    finally { setSaving(false); }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <form className="modal" onClick={(e) => e.stopPropagation()} onSubmit={submit} style={{ width: 460 }}>
        <div className="modal-head">
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Registra pagamento</div>
            <h2 style={{ fontFamily: 'Fraunces', fontSize: 20, fontWeight: 500, margin: '4px 0 0' }}>{invoice.numero_completo}</h2>
          </div>
          <button type="button" className="btn btn-ic btn-ghost" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div className="modal-body">
          {err && <div className="err" style={{ marginBottom: 12 }}><Icon name="alert-circle" size={14} /> {err}</div>}

          {summary && (
            <div style={{ padding: 10, background: 'var(--paper-2)', borderRadius: 6, fontSize: 12, color: 'var(--ink-2)', marginBottom: 14 }}>
              Totale fattura <span className="mono">{fmtEur(summary.total)}</span>
              {summary.paid > 0 && <> · già pagato <span className="mono" style={{ color: 'var(--green)' }}>{fmtEur(summary.paid)}</span></>}
              <div style={{ marginTop: 4, fontWeight: 500 }}>Residuo: <span className="mono" style={{ color: remaining > 0.01 ? 'var(--amber)' : 'var(--green)' }}>{fmtEur(remaining)}</span></div>
            </div>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <div className="field"><label className="label">Importo €</label>
              <input className="input mono" type="number" step="0.01" min="0.01" required autoFocus value={f.amount} onChange={set('amount')} />
            </div>
            <div className="field"><label className="label">Data</label>
              <input className="input" type="date" required value={f.payment_date} onChange={set('payment_date')} />
            </div>
          </div>
          <div className="field"><label className="label">Metodo</label>
            <select className="input" value={f.method} onChange={set('method')}>
              {PAYMENT_METHODS.map(p => <option key={p.id} value={p.id}>{p.label}</option>)}
            </select>
          </div>
          <div className="field"><label className="label">Riferimento (opzionale)</label>
            <input className="input" value={f.reference || ''} onChange={set('reference')} placeholder="es. CRO bonifico / ID transazione" />
          </div>
          <div className="field"><label className="label">Note (opzionale)</label>
            <input className="input" 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 ? 'Registro…' : 'Registra pagamento'}</button>
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { WizardNuovaFattura, FatturaScreen, PaymentFormModal });
