// hydor-drilldown.jsx — slide-over panel for interrogating any entity.
function DrillPanel({ drill, onClose, onNav }) {
  const s = useHydor();
  const d = useDerive();
  React.useEffect(() => {
    const k = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k); return () => window.removeEventListener("keydown", k);
  }, [onClose]);
  if (!drill) return null;
  const pname = (id) => { const p = s.products.find((x) => x.id === id); return p ? p : { code: "—", name: "" }; };
  const partyName = (id) => { const p = s.parties.find((x) => x.id === id); return p ? p.name : "—"; };

  let title = "", subtitle = "", body = null;

  if (drill.type === "product") {
    const p = s.products.find((x) => x.id === drill.id); const st = d.productStats[drill.id];
    if (p) {
      title = p.code; subtitle = p.name;
      const txs = s.transactions.filter((t) => !t.deleted && t.productId === p.id).sort((a, b) => a.date < b.date ? 1 : -1);
      body = <>
        <DrillStats items={[
          ["On hand", Hydor.fmtQty(st.remaining), null], ["Avg cost", Hydor.fmtMoney(st.avgCost), null],
          ["Rec. price", Hydor.fmtMoney(st.recPrice), "var(--accent-2)"], ["Inv. value", Hydor.fmtMoney0(st.invValue), null],
          ["Units sold", Hydor.fmtQty(st.sold), null], ["Revenue", Hydor.fmtMoney0(st.revenue), null],
          ["Profit", Hydor.fmtMoney0(st.profit), "var(--pos)"], ["Margin", Hydor.fmtPct(st.margin), null],
          ["ABC class", st.abc, null], ["30d velocity", st.velocity.toFixed(1) + " u", null],
        ]} />
        <DrillTxTable txs={txs} d={d} pname={pname} partyName={partyName} />
      </>;
    }
  } else if (drill.type === "employee") {
    const e = d.employees.find((x) => x.code === drill.code);
    if (e) {
      title = "Employee " + e.code; subtitle = "Sales performance";
      const txs = s.transactions.filter((t) => !t.deleted && t.type === "sale" && t.employee === e.code).sort((a, b) => a.date < b.date ? 1 : -1);
      body = <>
        <DrillStats items={[
          ["Total sales", Hydor.fmtMoney0(e.sales), "var(--accent)"], ["Gross profit", Hydor.fmtMoney0(e.gp), "var(--pos)"],
          ["Units", Hydor.fmtQty(e.qty), null], ["Orders", e.txns, null],
          ["Avg margin", Hydor.fmtPct(e.margin), null], ["vs Recommended", e.perf.toFixed(1) + "%", e.perf >= 100 ? "var(--pos)" : "var(--warn)"],
        ]} />
        <div style={{ margin: "4px 0 18px" }}><PerfBar value={e.perf} /></div>
        <DrillTxTable txs={txs} d={d} pname={pname} partyName={partyName} showCustomer />
      </>;
    }
  } else if (drill.type === "party") {
    const p = s.parties.find((x) => x.id === drill.id);
    if (p) {
      title = p.name; subtitle = Hydor.cap(p.type) + (p.phone ? " · " + p.phone : "");
      const txs = s.transactions.filter((t) => !t.deleted && t.partyId === p.id).sort((a, b) => a.date < b.date ? 1 : -1);
      const total = txs.reduce((a, t) => a + ((d.txc[t.id] || {}).subtotal || (t.qty * (t.unitCost || 0))), 0);
      const owed = txs.filter((t) => !t.paid).reduce((a, t) => a + ((d.txc[t.id] || {}).total || (t.qty * (t.unitCost || 0))), 0);
      body = <>
        <DrillStats items={[["Transactions", txs.length, null], [p.type === "customer" ? "Total sales" : "Total spend", Hydor.fmtMoney0(total), "var(--accent)"], ["Outstanding", Hydor.fmtMoney0(owed), owed > 0 ? "var(--warn)" : null]]} />
        <DrillTxTable txs={txs} d={d} pname={pname} partyName={partyName} />
      </>;
    }
  } else if (drill.type === "salesDrill") {
    title = "Sales detail"; subtitle = drill.q === null ? `Full year ${drill.year}` : `${drill.year} Q${drill.q + 1}`;
    const txs = s.transactions.filter((t) => !t.deleted && t.type === "sale" && Hydor.yearOf(t.date) === drill.year && (drill.q === null || Hydor.quarterOf(t.date) === drill.q + 1)).sort((a, b) => a.date < b.date ? 1 : -1);
    const total = txs.reduce((a, t) => a + ((d.txc[t.id] || {}).subtotal || 0), 0);
    const profit = txs.reduce((a, t) => a + ((d.txc[t.id] || {}).profit || 0), 0);
    body = <>
      <DrillStats items={[["Sales", txs.length, null], ["Value", Hydor.fmtMoney0(total), "var(--accent)"], ["Profit", Hydor.fmtMoney0(profit), "var(--pos)"]]} />
      <DrillTxTable txs={txs} d={d} pname={pname} partyName={partyName} showCustomer showEmp />
    </>;
  } else if (drill.type === "tx") {
    const t = s.transactions.find((x) => x.id === drill.id); const c = d.txc[t && t.id] || {};
    if (t) {
      const p = pname(t.productId);
      title = Hydor.cap(t.type); subtitle = Hydor.fmtDate(t.date) + " · " + p.code;
      const items = [["Product", p.code, null], ["Quantity", Hydor.fmtQty(t.qty), null]];
      if (t.type === "sale") {
        items.push(["Sell price", Hydor.fmtMoney(t.actualSell), null], ["Recommended", Hydor.fmtMoney(c.recPrice), c.belowRec ? "var(--warn)" : "var(--accent-2)"],
          ["COGS (FIFO)", Hydor.fmtMoney0(c.cogs), null], ["Profit", Hydor.fmtMoney0(c.profit), c.profit >= 0 ? "var(--pos)" : "var(--neg)"],
          ["Margin", Hydor.fmtPct(c.margin), null], ["Tax", Hydor.fmtMoney0(c.tax), null], ["Total", Hydor.fmtMoney0(c.total), null], ["Employee", t.employee || "—", null]);
      } else if (t.type === "purchase") {
        items.push(["Unit cost", Hydor.fmtMoney(t.unitCost), null], ["Total cost", Hydor.fmtMoney0(c.value), null], ["Supplier", partyName(t.partyId), null]);
      }
      items.push(["Status", t.paid ? "Paid" : (t.type === "sale" ? "Receivable" : "Payable"), t.paid ? null : "var(--warn)"]);
      body = <>
        <DrillStats items={items} cols={2} />
        {t.notes && <div style={{ marginTop: 8, padding: "12px 14px", background: "var(--bg-2)", borderRadius: 10, fontSize: 13, color: "var(--text-2)" }}>{t.notes}</div>}
        {c.belowRec && <div style={{ marginTop: 12, display: "flex", gap: 9, alignItems: "center", padding: "11px 14px", background: "#ffc24b14", borderRadius: 10, fontSize: 12.5, color: "var(--warn)" }}><Icon name="alert" size={15} />Sold below recommended price — margin impact flagged.</div>}
      </>;
    }
  }

  return (
    <div className="scrim" onMouseDown={(e) => e.target === e.currentTarget && onClose()} style={{ justifyContent: "flex-end", padding: 0 }}>
      <div className="drawer">
        <div className="modal-head">
          <div><h3 style={{ margin: 0 }}>{title}</h3><div className="hx-sub" style={{ marginTop: 2 }}>{subtitle}</div></div>
          <Btn variant="ghost" icon="x" onClick={onClose} />
        </div>
        <div className="modal-body">{body || <Empty icon="search" title="Not found">This record may have been removed.</Empty>}</div>
      </div>
    </div>
  );
}

function DrillStats({ items, cols = 2 }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols},1fr)`, gap: 1, background: "var(--border)", border: "1px solid var(--border)", borderRadius: 12, overflow: "hidden", marginBottom: 20 }}>
      {items.map(([label, val, color], i) => (
        <div key={i} style={{ background: "var(--surface)", padding: "13px 15px" }}>
          <div style={{ fontSize: 11, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".05em", fontWeight: 600 }}>{label}</div>
          <div className="hx-num" style={{ fontSize: 18, fontWeight: 600, marginTop: 5, color: color || "var(--text)" }}>{val}</div>
        </div>
      ))}
    </div>
  );
}

function DrillTxTable({ txs, d, pname, partyName, showCustomer, showEmp }) {
  if (!txs.length) return <div style={{ padding: "30px 0", textAlign: "center", color: "var(--text-3)", fontSize: 13 }}>No transactions.</div>;
  return (
    <>
      <div className="hx-eyebrow" style={{ marginBottom: 10 }}>{txs.length} transaction{txs.length !== 1 ? "s" : ""}</div>
      <table className="hx-table">
        <thead><tr><th>Date</th><th>Type</th>{showEmp && <th>Staff</th>}{showCustomer && <th>Customer</th>}<th className="r">Qty</th><th className="r">Value</th><th className="r">Profit</th></tr></thead>
        <tbody>
          {txs.map((t) => { const c = d.txc[t.id] || {}; const val = t.type === "sale" ? c.subtotal : t.type === "purchase" ? c.value : 0;
            return (
              <tr key={t.id}>
                <td className="num" style={{ color: "var(--text-2)", whiteSpace: "nowrap" }}>{Hydor.fmtDate(t.date)}</td>
                <td><span className={"tag-type tag-" + t.type}>{t.type}</span></td>
                {showEmp && <td>{t.employee ? <EmpBadge code={t.employee} /> : "—"}</td>}
                {showCustomer && <td style={{ fontSize: 12.5, color: "var(--text-2)" }}>{partyName(t.partyId)}</td>}
                <td className="r num">{Hydor.fmtQty(t.qty)}</td>
                <td className="r num">{val ? Hydor.fmtMoney0(val) : "—"}</td>
                <td className="r num">{t.type === "sale" ? <span className={c.profit >= 0 ? "hx-pos" : "hx-neg"}>{Hydor.fmtMoney0(c.profit)}</span> : "—"}</td>
              </tr>
            ); })}
        </tbody>
      </table>
    </>
  );
}

Object.assign(window, { DrillPanel });
