/* overview.jsx — executive glance */
const { D, fmt, fmtSign, pct, monthLabel, monthLabelShort, slVar } = window.RX;

const lensKey = (pb) => pb === "xpb" ? "xpb" : pb === "xent" ? "xent" : "all";
const lensName = (pb) => pb === "xpb" ? "Excl. all paper-bill" : pb === "xent" ? "Excl. enteral paper-bill" : "All payers";

function MixBars({ byLine }) {
  const total = Object.values(byLine).reduce((a, b) => a + b, 0) || 1;
  const rows = D.lines.map(l => ({ l, v: byLine[l] || 0 })).filter(r => r.v > 0).sort((a, b) => b.v - a.v);
  return (
    <div className="rank">
      {rows.map(r => (
        <div className="rank-row" key={r.l} style={{ gridTemplateColumns: "1fr auto auto" }}>
          <div className="bar-track">
            <div className="bar-fill" style={{ width: (r.v / rows[0].v * 100) + "%", background: slVar(r.l), opacity: .85 }} />
            <div className="bar-label"><span className="sw" style={{ background: slVar(r.l) }} />{r.l}</div>
          </div>
          <div className="val">{fmt(r.v)}</div>
          <div className="pct">{pct(r.v / total * 100, 1)}</div>
        </div>
      ))}
    </div>
  );
}

function Overview({ filter, agg, chartFilled, setView }) {
  if (!D.headlines) return (
    <div className="page"><div className="page-head"><div><h1>Overview</h1></div></div>
      <Card><Unavail what="Patient headline metrics" /></Card></div>);
  const H = D.headlines[lensKey(filter.pbLens)];
  const curve = D.on_service_curve;
  const marIdx = curve.findIndex(c => c.month === "2026-03");
  const primaryKey = filter.pbLens === "xpb" ? "xpb" : filter.pbLens === "xent" ? "xent" : "all";
  const series = [{ label: "On service", values: curve.map(c => c[primaryKey]), color: "var(--accent)" }];
  if (primaryKey !== "all") series.push({ label: "All payers", values: curve.map(c => c.all), color: "var(--text-3)", dashed: true });
  const osDelta = curve[curve.length - 1][primaryKey] - curve[curve.length - 2][primaryKey];

  // dispensed volume (filter-driven) — daily for short ranges, monthly otherwise
  const rangeDays = (window.RX.D.byDay && (new Date(filter.to) - new Date(filter.from)) / 864e5) + 1;
  const useDaily = (filter.mTo - filter.mFrom) < 1 || rangeDays <= 70;
  let volSeries, volLabels;
  if (useDaily) {
    const bd = window.RX.byDayRange(filter.from, filter.to);
    volLabels = bd.map(x => window.RX.fmtDate(x.d));
    volSeries = [{ label: "Fills", values: bd.map(x => x.c), color: "var(--sl-supplies)" }];
  } else {
    volLabels = D.months.slice(filter.mFrom, filter.mTo + 1).map(monthLabelShort);
    volSeries = [{ label: "Fills", values: agg.byMonth.slice(filter.mFrom, filter.mTo + 1), color: "var(--sl-supplies)" }];
  }

  const topProds = agg.byDrug.map((v, i) => ({ i, v })).sort((a, b) => b.v - a.v).slice(0, 6);
  const maxProd = topProds[0] ? topProds[0].v : 1;
  const ops = window.RX.opsInRange(filter.from, filter.to);
  const pa = D.ops.pa_onhold;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>Overview</h1>
          <p>The book of business at a glance. Headline patient counts follow the paper-bill lens; the volume & mix charts respond to every filter in the rail.</p>
        </div>
        <div className="lens-flag"><span className="dot" style={{ width: 7, height: 7, borderRadius: 9, background: "var(--accent)" }} />Lens · <b>{lensName(filter.pbLens)}</b></div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(6,1fr)", marginBottom: "var(--gap)" }}>
        <KPI feature label="On service now" value={fmt(H.on_service)}
          tip={H.on_service_pct != null ? `${pct(H.on_service_pct, 1)} of the recently-active book — currently covered or lapsed ≤90 days (${fmt(H.reachable)} patients).` : null}
          sub={`${H.on_service_pct != null ? pct(H.on_service_pct, 0) + " of active book · " : ""}Pump ${fmt(H.by_line["Pump Supplies"])} · Ent ${fmt(H.by_line["Enteral"])} · CGM ${fmt(H.by_line["CGM"])}`}>
          <div style={{ marginTop: 8 }}><Spark values={D.on_service_curve.map(c => c[primaryKey])} color="#fff" w={150} h={28} /></div>
        </KPI>
        <KPI label="Net · 30d" value={fmtSign(H.net_30d)} delta={H.net_30d} invert={false}
          sub="new − churned" accentBar={H.net_30d >= 0 ? "var(--pos)" : "var(--neg)"} valClass={H.net_30d < 0 ? "" : ""} tip="New minus churned over the last 30 days. Above zero = the book is growing." />
        <KPI label="New · 30d" value={fmt(H.new_30d)} sub="history-verified" accentBar="var(--pos)" tip="First-ever fill (or first after a long gap) in the last 30 days." />
        <KPI label="Churned · 30d" value={fmt(H.churned_30d)} sub="coverage lapsed" accentBar="var(--neg)" tip="Supplies + grace ran out in the last 30 days with no new fill." />
        <KPI label="Forecast · next 7d" value={fmt(D.forecast_windows.d7)} sub="projected refills" accentBar="var(--sl-supplies)" tip="Expected refill workload over the next 7 days, weighted by on-service status." />
        <KPI label="Auto-refill consent" value={pct(H.autofill, 0)} sub="of on-service" accentBar="var(--sl-cgm)" tip="Share of on-service patients with auto-refill enabled on their profile." />
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1.5fr 1fr", marginBottom: "var(--gap)" }}>
        <Card title="On-service trend" desc="Patients whose recurring supply still covers today, month over month."
          meta={`${monthLabel(curve[0].month)} – ${monthLabel(curve[curve.length - 1].month)}`}>
          <AreaLine series={series} labels={curve.map(c => monthLabelShort(c.month))} height={232} filled={chartFilled}
            yFromZero={false} annotations={marIdx >= 0 ? [{ idx: marIdx, label: ["Mar 2026 — enteral joins", "model coverage grows, not the business"] }] : []} />
          {primaryKey !== "all" &&
            <div className="legend"><span><i style={{ background: "var(--accent)" }} />{lensName(filter.pbLens)}</span><span><i style={{ background: "var(--text-3)" }} />All payers</span></div>}
        </Card>
        <Card title="Dispensed volume" desc={useDaily ? "Daily fills in the selected window — follows every filter." : "Monthly fills — follows payer, line & month filters."}
          meta={`${fmt(agg.grand)} fills`}>
          <AreaLine series={volSeries} labels={volLabels} height={232} filled={chartFilled} />
        </Card>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1.1fr", marginBottom: "var(--gap)" }}>
        <Card title="Volume by service line" desc="Share of filtered fills across device lines.">
          {agg.grand > 0 ? <MixBars byLine={agg.byLine} /> : <div className="empty">No fills match the current filters.</div>}
        </Card>
        <Card title="Top products" desc="Best sellers in the current filter set." right={<button className="pillbtn" onClick={() => setView("mix")}>Open explorer <Ico size={13} d={ICONS.chevR} /></button>}>
          <div className="rank">
            {topProds.map(p => (
              <div className="rank-row" key={p.i} style={{ gridTemplateColumns: "1fr auto auto" }}>
                <div className="bar-track">
                  <div className="bar-fill" style={{ width: (p.v / maxProd * 100) + "%", background: slVar(D.drugs[p.i].line), opacity: .8 }} />
                  <div className="bar-label"><span className="sw" style={{ background: slVar(D.drugs[p.i].line) }} />{D.drugs[p.i].name}</div>
                </div>
                <div className="val">{fmt(p.v)}</div>
                <div className="pct">{pct(p.v / agg.grand * 100, 1)}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <Card title="Operations" desc="Throughput health — kept light by design. Lags and shipped % follow the date filter; PA is the live queue.">
        <div className="grid" style={{ gridTemplateColumns: "repeat(4,1fr)" }}>
          <KPI label="Avg ship lag" value={ops.ship_lag == null ? "—" : ops.ship_lag.toFixed(2)} sub="days · dispense → ship · selected range" />
          <KPI label="Avg verify lag" value={ops.verify_lag == null ? "—" : ops.verify_lag.toFixed(2)} sub="days · dispense → verified · selected range" />
          <KPI label="Shipped" value={ops.shipped_pct == null ? "—" : pct(ops.shipped_pct, 1)} sub="verified scripts with a tracking number"
            tip="Pharmacist-verified scripts that carry a shipment tracking number, over the selected range." />
          <KPI label="PA on hold" value={pa ? fmt(pa.total) : "—"} sub={pa ? `Prior Authorization queue · as-of snapshot${pa.ccs_reauth ? ` · CCS re-auth ${fmt(pa.ccs_reauth)} separate` : ""}` : "unavailable"} />
        </div>
      </Card>

      <details className="card" style={{ marginTop: "var(--gap)" }}>
        <summary style={{ cursor: "pointer", padding: "2px 0" }}>
          <b>Retail / Other — separate book (volume & profit)</b>
          <div className="d" style={{ marginTop: 3 }}>Maintenance meds and other non-device items. Tracked for volume and profit only — this line never mixes into the device-line KPIs or the on-service model above.</div>
        </summary>
        {D.retail ? (
          <div style={{ marginTop: 12 }}>
            <div className="grid" style={{ gridTemplateColumns: "repeat(3,1fr)", marginBottom: 12 }}>
              <KPI label="Retail fills" value={fmt(D.retail.fills_total)} sub="all-time" />
              <KPI label="Retail patients" value={fmt(D.retail.patients_total)} sub="all-time" />
              <KPI label="Net profit" value={"$" + fmt(D.retail.net_profit_total)} sub={`across ${fmt(D.retail.net_profit_fills)} priced fills`} />
            </div>
            <div className="rank">
              {Object.entries(D.retail.by_month).map(([m, v]) => {
                const mx = Math.max(...Object.values(D.retail.by_month));
                return (
                  <div className="rank-row" key={m} style={{ gridTemplateColumns: "1fr auto" }}>
                    <div className="bar-track">
                      <div className="bar-fill" style={{ width: (v / mx * 100) + "%", background: "var(--sl-acc)", opacity: .7 }} />
                      <div className="bar-label">{window.RX.fmtMonthLong(m)}</div>
                    </div>
                    <div className="val">{fmt(v)}</div>
                  </div>);
              })}
            </div>
            <div className="note">{D.retail.note}</div>
          </div>
        ) : <div className="empty" style={{ marginTop: 10 }}>Retail aggregates are unavailable in this build and will return on the next data refresh.</div>}
      </details>
    </div>
  );
}
Object.assign(window, { Overview, lensKey, lensName });
