// ───────────────────────────────────────────────────────────────
// Busco Ops — Financial + HR & Procurement screens · v2
// ───────────────────────────────────────────────────────────────

// ── FINANCIAL ────────────────────────────────────────────────
function FinancialScreen({ unlocked, setUnlocked, onToast }) {
  if (!unlocked) return <PinGate onUnlock={() => { setUnlocked(true); onToast("Owner access granted"); }} />;
  return <FinancialDashboard onLock={() => setUnlocked(false)} onToast={onToast} />;
}

function PinGate({ onUnlock }) {
  const [pin, setPin] = useState(["", "", "", ""]);
  const [attempts, setAttempts] = useState(0);
  const [shake, setShake] = useState(false);
  const [verifying, setVerifying] = useState(false);
  const refs = [useRef(), useRef(), useRef(), useRef()];

  useEffect(() => { refs[0].current && refs[0].current.focus(); }, []);

  const setDigit = (i, v) => {
    if (!/^[0-9]?$/.test(v)) return;
    if (verifying) return;
    const next = [...pin]; next[i] = v; setPin(next);
    if (v && i < 3) refs[i + 1].current.focus();
    if (next.every(x => x !== "")) check(next.join(""));
  };
  const onKey = (i, e) => {
    if (e.key === "Backspace" && !pin[i] && i > 0) refs[i - 1].current.focus();
  };
  const check = async (val) => {
    if (verifying) return;
    setVerifying(true);
    const ok = await window.buscoVerifyPin(val);
    setVerifying(false);
    if (ok) { onUnlock(); return; }
    setShake(true); setTimeout(() => setShake(false), 400);
    setAttempts(a => a + 1);
    setPin(["", "", "", ""]);
    setTimeout(() => refs[0].current && refs[0].current.focus(), 50);
  };
  const locked = attempts >= 5;

  return (
    <div className="pin-screen">
      <div className="pin-card" data-tour="financial">
        <div className="pin-lock"><Icon name="lock" size={22} /></div>
        <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: "-0.01em" }}>{window.t("Owner access required")}</div>
        <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 5 }}>
          The Financial module is restricted. Enter your 4-digit owner PIN to continue.
        </div>
        <div className={"pin-inputs" + (shake ? " shake" : "")}>
          {pin.map((d, i) => (
            <input key={i} ref={refs[i]} value={d} disabled={locked}
              onChange={e => setDigit(i, e.target.value)}
              onKeyDown={e => onKey(i, e)}
              maxLength={1} inputMode="numeric" />
          ))}
        </div>
        {locked ? (
          <div style={{ fontSize: 12, color: "var(--crit-700)", background: "var(--crit-50)", border: "1px solid var(--crit-100)", padding: "9px 11px", borderRadius: "var(--r-sm)" }}>
            Too many failed attempts. Locked for 5 minutes.
          </div>
        ) : attempts > 0 ? (
          <div style={{ fontSize: 11.5, color: "var(--crit-700)" }}>Incorrect PIN. {5 - attempts} attempt{5 - attempts !== 1 ? "s" : ""} remaining.</div>
        ) : (
          <div style={{ fontSize: 11, color: "var(--muted)", display: "flex", alignItems: "center", gap: 6 }}>
            <Icon name="info" size={11} /> {window.t("Enter your 4-digit owner PIN")}
          </div>
        )}
        <button className="btn primary lg" style={{ width: "100%", justifyContent: "center", marginTop: 18 }} onClick={() => check(pin.join(""))} disabled={pin.some(x => !x) || locked || verifying}>
          {verifying ? <span className="spinner" /> : <Icon name="unlock" size={13} color="#fff" />}
          {verifying ? window.t("Verifying…") : window.t("Unlock financial")}
        </button>
        <div style={{ fontSize: 10.5, color: "var(--muted-2)", marginTop: 14, display: "flex", alignItems: "center", gap: 6, justifyContent: "center" }}>
          <Icon name="lock" size={10} /> PIN is hashed server-side · resets each session
        </div>
      </div>
    </div>
  );
}

function FinancialDashboard({ onLock, onToast }) {
  const [tab, setTab] = useState("Overview");
  const [cur, setCurState] = useState(() => buscoPref.get("busco-fin-currency", "all"));   // all | SAR | BHD
  const setCur = (c) => { setCurState(c); buscoPref.set("busco-fin-currency", c); };
  const fin = cur === "all" ? FINANCIALS : FINANCIALS.filter((f) => f.currency === cur);
  // Totals grouped by currency — never summed across SAR and BHD.
  const totalsByCur = {};
  for (const f of fin) {
    const k = f.currency || "SAR";
    (totalsByCur[k] || (totalsByCur[k] = { rev: 0, cost: 0, profit: 0 }));
    totalsByCur[k].rev += f.totalRev; totalsByCur[k].cost += f.courierCost; totalsByCur[k].profit += f.netProfit;
  }
  const curList = Object.keys(totalsByCur);
  const moneyLines = (field) => curList.length === 0
    ? <span>—</span>
    : <span>{curList.map((k) => <span key={k} style={{ display: "block", fontSize: curList.length > 1 ? 18 : undefined, lineHeight: 1.3 }}>{fmtMoney(totalsByCur[k][field], k)}</span>)}</span>;

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12, gap: 12, flexWrap: "wrap" }}>
        <div className="tabs" style={{ marginBottom: 0, border: 0 }}>
          {["Overview", "Clients P&L", "Invoices", "Courier Costs", "Cashflow"].map(t2 => (
            <button key={t2} className={"tab " + (tab === t2 ? "on" : "")} onClick={() => setTab(t2)}>{window.t(t2)}</button>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Segmented options={["All", "SAR", "BHD"]} value={cur === "all" ? "All" : cur} onChange={(v) => setCur(v === "All" ? "all" : v)} />
          <button className="btn sm" onClick={onLock}>
            <Icon name="lock" size={12} /> {window.t("Lock module")}
          </button>
        </div>
      </div>

      {tab === "Overview" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="kpi-row" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
            <KPI label={window.t("Total revenue · MTD")}  value={moneyLines("rev")}    sub={`${fin.length} ${window.t("clients")}`} icon="trend"  tint="var(--b50)"    accent="var(--b600)" />
            <KPI label={window.t("Total courier cost")}   value={moneyLines("cost")}   sub={window.t("freelance + salary")}        icon="truck"  tint="var(--warn-50)" accent="var(--warn-700)" />
            <KPI label={window.t("Net profit · MTD")}     value={moneyLines("profit")} sub={window.t("revenue − cost")}            icon="wallet" tint="var(--good-50)" accent="var(--good-700)" tone="good" />
          </div>
          <div className="card">
            <div className="card-head">
              <div className="ch-l">
                <h3>{window.t("Revenue · Cost · Profit by client")}</h3>
                <div className="ch-sub">{new Date().toLocaleDateString("en-US", { month: "long", year: "numeric" })} · {cur === "all" ? (curList.join(" + ") || "—") : cur}</div>
              </div>
              <span style={{ display: "inline-flex", gap: 12, fontSize: 11, color: "var(--muted)" }}>
                <span><span className="dot" style={{ background: "var(--b500)" }} /> Revenue</span>
                <span><span className="dot" style={{ background: "var(--warn)" }} /> Cost</span>
                <span><span className="dot" style={{ background: "var(--good)" }} /> Profit</span>
              </span>
            </div>
            <div className="card-body" style={{ paddingTop: 6 }}>
              <div style={{ height: 320 }}>
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={fin} margin={{ top: 10, right: 12, left: -8, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="var(--border-soft)" vertical={false} />
                    <XAxis dataKey="name" tick={{ ...tickStyle, fontFamily: "IBM Plex Sans", fontSize: 11 }} axisLine={false} tickLine={false} />
                    <YAxis tick={tickStyle} axisLine={false} tickLine={false} width={56} tickFormatter={v => (v / 1000) + "k"} />
                    <Tooltip contentStyle={tipStyle} formatter={(v, n, p) => fmtMoney(v, p && p.payload && p.payload.currency)} />
                    <Bar dataKey="totalRev"    name="Revenue" fill="var(--b500)" radius={[3, 3, 0, 0]} />
                    <Bar dataKey="courierCost" name="Cost"    fill="var(--warn)" radius={[3, 3, 0, 0]} />
                    <Bar dataKey="netProfit"   name="Profit"  fill="var(--good)" radius={[3, 3, 0, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>
          </div>
        </div>
      )}

      {tab === "Clients P&L" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div className="tbl-wrap">
            <div className="tbl-head">
              <h3>{window.t("Clients P&L")} · {new Date().toLocaleDateString("en-US", { month: "long", year: "numeric" })}</h3>
              <ExportMenu onToast={onToast}
                getRows={() => ({
                  rows: fin.map((f) => ({
                    Client: f.name, Currency: f.currency,
                    "PPD Revenue": f.ppdRev, "COD Revenue": f.codRev,
                    "Total Revenue": f.totalRev, "Courier Cost": f.courierCost,
                    "Net Profit": f.netProfit, "Margin %": Math.round(f.margin),
                    "Invoice Date": f.invoiceDate, "Due Date": f.dueDate,
                  })),
                  filename: `busco-clients-pl-${new Date().toISOString().slice(0, 10)}`,
                })} />
            </div>
            <table className="data">
              <thead>
                <tr>
                  <th>{window.t("Client")}</th>
                  <th>{window.t("Cur")}</th>
                  <th className="num">{window.t("PPD Rev")}</th>
                  <th className="num">{window.t("COD Rev")}</th>
                  <th className="num">{window.t("Total Rev")}</th>
                  <th className="num">{window.t("Cost")}</th>
                  <th className="num">{window.t("Net Profit")}</th>
                  <th className="num">{window.t("Margin")}</th>
                  <th>{window.t("Invoice")}</th>
                  <th>{window.t("Due")}</th>
                </tr>
              </thead>
              <tbody>
                {fin.map(c => (
                  <tr key={c.id} className={c.overdue ? "row-bad" : ""}>
                    <td className="strong">{c.name}</td>
                    <td className="mono muted" style={{ fontSize: 11 }}>{c.currency}</td>
                    <td className="num">{fmtMoneyNum(c.ppdRev, c.currency)}</td>
                    <td className="num">{fmtMoneyNum(c.codRev, c.currency)}</td>
                    <td className="num strong">{fmtMoneyNum(c.totalRev, c.currency)}</td>
                    <td className="num">{fmtMoneyNum(c.courierCost, c.currency)}</td>
                    <td className="num strong" style={{ color: c.netProfit > 0 ? "var(--good-700)" : "var(--crit-700)" }}>{fmtMoneyNum(c.netProfit, c.currency)}</td>
                    <td className="num">{c.margin.toFixed(1)}%</td>
                    <td className="mono" style={{ fontSize: 11.5 }}>{fmtDate(c.invoiceDate)}</td>
                    <td>
                      <span className="mono" style={{ fontSize: 11.5 }}>{fmtDate(c.dueDate)}</span>
                      {c.overdue && <span className="status overdue" style={{ marginLeft: 6 }}>Overdue</span>}
                    </td>
                  </tr>
                ))}
              </tbody>
              {curList.length > 0 &&
                <tfoot>
                  {curList.map((k) => (
                    <tr key={k} className="row-total">
                      <td className="strong">{window.t("Total")}</td>
                      <td className="mono muted" style={{ fontSize: 11 }}>{k}</td>
                      <td></td><td></td>
                      <td className="num strong">{fmtMoneyNum(totalsByCur[k].rev, k)}</td>
                      <td className="num strong">{fmtMoneyNum(totalsByCur[k].cost, k)}</td>
                      <td className="num strong" style={{ color: totalsByCur[k].profit >= 0 ? "var(--good-700)" : "var(--crit-700)" }}>{fmtMoneyNum(totalsByCur[k].profit, k)}</td>
                      <td className="num">{totalsByCur[k].rev > 0 ? (totalsByCur[k].profit / totalsByCur[k].rev * 100).toFixed(1) + "%" : "—"}</td>
                      <td></td><td></td>
                    </tr>
                  ))}
                </tfoot>
              }
            </table>
          </div>

        </div>
      )}

      {tab === "Invoices" && <InvoiceGenerator onToast={onToast} />}

      {tab === "Courier Costs" && <CourierCostsView onToast={onToast} cur={cur} />}

      {tab === "Cashflow" && <CashflowView cur={cur} />}
    </div>
  );
}

// (Client rate editing now lives only on the Clients page — edit a client there.)

function CashflowView({ cur = "all" }) {
  const finRows = cur === "all" ? FINANCIALS : FINANCIALS.filter((f) => f.currency === cur);
  const payRows = cur === "all" ? COURIER_PAY : COURIER_PAY.filter((p) => p.currency === cur);
  const inflows = finRows.map(c => ({ name: c.name, amount: c.totalRev, date: c.dueDate, overdue: c.overdue, currency: c.currency }));
  const outflows = payRows;
  // Totals grouped by currency — money in/out/net never mix SAR and BHD.
  const byCur = {};
  for (const x of inflows) { const k = x.currency || "SAR"; (byCur[k] || (byCur[k] = { in: 0, out: 0 })).in += x.amount; }
  for (const p of outflows) { const k = p.currency || "SAR"; (byCur[k] || (byCur[k] = { in: 0, out: 0 })).out += p.amount; }
  const curs = Object.keys(byCur);
  const totalLines = (kind) => curs.length === 0
    ? (kind === "in" ? "+0" : "−0")
    : curs.map((k) => <div key={k}>{kind === "in" ? "+" : "−"}{fmtMoney(byCur[k][kind], k)}</div>);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="card">
          <div className="card-head" style={{ background: "var(--good-50)", borderBottom: "1px solid var(--good-100)" }}>
            <div className="ch-l">
              <h3 style={{ color: "var(--good-700)" }}>{window.t("Money in · client invoices")}</h3>
              <div className="ch-sub" style={{ color: "var(--good-700)", opacity: 0.8 }}>{inflows.length} invoices pending</div>
            </div>
            <div className="mono" style={{ fontSize: 19, fontWeight: 700, color: "var(--good-700)", textAlign: "right" }}>{totalLines("in")}</div>
          </div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 7 }}>
            {inflows.map((x, i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "10px 12px", background: "var(--surface-2)", border: "1px solid var(--border-soft)", borderRadius: "var(--r-sm)" }}>
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 600 }}>{x.name}</div>
                  <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>
                    Due {fmtDate(x.date)} {x.overdue && <span className="status overdue" style={{ marginLeft: 6 }}>Overdue</span>}
                  </div>
                </div>
                <div className="mono" style={{ fontWeight: 600, color: "var(--good-700)" }}>+{fmtMoney(x.amount, x.currency)}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="card">
          <div className="card-head" style={{ background: "var(--warn-50)", borderBottom: "1px solid var(--warn-100)" }}>
            <div className="ch-l">
              <h3 style={{ color: "var(--warn-700)" }}>{window.t("Money out · courier payments")}</h3>
              <div className="ch-sub" style={{ color: "var(--warn-700)", opacity: 0.8 }}>{outflows.length} couriers</div>
            </div>
            <div className="mono" style={{ fontSize: 19, fontWeight: 700, color: "var(--warn-700)", textAlign: "right" }}>{totalLines("out")}</div>
          </div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 6, maxHeight: 480, overflowY: "auto" }}>
            {outflows.map((p, i) => (
              <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "9px 11px", background: "var(--surface-2)", border: "1px solid var(--border-soft)", borderRadius: "var(--r-sm)" }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</div>
                  <div style={{ fontSize: 11, color: "var(--muted)" }}>{p.type === "salary" ? "Salaried" : "Freelancer"} · {fmtDate(p.dueDate)}</div>
                </div>
                <div className="mono" style={{ fontWeight: 600, color: "var(--warn-700)" }}>−{fmtMoney(p.amount, p.currency)}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="card">
        <div style={{ padding: "20px 22px", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <div>
            <div className="label-tiny">{window.t("Net cashflow")} · {new Date().toLocaleDateString("en-US", { month: "long", year: "numeric" })}</div>
            <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4 }}>{window.t("Money in − money out")}</div>
          </div>
          <div style={{ display: "flex", gap: 24, flexWrap: "wrap" }}>
            {(curs.length ? curs : ["SAR"]).map((k) => {
              const net = (byCur[k] ? byCur[k].in - byCur[k].out : 0);
              return (
                <div key={k} style={{ textAlign: "right" }}>
                  <div className="mono" style={{ fontSize: 28, fontWeight: 700, color: net >= 0 ? "var(--good-700)" : "var(--crit-700)", letterSpacing: "-0.02em" }}>
                    {net >= 0 ? "+" : "−"}{fmtMoneyNum(Math.abs(net), k)} <span style={{ fontSize: 13, fontWeight: 500 }}>{k}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── HR & PROCUREMENT ─────────────────────────────────────────
function HRScreen({ onToast }) {
  const requests = window.HR_REQUESTS || [];
  const [selectedRef, setSelectedRef] = useState(null);
  const selected = requests.find(r => r.ref === selectedRef);

  const advance = async (ref) => {
    try {
      await window.buscoAdvanceHrStatus(ref);
      onToast("Status advanced");
    } catch (e) {
      onToast(e?.message || "Failed to advance status", "danger");
    }
  };

  const createRequest = async (req) => {
    try {
      const saved = await window.buscoSaveHrRequest(req);
      onToast(`Submitted ${saved.ref}`);
    } catch (e) {
      onToast(e?.message || "Failed to submit request", "danger");
    }
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
      <div className="banner" style={{ background: "var(--warn-50)", borderColor: "var(--warn-100)", color: "var(--warn-700)" }}>
        <Icon name="alert-circle" size={15} color="var(--warn-700)" />
        <div style={{ fontSize: 12.5 }}>
          <b>{window.t("Leftover module — not actively used.")}</b>{" "}
          {window.t("HR & Procurement was an early idea that never became part of the daily workflow. It's hidden from the nav on purpose (only reachable via the console) and isn't maintained — treat anything here as experimental.")}
        </div>
      </div>
      <NewRequirementForm onCreate={createRequest} />

      <div className="sec">
        <h2>{window.t("Hiring pipeline")} <span className="ct">{requests.filter(r => r.status !== "deployed").length} {window.t("active")}</span></h2>
        <div className="sec-right">
          <span className="muted" style={{ fontSize: 11.5 }}>{window.t("Click a card for detail")}</span>
        </div>
      </div>

      {selected && (
        <RequirementDetail
          req={selected}
          onClose={() => setSelectedRef(null)}
          onAdvance={() => advance(selected.ref)}
          onToast={onToast}
        />
      )}

      <div className="kanban">
        {[
          { key: "open",         label: window.t("Open") },
          { key: "cvs_received", label: window.t("CVs Received") },
          { key: "interviewing", label: window.t("Interviewing") },
          { key: "training",     label: window.t("Training") },
          { key: "deployed",     label: window.t("Deployed") },
        ].map(col => {
          const items = requests.filter(r => r.status === col.key);
          return (
            <div key={col.key} className="kan-col">
              <div className="kan-col-h">
                <span>{col.label}</span>
                <span className="ct">{items.length}</span>
              </div>
              <div className="kan-cards">
                {items.length === 0 ? (
                  <div style={{ fontSize: 11, color: "var(--muted-2)", textAlign: "center", padding: "18px 0" }}>—</div>
                ) : items.map(r => (
                  <div
                    key={r.ref}
                    className={"kan-card " + (selectedRef === r.ref ? "selected" : "")}
                    onClick={() => setSelectedRef(r.ref)}
                  >
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                      <span className="mono" style={{ fontSize: 10.5, fontWeight: 700, color: "var(--b700)" }}>{r.ref}</span>
                      {r.priority === "urgent" && <span className="badge badge-crit">{window.t("Urgent")}</span>}
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 600, marginTop: 6 }}>{r.client}</div>
                    <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{r.city} · {r.warehouses.join(", ")}</div>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 8, gap: 6 }}>
                      <span className="badge badge-slate"><span className="mono">×{r.count}</span> needed</span>
                      <span className={"ctype " + r.model}>
                        <Icon name={r.model === "salary" ? "briefcase" : "tool"} size={10} />
                        {r.package}
                      </span>
                    </div>
                    {(r.cvs > 0 || r.interviewed > 0 || r.training > 0) && (
                      <div style={{ display: "flex", gap: 8, marginTop: 8, fontSize: 10, color: "var(--muted)" }}>
                        {r.cvs > 0         && <span>CVs <span className="mono" style={{ color: "var(--text)" }}>{r.cvs}</span></span>}
                        {r.interviewed > 0 && <span>Int <span className="mono" style={{ color: "var(--text)" }}>{r.interviewed}</span></span>}
                        {r.training > 0    && <span>Trn <span className="mono" style={{ color: "var(--text)" }}>{r.training}</span></span>}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      <HRReport requests={requests} onToast={onToast} />
    </div>
  );
}

function NewRequirementForm({ onCreate }) {
  const [clientId, setClientId] = useState("c1");
  const [city, setCity] = useState("Riyadh");
  const [whSel, setWhSel] = useState([]);
  const [count, setCount] = useState(4);
  const [model, setModel] = useState("freelancer");
  const [pkg, setPkg] = useState(PACKAGES.freelancer[1].name);
  const [priority, setPriority] = useState("normal");
  const [target, setTarget] = useState("2026-06-15");
  const [notes, setNotes] = useState("");

  const client = CLIENTS.find(c => c.id === clientId);
  const cities = client ? client.cities : [];
  const warehouses = (cities.find(c => c.name === city) || {}).warehouses || [];
  const pkgList = PACKAGES[model];
  const pkgInfo = pkgList.find(p => p.name === pkg) || pkgList[0];

  const toggleWh = (w) => setWhSel(s => s.includes(w) ? s.filter(x => x !== w) : [...s, w]);

  const submit = () => {
    if (!client) return;
    const req = {
      ref: "REQ-" + String(8 + Math.floor(Math.random() * 90)).padStart(3, "0"),
      status: "open",
      client: client.name,
      city,
      warehouses: whSel.length ? whSel : warehouses.slice(0, 1),
      count,
      model,
      package: pkgInfo.name,
      rate: pkgInfo.rate,
      priority,
      cvs: 0, interviewed: 0, training: 0,
      target,
      notes,
    };
    onCreate(req);
  };

  return (
    <div className="card">
      <div className="card-head">
        <div className="ch-l">
          <h3>{window.t("New requirement")}</h3>
          <div className="ch-sub">Submit a hiring request — auto-generates REQ-XXX reference</div>
        </div>
      </div>
      <div className="card-body" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 22 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div className="field">
            <label>{window.t("Client")}</label>
            <PillRow options={CLIENTS.map(c => c.name)} value={client?.name} onChange={(n) => { const c = CLIENTS.find(x => x.name === n); setClientId(c.id); setCity(c.cities[0].name); setWhSel([]); }} />
          </div>

          <div className="field">
            <label>{window.t("City")}</label>
            <PillRow options={cities.map(c => c.name)} value={city} onChange={(n) => { setCity(n); setWhSel([]); }} />
          </div>

          <div className="field">
            <label>Warehouses · multi-select</label>
            <PillRow options={warehouses} value={whSel} onChange={setWhSel} multi />
          </div>

          <div className="field-row c3">
            <div className="field">
              <label>{window.t("Couriers needed")}</label>
              <div className="stepper">
                <button onClick={() => setCount(Math.max(1, count - 1))}><Icon name="minus" size={12} /></button>
                <span className="val">{count}</span>
                <button onClick={() => setCount(Math.min(30, count + 1))}><Icon name="plus" size={12} /></button>
              </div>
            </div>
            <div className="field">
              <label>{window.t("Priority")}</label>
              <div className="segmented" style={{ width: "100%" }}>
                {["normal", "urgent", "planned"].map(p => (
                  <button key={p} className={priority === p ? "on" : ""} onClick={() => setPriority(p)} style={{ flex: 1, textTransform: "capitalize" }}>{p}</button>
                ))}
              </div>
            </div>
            <div className="field">
              <label>{window.t("Target start")}</label>
              <input type="date" value={target} onChange={e => setTarget(e.target.value)} />
            </div>
          </div>

          <div className="field">
            <label>{window.t("Employment model")}</label>
            <div className="segmented" style={{ width: 320 }}>
              <button className={model === "freelancer" ? "on" : ""} onClick={() => { setModel("freelancer"); setPkg(PACKAGES.freelancer[0].name); }} style={{ flex: 1 }}>Freelancer</button>
              <button className={model === "salary" ? "on" : ""}     onClick={() => { setModel("salary");     setPkg(PACKAGES.salary[0].name); }}     style={{ flex: 1 }}>Salaried</button>
            </div>
          </div>

          <div className="field">
            <label>{window.t("Package")}</label>
            <div style={{ display: "flex", gap: 8, overflowX: "auto", paddingBottom: 4 }}>
              {pkgList.map(p => (
                <button key={p.name}
                  onClick={() => setPkg(p.name)}
                  style={{
                    flex: "0 0 auto",
                    border: "1px solid " + (pkg === p.name ? "var(--b500)" : "var(--border)"),
                    background: pkg === p.name ? "var(--b50)" : "var(--surface)",
                    color: pkg === p.name ? "var(--b800)" : "var(--text)",
                    borderRadius: "var(--r-sm)", padding: "10px 14px", textAlign: "left", cursor: "pointer", minWidth: 130,
                    boxShadow: pkg === p.name ? "0 0 0 2px var(--b100)" : "none",
                  }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <span style={{ fontWeight: 600, fontSize: 12.5 }}>{p.name}</span>
                    {pkg === p.name && <Icon name="check" size={13} color="var(--b600)" />}
                  </div>
                  <div className="mono" style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 4 }}>{p.rate}</div>
                </button>
              ))}
            </div>
          </div>

          <div className="field">
            <label>{window.t("Notes")}</label>
            <textarea rows={2} value={notes} onChange={e => setNotes(e.target.value)} placeholder={window.t("Specific requirements, vehicle needs, language…")} />
          </div>
        </div>

        <div style={{ background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: "var(--r-md)", padding: 16, display: "flex", flexDirection: "column", gap: 12, alignSelf: "start" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <div className="label-tiny">{window.t("Live summary")}</div>
              <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 3 }}>{window.t("Updates as you fill the form")}</div>
            </div>
            <span className={"badge " + (priority === "urgent" ? "badge-crit" : priority === "planned" ? "badge-info" : "badge-slate")} style={{ textTransform: "capitalize" }}>{priority}</span>
          </div>

          <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-sm)", padding: 12, display: "flex", flexDirection: "column", gap: 8 }}>
            <SumRow label="Client"          value={client?.name} />
            <SumRow label="City"            value={city} />
            <SumRow label="Warehouses"      value={whSel.length ? whSel.join(", ") : "—"} />
            <SumRow label="Couriers needed" value={<span className="mono"><b>×{count}</b></span>} />
            <SumRow label="Model"           value={model === "salary" ? "Salaried" : "Freelancer"} />
            <SumRow label="Package"         value={<span><b>{pkgInfo.name}</b> · <span className="mono">{pkgInfo.rate}</span></span>} />
            <SumRow label="Target start"    value={fmtDate(target)} />
          </div>

          <div style={{ background: "var(--b50)", border: "1px solid var(--b100)", borderRadius: "var(--r-sm)", padding: 12 }}>
            <div className="label-tiny" style={{ color: "var(--b700)" }}>Est. monthly cost</div>
            <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: "var(--b800)", marginTop: 4, letterSpacing: "-0.01em" }}>
              {fmtSAR(count * (pkgInfo.monthlyEst || parseInt(String(pkgInfo.rate).replace(/[^0-9]/g, ""))))} <span style={{ fontSize: 12, color: "var(--b700)" }}>SAR</span>
            </div>
          </div>

          <button className="btn primary lg" style={{ justifyContent: "center" }} onClick={submit} disabled={!client}>
            <Icon name="send" size={13} color="#fff" /> {window.t("Submit requirement")}
          </button>
        </div>
      </div>
    </div>
  );
}

function SumRow({ label, value }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12, fontSize: 12 }}>
      <span style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.07em", fontWeight: 600, color: "var(--muted)" }}>{label}</span>
      <span style={{ textAlign: "right" }}>{value || <span className="muted-2">—</span>}</span>
    </div>
  );
}

function RequirementDetail({ req, onClose, onAdvance, onToast }) {
  const stages = ["open", "cvs_received", "interviewing", "training", "deployed"];
  const stageLabels = ["Open", "CVs received", "Interviewing", "Training", "Deployed"];
  const idx = stages.indexOf(req.status);

  return (
    <div className="card" style={{ borderColor: "var(--b300)", boxShadow: "0 0 0 2px var(--b50), var(--sh-2)" }}>
      <div className="card-head">
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <span className="badge badge-brand mono" style={{ fontSize: 11.5 }}>{req.ref}</span>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{req.client} · {req.city}</div>
            <div style={{ fontSize: 11.5, color: "var(--muted)" }}>{req.warehouses.join(" · ")} · target {fmtDate(req.target)}</div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          <button className="btn sm" onClick={async () => {
            const raw = window.prompt(`How many new CVs received for ${req.ref}?`, "1");
            const n = parseInt(raw); if (!n || n <= 0) return;
            try { await window.buscoLogCvs(req.ref, n); onToast(`+${n} CV${n > 1 ? "s" : ""} logged`); }
            catch (e) { onToast(e?.message || "Failed", "danger"); }
          }}><Icon name="plus" size={11} /> Log CVs</button>
          <button className="btn sm" onClick={async () => {
            const raw = window.prompt(`How many interviews completed for ${req.ref}?`, "1");
            const n = parseInt(raw); if (!n || n <= 0) return;
            try { await window.buscoLogInterview(req.ref, n); onToast(`+${n} interview${n > 1 ? "s" : ""} logged`); }
            catch (e) { onToast(e?.message || "Failed", "danger"); }
          }}><Icon name="check" size={11} /> Log interview</button>
          <button className="btn sm" onClick={async () => {
            try { await window.buscoFlagHr(req.ref); onToast(`${req.ref} flagged as urgent`); }
            catch (e) { onToast(e?.message || "Failed", "danger"); }
          }}><Icon name="flag" size={11} color="var(--crit)" /> Flag</button>
          <button className="btn primary sm" onClick={onAdvance}>Advance <Icon name="arrow-right" size={11} color="#fff" /></button>
          <button className="close-x" onClick={onClose}><Icon name="x" size={13} /></button>
        </div>
      </div>
      <div className="card-body">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 6, marginBottom: 18 }}>
          {stageLabels.map((s, i) => (
            <div key={s} style={{
              padding: "8px 10px", borderRadius: "var(--r-sm)",
              background: i <= idx ? "var(--b500)" : "var(--surface-2)",
              color: i <= idx ? "white" : "var(--muted)",
              border: "1px solid " + (i <= idx ? "var(--b500)" : "var(--border)"),
              fontSize: 11.5, fontWeight: 600, textAlign: "center",
            }}>
              {i + 1}. {s}
            </div>
          ))}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, marginBottom: 16 }}>
          <Stat lbl="Needed"      val={req.count}        color="var(--text)" />
          <Stat lbl="CVs received" val={req.cvs}         color="var(--info-700)" />
          <Stat lbl="Interviewed" val={req.interviewed}  color="var(--warn-700)" />
          <Stat lbl="In training" val={req.training}     color="var(--good-700)" />
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
          <div>
            <div className="label-tiny" style={{ marginBottom: 8 }}>{window.t("Details")}</div>
            <div style={{ background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: "var(--r-sm)", padding: 12, display: "flex", flexDirection: "column", gap: 7 }}>
              <SumRow label="Model"    value={req.model === "salary" ? "Salaried" : "Freelancer"} />
              <SumRow label="Package"  value={<span><b>{req.package}</b> · <span className="mono">{req.rate}</span></span>} />
              <SumRow label="Priority" value={<span className={"badge " + (req.priority === "urgent" ? "badge-crit" : "badge-slate")} style={{ textTransform: "capitalize" }}>{req.priority}</span>} />
            </div>
          </div>
          <div>
            <div className="label-tiny" style={{ marginBottom: 8 }}>{window.t("Notes")}</div>
            <div style={{ background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: "var(--r-sm)", padding: 12, fontSize: 12.5, color: req.notes ? "var(--text)" : "var(--muted)", minHeight: 72 }}>
              {req.notes || "No notes yet."}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Stat({ lbl, val, color }) {
  return (
    <div className="tile">
      <div className="tl">{lbl}</div>
      <div className="tv" style={{ color, fontSize: 20 }}>{val}</div>
    </div>
  );
}

function HRReport({ requests, onToast }) {
  const [hrEmail, setHrEmail] = useState("hr@busco.sa");
  const [procEmail, setProcEmail] = useState("procurement@busco.sa");
  const [sending, setSending] = useState(false);
  const sendReport = async () => {
    if (sending) return;
    setSending(true);
    try {
      const r = await window.buscoSendHrReport({ hrEmail, procurementEmail: procEmail });
      onToast(`Report emailed to ${r.sent} recipient(s)`);
    } catch (e) {
      onToast(e?.message || "Failed to send report", "danger");
    } finally { setSending(false); }
  };
  const open = requests.filter(r => r.status !== "deployed");
  const totals = open.reduce((a, r) => ({
    needed: a.needed + r.count, cvs: a.cvs + r.cvs, interviewed: a.interviewed + r.interviewed, training: a.training + r.training,
  }), { needed: 0, cvs: 0, interviewed: 0, training: 0 });

  const byCity = {};
  open.forEach(r => { byCity[r.city] = (byCity[r.city] || 0) + r.count; });

  const freelancer = open.filter(r => r.model === "freelancer").reduce((a, r) => a + r.count, 0);
  const salary = open.filter(r => r.model === "salary").reduce((a, r) => a + r.count, 0);

  const monthlyCost = open.reduce((a, r) => {
    const pkg = PACKAGES[r.model].find(p => p.name === r.package);
    const monthly = pkg?.monthlyEst || parseInt(String(pkg?.rate || "0").replace(/[^0-9]/g, ""));
    return a + monthly * r.count;
  }, 0);

  return (
    <div className="card">
      <div className="card-head">
        <div className="ch-l">
          <h3>{window.t("HR report · all open requirements")}</h3>
          <div className="ch-sub">RPT-{fmtDate(new Date())} · generated {fmtDate(new Date())}</div>
        </div>
        <ExportMenu onToast={onToast}
          getRows={() => ({
            rows: requests.map((r) => ({
              Ref: r.ref, Client: r.client, City: r.city,
              Warehouses: (r.warehouses || []).join(" | "),
              Needed: r.count, Model: r.model, Package: r.package, Rate: r.rate,
              Priority: r.priority, Status: r.status,
              CVs: r.cvs, Interviewed: r.interviewed, Training: r.training,
              "Target Date": r.target, Notes: r.notes || "",
            })),
            filename: `busco-hr-report-${new Date().toISOString().slice(0, 10)}`,
          })} />
      </div>
      <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 16 }}>
        <div className="kpi-row">
          <KPI label="Total needed"   value={totals.needed}      sub={`across ${open.length} open requests`} icon="users" tint="var(--b50)"     accent="var(--b600)" />
          <KPI label="CVs received"   value={totals.cvs}         sub="this period"     icon="file"  tint="var(--info-50)" accent="var(--info-700)" />
          <KPI label="Interviewed"    value={totals.interviewed} sub="candidates"      icon="phone" tint="var(--warn-50)" accent="var(--warn-700)" />
          <KPI label="In training"    value={totals.training}    sub="onboarding"      icon="check-circle" tint="var(--good-50)" accent="var(--good-700)" />
        </div>

        <div className="tbl-wrap">
          <table className="data">
            <thead>
              <tr>
                <th>{window.t("Ref")}</th><th>{window.t("Client")}</th><th>{window.t("City")}</th><th>{window.t("Warehouses")}</th>
                <th className="num">{window.t("Needed")}</th><th>{window.t("Model")}</th><th>{window.t("Package")}</th>
                <th>{window.t("Priority")}</th><th>{window.t("Status")}</th>
                <th className="num">CVs</th><th className="num">Int</th><th className="num">Trn</th>
              </tr>
            </thead>
            <tbody>
              {open.map(r => (
                <tr key={r.ref}>
                  <td className="mono strong">{r.ref}</td>
                  <td className="strong">{r.client}</td>
                  <td>{r.city}</td>
                  <td className="muted" style={{ fontSize: 11.5 }}>{r.warehouses.join(", ")}</td>
                  <td className="num">{r.count}</td>
                  <td><ContractBadge type={r.model} /></td>
                  <td>{r.package}</td>
                  <td><span className={"badge " + (r.priority === "urgent" ? "badge-crit" : "badge-slate")} style={{ textTransform: "capitalize" }}>{r.priority}</span></td>
                  <td><span className="badge badge-brand" style={{ textTransform: "capitalize" }}>{r.status.replace("_", " ")}</span></td>
                  <td className="num">{r.cvs}</td>
                  <td className="num">{r.interviewed}</td>
                  <td className="num">{r.training}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr", gap: 14 }}>
          <div className="card">
            <div className="card-head"><h3>City breakdown</h3></div>
            <div className="card-body">
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(110px, 1fr))", gap: 10 }}>
                {Object.entries(byCity).map(([city, n]) => (
                  <div key={city} className="tile">
                    <div className="tl">{city}</div>
                    <div className="tv">×{n}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
          <div className="card">
            <div className="card-head"><h3>Model split</h3></div>
            <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <SplitRow label="Freelancer" value={freelancer} total={freelancer + salary} color="var(--warn)" />
              <SplitRow label="Salaried"   value={salary}     total={freelancer + salary} color="var(--info-600)" />
            </div>
          </div>
          <div className="card" style={{ background: "var(--good-50)", borderColor: "var(--good-100)" }}>
            <div className="card-body">
              <div className="label-tiny" style={{ color: "var(--good-700)" }}>Est. monthly cost</div>
              <div className="mono" style={{ fontSize: 26, fontWeight: 700, color: "var(--good-700)", marginTop: 6, letterSpacing: "-0.02em" }}>{fmtSAR(monthlyCost)}</div>
              <div style={{ fontSize: 11.5, color: "var(--good-700)", opacity: 0.7, marginTop: 4 }}>SAR · all open hires</div>
            </div>
          </div>
        </div>

        <div style={{ background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: "var(--r-md)", padding: 16, display: "grid", gridTemplateColumns: "1fr 1fr auto", gap: 12, alignItems: "end" }}>
          <div className="field">
            <label>{window.t("HR email")}</label>
            <input value={hrEmail} onChange={(e) => setHrEmail(e.target.value)} />
          </div>
          <div className="field">
            <label>{window.t("Procurement email")}</label>
            <input value={procEmail} onChange={(e) => setProcEmail(e.target.value)} />
          </div>
          <button className="btn primary lg" onClick={sendReport} disabled={sending}>
            {sending ? <span className="spinner" /> : <Icon name="send" size={13} color="#fff" />} {window.t("Send report")}
          </button>
        </div>
      </div>
    </div>
  );
}

function SplitRow({ label, value, total, color }) {
  const pct = total > 0 ? (value / total) * 100 : 0;
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 5 }}>
        <span>{label}</span>
        <span className="mono"><b>{value}</b> <span className="muted">· {Math.round(pct)}%</span></span>
      </div>
      <div style={{ height: 6, background: "var(--border-soft)", borderRadius: 999, overflow: "hidden" }}>
        <div style={{ width: pct + "%", height: "100%", background: color }} />
      </div>
    </div>
  );
}

// ── Invoice generator ────────────────────────────────────────
// Builds the real Busco invoice: KSA clients get the Busco Xpress TAX INVOICE
// (SAR, PP + COD lines, VAT 15%); Bahrain clients get the Busco Shipping
// W.L.L INVOICE (BHD, one Delivery Charge line, no VAT). Format copied from
// the actual May-2026 invoices.
function InvoiceGenerator({ onToast }) {
  const CLIENTS = useStore((s) => s.clients);
  const thisMonth = new Date().toISOString().slice(0, 7);
  const [clientId, setClientId] = useState("");
  const [month, setMonth] = useState(thisMonth);
  const [invoiceNo, setInvoiceNo] = useState("");
  const [ref, setRef] = useState("");
  const [invoice, setInvoice] = useState(null);

  const client = (window.CLIENTS || []).find(c => c.id === clientId);
  const country = client ? window.buscoClientCountry(client) : null;

  const generate = () => {
    if (!client) { onToast("Pick a client first", "danger"); return; }
    try {
      const inv = Store.generateInvoice({ clientName: client.name, month, invoiceNo: invoiceNo || undefined, ref: ref || undefined });
      if (!inv.totals.del && !inv.totals.off) { onToast("No delivery data for that month", "danger"); setInvoice(null); return; }
      setInvoice(inv);
      if (!client.bill_to) onToast(window.t("Tip: set this client's Bill To block (Clients → edit) so the invoice shows their legal details"), "danger");
    } catch (e) { onToast(e?.message || "Could not generate invoice", "danger"); }
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div className="card">
        <div className="card-head">
          <div className="ch-l">
            <h3>{window.t("Generate invoice")}</h3>
            <div className="ch-sub">{window.t("The official format — picked automatically from the client's country")}</div>
          </div>
          {country && <span className="badge badge-brand">{country === "bahrain" ? window.t("Bahrain · BHD · no VAT") : window.t("KSA · SAR · VAT 15%")}</span>}
        </div>
        <div className="card-body">
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr 1fr auto", gap: 12, alignItems: "end" }}>
            <div className="field">
              <label>{window.t("Client")}</label>
              <select value={clientId} onChange={e => { setClientId(e.target.value); setInvoice(null); }}>
                <option value="">{window.t("Select client…")}</option>
                {CLIENTS.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div className="field">
              <label>{window.t("Month")}</label>
              <input type="month" value={month} onChange={e => setMonth(e.target.value)} />
            </div>
            <div className="field">
              <label>{window.t("Invoice number")}</label>
              <input className="mono" value={invoiceNo} onChange={e => setInvoiceNo(e.target.value)} placeholder={country === "bahrain" ? "BS/1037" : "BX/1004"} />
            </div>
            <div className="field">
              <label>{window.t("Ref No")} <span className="muted" style={{ textTransform: "none", fontWeight: 400 }}>{window.t("opt")}</span></label>
              <input className="mono" value={ref} onChange={e => setRef(e.target.value)} placeholder="Busco/Ajex/May" />
            </div>
            <button className="btn primary" onClick={generate}>
              <Icon name="file" size={13} color="#fff" /> {window.t("Generate")}
            </button>
          </div>
        </div>
      </div>

      {invoice && <InvoicePreview invoice={invoice} onToast={onToast} />}
    </div>
  );
}

function InvoicePreview({ invoice, onToast }) {
  const inv = invoice;
  const n = (v) => (Number(v) || 0).toFixed(inv.dp);
  const html = window.buscoInvoiceHTML(inv);                       // preview
  const [downloading, setDownloading] = useState(false);

  const downloadPdf = async () => {
    const safe = (s) => String(s || "invoice").replace(/[\\/:*?"<>|]+/g, "-").trim();
    const filename = `${safe(inv.invoiceNo || inv.entity.numPrefix)} ${safe(inv.client)} ${inv.month}.pdf`;
    setDownloading(true);
    try {
      await window.buscoHtmlToPdf(html, filename);
    } catch (e) {
      onToast(`Couldn’t make the PDF: ${e.message}`, "danger");
    } finally {
      setDownloading(false);
    }
  };

  return (
    <div className="card">
      <div className="card-head">
        <div className="ch-l">
          <h3 className="mono">{inv.invoiceNo || inv.entity.numPrefix} · {inv.client}</h3>
          <div className="ch-sub">
            {inv.month} · {inv.totals.del} {window.t("delivered")} · {window.t("Total")} {n(inv.total)} {inv.currency}
            {inv.country !== "bahrain" && ` (${window.t("incl. VAT")} ${n(inv.vatAmount)})`}
          </div>
        </div>
        <button className="btn primary sm" onClick={downloadPdf} disabled={downloading}>
          <Icon name="file" size={12} color="#fff" /> {downloading ? window.t("Preparing…") : window.t("Save as PDF")}
        </button>
      </div>
      <div className="card-body" style={{ padding: 0, background: "var(--canvas)" }}>
        <iframe title="invoice-preview" srcDoc={html}
          style={{ width: "100%", height: 1050, border: 0, background: "#fff", display: "block" }} />
      </div>
    </div>
  );
}

// ── Courier costs — month breakdown ──────────────────────────
// Shows exactly HOW each courier's pay is calculated for the chosen month:
// salaried = flat salary; freelancers = per client, PPD delivered × PPD rate
// + COD delivered × COD rate (rates from the courier's per-client details).
function CourierCostsView({ onToast, cur = "all" }) {
  useStore((s) => s.entries);   // re-render on data changes
  const [month, setMonth] = useState(new Date().toISOString().slice(0, 7));
  const breakdown = window.buscoCourierCostBreakdown(month);
  const active = breakdown.filter((b) => (b.total > 0 || b.courier.contract_type === "salary") && (cur === "all" || b.currency === cur));
  // Totals grouped by currency — never summed across SAR and BHD.
  const byCur = {};
  for (const b of active) {
    const k = b.currency || "SAR";
    (byCur[k] || (byCur[k] = { total: 0, sal: 0, free: 0 }));
    byCur[k].total += b.total;
    if (b.courier.contract_type === "salary") byCur[k].sal += b.total; else byCur[k].free += b.total;
  }
  const curList = Object.keys(byCur);
  const costLines = (field) => curList.length === 0
    ? <span>—</span>
    : <span>{curList.map((k) => <span key={k} style={{ display: "block", fontSize: curList.length > 1 ? 18 : undefined, lineHeight: 1.3 }}>{fmtMoney(byCur[k][field], k)}</span>)}</span>;
  const monthLabel = new Date(month + "-01").toLocaleDateString("en-GB", { month: "long", year: "numeric" });

  const exportPdf = () => {
    const esc = (v) => String(v ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    const rows = active.map((b) => `
      <tr class="main"><td><b>${esc(b.courier.name)}</b> <span class="mut">${esc(b.courier.courier_code || "")}</span></td>
        <td>${b.courier.contract_type === "salary" ? "Salaried" : "Freelancer"}</td>
        <td class="r"><b>${fmtMoneyNum(b.total, b.currency)} ${esc(b.currency)}</b></td></tr>
      ${b.lines.map((l) => `<tr class="sub"><td colspan="2">— ${esc(l.label)}${l.detail ? ` · <span class="mut">${esc(l.detail)}</span>` : ""}</td><td class="r">${fmtMoneyNum(l.amount, b.currency)} ${esc(b.currency)}</td></tr>`).join("")}
    `).join("");
    const footRows = curList.map((k) => `<tr><td colspan="2">Total courier costs (${esc(k)})</td><td class="r">${fmtMoneyNum(byCur[k].total, k)} ${esc(k)}</td></tr>`).join("");
    const win = window.open("", "_blank");
    if (!win) { onToast("Pop-up blocked — allow pop-ups to export", "danger"); return; }
    win.document.write(`<!DOCTYPE html><html><head><title>Courier costs ${esc(month)}</title><style>
      body{font-family:'IBM Plex Sans',Arial,sans-serif;margin:24px;color:#0b1720}
      h2{font-size:16px;margin:0} .sub-t{font-size:11px;color:#64748b;margin:2px 0 14px}
      table{border-collapse:collapse;width:100%;font-size:11.5px}
      td{padding:6px 8px;border-bottom:1px solid #e9eef3} .r{text-align:right}
      tr.main td{background:#f8fafc;border-top:1px solid #cbd5e1} tr.sub td{color:#334155}
      .mut{color:#94a3b8} tfoot td{font-weight:700;font-size:13px;border-top:2px solid #334155}
      @media print{body{margin:8mm}}
    </style></head><body>
      <h2>Busco — Courier cost breakdown</h2><div class="sub-t">${esc(monthLabel)} · ${active.length} couriers</div>
      <table><tbody>${rows}</tbody>
      <tfoot>${footRows}</tfoot></table>
      <script>window.onload=function(){window.print();}</` + `script></body></html>`);
    win.document.close();
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="sec no-pad">
        <h2>{window.t("Courier costs")} · {monthLabel} <span className="ct">{active.length}</span></h2>
        <div className="sec-right">
          <input type="month" value={month} onChange={(e) => setMonth(e.target.value)}
            style={{ border: "1px solid var(--border)", borderRadius: "var(--r-sm)", padding: "6px 9px", fontSize: 12 }} />
          <button className="btn sm" onClick={exportPdf}><Icon name="file" size={12} /> {window.t("Export PDF")}</button>
        </div>
      </div>

      <div className="kpi-row" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
        <KPI label={window.t("Total courier costs")} value={costLines("total")} sub={monthLabel} icon="wallet" tint="var(--warn-50)" accent="var(--warn-700)" />
        <KPI label={window.t("Salaried")} value={costLines("sal")} sub={`${active.filter((b) => b.courier.contract_type === "salary").length} ${window.t("couriers")}`} icon="briefcase" tint="var(--info-50)" accent="var(--info-700)" />
        <KPI label={window.t("Freelancers")} value={costLines("free")} sub={`${active.filter((b) => b.courier.contract_type !== "salary").length} ${window.t("couriers")}`} icon="tool" tint="var(--good-50)" accent="var(--good-700)" />
      </div>

      <div className="tbl-wrap">
        <table className="data">
          <thead>
            <tr>
              <th>{window.t("Courier")}</th>
              <th>{window.t("Contract")}</th>
              <th>{window.t("How it's calculated")}</th>
              <th className="num">{window.t("Amount due")}</th>
            </tr>
          </thead>
          <tbody>
            {active.length === 0 &&
              <tr><td colSpan={4} style={{ textAlign: "center", padding: "22px 0", color: "var(--muted)" }}>
                {window.t("No courier activity this month.")}
              </td></tr>
            }
            {active.map((b) => (
              <React.Fragment key={b.courier.id}>
                <tr style={{ background: "var(--surface-2)" }}>
                  <td className="strong">{b.courier.name} <span className="mono muted" style={{ fontSize: 10.5 }}>{b.courier.courier_code}</span></td>
                  <td><ContractBadge type={b.courier.contract_type} /></td>
                  <td className="muted" style={{ fontSize: 11.5 }}>
                    {b.courier.contract_type === "salary" ? window.t("Fixed monthly salary") : `${b.lines.length} ${window.t("client(s) this month")}`}
                  </td>
                  <td className="num strong">{fmtMoney(b.total, b.currency)}</td>
                </tr>
                {b.courier.contract_type !== "salary" && b.lines.map((l, i) => (
                  <tr key={i}>
                    <td style={{ paddingInlineStart: 28, fontSize: 12 }} colSpan={2}>↳ {l.label}</td>
                    <td className="mono" style={{ fontSize: 11.5, color: "var(--muted)" }}>{l.detail}</td>
                    <td className="num">{fmtMoney(l.amount, b.currency)}</td>
                  </tr>
                ))}
                {b.courier.contract_type !== "salary" && b.lines.length === 0 &&
                  <tr><td colSpan={4} style={{ paddingInlineStart: 28, fontSize: 11.5, color: "var(--muted)" }}>{window.t("No deliveries recorded this month.")}</td></tr>
                }
              </React.Fragment>
            ))}
          </tbody>
          <tfoot>
            {(curList.length ? curList : ["SAR"]).map((k) => (
              <tr key={k} className="row-total">
                <td className="strong" colSpan={3}>{window.t("Total courier costs")} <span className="mono muted" style={{ fontSize: 11 }}>· {k}</span></td>
                <td className="num strong" style={{ color: "var(--warn-700)" }}>{fmtMoney(byCur[k] ? byCur[k].total : 0, k)}</td>
              </tr>
            ))}
          </tfoot>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { FinancialScreen, HRScreen, InvoiceGenerator, InvoicePreview, CourierCostsView });
