// hydor-page-dashboard.jsx — Dashboard (Layout A) + analytics. Uses hydor-charts.jsx globals.
function DashboardPage({ onDrill, goTo }) {
  const s = useHydor();
  const d = useDerive();
  const [year, setYear] = React.useState(null);
  const [q, setQ] = React.useState(null); // null=full, 0-3

  const years = d.yearList.length ? d.yearList : [new Date().getFullYear()];
  const yr = year || years[years.length - 1];
  const qkeys = [1, 2, 3, 4].map((n) => yr + "-Q" + n);
  const qData = qkeys.map((k) => d.quarters[k] || { sales: 0, cogs: 0, gp: 0, fixed: 0, op: 0, costs: 0, net: 0, allocAmt: 0, alloc: 0, margin: 0, units: 0, txns: 0 });

  // year aggregate
  const yAgg = qData.reduce((a, x) => ({
    sales: a.sales + x.sales, cogs: a.cogs + x.cogs, gp: a.gp + x.gp, fixed: a.fixed + x.fixed,
    op: a.op + x.op, costs: a.costs + x.costs, net: a.net + x.net, allocAmt: a.allocAmt + x.allocAmt,
    units: a.units + x.units, txns: a.txns + x.txns,
  }), { sales: 0, cogs: 0, gp: 0, fixed: 0, op: 0, costs: 0, net: 0, allocAmt: 0, units: 0, txns: 0 });
  yAgg.margin = yAgg.sales ? yAgg.gp / yAgg.sales : 0;
  yAgg.alloc = yAgg.net > 10000 ? 7 : yAgg.net > 5000 ? 5 : 0;
  const view = q === null ? yAgg : qData[q];

  // monthly sales for the selected year
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  const monthly = new Array(12).fill(0);
  s.transactions.filter((t) => !t.deleted && t.type === "sale" && Hydor.yearOf(t.date) === yr)
    .forEach((t) => { monthly[new Date(t.date).getMonth()] += (d.txc[t.id] || {}).subtotal || 0; });
  const monthlyK = monthly.map((m) => m / 1000);

  const hasData = d.totals.txns > 0 || s.transactions.some((t) => !t.deleted);

  if (!hasData) {
    return (
      <div className="content-narrow">
        <div className="hx-panel">
          <Empty icon="dashboard" title="Your dashboard is waiting for data"
            action={<div style={{ display: "flex", gap: 10 }}>
              <Btn variant="primary" icon="plus" onClick={() => goTo("products")}>Add a product</Btn>
              <Btn icon="ledger" onClick={() => goTo("transactions")}>Record a sale</Btn>
            </div>}>
            Once you record purchases and sales, HYDOR computes sales, gross &amp; net profit, cost structure, quarterly trends and employee performance — all here, live.
          </Empty>
        </div>
      </div>
    );
  }

  return (
    <div>
      {/* header w/ selectors */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20, flexWrap: "wrap", gap: 12 }}>
        <div className="hx-seg">
          <button className={q === null ? "on" : ""} onClick={() => setQ(null)}>Full Year</button>
          {["Q1", "Q2", "Q3", "Q4"].map((x, i) => <button key={i} className={q === i ? "on" : ""} onClick={() => setQ(i)}>{x}</button>)}
        </div>
        {years.length > 1 && (
          <select className="sel" style={{ width: 120 }} value={yr} onChange={(e) => { setYear(+e.target.value); }}>
            {years.map((y) => <option key={y} value={y}>{y}</option>)}
          </select>
        )}
      </div>

      {/* KPI row */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14, marginBottom: 14 }}>
        <KPICard label="Total Sales" value={Hydor.fmtMoney0(view.sales)} unit=" JOD" accent="var(--accent)" spark={monthlyK} sub="click to drill"
          onClick={() => onDrill({ type: "salesDrill", year: yr, q })} />
        <KPICard label="Gross Profit" value={Hydor.fmtMoney0(view.gp)} unit=" JOD" accent="var(--accent-2)" sub={Hydor.fmtPct(view.margin) + " margin"} />
        <KPICard label="Net Profit" value={Hydor.fmtMoney0(view.net)} unit=" JOD" accent={view.net >= 0 ? "var(--pos)" : "var(--neg)"} sub={(view.sales ? (view.net / view.sales * 100).toFixed(1) : "0.0") + "% of sales"} />
        <KPICard label="Dev. Allocation" value={Hydor.fmtMoney0(view.allocAmt)} unit=" JOD" accent="var(--accent-3)" sub={(view.alloc || 0) + "% of net profit"} />
      </div>

      {/* charts row */}
      <div style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: 14, marginBottom: 14 }}>
        <div className="hx-panel hx-panel-pad">
          <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 14 }}>
            <div><div className="hx-eyebrow">Revenue</div><h3 className="hx-h2" style={{ marginTop: 5 }}>Monthly Sales · {yr}</h3></div>
            <div className="hx-legend"><span><i style={{ background: "var(--accent)" }} />Sales (k JOD)</span></div>
          </div>
          {monthly.some((m) => m > 0)
            ? <AreaChart data={monthlyK} labels={months} h={232} yfmt={(n) => n.toFixed(0) + "k"} valueFmt={(v) => Hydor.fmtMoney0(v * 1000)} unit=" JOD" />
            : <div style={{ height: 232, display: "grid", placeItems: "center", color: "var(--text-3)", fontSize: 13 }}>No sales in {yr}</div>}
        </div>
        <div className="hx-panel hx-panel-pad">
          <div className="hx-eyebrow" style={{ marginBottom: 4 }}>Cost Structure</div>
          <h3 className="hx-h2" style={{ marginBottom: 18 }}>Where the money goes</h3>
          <CostDonut view={view} />
        </div>
      </div>

      {/* tables row */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="hx-panel hx-panel-pad">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
            <h3 className="hx-h2">Quarterly Performance · {yr}</h3>
          </div>
          <table className="hx-table">
            <thead><tr><th>Quarter</th><th className="r">Sales</th><th className="r">Gross</th><th className="r">Costs</th><th className="r">Net</th></tr></thead>
            <tbody>
              {qData.map((x, i) => (
                <tr key={i} className={"clickrow" + (q === i ? "" : "")} onClick={() => setQ(i)} style={q === i ? { background: "var(--accent-soft)" } : null}>
                  <td style={{ fontWeight: 600 }}>Q{i + 1}</td>
                  <td className="r num">{Hydor.fmtMoney0(x.sales)}</td>
                  <td className="r num">{Hydor.fmtMoney0(x.gp)}</td>
                  <td className="r num" style={{ color: "var(--text-2)" }}>{Hydor.fmtMoney0(x.costs)}</td>
                  <td className="r num" style={{ color: x.net >= 0 ? "var(--pos)" : "var(--neg)" }}>{Hydor.fmtMoney0(x.net)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="hx-panel hx-panel-pad">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
            <h3 className="hx-h2">Employee Performance</h3>
            <span className="hx-sub" style={{ fontSize: 11.5 }}>actual vs recommended</span>
          </div>
          {d.employees.length === 0 ? <div style={{ padding: "30px 0", textAlign: "center", color: "var(--text-3)", fontSize: 13 }}>No sales recorded yet</div> : (
            <table className="hx-table">
              <thead><tr><th>Staff</th><th className="r">Sales</th><th className="r">Profit</th><th style={{ width: 150 }}>vs Recommended</th></tr></thead>
              <tbody>
                {d.employees.map((e) => (
                  <tr key={e.code} className="clickrow" onClick={() => onDrill({ type: "employee", code: e.code })}>
                    <td><EmpBadge code={e.code} /></td>
                    <td className="r num">{Hydor.fmtMoney0(e.sales)}</td>
                    <td className="r num hx-pos">{Hydor.fmtMoney0(e.gp)}</td>
                    <td><PerfBar value={e.perf} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}

function CostDonut({ view }) {
  const segs = [
    { label: "COGS", value: view.cogs, color: "var(--accent)" },
    { label: "Fixed costs", value: view.fixed, color: "var(--accent-3)" },
    { label: "Operational", value: view.op, color: "var(--accent-2)" },
    { label: "Net profit", value: Math.max(view.net, 0), color: "var(--pos)" },
  ];
  const total = segs.reduce((a, x) => a + x.value, 0);
  if (total <= 0) return <div style={{ height: 150, display: "grid", placeItems: "center", color: "var(--text-3)", fontSize: 13 }}>No data for this period</div>;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 22 }}>
      <Donut size={150} thickness={22} data={segs} />
      <div style={{ display: "flex", flexDirection: "column", gap: 11, flex: 1 }}>
        {segs.map((sg) => (
          <div key={sg.label} style={{ display: "flex", alignItems: "center", gap: 9 }}>
            <i style={{ width: 9, height: 9, borderRadius: 3, background: sg.color, display: "inline-block", flex: "none" }} />
            <span style={{ fontSize: 12.5, color: "var(--text-2)", flex: 1 }}>{sg.label}</span>
            <span className="hx-num" style={{ fontSize: 12.5 }}>{Hydor.fmtMoney0(sg.value)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { DashboardPage });
