/* ============================================================
   finance.jsx — NetWorth, Budget, Accounts
   All data comes through the api.jsx seam (fetchNetWorth /
   fetchBudget / fetchAccounts) so swapping mock → real backend
   lights up these cards automatically.
   ============================================================ */

function CardSkeleton({ lines = 3, chart }) {
  return (
    <div style={{ display: "grid", gap: 12, flex: 1 }}>
      <div className="skel" style={{ height: 38, width: "55%", borderRadius: 10 }} />
      {chart && <div className="skel" style={{ height: 120, borderRadius: 12, marginTop: 4 }} />}
      {Array.from({ length: lines }).map((_, i) => <div key={i} className="skel" style={{ height: 30, borderRadius: 9 }} />)}
    </div>
  );
}

function NetWorthWidget() {
  const [range, setRange] = useState("1J");
  const { data, error } = useAsync(() => fetchNetWorth(range), [range]);
  const [open, setOpen] = useState(false);

  return (
    <div className="card fade-in" style={{ gridRow: "span 1" }}>
      <WHead icon="chart" title="Vermogen" sub="Totaal netto vermogen" accent
        action={<>Details <Icon name="chevR" /></>} onAction={() => setOpen(true)} />
      {error ? <ModalError error={error} /> : !data ? <CardSkeleton chart lines={1} /> : (
        <>
          <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
            <div>
              <div className="big-num" style={{ fontSize: 38, lineHeight: 1 }}>{fmtEur(data.total)}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 10 }}>
                <span className={"chip " + (data.delta >= 0 ? "up" : "down")}>
                  <Icon name={data.delta >= 0 ? "arrowUp" : "arrowDn"} /> {data.delta >= 0 ? "+" : ""}{fmtEur(data.delta)}
                </span>
                <span style={{ fontSize: 13, color: "var(--text-2)", fontWeight: 600 }}>
                  {data.delta >= 0 ? "+" : ""}{data.pct.toFixed(1)}% in {range === "1M" ? "30 dagen" : range === "6M" ? "6 maanden" : "12 maanden"}
                </span>
              </div>
            </div>
            <div className="seg">
              {["1M", "6M", "1J"].map(r => (
                <button key={r} className={range === r ? "on" : ""} onClick={() => setRange(r)}>{r}</button>
              ))}
            </div>
          </div>
          <div style={{ marginTop: 18, flex: 1, minHeight: 150 }}>
            <LineChart data={data.series} height={158} />
          </div>
          {data.labels && (
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, padding: "0 4px" }}>
              {data.labels.map((l, i) => <span key={i} style={{ fontSize: 10.5, color: "var(--text-3)", fontWeight: 600 }}>{l}</span>)}
            </div>
          )}
        </>
      )}
      {open && <NetWorthDetailModal onClose={() => setOpen(false)} />}
    </div>
  );
}

function BudgetWidget() {
  const { data, error } = useAsync(() => fetchBudget(0), []);
  const [open, setOpen] = useState(false);

  const size = 116, stroke = 13, r = (size - stroke) / 2, c = 2 * Math.PI * r;

  return (
    <div className="card fade-in" style={{ animationDelay: "0.05s" }}>
      <WHead icon="wallet" title="Maandbudget" sub={data ? data.monthLabel : "Laden…"}
        action={<>Beheer <Icon name="chevR" /></>} onAction={() => setOpen(true)} />
      {error ? <ModalError error={error} /> : !data ? <CardSkeleton lines={5} /> : (() => {
        const totalSpent = data.totalSpent, totalBudget = data.totalBudget;
        const left = totalBudget - totalSpent;
        const saved = data.income - totalSpent;
        const savedPct = Math.round((saved / data.income) * 100);
        let acc = 0;
        return (
          <>
            <div style={{ display: "flex", gap: 18, alignItems: "center" }}>
              <div style={{ position: "relative", width: size, height: size, flexShrink: 0 }}>
                <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
                  <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--surface-3)" strokeWidth={stroke} />
                  {data.categories.map((b, i) => {
                    const frac = b.spent / totalBudget;
                    const dash = frac * c;
                    const off = acc * c;
                    acc += frac;
                    return <circle key={i} cx={size / 2} cy={size / 2} r={r} fill="none" stroke={b.color} strokeWidth={stroke}
                      strokeDasharray={`${dash} ${c - dash}`} strokeDashoffset={-off} />;
                  })}
                </svg>
                <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center" }}>
                  <div>
                    <div className="big-num" style={{ fontSize: 20 }}>{fmtEur(totalSpent)}</div>
                    <div style={{ fontSize: 10.5, color: "var(--text-3)", fontWeight: 600 }}>van {fmtEur(totalBudget)}</div>
                  </div>
                </div>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, color: "var(--text-2)", fontWeight: 600 }}>Nog te besteden</div>
                <div className="big-num" style={{ fontSize: 22, color: "var(--good)" }}>{fmtEur(left)}</div>
                <div style={{ marginTop: 12, padding: "10px 12px", background: "var(--accent-soft)", borderRadius: 10 }}>
                  <div style={{ fontSize: 11.5, color: "var(--text-2)", fontWeight: 600 }}>Bespaard deze maand</div>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 7 }}>
                    <span className="big-num" style={{ fontSize: 18, color: "var(--accent)" }}>{fmtEur(saved)}</span>
                    <span style={{ fontSize: 12, color: "var(--text-2)", fontWeight: 600 }}>{savedPct}% van inkomen</span>
                  </div>
                </div>
              </div>
            </div>
            <div className="divider" />
            <div style={{ display: "grid", gap: 11 }}>
              {data.categories.map((b, i) => {
                const p = b.spent / b.budget;
                const over = b.spent > b.budget;
                return (
                  <div key={i}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 5, gap: 10 }}>
                      <span style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13, fontWeight: 600, minWidth: 0, flex: 1, whiteSpace: "nowrap", overflow: "hidden" }}>
                        <span style={{ width: 8, height: 8, borderRadius: 3, background: b.color, flexShrink: 0 }} />
                        {b.name}
                      </span>
                      <span className="mono" style={{ fontSize: 12.5, color: over ? "var(--bad)" : "var(--text-2)", fontWeight: 600, flexShrink: 0 }}>
                        {fmtEur(b.spent)} <span style={{ color: "var(--text-3)" }}>/ {fmtEur(b.budget)}</span>
                      </span>
                    </div>
                    <div className="bar"><i style={{ width: `${clamp(p * 100, 3, 100)}%`, background: over ? "var(--bad)" : b.color }} /></div>
                  </div>
                );
              })}
            </div>
          </>
        );
      })()}
      {open && <BudgetDetailModal onClose={() => setOpen(false)} />}
    </div>
  );
}

function AccountsWidget() {
  const { data, error } = useAsync(() => fetchAccounts(), []);
  const [open, setOpen] = useState(false);
  const total = data ? data.reduce((s, a) => s + a.balance, 0) : 0;

  return (
    <div className="card fade-in" style={{ animationDelay: "0.1s" }}>
      <WHead icon="wallet" title="Rekeningen" sub={data ? fmtEur(total) + " totaal" : "Laden…"}
        action={<>Details <Icon name="chevR" /></>} onAction={() => setOpen(true)} />
      {error ? <ModalError error={error} /> : !data ? <CardSkeleton lines={4} /> : (
        <div style={{ display: "grid", gap: 9, flex: 1 }}>
          {data.map((a) => (
            <button key={a.id} onClick={() => setOpen(true)}
              style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: 12, background: "var(--surface-2)", border: "1px solid var(--border)", textAlign: "left", transition: "border-color .15s" }}
              className="acc-mini">
              <div style={{ width: 36, height: 36, borderRadius: 10, background: a.color, color: "#fff", display: "grid", placeItems: "center", flexShrink: 0 }}>
                <Icon name={a.icon} width="18" height="18" />
              </div>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.name}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)", fontWeight: 600 }}>{a.bank}</div>
              </div>
              <div className="big-num" style={{ fontSize: 15, fontWeight: 600 }}>{fmtEur(a.balance, 2)}</div>
            </button>
          ))}
        </div>
      )}
      {open && <AccountsDetailModal onClose={() => setOpen(false)} />}
    </div>
  );
}

Object.assign(window, { NetWorthWidget, BudgetWidget, AccountsWidget });
