// Dashboard — Dépenses (table + catégorisation). window.OryzeDash.DepensesView
(function () {
  const { Card, Amount, Tag, Button, Input, ProgressRing, InsightCard, ReceiptThumb, EmptyState } = window.OryzeDesignSystem_78c60a;
  const Ic = window.OryzeIcons;
  const CATS = window.OryzeExpenseCats;

  function DepensesView({ onOpen, demoState = "normal" }) {
    const ALL = window.OryzeExpenses;
    const [filter, setFilter] = React.useState("all");
    const [q, setQ] = React.useState("");

    // ---- États démo : chargement / vide / erreur (patterns guidelines/states.html) ----
    const { ErrorState, SkelListCard, SkelBlockCard } = window.OryzeShared;
    if (demoState === "empty") {
      return (
        <EmptyState framed title="Aucune dépense ce mois-ci"
          description="Vos opérations apparaîtront ici, catégorisées automatiquement — vous gardez la main sur chaque catégorie."
          action={<Button size="sm" variant="secondary" iconLeft={<Ic.plus size={15} />}>Ajouter une dépense</Button>} />
      );
    }
    if (demoState === "loading") {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 16 }}>
            <SkelBlockCard height={120} />
            <SkelBlockCard height={120} />
          </div>
          <SkelListCard rows={6} avatar={false} />
        </div>
      );
    }
    if (demoState === "error") {
      return <ErrorState what="Impossible de charger vos dépenses" endpoint="GET /depenses · 503 · réf. f4b3-…" />;
    }

    const list = ALL
      .filter((e) => (filter === "all" ? true : e.cat === filter))
      .filter((e) => e.merchant.toLowerCase().includes(q.toLowerCase()) || e.id.toLowerCase().includes(q.toLowerCase()));
    const monthTotal = window.OryzeExpenseAprilTTC; // 3 110,00 € canonique (= Décaissé · avril)
    const toConfirm = ALL.filter((e) => !e.auto);

    // category totals (TTC)
    const totals = {}; ALL.forEach((e) => { totals[e.cat] = (totals[e.cat] || 0) + window.OryzeExpenseCalc(e).ttc; });
    const ttcSum = Object.values(totals).reduce((a, v) => a + v, 0);

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {/* Top: total donut + categorisation */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 16 }}>
          <Card variant="flat" padding="20px" style={{ display: "flex", alignItems: "center", gap: 18 }}>
            <ProgressRing size={120} thickness={22} rounded={false}
              label={fmtK(monthTotal)} sublabel="avril · TTC"
              segments={Object.keys(CATS).map((k) => ({ value: ttcSum ? (totals[k] || 0) / ttcSum * 100 : 0, color: CATS[k].color }))} />
            <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 7 }}>
              {Object.keys(CATS).map((k) => (
                <div key={k} style={{ display: "flex", alignItems: "center", gap: 9 }}>
                  <span style={{ width: 8, height: 8, flex: "none", borderRadius: "50%", background: CATS[k].color, border: "1px solid var(--line-keyline)" }} />
                  <span style={{ flex: 1, minWidth: 0, fontSize: 13, color: "var(--text-body)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{CATS[k].label}</span>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", flex: "none" }}>{pctLabel((totals[k] || 0), ttcSum)}</span>
                </div>
              ))}
            </div>
          </Card>

          <InsightCard capability="categorisation" title={`${ALL.length - toConfirm.length} dépenses catégorisées automatiquement`}
            primaryAction={toConfirm.length > 0 ? <Button size="sm" onClick={() => onOpen && onOpen(toConfirm[0])}>Vérifier ({toConfirm.length})</Button> : <Button size="sm" variant="ghost">Tout est à jour</Button>}>
            On range vos opérations par catégorie (Charges fixes · Achats & SaaS · Déplacements · Frais pro).
            {toConfirm.length > 0 ? " Une dépense reste à confirmer." : ""}
          </InsightCard>
        </div>

        {/* Toolbar */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
          <Input placeholder="Rechercher un marchand, une référence…" value={q} onChange={(e) => setQ(e.target.value)} iconLeft={<Ic.search size={18} />} style={{ flex: 1, maxWidth: 380 }} />
          <Button iconLeft={<Ic.plus size={16} />}>Ajouter une dépense</Button>
        </div>

        {/* 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>

        {/* Table */}
        <Card variant="flat" padding="0">
          <div style={{ display: "grid", gridTemplateColumns: "2fr 1.4fr 1fr 64px 1fr", gap: 12, padding: "11px 18px", borderBottom: "1.5px solid var(--line-keyline)", background: "var(--surface-page)" }}>
            {["Marchand", "Catégorie", "Date", "Reçu", "Montant TTC"].map((h, i) => (
              <div key={i} style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--text-muted)", textAlign: i === 4 ? "right" : i === 3 ? "center" : "left" }}>{h}</div>
            ))}
          </div>
          {list.map((e) => <Row key={e.id} e={e} onOpen={onOpen} />)}
          {list.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--text-muted)", fontSize: 14 }}>Aucune dépense ne correspond.</div>}
        </Card>
      </div>
    );
  }

  function Row({ e, onOpen }) {
    const [h, setH] = React.useState(false);
    const c = CATS[e.cat];
    const CatIcon = Ic[c.icon] || Ic.receipt;
    const ttc = window.OryzeExpenseCalc(e).ttc;
    return (
      <div onClick={() => onOpen && onOpen(e)} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
        style={{ display: "grid", gridTemplateColumns: "2fr 1.4fr 1fr 64px 1fr", gap: 12, padding: "11px 18px", borderBottom: "1px solid var(--line-divider)", alignItems: "center", cursor: "pointer", background: h ? "var(--surface-page)" : "transparent", transition: "background var(--dur-fast) var(--ease-out)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, minWidth: 0 }}>
          <span style={{ width: 32, height: 32, flex: "none", borderRadius: "var(--radius-sm)", background: c.color, border: "var(--border-thin) solid var(--line-keyline)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-strong)" }}><CatIcon size={16} /></span>
          <span style={{ fontWeight: 600, fontSize: 14, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{e.merchant}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, minWidth: 0 }}>
          <Tag tone="neutral" dot>{c.label}</Tag>
          {!e.auto && <Tag tone="butter">À confirmer</Tag>}
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--text-muted)" }}>{e.date.slice(0, 5)}</div>
        <div style={{ display: "flex", justifyContent: "center" }}>
          {e.receipt === "attached" ? <Ic.check size={17} style={{ color: "var(--fin-positive-text)" }} /> : <Ic.alert size={16} style={{ color: "var(--oryze-warning-ink)" }} />}
        </div>
        <div style={{ textAlign: "right" }}><Amount value={-ttc} size="md" tone="negative" sign /></div>
      </div>
    );
  }

  function fmtK(n) { return (n / 1000).toFixed(1).replace(".", ",") + " k€"; }
  function pctLabel(amt, total) {
    if (!total) return "0 %";
    const p = amt / total * 100;
    return (p > 0 && p < 1) ? "<1 %" : Math.round(p) + " %";
  }

  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.OryzeDash = window.OryzeDash || {};
  window.OryzeDash.DepensesView = DepensesView;
})();
