/* verification.jsx — Onboarding/Verification: benefit-verification intake trail
   (full filter rail) + pharmacist verify-lag stats (date-only, downstream step). */
const { D, fmt, pct, monthLabelShort, fmtMonthLong, opsInRange } = window.RX;

function Verification({ filter }) {
  const ops = opsInRange(filter.from, filter.to);
  const pa = D.ops.pa_onhold;

  // Verifications trail, filterable by payer/line/brand via the dims.
  // Item-level product selections apply at BRAND level here (dims carry family,
  // not item) — any selected item activates its whole family.
  const payerNames = new Set([...filter.payers].map(i => D.payers[i].name.toUpperCase()));
  const allProducts = filter.products.size === D.drugs.length;
  const fams = allProducts ? null : new Set([...filter.products].map(i => (D.drugs[i].family || "Other").toUpperCase()));
  const filtered = !D.benefit_checks_dim ? null :
    (payerNames.size === D.payers.length && filter.lines.size === D.lines.length && allProducts);
  const byMonth = {};
  if (D.benefit_checks_dim) {
    for (const [m, payer, line, family, n] of D.benefit_checks_dim) {
      if (!payerNames.has(String(payer).toUpperCase()) && payerNames.size !== D.payers.length) continue;
      if (!filter.lines.has(line) && D.lines.includes(line)) continue;
      if (fams && !fams.has(String(family).toUpperCase())) continue;
      byMonth[m] = (byMonth[m] || 0) + n;
    }
  } else if (D.benefit_by_month) {
    Object.assign(byMonth, D.benefit_by_month);
  }
  // Anchored at Jan 2025 (handoff 2026-06-27): the complete on-hold export is
  // already floored to 2025-01, so show the full Jan-2025 -> present series.
  const bm = Object.entries(byMonth).filter(([m]) => m >= "2025-01").sort((a, b) => a[0] < b[0] ? -1 : 1);
  const benefitTotal = bm.reduce((a, b) => a + b[1], 0);
  const bars = bm.map(([m, v]) => ({ label: monthLabelShort(m), full: fmtMonthLong(m), value: v, faint: v < 2000 }));

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>Onboarding/Verification</h1>
          <p>Intake department: patient referrals in, benefits verified through the Verification queue, refill requests out to providers. Verify-lag stats are the pharmacist step downstream and follow the date filter only.</p>
        </div>
        <div className="lens-flag"><Ico size={13} d={ICONS.clock} />Avg clear · <b>{ops.verify_lag == null ? "—" : ops.verify_lag.toFixed(2)} days</b></div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(5,1fr)", marginBottom: "var(--gap)" }}>
        <KPI feature label="Avg verify lag" value={ops.verify_lag == null ? "—" : ops.verify_lag.toFixed(2)} sub="days · dispense → verified · selected range" />
        <KPI label="Fills verified" value={fmt(ops.verified)} accentBar="var(--sl-supplies)" sub="selected range · all queues" />
        <KPI label="Verifications logged" value={fmt(benefitTotal)} accentBar="var(--sl-cgm)" sub="still on hold · by month entered"
          tip="Verification-queue scripts by month entered. Resolved verifications disappear from the data, so older months undercount real work." />
        <KPI label="Cleared ≤ 1 day" value={D.ops.verified_within_1d_pct == null ? "—" : pct(D.ops.verified_within_1d_pct, 0)} accentBar="var(--pos)" sub="of verifications · all-time" />
        <KPI label="PA on hold" value={pa ? fmt(pa.total) : "—"} accentBar="var(--warn)"
          sub={pa ? `Prior Authorization queue${pa.ccs_reauth ? ` · CCS re-auth ${fmt(pa.ccs_reauth)} separate` : ""}` : "unavailable"} />
      </div>

      <Card title="Verifications volume by month"
        desc="Work trail of the benefits department: verification scripts created in the Verification queue to check coverage or generate refill requests, by the month they were entered."
        meta={D.benefit_checks_dim || D.benefit_by_month ? `${fmt(benefitTotal)} verification scripts that are still on hold${filtered === false ? " · filtered" : ""}` : "as-of snapshot"}>
        {(D.benefit_checks_dim || D.benefit_by_month)
          ? (bm.length
            ? <>
              <VBars data={bars} height={230} color="var(--sl-cgm)" />
              <div className="note">Counts only verification scripts <b>still on hold</b> — resolved verifications disappear from the data, so historical months undercount the real work done. The trend reads best in recent months. Per-tech breakdown awaits the department roster.</div>
            </>
            : <div className="empty">No verification scripts are on hold in the data.</div>)
          : <Unavail what="Verification volumes" />}
      </Card>
    </div>
  );
}
Object.assign(window, { Verification });
