// hydor-page-analytics.jsx — deep analytics: ABC/Pareto, dead stock, group-by explorer, compare.
function AnalyticsPage({ onDrill }) {
  const s = useHydor();
  const d = useDerive();
  const [tab, setTab] = React.useState("pareto");
  return (
    <div>
      <div className="tabs">
        {[["pareto", "ABC / Pareto"], ["groupby", "Group-by explorer"], ["compare", "Compare periods"], ["dead", "Dead stock"]].map(([k, l]) => (
          <button key={k} className={"tab" + (tab === k ? " on" : "")} onClick={() => setTab(k)}>{l}</button>
        ))}
      </div>
      {tab === "pareto" && <ParetoView s={s} d={d} onDrill={onDrill} />}
      {tab === "groupby" && <GroupByView s={s} d={d} />}
      {tab === "compare" && <CompareView s={s} d={d} />}
      {tab === "dead" && <DeadStockView s={s} d={d} onDrill={onDrill} />}
    </div>
  );
}

/* ---------- ABC / Pareto ---------- */
function ParetoView({ s, d, onDrill }) {
  const rows = s.products.map((p) => ({ p, st: d.productStats[p.id] }))
    .filter((r) => r.st.profit > 0).sort((a, b) => b.st.profit - a.st.profit);
  if (!rows.length) return <div className="hx-panel"><Empty icon="chart" title="Not enough data">Record some sales to see which products drive your profit.</Empty></div>;
  const totalProfit = rows.reduce((a, r) => a + r.st.profit, 0);
  let cum = 0;
  const withCum = rows.map((r) => { cum += r.st.profit; return { ...r, cumPct: cum / totalProfit }; });
  const counts = { A: 0, B: 0, C: 0 };
  rows.forEach((r) => counts[r.st.abc] != null && counts[r.st.abc]++);

  return (
    <div>
      <div className="stat-strip" style={{ gridTemplateColumns: "repeat(3,1fr)" }}>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--pos)" }}><div className="ms-label">Class A</div><div className="ms-value">{counts.A}</div><div className="ms-sub">top ~80% of profit</div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--accent)" }}><div className="ms-label">Class B</div><div className="ms-value">{counts.B}</div><div className="ms-sub">next ~15%</div></div>
        <div className="mini-stat"><div className="ms-label">Class C</div><div className="ms-value">{counts.C}</div><div className="ms-sub">tail ~5%</div></div>
      </div>
      <div className="hx-panel hx-panel-pad">
        <h3 className="hx-h2" style={{ marginBottom: 4 }}>Profit concentration</h3>
        <p className="hx-sub" style={{ marginBottom: 18 }}>Which products generate the most profit — your vital few vs. trivial many. Click any row to drill in.</p>
        <table className="hx-table">
          <thead><tr><th>#</th><th>Product</th><th>Class</th><th className="r">Profit</th><th className="r">Share</th><th className="r">Cumulative</th><th style={{ width: 180 }}>Contribution</th></tr></thead>
          <tbody>
            {withCum.map((r, i) => (
              <tr key={r.p.id} className="clickrow" onClick={() => onDrill({ type: "product", id: r.p.id })}>
                <td className="num" style={{ color: "var(--text-3)" }}>{i + 1}</td>
                <td><span className="hx-code">{r.p.code}</span> <span style={{ fontSize: 12.5, color: "var(--text-2)" }}>{r.p.name}</span></td>
                <td><span className={"abc " + r.st.abc}>{r.st.abc}</span></td>
                <td className="r num hx-pos">{Hydor.fmtMoney0(r.st.profit)}</td>
                <td className="r num" style={{ color: "var(--text-2)" }}>{Hydor.fmtPct(r.st.profit / totalProfit)}</td>
                <td className="r num">{Hydor.fmtPct(r.cumPct)}</td>
                <td><div className="hx-progress"><i style={{ width: (r.st.profit / withCum[0].st.profit * 100) + "%" }} /></div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ---------- Group-by explorer (pivot) ---------- */
function GroupByView({ s, d }) {
  const [dim, setDim] = React.useState("product");
  const [metric, setMetric] = React.useState("profit");
  const sales = s.transactions.filter((t) => !t.deleted && t.type === "sale");
  const pname = (id) => { const p = s.products.find((x) => x.id === id); return p ? p.code + " · " + p.name : "—"; };
  const partyName = (id) => { const p = s.parties.find((x) => x.id === id); return p ? p.name : "(no customer)"; };
  const keyOf = (t) => {
    if (dim === "product") return pname(t.productId);
    if (dim === "employee") return t.employee ? "Employee " + t.employee : "(unassigned)";
    if (dim === "customer") return partyName(t.partyId);
    if (dim === "month") return new Date(t.date).toLocaleDateString("en-GB", { month: "short", year: "numeric" });
    if (dim === "quarter") return Hydor.qKey(t.date);
    return "—";
  };
  const groups = {};
  sales.forEach((t) => {
    const c = d.txc[t.id] || {}; const k = keyOf(t);
    const g = groups[k] || (groups[k] = { key: k, sales: 0, profit: 0, qty: 0, txns: 0 });
    g.sales += c.subtotal || 0; g.profit += c.profit || 0; g.qty += t.qty; g.txns += 1;
  });
  const metricKey = { sales: "sales", profit: "profit", units: "qty", orders: "txns" }[metric];
  const arr = Object.values(groups).sort((a, b) => b[metricKey] - a[metricKey]);
  const max = arr.length ? arr[0][metricKey] : 1;
  const fmtM = (v) => metric === "units" || metric === "orders" ? Hydor.fmtQty(v) : Hydor.fmtMoney0(v);

  return (
    <div>
      <p className="hx-sub" style={{ marginBottom: 14 }}>Slice your sales by any dimension and measure. Pick what to group by, then what to measure — like a built-in pivot table.</p>
      <div className="toolbar">
        <span style={{ fontSize: 12.5, color: "var(--text-3)" }}>Group by</span>
        <div className="chip-row">
          {[["product", "Product"], ["employee", "Employee"], ["customer", "Customer"], ["month", "Month"], ["quarter", "Quarter"]].map(([k, l]) =>
            <button key={k} className={"chip" + (dim === k ? " on" : "")} onClick={() => setDim(k)}>{l}</button>)}
        </div>
        <div className="grow" />
        <span style={{ fontSize: 12.5, color: "var(--text-3)" }}>Measure</span>
        <select className="sel" style={{ width: 130 }} value={metric} onChange={(e) => setMetric(e.target.value)}>
          <option value="profit">Profit</option><option value="sales">Sales</option><option value="units">Units</option><option value="orders">Orders</option>
        </select>
      </div>
      <div className="hx-panel" style={{ overflow: "hidden" }}>
        {arr.length === 0 ? <Empty icon="layers" title="No sales to analyze">Record sales to slice them by any dimension.</Empty> : (
          <table className="hx-table">
            <thead><tr><th>{dim[0].toUpperCase() + dim.slice(1)}</th><th className="r">Sales</th><th className="r">Profit</th><th className="r">Units</th><th className="r">Orders</th><th style={{ width: 200 }}>{metric}</th></tr></thead>
            <tbody>
              {arr.map((g) => (
                <tr key={g.key}>
                  <td style={{ fontWeight: 500 }}>{g.key}</td>
                  <td className="r num">{Hydor.fmtMoney0(g.sales)}</td>
                  <td className="r num hx-pos">{Hydor.fmtMoney0(g.profit)}</td>
                  <td className="r num" style={{ color: "var(--text-2)" }}>{Hydor.fmtQty(g.qty)}</td>
                  <td className="r num" style={{ color: "var(--text-2)" }}>{g.txns}</td>
                  <td><div style={{ display: "flex", alignItems: "center", gap: 9 }}><div className="hx-progress" style={{ flex: 1 }}><i style={{ width: (g[metricKey] / max * 100) + "%" }} /></div><span className="hx-num" style={{ fontSize: 12, width: 64, textAlign: "right" }}>{fmtM(g[metricKey])}</span></div></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

/* ---------- Compare periods ---------- */
function CompareView({ s, d }) {
  const keys = d.quarterKeys.filter((k) => { const q = d.quarters[k]; return q.sales || q.costs; });
  const [a, setA] = React.useState("");
  const [b, setB] = React.useState("");
  React.useEffect(() => { if (keys.length && !a) { setA(keys[keys.length - 2] || keys[0]); setB(keys[keys.length - 1]); } }, [keys.length]);
  if (keys.length < 1) return <div className="hx-panel"><Empty icon="chart" title="Need more history">Record transactions across at least one quarter to compare.</Empty></div>;
  const qa = d.quarters[a] || {}, qb = d.quarters[b] || {};
  const rows = [["Sales", "sales"], ["COGS", "cogs"], ["Gross profit", "gp"], ["Fixed costs", "fixed"], ["Operational", "op"], ["Net profit", "net"], ["Units sold", "units"], ["Transactions", "txns"]];
  const delta = (x, y) => y === 0 ? (x > 0 ? 100 : 0) : ((x - y) / Math.abs(y)) * 100;
  return (
    <div>
      <div className="toolbar">
        <select className="sel" style={{ width: 150 }} value={a} onChange={(e) => setA(e.target.value)}>{keys.map((k) => <option key={k} value={k}>{k}</option>)}</select>
        <Icon name="arrow" style={{ color: "var(--text-3)" }} />
        <select className="sel" style={{ width: 150 }} value={b} onChange={(e) => setB(e.target.value)}>{keys.map((k) => <option key={k} value={k}>{k}</option>)}</select>
      </div>
      <div className="hx-panel" style={{ overflow: "hidden" }}>
        <table className="hx-table">
          <thead><tr><th>Metric</th><th className="r">{a}</th><th className="r">{b}</th><th className="r">Change</th><th style={{ width: 160 }}></th></tr></thead>
          <tbody>
            {rows.map(([label, key]) => {
              const va = qa[key] || 0, vb = qb[key] || 0; const dl = delta(vb, va);
              const isMoney = !["units", "txns"].includes(key);
              return (
                <tr key={key}>
                  <td style={{ fontWeight: 500 }}>{label}</td>
                  <td className="r num" style={{ color: "var(--text-2)" }}>{isMoney ? Hydor.fmtMoney0(va) : Hydor.fmtQty(va)}</td>
                  <td className="r num">{isMoney ? Hydor.fmtMoney0(vb) : Hydor.fmtQty(vb)}</td>
                  <td className="r num"><span className={dl >= 0 ? "hx-pos" : "hx-neg"}>{dl >= 0 ? "+" : ""}{dl.toFixed(1)}%</span></td>
                  <td><div className="hx-perfbar"><div className="hx-perfbar-track"><div className="hx-perfbar-mid" style={{ left: "50%" }} /><div className={"hx-perfbar-fill " + (dl >= 0 ? "over" : "under")} style={{ width: Math.min(Math.abs(dl) / 100 * 50 + 50, 100) + "%", marginLeft: dl < 0 ? "auto" : 0 }} /></div></div></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ---------- Dead stock ---------- */
function DeadStockView({ s, d, onDrill }) {
  const dead = s.products.map((p) => ({ p, st: d.productStats[p.id] })).filter((r) => r.st.dead);
  const slow = s.products.map((p) => ({ p, st: d.productStats[p.id] })).filter((r) => !r.st.dead && r.st.remaining > 0 && r.st.daysCover != null && r.st.daysCover > 120);
  const tied = dead.reduce((a, r) => a + r.st.invValue, 0);
  return (
    <div>
      <div className="stat-strip" style={{ gridTemplateColumns: "repeat(2,1fr)" }}>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--warn)" }}><div className="ms-label">Dead SKUs</div><div className="ms-value">{dead.length}</div><div className="ms-sub">no sale in {s.meta.deadStockDays}+ days</div></div>
        <div className="mini-stat" style={{ borderLeft: "3px solid var(--neg)" }}><div className="ms-label">Capital tied up</div><div className="ms-value">{Hydor.fmtMoney0(tied)}</div><div className="ms-sub">JOD in dead stock</div></div>
      </div>
      <div className="hx-panel" style={{ overflow: "hidden", marginBottom: 14 }}>
        {dead.length === 0 ? <Empty icon="check" title="No dead stock">Everything with inventory has sold recently. Healthy turnover.</Empty> : (
          <table className="hx-table">
            <thead><tr><th>Product</th><th className="r">On hand</th><th className="r">Inv. value</th><th className="r">Last sold</th><th>Status</th></tr></thead>
            <tbody>
              {dead.map((r) => (
                <tr key={r.p.id} className="clickrow" onClick={() => onDrill({ type: "product", id: r.p.id })}>
                  <td><span className="hx-code">{r.p.code}</span> <span style={{ fontSize: 12.5, color: "var(--text-2)" }}>{r.p.name}</span></td>
                  <td className="r num">{Hydor.fmtQty(r.st.remaining)}</td>
                  <td className="r num">{Hydor.fmtMoney0(r.st.invValue)}</td>
                  <td className="r num" style={{ color: "var(--text-2)" }}>{r.st.lastSold ? Hydor.fmtDate(r.st.lastSold) : "never"}</td>
                  <td><Badge color="amber">{r.st.daysSinceSale == null ? "never sold" : r.st.daysSinceSale + "d idle"}</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
      {slow.length > 0 && (
        <div className="hx-panel hx-panel-pad">
          <h3 className="hx-h2" style={{ marginBottom: 4 }}>Slow movers</h3>
          <p className="hx-sub" style={{ marginBottom: 14 }}>Selling, but more than 4 months of cover on hand at current pace.</p>
          <table className="hx-table">
            <thead><tr><th>Product</th><th className="r">On hand</th><th className="r">Days cover</th><th className="r">30-day velocity</th></tr></thead>
            <tbody>
              {slow.map((r) => (
                <tr key={r.p.id}>
                  <td><span className="hx-code">{r.p.code}</span> <span style={{ fontSize: 12.5, color: "var(--text-2)" }}>{r.p.name}</span></td>
                  <td className="r num">{Hydor.fmtQty(r.st.remaining)}</td>
                  <td className="r num" style={{ color: "var(--warn)" }}>{Math.round(r.st.daysCover)}d</td>
                  <td className="r num" style={{ color: "var(--text-2)" }}>{r.st.velocity.toFixed(1)} units</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AnalyticsPage });
