// Bellia — Module Dépenses : workflow de validation des factures

const FACTURES = [
  { id: 'F-4218', supplier: 'Metro Cash & Carry', cat: 'Boucherie', amount: 1284.50, ht: 1070.42, tva: 214.08, date: '08/05/2026', due: '23/05/2026', status: 'a_valider', urgent: true,  hasFile: true,  by: 'Agent Dépenses', items: 12 },
  { id: 'F-4217', supplier: 'Boulangerie Utopie', cat: 'Pain & viennoiseries', amount: 312.80, ht: 295.85, tva: 16.95, date: '07/05/2026', due: '22/05/2026', status: 'a_valider', urgent: false, hasFile: true,  by: 'Agent Dépenses', items: 5 },
  { id: 'F-4216', supplier: 'Brasseries de Paris', cat: 'Boissons', amount: 892.00, ht: 743.33, tva: 148.67, date: '07/05/2026', due: '06/06/2026', status: 'a_valider', urgent: false, hasFile: true,  by: 'Agent Dépenses', items: 8 },
  { id: 'F-4215', supplier: 'Rungis Primeurs',     cat: 'Fruits & légumes', amount: 478.20, ht: 453.75, tva: 24.45, date: '06/05/2026', due: '21/05/2026', status: 'a_valider', urgent: true,  hasFile: true,  by: 'Yannis',          items: 24 },
  { id: 'F-4214', supplier: 'EDF Pro',             cat: 'Énergie', amount: 1654.30, ht: 1378.58, tva: 275.72, date: '05/05/2026', due: '04/06/2026', status: 'planifie', urgent: false, hasFile: true,  by: 'Agent Paiements',  items: 1 },
  { id: 'F-4213', supplier: 'Poissonnerie Loïc',   cat: 'Poissons', amount: 642.80, ht: 535.67, tva: 107.13, date: '04/05/2026', due: '19/05/2026', status: 'paye',     urgent: false, hasFile: true,  by: 'Yannis',          items: 9 },
  { id: 'F-4212', supplier: 'Coca-Cola France',    cat: 'Boissons', amount: 1124.00, ht: 936.67, tva: 187.33, date: '03/05/2026', due: '02/06/2026', status: 'planifie', urgent: false, hasFile: true,  by: 'Agent Paiements',  items: 3 },
  { id: 'F-4211', supplier: 'Mariage Frères',      cat: 'Café & thé', amount: 286.40, ht: 238.67, tva: 47.73, date: '02/05/2026', due: '17/05/2026', status: 'paye',     urgent: false, hasFile: true,  by: 'Yannis',          items: 6 },
  { id: 'F-4210', supplier: 'France Boissons',     cat: 'Boissons', amount: 1452.60, ht: 1210.50, tva: 242.10, date: '01/05/2026', due: '31/05/2026', status: 'paye',     urgent: false, hasFile: true,  by: 'Yannis',          items: 14 },
  { id: 'F-4209', supplier: 'Davigel',             cat: 'Surgelés', amount: 824.50, ht: 686.83, tva: 137.67, date: '30/04/2026', due: '15/05/2026', status: 'litige',    urgent: true,  hasFile: true,  by: 'Yannis',          items: 11, note: '2 colis manquants' },
];

const STATUS_FACTURE = {
  a_valider: { l: 'À valider', c: C.warn, bg: C.warnSft },
  planifie:  { l: 'Planifié',  c: C.orangeDp, bg: C.orangeWh },
  paye:      { l: 'Payé',      c: C.ok,   bg: C.okSft },
  litige:    { l: 'Litige',    c: C.err,  bg: C.errSft },
};

const DepensesScreen = ({ onNav }) => {
  const [tab, setTab] = React.useState('a_valider');
  const [sel, setSel] = React.useState('F-4218');
  const [selected, setSelected] = React.useState(new Set());

  const filtered = FACTURES.filter(f => tab === 'tous' || f.status === tab);
  const current = FACTURES.find(f => f.id === sel) || FACTURES[0];

  const totalAValider = FACTURES.filter(f => f.status === 'a_valider').reduce((a, b) => a + b.amount, 0);
  const totalPlanifie = FACTURES.filter(f => f.status === 'planifie').reduce((a, b) => a + b.amount, 0);
  const totalMois     = FACTURES.reduce((a, b) => a + b.amount, 0);

  const toggleSel = (id) => {
    const n = new Set(selected);
    n.has(id) ? n.delete(id) : n.add(id);
    setSelected(n);
  };

  return (
    <PageShell current="depenses" onNav={onNav}>
      <Header
        title="Dépenses"
        subtitle={`${FACTURES.length} factures ce mois · ${eur(totalMois, 0)} TTC`}
        right={<>
          <Btn kind="ghost" icon={<Icon name="download" size={14} color={C.ink2} />}>Exporter</Btn>
          <Btn kind="primary" icon={<Icon name="plus" size={14} />}>Nouvelle facture</Btn>
        </>}
      />

      {/* Stat banner */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 20 }}>
        <BigStat label="À valider" value={eur(totalAValider)} count={`${FACTURES.filter(f => f.status === 'a_valider').length} factures`} accent="warn" />
        <BigStat label="Planifié" value={eur(totalPlanifie)} count={`${FACTURES.filter(f => f.status === 'planifie').length} factures`} accent="accent" />
        <BigStat label="Payé ce mois" value={eur(FACTURES.filter(f => f.status === 'paye').reduce((a, b) => a + b.amount, 0))} count={`${FACTURES.filter(f => f.status === 'paye').length} factures`} accent="ok" />
        <BigStat label="Food cost réel" value={pct(32.0)} count="cible 28 %" accent="err" delta={signedPct(4)} />
      </div>

      {/* Split: liste + détail */}
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)', gap: 18 }}>
        {/* ===== LISTE ===== */}
        <div style={{ background: C.cardWash, borderRadius: 22, border: `1px solid ${C.line}`, overflow: 'hidden' }}>
          {/* Tabs */}
          <div style={{ padding: '14px 16px', borderBottom: `1px solid ${C.line}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
            <div style={{ display: 'inline-flex', padding: 4, background: C.card, border: `1px solid ${C.line}`, borderRadius: 999, gap: 2 }}>
              {[
                { id: 'a_valider', l: 'À valider', n: FACTURES.filter(f => f.status === 'a_valider').length },
                { id: 'planifie',  l: 'Planifié',  n: FACTURES.filter(f => f.status === 'planifie').length },
                { id: 'paye',      l: 'Payé',      n: FACTURES.filter(f => f.status === 'paye').length },
                { id: 'litige',    l: 'Litige',    n: FACTURES.filter(f => f.status === 'litige').length },
                { id: 'tous',      l: 'Tous',      n: FACTURES.length },
              ].map(t => {
                const active = tab === t.id;
                return (
                  <button key={t.id} onClick={() => setTab(t.id)} style={{
                    padding: '6px 12px', borderRadius: 999, background: active ? C.orange : 'transparent',
                    color: active ? '#fff' : C.mute, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
                    fontSize: 11, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 5,
                  }}>{t.l} <span style={{ fontSize: 10, opacity: 0.85 }}>{t.n}</span></button>
                );
              })}
            </div>
            <button style={{
              padding: '7px 12px', background: C.card, border: `1px solid ${C.line}`, borderRadius: 999,
              cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, fontWeight: 600, color: C.ink2,
              display: 'inline-flex', alignItems: 'center', gap: 5,
            }}><Icon name="filter" size={12} color={C.mute} /> Filtres</button>
          </div>

          {/* Bulk bar */}
          {selected.size > 0 && (
            <div style={{ padding: '10px 16px', background: C.orangeWh, borderBottom: `1px solid ${C.line}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
              <span style={{ fontSize: 12, color: C.orangeDp, fontWeight: 600 }}>{selected.size} sélectionnée{selected.size > 1 ? 's' : ''} · {eur([...selected].reduce((a, id) => a + (FACTURES.find(f => f.id === id)?.amount || 0), 0))}</span>
              <div style={{ display: 'flex', gap: 6 }}>
                <Btn kind="ghost" size="sm" onClick={() => setSelected(new Set())}>Annuler</Btn>
                <Btn kind="primary" size="sm" icon={<Icon name="check" size={12} stroke={2.4} />}>Valider la sélection</Btn>
              </div>
            </div>
          )}

          {/* Table */}
          <div style={{ maxHeight: 620, overflow: 'auto' }}>
            {filtered.map((f, idx) => {
              const s = STATUS_FACTURE[f.status];
              const isSel = sel === f.id;
              const isChecked = selected.has(f.id);
              return (
                <div key={f.id} onClick={() => setSel(f.id)} style={{
                  display: 'grid', gridTemplateColumns: '24px 1fr auto auto', gap: 14, alignItems: 'center',
                  padding: '14px 16px', borderBottom: idx === filtered.length - 1 ? 'none' : `1px solid ${C.lineSoft}`,
                  background: isSel ? C.card : 'transparent', cursor: 'pointer', borderLeft: isSel ? `3px solid ${C.orange}` : '3px solid transparent',
                }}>
                  <Checkbox checked={isChecked} onChange={() => toggleSel(f.id)} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                      <span style={{ fontSize: 13, fontWeight: 700, color: C.ink, letterSpacing: -0.2 }}>{f.supplier}</span>
                      {f.urgent && <Pill kind="err" size="sm">Échéance proche</Pill>}
                    </div>
                    <div style={{ fontSize: 11, color: C.mute, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                      <span>{f.id}</span>
                      <span>·</span>
                      <span>{f.cat}</span>
                      <span>·</span>
                      <span>{f.date}</span>
                      <span>·</span>
                      <span>Échéance {f.due}</span>
                      {f.by === 'Agent Dépenses' && <><span>·</span><span style={{ color: C.orangeDp, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 3 }}><Icon name="zap" size={10} /> Traité auto</span></>}
                    </div>
                  </div>
                  <Pill kind={f.status === 'paye' ? 'ok' : f.status === 'planifie' ? 'accent' : f.status === 'litige' ? 'err' : 'warn'}>{s.l}</Pill>
                  <div style={{ textAlign: 'right', minWidth: 100 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: C.ink, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3 }}>{eur(f.amount, 2)}</div>
                    <div style={{ fontSize: 10, color: C.mute, fontVariantNumeric: 'tabular-nums' }}>HT {eur(f.ht, 2)}</div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Footer total */}
          <div style={{ padding: '14px 16px', borderTop: `1px solid ${C.line}`, background: C.card, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 11, color: C.mute }}>{filtered.length} factures affichées</span>
            <span style={{ fontSize: 13, fontWeight: 700, color: C.ink, fontVariantNumeric: 'tabular-nums' }}>
              Total : {eur(filtered.reduce((a, b) => a + b.amount, 0), 2)}
            </span>
          </div>
        </div>

        {/* ===== DÉTAIL ===== */}
        <FactureDetail facture={current} />
      </div>
    </PageShell>
  );
};

const Checkbox = ({ checked, onChange }) => (
  <button onClick={(e) => { e.stopPropagation(); onChange(); }} aria-checked={checked} role="checkbox" style={{
    width: 18, height: 18, borderRadius: 6, background: checked ? C.orange : C.card,
    border: `1.5px solid ${checked ? C.orange : C.line}`, cursor: 'pointer', padding: 0,
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  }}>
    {checked && <Icon name="check" size={12} color="#fff" stroke={3} />}
  </button>
);

const BigStat = ({ label, value, count, accent, delta }) => {
  const cmap = {
    warn:   { fg: C.warn,    bg: C.warnSft },
    accent: { fg: C.orangeDp, bg: C.orangeWh },
    ok:     { fg: C.ok,      bg: C.okSft },
    err:    { fg: C.err,     bg: C.errSft },
  };
  const m = cmap[accent];
  return (
    <div style={{ background: C.card, border: `1px solid ${C.line}`, borderRadius: 20, padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <span style={{ width: 8, height: 8, borderRadius: 999, background: m.fg }} />
        <span style={{ fontSize: 11, color: m.fg, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>{label}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <div style={{ fontSize: 24, fontWeight: 700, color: C.ink, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.4 }}>{value}</div>
        {delta && <span style={{ fontSize: 11, color: C.err, fontWeight: 600 }}>{delta}</span>}
      </div>
      <div style={{ fontSize: 11, color: C.mute, marginTop: 4 }}>{count}</div>
    </div>
  );
};

// ===== Detail panel =====
const FactureDetail = ({ facture }) => {
  if (!facture) return null;
  const s = STATUS_FACTURE[facture.status];
  return (
    <div style={{ background: C.card, border: `1px solid ${C.line}`, borderRadius: 22, overflow: 'hidden', display: 'flex', flexDirection: 'column', alignSelf: 'flex-start', position: 'sticky', top: 20 }}>
      {/* mini preview */}
      <div style={{ padding: 18, background: C.cardWash, borderBottom: `1px solid ${C.line}`, display: 'flex', gap: 14, alignItems: 'center' }}>
        <div style={{
          width: 60, height: 76, borderRadius: 8, background: C.card, border: `1px solid ${C.line}`,
          display: 'flex', flexDirection: 'column', justifyContent: 'space-between', padding: 8, flexShrink: 0,
        }}>
          <div style={{ height: 2, background: C.line, borderRadius: 1 }} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
            {[60, 80, 50, 70].map((w, i) => <div key={i} style={{ height: 2, background: C.lineSoft, borderRadius: 1, width: `${w}%` }} />)}
          </div>
          <div style={{ height: 2, background: C.orange, borderRadius: 1, width: '40%', alignSelf: 'flex-end' }} />
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 11, color: C.mute, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 4 }}>{facture.id} · {facture.cat}</div>
          <h3 style={{ fontSize: 17, fontWeight: 700, color: C.ink, margin: 0, letterSpacing: -0.3 }}>{facture.supplier}</h3>
          <div style={{ display: 'flex', gap: 6, marginTop: 8, alignItems: 'center' }}>
            <Pill kind={facture.status === 'paye' ? 'ok' : facture.status === 'planifie' ? 'accent' : facture.status === 'litige' ? 'err' : 'warn'}>{s.l}</Pill>
            {facture.by === 'Agent Dépenses' && <Pill kind="accent" icon={<Icon name="zap" size={10} />}>Auto</Pill>}
          </div>
        </div>
      </div>

      {/* breakdown */}
      <div style={{ padding: 18 }}>
        <SectionLabel>Montant</SectionLabel>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginBottom: 18 }}>
          <MiniBlock label="HT" value={eur(facture.ht, 2)} />
          <MiniBlock label="TVA" value={eur(facture.tva, 2)} />
          <MiniBlock label="TTC" value={eur(facture.amount, 2)} accent />
        </div>

        <SectionLabel>Détails</SectionLabel>
        <div style={{ background: C.cardWash, borderRadius: 14, padding: 14, marginBottom: 18 }}>
          <KV label="Date d'émission" v={facture.date} />
          <KV label="Échéance de paiement" v={facture.due} accent={facture.urgent} />
          <KV label="Nombre de lignes" v={`${facture.items} articles`} />
          <KV label="Imputé par" v={facture.by} />
          <KV label="Compte comptable" v="6022 — Achats matières" last />
        </div>

        {facture.note && (
          <div style={{ background: C.errSft, color: C.err, padding: '10px 14px', borderRadius: 12, marginBottom: 16, display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 12 }}>
            <Icon name="alertT" size={14} stroke={2} />
            <span><strong>Note de litige · </strong>{facture.note}</span>
          </div>
        )}

        {facture.status === 'a_valider' && (
          <div style={{ background: C.orangeWh, borderRadius: 14, padding: 14, marginBottom: 16, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <Icon name="sparkles" size={14} color={C.orangeDp} />
            <div style={{ fontSize: 12, color: C.orangeDp, lineHeight: 1.5 }}>
              <strong>Agent Dépenses · </strong>extraction OCR vérifiée, TVA cohérente, fournisseur identifié. Pré-imputation en compte 6022.
            </div>
          </div>
        )}

        {/* Actions */}
        {facture.status === 'a_valider' ? (
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn kind="ghost" full icon={<Icon name="x" size={13} color={C.ink2} />}>Refuser</Btn>
            <Btn kind="primary" full icon={<Icon name="check" size={13} stroke={2.4} />}>Valider</Btn>
          </div>
        ) : facture.status === 'planifie' ? (
          <Btn kind="primary" full icon={<Icon name="card" size={13} />}>Payer maintenant</Btn>
        ) : facture.status === 'litige' ? (
          <Btn kind="primary" full icon={<Icon name="mail" size={13} />}>Contacter le fournisseur</Btn>
        ) : (
          <Btn kind="ghost" full icon={<Icon name="download" size={13} color={C.ink2} />}>Télécharger le PDF</Btn>
        )}

        {/* Activity */}
        <div style={{ marginTop: 18 }}>
          <SectionLabel>Activité</SectionLabel>
          <Timeline items={[
            { ok: true, t: 'Pré-imputation comptable', when: 'il y a 12 min', by: 'Agent Dépenses' },
            { ok: true, t: 'OCR extraction & TVA vérifiée', when: 'il y a 14 min', by: 'Agent Dépenses' },
            { ok: true, t: 'Facture reçue par e-mail', when: 'il y a 22 min', by: facture.supplier },
          ]} />
        </div>
      </div>
    </div>
  );
};

const SectionLabel = ({ children }) => (
  <div style={{ fontSize: 10, color: C.mute, fontWeight: 700, letterSpacing: 0.7, textTransform: 'uppercase', marginBottom: 10 }}>{children}</div>
);

const MiniBlock = ({ label, value, accent }) => (
  <div style={{
    background: accent ? C.orange : C.cardWash, color: accent ? '#fff' : C.ink, padding: '10px 12px', borderRadius: 12,
  }}>
    <div style={{ fontSize: 10, color: accent ? 'rgba(255,255,255,0.85)' : C.mute, fontWeight: 600, letterSpacing: 0.3 }}>{label}</div>
    <div style={{ fontSize: 15, fontWeight: 700, marginTop: 3, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3 }}>{value}</div>
  </div>
);

const KV = ({ label, v, accent, last }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: last ? 'none' : `1px dashed ${C.line}` }}>
    <span style={{ fontSize: 12, color: C.mute }}>{label}</span>
    <span style={{ fontSize: 12, color: accent ? C.err : C.ink, fontWeight: 600 }}>{v}</span>
  </div>
);

const Timeline = ({ items }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
    {items.map((it, i) => (
      <div key={i} style={{ display: 'flex', gap: 12, position: 'relative' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
          <span style={{ width: 8, height: 8, borderRadius: 999, background: C.orange, marginTop: 6 }} />
          {i < items.length - 1 && <span style={{ width: 1, flex: 1, background: C.line }} />}
        </div>
        <div style={{ paddingBottom: i < items.length - 1 ? 12 : 0, flex: 1 }}>
          <div style={{ fontSize: 12, color: C.ink, fontWeight: 600 }}>{it.t}</div>
          <div style={{ fontSize: 10, color: C.mute, marginTop: 2 }}>{it.when} · {it.by}</div>
        </div>
      </div>
    ))}
  </div>
);

window.DepensesScreen = DepensesScreen;
