// efactura.jsx — ANAF e-Factura inbox + auto-import

function efacturaStatusCfg(status) {
  return {
    pending:   { label: 'Nou — neacționat',  color: '#D97706', bg: '#FEF3C7' },
    imported:  { label: 'Importat',           color: '#059669', bg: '#D1FAE5' },
    duplicate: { label: 'Suspect duplicat',   color: '#DC2626', bg: '#FADEDB' },
    paid:      { label: 'Plătit prin Vault', color: '#059669', bg: '#D1FAE5' },
    rejected:  { label: 'Refuzat',            color: '#6B7280', bg: '#F3F4F6' },
  }[status] || { label: status, color: '#6B7280', bg: '#F3F4F6' };
}

function EFacturaScreen({ state, tr, lang }) {
  const [inbox, setInbox] = React.useState(window.EFACTURA_INBOX);
  const [tab, setTab] = React.useState('pending');
  const [selected, setSelected] = React.useState(null);
  const toast = useToast();

  const pending = inbox.filter(f => f.status === 'pending');
  const flagged = inbox.filter(f => f.anomaly || f.status === 'duplicate');
  const handled = inbox.filter(f => f.status === 'imported' || f.status === 'paid' || f.status === 'rejected');

  const list = tab === 'pending' ? pending : tab === 'flagged' ? flagged : handled;

  const approveImport = (fId) => {
    const f = inbox.find(x => x.id === fId);
    if (!f) return;
    // Create new expense
    state.setExpenses(es => [...es, {
      id: 'e' + Math.random().toString(36).slice(2, 8),
      category_id: f.category_suggestion,
      description: f.description,
      supplier: f.supplier,
      invoice_number: f.invoice_no,
      amount: f.amount,
      _from_efactura: f.id,
    }]);
    setInbox(prev => prev.map(x => x.id === fId ? { ...x, status: 'imported', imported_at: new Date().toISOString() } : x));
    toast(`Importat în Cheltuieli — ${f.supplier} ${window.fmtRONshort(f.amount)} RON`);
    setSelected(null);
  };

  const rejectFactura = (fId) => {
    setInbox(prev => prev.map(x => x.id === fId ? { ...x, status: 'rejected' } : x));
    toast('Factură refuzată');
    setSelected(null);
  };

  const proposeVaultPayment = (fId) => {
    const f = inbox.find(x => x.id === fId);
    if (!f) return;
    state.setVaultTx(txs => [{
      id: 'tx_' + Math.random().toString(36).slice(2, 8),
      type: 'outflow', status: 'pending_signatures',
      title: `Plată ${f.supplier}`,
      description: f.description,
      amount: f.amount,
      proposed_at: new Date().toISOString(),
      proposed_by: state.currentSigner,
      deadline: f.due_date,
      payee: f.supplier,
      invoice: {
        number: f.invoice_no, date: f.invoice_date,
        anaf_validated: true, anaf_efactura_id: f.anaf_id,
      },
      signatures: [{ signer_id: state.currentSigner, signed_at: new Date().toISOString(), method: 'app_2fa' }],
    }, ...txs]);
    toast(`Propunere plată Vault creată — așteaptă 2 semnături comitet`);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="e-Factura ANAF"
        subtitle="Facturile primite automat prin SPV (Spațiul Privat Virtual). Import în 1 click."
        right={<div style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 12 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 999, background: '#DDF0E4', color: '#065F46', fontWeight: 600 }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: '#059669', boxShadow: '0 0 0 4px rgba(5, 150, 105, 0.15)' }} />
            Conectat la ANAF SPV
          </span>
        </div>}
      />

      {/* Stats explainer */}
      <Card style={{ background: 'linear-gradient(135deg, #E0F2FE, #cae8f8)', border: '1px solid #0EA5E9' }}>
        <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
          <div style={{ width: 52, height: 52, borderRadius: 14, background: '#0EA5E9', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 26, flexShrink: 0 }}>📥</div>
          <div style={{ flex: 1, fontSize: 13.5, color: '#0C4A6E', lineHeight: 1.55 }}>
            <b>Cum funcționează:</b> Toate facturile B2B din România trec obligatoriu prin <b>ANAF e-Factura</b> (RO e-Factura, OUG 120/2021). BlocApp se conectează la SPV-ul scării și descarcă automat orice factură. Imposibil de făcut factură falsă — toate sunt validate ANAF, semnate digital, neschimbabile.
          </div>
          <div style={{ display: 'flex', gap: 20, flexShrink: 0 }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 700, color: '#0C4A6E', lineHeight: 1 }}>{window.EFACTURA_STATS.this_month_count}</div>
              <div style={{ fontSize: 10, color: '#0C4A6E', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600, marginTop: 4 }}>Facturi luna asta</div>
            </div>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 700, color: '#0C4A6E', lineHeight: 1 }}>~{window.EFACTURA_STATS.saved_hours}h</div>
              <div style={{ fontSize: 10, color: '#0C4A6E', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600, marginTop: 4 }}>Economisite lunar</div>
            </div>
          </div>
        </div>
      </Card>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--surface-2)', borderRadius: 12, width: 'fit-content' }}>
        {[
          { id: 'pending',  label: `Inbox (${pending.length})`, badge: pending.length },
          { id: 'flagged',  label: `Suspecte (${flagged.length})`, badge: flagged.length, danger: flagged.length > 0 },
          { id: 'handled',  label: `Procesate (${handled.length})` },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 16px', borderRadius: 8, border: 0, cursor: 'pointer',
            background: tab === t.id ? 'var(--surface)' : 'transparent',
            color: t.danger ? '#DC2626' : tab === t.id ? 'var(--ink)' : 'var(--muted)',
            fontFamily: 'inherit', fontSize: 13.5, fontWeight: 600,
            boxShadow: tab === t.id ? '0 1px 2px rgba(28,22,12,0.08)' : 'none',
          }}>{t.label}</button>
        ))}
      </div>

      {/* List */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {list.length === 0 ? (
          <Card><div style={{ textAlign: 'center', padding: 24, color: 'var(--muted)' }}>Nimic aici.</div></Card>
        ) : list.map(f => (
          <EFacturaCard key={f.id} f={f} state={state} onClick={() => setSelected(f)} onApprove={() => approveImport(f.id)} />
        ))}
      </div>

      <Drawer open={!!selected} onClose={() => setSelected(null)} title={selected ? `Factură ${selected.invoice_no}` : ''} width={620}>
        {selected && <EFacturaDetail
          f={inbox.find(x => x.id === selected.id) || selected}
          state={state}
          onApprove={() => approveImport(selected.id)}
          onReject={() => rejectFactura(selected.id)}
          onPropose={() => proposeVaultPayment(selected.id)}
        />}
      </Drawer>
    </div>
  );
}

function EFacturaCard({ f, state, onClick, onApprove }) {
  const cat = window.CATEGORIES.find(c => c.id === f.category_suggestion);
  const status = efacturaStatusCfg(f.status);
  const isFlagged = f.anomaly || f.status === 'duplicate';

  return (
    <Card onClick={onClick} style={{
      borderColor: isFlagged ? '#FECACA' : 'var(--border)',
      borderWidth: isFlagged ? 1.5 : 1,
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
        {/* Mini "PDF" */}
        <div style={{
          width: 44, height: 56, borderRadius: 6, flexShrink: 0,
          background: 'linear-gradient(160deg, #fff, #f5f0e6)',
          border: '1px solid var(--border)',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          fontSize: 11, color: 'var(--muted)', fontFamily: 'var(--font-mono)',
          boxShadow: '0 1px 2px rgba(28, 22, 12, 0.06)',
          position: 'relative',
        }}>
          📄
          {f.xml_valid && (
            <div title="XML valid ANAF" style={{
              position: 'absolute', top: -4, right: -4,
              width: 18, height: 18, borderRadius: 999,
              background: '#0EA5E9', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 10, fontWeight: 700,
            }}>✓</div>
          )}
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--ink)' }}>{f.supplier}</span>
            <span style={{ fontSize: 10.5, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>CUI {f.supplier_cui}</span>
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.4, marginBottom: 6 }}>
            {f.description}
          </div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', fontSize: 11, color: 'var(--muted)', alignItems: 'center' }}>
            <span>📅 {new Date(f.invoice_date).toLocaleDateString('ro-RO', { day: 'numeric', month: 'short' })}</span>
            <span>Scadență {new Date(f.due_date).toLocaleDateString('ro-RO', { day: 'numeric', month: 'short' })}</span>
            <span style={{ fontFamily: 'var(--font-mono)' }}>· {f.invoice_no}</span>
            {cat && (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px', borderRadius: 999, background: cat.color + '22', color: cat.color, fontWeight: 600 }}>
                <span>{cat.icon}</span>
                <span>{cat.name}</span>
                {f.confidence && <span style={{ fontSize: 9, opacity: 0.7 }}>· {Math.round(f.confidence * 100)}%</span>}
              </span>
            )}
          </div>

          {/* Anomaly / duplicate flags */}
          {f.anomaly && (
            <div style={{ marginTop: 10, padding: '8px 12px', borderRadius: 8, background: '#FEE2E2', color: '#991B1B', fontSize: 12, lineHeight: 1.4 }}>
              <b>⚠ Sumă neobișnuită:</b> {window.fmtRONshort(f.amount)} RON vs. media de {window.fmtRONshort(f.anomaly.historic_avg)} RON ({f.anomaly.ratio.toFixed(1)}× peste medie)
            </div>
          )}
          {f.status === 'duplicate' && (
            <div style={{ marginTop: 10, padding: '8px 12px', borderRadius: 8, background: '#FEE2E2', color: '#991B1B', fontSize: 12 }}>
              <b>⚠ Suspect duplicat:</b> O factură similară a fost deja importată recent
            </div>
          )}
          {f.recurring_match && (
            <div style={{ marginTop: 10, padding: '8px 12px', borderRadius: 8, background: '#DDF0E4', color: '#065F46', fontSize: 12 }}>
              ✓ Recunoscută din pattern — exact aceeași sumă lunară
            </div>
          )}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 8, flexShrink: 0 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 700, color: 'var(--ink)' }}>
            {window.fmtRONshort(f.amount)} <span style={{ fontSize: 12, color: 'var(--muted)' }}>RON</span>
          </div>
          {f.vat > 0 && (
            <div style={{ fontSize: 10.5, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>+TVA {f.vat.toFixed(2)}</div>
          )}
          <span style={{ padding: '3px 10px', borderRadius: 999, background: status.bg, color: status.color, fontSize: 11, fontWeight: 600 }}>{status.label}</span>
          {f.status === 'pending' && !isFlagged && !f.recurring_match && (
            <button onClick={(e) => { e.stopPropagation(); onApprove(); }} style={{
              padding: '6px 12px', borderRadius: 8,
              background: 'var(--primary)', color: '#fff', border: 0, cursor: 'pointer',
              fontFamily: 'inherit', fontSize: 11.5, fontWeight: 700,
              display: 'inline-flex', alignItems: 'center', gap: 5,
            }}>
              <Icon name="check" size={12} stroke={2.4} /> Importă
            </button>
          )}
          {f.recurring_match && f.status === 'pending' && (
            <button onClick={(e) => { e.stopPropagation(); onApprove(); }} style={{
              padding: '6px 12px', borderRadius: 8,
              background: '#059669', color: '#fff', border: 0, cursor: 'pointer',
              fontFamily: 'inherit', fontSize: 11.5, fontWeight: 700,
              display: 'inline-flex', alignItems: 'center', gap: 5,
            }}>
              <Icon name="check" size={12} stroke={2.4} /> Auto-import
            </button>
          )}
        </div>
      </div>
    </Card>
  );
}

function EFacturaDetail({ f, state, onApprove, onReject, onPropose }) {
  const cat = window.CATEGORIES.find(c => c.id === f.category_suggestion);
  const status = efacturaStatusCfg(f.status);
  const isFlagged = f.anomaly || f.status === 'duplicate';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* Status header */}
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
        <span style={{ padding: '4px 10px', borderRadius: 999, background: status.bg, color: status.color, fontSize: 11.5, fontWeight: 700 }}>{status.label}</span>
        <span style={{ padding: '4px 10px', borderRadius: 999, background: '#E0F2FE', color: '#0369A1', fontSize: 11.5, fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 5 }}>
          ✓ ANAF e-Factura
        </span>
        <span style={{ padding: '4px 10px', borderRadius: 999, background: '#F0FDF4', color: '#065F46', fontSize: 11.5, fontWeight: 600 }}>
          XML valid · semnat digital
        </span>
      </div>

      {/* Big amount */}
      <div style={{ padding: 18, borderRadius: 14, background: 'var(--surface-2)' }}>
        <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4 }}>Total factură</div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.01em' }}>
          {window.fmtRON(f.amount)}
        </div>
        {f.vat > 0 && (
          <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4 }}>din care TVA <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--ink-2)' }}>{f.vat.toFixed(2)} RON</span></div>
        )}
      </div>

      {/* Anomaly explanation */}
      {f.anomaly && (
        <div style={{ padding: 14, borderRadius: 12, background: '#FEE2E2', border: '1.5px solid #DC2626' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <span style={{ fontSize: 18 }}>⚠️</span>
            <span style={{ fontWeight: 700, color: '#991B1B', fontSize: 14 }}>Verifică această factură</span>
          </div>
          <div style={{ fontSize: 12.5, color: '#991B1B', lineHeight: 1.5 }}>
            Suma este <b>{f.anomaly.ratio.toFixed(1)}× peste media istorică</b> ({window.fmtRONshort(f.anomaly.historic_avg)} RON). Posibile cauze: <br/>
            • Sezonul rece — consum mai mare<br/>
            • Tarif modificat de furnizor<br/>
            • Eroare furnizor — verifică <a href="#" style={{ color: '#991B1B', fontWeight: 700 }}>indexul transmis</a><br/>
            • Verifică PDF-ul atașat
          </div>
        </div>
      )}

      {/* Supplier + invoice info */}
      <div>
        <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 10 }}>Furnizor</div>
        <Card style={{ background: 'var(--surface-2)', boxShadow: 'none' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: 'var(--primary-light)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16 }}>
              {f.supplier.split(' ').map(p => p[0]).join('').slice(0, 2)}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{f.supplier}</div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>CUI {f.supplier_cui}</div>
            </div>
          </div>
        </Card>
      </div>

      {/* Invoice meta */}
      <div>
        <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 10 }}>Detalii factură</div>
        <Card style={{ padding: 14, background: 'var(--surface-2)', boxShadow: 'none' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 13 }}>
            <Row label="Număr factură" value={f.invoice_no} />
            <Row label="ID ANAF" value={f.anaf_id} mono />
            <Row label="Data emiterii" value={new Date(f.invoice_date).toLocaleDateString('ro-RO')} />
            <Row label="Scadență" value={new Date(f.due_date).toLocaleDateString('ro-RO')} />
            <Row label="Descriere" value={f.description} />
            <Row label="Categorie sugerată" value={cat ? `${cat.icon} ${cat.name}` : '—'} />
          </div>
        </Card>
      </div>

      {/* PDF preview */}
      <div>
        <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 10 }}>Document original</div>
        <button style={{
          width: '100%', padding: '14px 16px', borderRadius: 12,
          background: 'var(--surface-2)', border: '1px solid var(--border)', cursor: 'pointer',
          fontFamily: 'inherit', textAlign: 'left',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{ width: 36, height: 48, borderRadius: 5, background: 'linear-gradient(160deg, #fff, #f5f0e6)', border: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>📄</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{f.invoice_no}.pdf</div>
            <div style={{ fontSize: 11, color: 'var(--muted)' }}>XML semnat digital · descărcat automat din SPV</div>
          </div>
          <Icon name="download" size={16} style={{ color: 'var(--muted)' }} />
        </button>
      </div>

      {/* Actions */}
      {f.status === 'pending' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {!isFlagged && <Button variant="success" full icon="check" onClick={onApprove}>Importă în Cheltuieli</Button>}
          {isFlagged && <Button variant="primary" full icon="check" onClick={onApprove}>Importă oricum (am verificat)</Button>}
          <Button variant="secondary" full icon="spark" onClick={onPropose}>Propune plată din Vault</Button>
          <Button variant="ghost" full icon="x" onClick={onReject}>Refuză factura (contestă la furnizor)</Button>
        </div>
      )}
      {f.status === 'imported' && (
        <div style={{ padding: 14, borderRadius: 12, background: '#F0FDF4', border: '1px solid #BBF7D0' }}>
          <div style={{ fontSize: 13, color: '#065F46', fontWeight: 600 }}>✓ Importat în Cheltuieli noiembrie 2025</div>
        </div>
      )}
    </div>
  );
}

function Row({ label, value, mono }) {
  return (
    <div>
      <div style={{ fontSize: 11, color: 'var(--muted)', marginBottom: 2 }}>{label}</div>
      <div style={{ color: 'var(--ink)', fontWeight: 500, fontFamily: mono ? 'var(--font-mono)' : 'inherit', fontSize: mono ? 12 : 13 }}>{value}</div>
    </div>
  );
}

Object.assign(window, { EFacturaScreen });
