// Dépenses — liste · détail · import factures fournisseurs (mobile). window.OryzeApp.DepensesScreen
(function () {
  const { Card, Amount, Tag, TransactionRow, Button, ProgressRing } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;
  const CATS = window.OryzeExpenseCats;

  function DepensesScreen() {
    const ALL = window.OryzeExpenses;
    const [filter, setFilter] = React.useState("all");
    const [mode, setMode] = React.useState("list");
    const [selected, setSelected] = React.useState(null);

    if (mode === "import") {
      return (
        <div style={{ padding: "16px 16px 28px", display: "flex", flexDirection: "column", gap: 16 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <button onClick={() => setMode("list")} aria-label="Retour" style={{ width: 36, height: 36, flex: "none", display: "inline-flex", alignItems: "center", justifyContent: "center", border: "var(--border-thin) solid var(--line-keyline)", borderRadius: "var(--radius-md)", background: "var(--surface-card)", cursor: "pointer", color: "var(--text-body)" }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m15 18-6-6 6-6" /></svg>
            </button>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--text-muted)" }}>Import documentaire — Factur-X ou PDF</div>
              <div style={{ fontWeight: 700, fontSize: 19, letterSpacing: "-0.02em" }}>Import factures fournisseurs</div>
            </div>
          </div>
          {React.createElement(window.OryzeShared.ImportFournisseurs, { compact: true })}
        </div>
      );
    }

    if (mode === "detail" && selected) {
      return (
        <div style={{ padding: "16px 16px 28px" }}>
          {React.createElement(window.OryzeShared.ExpenseDetail, { exp: selected, onBack: () => setMode("list") })}
        </div>
      );
    }

    const list = ALL.filter((e) => (filter === "all" ? true : e.cat === filter));
    const monthTotal = window.OryzeExpenseAprilTTC; // 3 110,00 € canonique
    const toConfirm = ALL.filter((e) => !e.auto);

    return (
      <div style={{ padding: "16px 16px 24px", display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
          <div style={{ fontWeight: 700, fontSize: 20, letterSpacing: "-0.02em" }}>Dépenses</div>
          <Button size="sm" variant="secondary" iconLeft={<Ic.upload size={15} />} onClick={() => setMode("import")} style={{ flex: "none" }}>Import fournisseurs</Button>
        </div>

        {/* Total summary */}
        <Card variant="elevated" padding="16px" style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" }}>Dépensé · avril</div>
            <div style={{ marginTop: 6 }}><Amount value={monthTotal} size="xl" /></div>
            <div style={{ fontSize: 11.5, color: "var(--text-subtle)", marginTop: 3 }}>{ALL.length} dépenses · TTC</div>
          </div>
          <ProgressRing size={68} thickness={14} rounded={false} segments={catSegments(ALL)} />
        </Card>

        {/* Catégorisation auto */}
        {toConfirm.length > 0 && (
          <Card variant="flat" padding="14px" style={{ border: "var(--border-thin) solid var(--line-keyline)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
              <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--oryze-mint)", border: "1px solid var(--line-keyline)" }} />
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)" }}>Catégorisation</span>
            </div>
            <div style={{ fontSize: 13.5, color: "var(--text-body)" }}>
              {ALL.length - toConfirm.length} dépenses catégorisées automatiquement. <strong>{toConfirm.length} à confirmer.</strong>
            </div>
            <button onClick={() => { setSelected(toConfirm[0]); setMode("detail"); }} style={{ marginTop: 10, border: "none", background: "none", color: "var(--text-link)", fontSize: 13.5, fontWeight: 600, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 4, fontFamily: "var(--font-sans)", padding: 0 }}>
              Vérifier maintenant <Ic.chevronRight size={15} />
            </button>
          </Card>
        )}

        {/* Category filter chips */}
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <Chip active={filter === "all"} onClick={() => setFilter("all")}>Tout</Chip>
          {Object.keys(CATS).map((k) => (
            <Chip key={k} active={filter === k} dot={CATS[k].color} onClick={() => setFilter(k)}>{CATS[k].label}</Chip>
          ))}
        </div>

        {/* List */}
        <Card variant="flat" padding="0">
          {list.map((e) => {
            const c = CATS[e.cat];
            const CatIcon = Ic[c.icon] || Ic.receipt;
            const ttc = window.OryzeExpenseCalc(e).ttc;
            return (
              <TransactionRow key={e.id} icon={<CatIcon size={18} />} iconBg={c.color}
                title={e.merchant} meta={e.date.slice(0, 5) + " · " + c.label}
                amount={-ttc} amountTone="negative" sign
                status={!e.auto ? <Tag tone="butter" dot>À confirmer</Tag> : (e.receipt === "missing" ? <Tag tone="butter" dot>Reçu manquant</Tag> : null)}
                onClick={() => { setSelected(e); setMode("detail"); }} />
            );
          })}
        </Card>
      </div>
    );
  }

  function catSegments(all) {
    const cats = window.OryzeExpenseCats;
    const totals = {};
    let sum = 0;
    all.forEach((e) => { const ttc = window.OryzeExpenseCalc(e).ttc; totals[e.cat] = (totals[e.cat] || 0) + ttc; sum += ttc; });
    return Object.keys(cats).map((k) => ({ value: sum ? (totals[k] || 0) / sum * 100 : 0, color: cats[k].color }));
  }

  function Chip({ active, dot, onClick, children }) {
    return (
      <button onClick={onClick} style={{
        display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 12px",
        borderRadius: "var(--radius-pill)", border: "1.5px solid var(--line-keyline)",
        background: active ? "var(--oryze-ink)" : "var(--surface-card)",
        color: active ? "var(--oryze-paper)" : "var(--text-body)",
        fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, cursor: "pointer",
      }}>
        {dot && <span style={{ width: 7, height: 7, borderRadius: "50%", background: dot, border: "1px solid " + (active ? "var(--oryze-paper)" : "var(--line-keyline)") }} />}
        {children}
      </button>
    );
  }

  window.OryzeApp = window.OryzeApp || {};
  window.OryzeApp.DepensesScreen = DepensesScreen;
})();
