/* Driftwood — Dashboard screen */
function ScreenDashboard({ nav, openAdd, txns }) {
  const { usd, netWorth } = window.FP; // netWorth.cash/investments/retirement have no edit UI — keep static

  const names = window.useMemberNames();
  const [people] = window.useMembers();
  const [cats]  = window.usePersist("budgets", () => window.FP.budget.categories.map((c) => ({ name: c.name, planned: c.planned, color: c.color })));
  const [bills] = window.usePersist("bills",   () => window.FP.bills.map((b) => ({ ...b })));
  const [goals] = window.usePersist("goals",   () => window.FP.goals.map((g, i) => ({ ...g, color: g.color || ["teal","violet","amber","sky","pink","green"][i%6] })));
  const [debts] = window.usePersist("debts",   () => window.FP.debts.map((d) => ({ ...d })));

  // Derive combined monthly net take-home from live member data (same logic as screen-income.jsx)
  const FREQS_MAP = { weekly: 52, biweekly: 26, semimonthly: 24, monthly: 12, annual: 1 };
  const combinedMonthly = Math.round(
    people.reduce((s, p) => {
      const gross = (parseFloat(p.amount) || 0) * (FREQS_MAP[p.freq] || 26);
      return s + gross * (1 - p.tax / 100);
    }, 0) / 12
  );

  // Compute per-category actual spend from transactions (same pattern as screen-budgets.jsx)
  const CAT_ALIAS = { healthcare: "health" };
  const catKey = (s) => { const n = (s || "").trim().toLowerCase(); return CAT_ALIAS[n] || n; };
  const spendByCat = {};
  (txns || window.FP.transactions).forEach((t) => {
    if (t.amount < 0) { const k = catKey(t.cat); spendByCat[k] = (spendByCat[k] || 0) + Math.abs(t.amount); }
  });
  const actualOf = (c) => spendByCat[catKey(c.name)] || 0;

  const segs         = cats.slice(0, 6).map((c) => ({ label: c.name, value: actualOf(c), color: PALETTE[c.color] }));
  const spentToDate  = cats.reduce((s, c) => s + actualOf(c), 0);
  const plannedSpend = cats.reduce((s, c) => s + c.planned, 0);

  // Net worth: assets static (no edit UI), debt from live debts
  const debtTotal     = debts.reduce((s, d) => s + d.balance, 0);
  const assets        = netWorth.cash + netWorth.investments + netWorth.retirement;
  const netWorthTotal = assets - debtTotal;

  const cashFlow    = combinedMonthly - plannedSpend;
  const savingsRate = combinedMonthly > 0 ? Math.round((cashFlow / combinedMonthly) * 100) : 0;
  const billsTotal  = bills.reduce((s, b) => s + b.amount, 0);

  const currentMonth = new Date().toLocaleString("en-US", { month: "long", year: "numeric" });

  const stats = [
    { label: "Monthly income",  val: usd(combinedMonthly),          foot: "Combined · net take-home",    color: "var(--green)",  icon: "income"  },
    { label: "Net cash flow",   val: usd(cashFlow, { sign: true }),  foot: "vs planned spend",            color: "var(--blue)",   icon: "arrowUp", up: cashFlow >= 0 },
    { label: "Savings rate",    val: `${savingsRate}%`,              foot: "Goal: 30%",                   color: "var(--violet)", icon: "goals"   },
    { label: "Bills due",       val: usd(billsTotal),                foot: `${bills.length} this month`,  color: "var(--amber)",  icon: "bills"   },
  ];

  return (
    <>
      <ScreenHeader title={window.householdLabel(names)} sub={`Your shared finances · ${currentMonth}`}>
        <div className="seg"><button>Month</button><button className="on">Year</button><button>All</button></div>
        <div className="avs">{names.slice(0, 4).map((n, i) => <span key={i}>{window.initialsOf(n)}</span>)}</div>
        <button className="btn btn-primary" onClick={openAdd}><Icon name="plus" /> Add Entry</button>
      </ScreenHeader>

      <div className="content">
        {/* Hero + donut */}
        <div className="grid" style={{ gridTemplateColumns: "1fr 1.12fr" }}>
          <div style={{ borderRadius: "var(--r-lg)", padding: "32px 34px", position: "relative", overflow: "hidden",
            background: "linear-gradient(140deg, var(--hero-from), var(--hero-to))", border: "1px solid var(--hero-border)" }}>
            <div style={{ fontSize: 14, color: "oklch(0.86 0.04 262)" }}>Total net worth</div>
            <div className="num" style={{ fontSize: 56, fontWeight: 700, letterSpacing: "-0.04em", lineHeight: 1.05, margin: "10px 0 6px" }}>{usd(netWorthTotal)}</div>
            <div style={{ fontSize: 14, color: "oklch(0.86 0.14 158)", fontWeight: 500, display: "flex", alignItems: "center", gap: 6 }}>
              <Icon name="wallet" style={{ width: 15, height: 15 }} /> Assets minus tracked debt
            </div>
            <div style={{ display: "flex", gap: 30, marginTop: 36 }}>
              <div style={{ fontSize: 14, color: "oklch(0.88 0.03 262)" }}><span className="dot" style={{ background: "var(--teal)", marginRight: 7, display: "inline-block" }} /> Assets<div className="num" style={{ fontSize: 20, fontWeight: 600, color: "#fff", marginTop: 4 }}>{usd(assets)}</div></div>
              <div style={{ fontSize: 14, color: "oklch(0.88 0.03 262)" }}><span className="dot" style={{ background: "var(--rose)", marginRight: 7, display: "inline-block" }} /> Debt<div className="num" style={{ fontSize: 20, fontWeight: 600, color: "#fff", marginTop: 4 }}>{usd(debtTotal)}</div></div>
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h2>Spending this month</h2><span className="link" onClick={() => nav("budgets")}>Budgets →</span></div>
            <div style={{ display: "flex", alignItems: "center", gap: 28 }}>
              <div style={{ position: "relative", flexShrink: 0 }}>
                <Donut segments={segs} />
                <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
                  <span className="num" style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.03em" }}>{usd(spentToDate)}</span>
                  <span style={{ fontSize: 12.5, color: "var(--dim)" }}>of {usd(plannedSpend)}</span>
                </div>
              </div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gridTemplateColumns: "1fr 1fr", gap: "11px 22px", flex: 1 }}>
                {segs.map((s) => (
                  <li key={s.label} style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: "var(--mid)" }}>
                    <span className="dot" style={{ background: s.color, marginRight: 2, flexShrink: 0 }} />
                    <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.label}</span>
                    <b className="num" style={{ color: "var(--hi)", fontWeight: 600, flexShrink: 0 }}>{usd(s.value)}</b>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>

        {/* Stat tiles */}
        <div className="grid g4">
          {stats.map((s) => (
            <div className="stat" key={s.label}>
              <div className="stat-ico" style={{ background: `color-mix(in oklch, ${s.color} 18%, transparent)`, color: s.color }}><Icon name={s.icon} /></div>
              <div className="stat-label">{s.label}</div>
              <div className="num stat-val">{s.val}</div>
              <div className="stat-foot">{s.foot}</div>
            </div>
          ))}
        </div>

        {/* Recent transactions + goals */}
        <div className="grid" style={{ gridTemplateColumns: "1.3fr 1fr" }}>
          <div className="card">
            <div className="card-head"><h2>Recent activity</h2><span className="link" onClick={() => nav("transactions")}>View all →</span></div>
            <table className="tbl">
              <tbody>
                {txns.slice(0, 6).map((t, i) => (
                  <tr key={i}>
                    <td><div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                      <span className="dot" style={{ width: 30, height: 30, borderRadius: 9, background: `color-mix(in oklch, ${PALETTE[t.color]} 20%, transparent)`, display: "flex", alignItems: "center", justifyContent: "center", color: PALETTE[t.color], fontSize: 13, fontWeight: 700 }}>{t.merchant[0]}</span>
                      <div><div style={{ fontWeight: 500 }}>{t.merchant}</div><div style={{ fontSize: 12, color: "var(--dim)" }}>{t.cat} · {t.who}</div></div>
                    </div></td>
                    <td style={{ color: "var(--dim)", fontSize: 13 }}>{t.date}</td>
                    <td className="num" style={{ fontWeight: 600, color: t.amount > 0 ? "var(--pos)" : "var(--hi)" }}>{usd(t.amount, { cents: true, sign: t.amount > 0 })}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="card">
            <div className="card-head"><h2>Goals</h2><span className="link" onClick={() => nav("goals")}>All →</span></div>
            <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              {goals.slice(0, 4).map((g, i) => {
                const colors = ["var(--teal)", "var(--violet)", "var(--amber)", "var(--sky)"];
                const goalColor = g.color ? `var(--${g.color})` : colors[i % colors.length];
                const pct = Math.round((g.saved / g.target) * 100);
                return (
                  <div key={g.name}>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, marginBottom: 8 }}>
                      <span style={{ fontWeight: 500 }}>{g.name}</span>
                      <span className="num" style={{ color: goalColor, fontWeight: 600 }}>{pct}%</span>
                    </div>
                    <div className="bar"><span style={{ width: `${pct}%`, background: goalColor }} /></div>
                    <div className="num" style={{ fontSize: 12, color: "var(--dim)", marginTop: 7 }}>{usd(g.saved)} of {usd(g.target)}</div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
window.ScreenDashboard = ScreenDashboard;
