/* Driftwood — Reports & analytics screen */
function ScreenReports({ openAdd, txns }) {
  const { usd, ytd, months, budget } = window.FP;
  const names = window.useMemberNames();
  const txList = txns || window.FP.transactions;
  const byPerson = names.map((who) => ({
    who,
    amount: txList.filter((t) => t.who === who && t.amount < 0).reduce((s, t) => s + Math.abs(t.amount), 0),
  }));
  const segs = budget.categories.map((c) => ({ label: c.name, value: c.actual, color: PALETTE[c.color] }));
  const personColors = ["var(--blue)", "var(--violet)", "var(--teal)", "var(--amber)", "var(--sky)", "var(--pink)"];
  const personTotal = byPerson.reduce((s, p) => s + p.amount, 0);
  const avgSavings = Math.round(ytd.savings / months.length);
  const savingsRate = Math.round((ytd.savings / ytd.income) * 100);

  return (
    <>
      <ScreenHeader title="Reports" sub="Year to date · 2026">
        <div className="seg"><button>Month</button><button className="on">YTD</button><button>All</button></div>
        <button className="btn btn-ghost" onClick={() => window.exportReportsXLSX && window.exportReportsXLSX()}><Icon name="reports" /> Export to Excel</button>
      </ScreenHeader>

      <div className="content">
        {/* YTD roll-ups */}
        <div className="grid g4">
          {[
            ["YTD income", usd(ytd.income), "var(--green)", "income"],
            ["YTD expenses", usd(ytd.expenses), "var(--blue)", "transactions"],
            ["YTD saved", usd(ytd.savings), "var(--violet)", "goals"],
            ["Savings rate", `${savingsRate}%`, "var(--amber)", "reports"],
          ].map(([l, v, c, ic]) => (
            <div className="stat" key={l}>
              <div className="stat-ico" style={{ background: `color-mix(in oklch, ${c} 18%, transparent)`, color: c }}><Icon name={ic} /></div>
              <div className="stat-label">{l}</div>
              <div className="num stat-val">{v}</div>
            </div>
          ))}
        </div>

        {/* Income vs expenses chart */}
        <div className="card">
          <div className="card-head">
            <h2>Income vs expenses</h2>
            <div style={{ display: "flex", gap: 18, fontSize: 13 }}>
              <span style={{ color: "var(--mid)" }}><span className="dot" style={{ background: "var(--green)", marginRight: 7, display: "inline-block" }} />Income</span>
              <span style={{ color: "var(--mid)" }}><span className="dot" style={{ background: "var(--blue-soft)", marginRight: 7, display: "inline-block" }} />Expenses</span>
            </div>
          </div>
          <AreaChart data={months} />
        </div>

        {/* Spending by person + by category */}
        <div className="grid g2">
          <div className="card">
            <div className="card-head"><h2>Spending by person</h2><span className="chip">This month</span></div>
            <div style={{ display: "flex", flexDirection: "column", gap: 22, marginTop: 6 }}>
              {byPerson.map((p, i) => {
                const pct = personTotal ? Math.round((p.amount / personTotal) * 100) : 0;
                const pc = personColors[i % personColors.length];
                return (
                  <div key={p.who}>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                        <span className="avs"><span style={{ background: pc, marginLeft: 0 }}>{window.initialsOf(p.who)}</span></span>
                        <span style={{ fontWeight: 500 }}>{p.who}</span>
                      </div>
                      <div className="num" style={{ fontWeight: 600, fontSize: 16 }}>{usd(p.amount)} <span style={{ color: "var(--dim)", fontWeight: 400, fontSize: 13 }}>· {pct}%</span></div>
                    </div>
                    <div className="bar lg"><span style={{ width: `${pct}%`, background: pc }} /></div>
                  </div>
                );
              })}
              <div style={{ display: "flex", justifyContent: "space-between", paddingTop: 16, borderTop: "1px solid var(--line)", fontSize: 14 }}>
                <span style={{ color: "var(--mid)" }}>Combined this month</span>
                <span className="num" style={{ fontWeight: 700 }}>{usd(personTotal)}</span>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-head"><h2>Top categories</h2><span className="chip">This month</span></div>
            <div style={{ display: "flex", flexDirection: "column", gap: 15, marginTop: 6 }}>
              {[...segs].sort((a, b) => b.value - a.value).slice(0, 6).map((s) => {
                const max = Math.max(...segs.map((x) => x.value));
                return (
                  <div key={s.label} style={{ display: "flex", alignItems: "center", gap: 14 }}>
                    <span style={{ width: 92, fontSize: 13.5, color: "var(--mid)", flexShrink: 0 }}>{s.label}</span>
                    <div className="bar" style={{ flex: 1 }}><span style={{ width: `${(s.value / max) * 100}%`, background: s.color }} /></div>
                    <span className="num" style={{ width: 64, textAlign: "right", fontWeight: 600, fontSize: 13.5 }}>{usd(s.value)}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Insight band */}
        <div className="card" style={{ display: "flex", alignItems: "center", gap: 20 }}>
          <div style={{ width: 46, height: 46, borderRadius: 13, background: "color-mix(in oklch, var(--green) 18%, transparent)", color: "var(--green)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="arrowUp" /></div>
          <div style={{ fontSize: 14.5, color: "var(--mid)", lineHeight: 1.5 }}>
            You're saving an average of <b style={{ color: "var(--hi)" }} className="num">{usd(avgSavings)}/month</b> this year — a <b style={{ color: "var(--pos)" }}>{savingsRate}% savings rate</b>. At this pace you'll add <b style={{ color: "var(--hi)" }} className="num">{usd(avgSavings * 12)}</b> to your net worth over 12 months.
          </div>
        </div>
      </div>
    </>
  );
}
window.ScreenReports = ScreenReports;
