/* shipping.jsx — Shipping department: lag, tracked share, daily shipped volume.
   Date filter only — downstream of intake. */
const { D, fmt, pct, opsInRange, dayLabel } = window.RX;

function Shipping({ filter, chartFilled }) {
  const ops = opsInRange(filter.from, filter.to);
  const untracked = ops.verified - ops.tracked;
  const days = D.byDay.filter(x => x.d >= filter.from && x.d <= filter.to);
  const slice = days.length > 92 ? days.slice(-92) : days;
  const bars = slice.map(x => ({ label: dayLabel(x.d), full: x.d, value: x.t || 0, faint: (x.t || 0) === 0 }));

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>Shipping</h1>
          <p>Outbound performance: how fast verified work leaves the building, and how much of it carries a tracking number. Date filter only — once a script clears intake it ships regardless of payer or product.</p>
        </div>
        <div className="lens-flag">{window.RX.fmtDate(filter.from)} – {window.RX.fmtDate(filter.to)}</div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(4,1fr)", marginBottom: "var(--gap)" }}>
        <KPI feature label="Avg ship lag" value={ops.ship_lag == null ? "—" : ops.ship_lag.toFixed(2)} sub="days · dispense → ship" />
        <KPI label="Shipped" value={ops.shipped_pct == null ? "—" : pct(ops.shipped_pct, 1)} accentBar="var(--sl-supplies)" sub="verified scripts with a tracking number"
          tip="Pharmacist-verified scripts in range that carry a shipment tracking number." />
        <KPI label="Scripts shipped" value={fmt(ops.tracked)} accentBar="var(--pos)" sub="tracking number on file · in range" />
        <KPI label="Verified, no tracking" value={fmt(Math.max(0, untracked))} accentBar="var(--warn)" sub="in range — the follow-up pile" />
      </div>

      <Card title="Shipped per day" desc="Verified-with-tracking volume by dispense date. Longer ranges show the most recent 92 days."
        meta={`${fmt(ops.tracked)} in range`}>
        {bars.length ? <VBars data={bars} height={240} color="var(--accent)" />
          : <div className="empty">No days in the selected range.</div>}
      </Card>
    </div>
  );
}
Object.assign(window, { Shipping });
