/* forecast.jsx — projected refill workload */
const { D, fmt, pct, dayLabel, slVar } = window.RX;

function Forecast({ filter, chartFilled }) {
  const fw = D.forecast_windows;
  const days = D.forecast_by_day.map(([date, count, wd]) => ({ date, count, wd }));
  // build a continuous business-day series with weekend markers between
  const bars = days.map(d => ({ label: dayLabel(d.date), full: d.wd + " " + d.date, value: d.count, sub: d.wd, faint: d.count < 80 }));
  const weekTotals = [];
  // group into ISO weeks of Mon-Fri (the data is business days)
  let acc = 0, lbl = null;
  // simple: chunk every 5 business days
  for (let i = 0; i < days.length; i += 5) {
    const chunk = days.slice(i, i + 5);
    weekTotals.push({ label: "Wk of " + dayLabel(chunk[0].date), value: chunk.reduce((a, b) => a + b.count, 0) });
  }
  // projected line split (from on-service line shares, all-payer) — guarded for unified-down
  const H = D.headlines && D.headlines[lensKey(filter.pbLens)];
  const lineShare = H ? D.lines.map(l => ({ l, s: H.by_line[l] || 0 })).filter(r => r.s > 0) : [];
  const lineTot = lineShare.reduce((a, b) => a + b.s, 0) || 1;

  // staffing callout — busiest/lightest upcoming weekday (production sentence)
  const next14 = D.forecast_by_day.slice(0, 14).filter(d => d[2] !== "Sat" && d[2] !== "Sun");
  let callout = null;
  if (next14.length >= 2) {
    const DOWFULL = { Mon: "Monday", Tue: "Tuesday", Wed: "Wednesday", Thu: "Thursday", Fri: "Friday" };
    const heavy = next14.reduce((a, b) => b[1] > a[1] ? b : a);
    const light = next14.reduce((a, b) => b[1] < a[1] ? b : a);
    const avg = Math.round(next14.reduce((a, b) => a + b[1], 0) / next14.length);
    callout = <div className="callout">Coming week: heaviest on <b>{DOWFULL[heavy[2]]} {heavy[0].slice(5)}</b> ({fmt(heavy[1])} fills), lightest on <b>{DOWFULL[light[2]]} {light[0].slice(5)}</b> ({fmt(light[1])}). 14-day average: <b>{fmt(avg)}/day</b>. Plan extra hands for {DOWFULL[heavy[2]]}; consider moving non-urgent work into {DOWFULL[light[2]]}.</div>;
  }

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>Forecast</h1>
          <p>Expected refill workload. Every active recurring fill is projected forward from its dispense date + day-supply − 3 days, weighted by current on-service status. A planning tool, not a promise.</p>
        </div>
        <div className="lens-flag">Method · <b>on-service weighted</b></div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "repeat(4,1fr)", marginBottom: "var(--gap)" }}>
        <KPI feature label="Next 7 days" value={fmt(fw.d7)} sub="projected refills" />
        <KPI label="Next 14 days" value={fmt(fw.d14)} accentBar="var(--sl-supplies)" sub="projected refills" />
        <KPI label="Next 30 days" value={fmt(fw.d30)} accentBar="var(--sl-cgm)" sub="projected refills" />
        <KPI label="Next 90 days" value={fmt(fw.d90)} accentBar="var(--sl-enteral)" sub="raw projection" />
      </div>

      {callout}

      <Card title="Daily projected refills" desc="Business days ahead. Saturdays & Sundays roll back to the prior Friday — weekend bars sit at zero by design."
        meta={`${days[0].date} → ${days[days.length - 1].date}`} style={{ marginBottom: "var(--gap)" }}>
        <VBars data={bars} height={260} color="var(--accent)" />
      </Card>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", marginBottom: "var(--gap)" }}>
        <Card title="Weekly rollup" desc="Projected fills per upcoming business week.">
          <div className="rank">
            {weekTotals.map((w, i) => (
              <div className="rank-row" key={i} style={{ gridTemplateColumns: "1fr auto" }}>
                <div className="bar-track">
                  <div className="bar-fill" style={{ width: (w.value / Math.max(...weekTotals.map(x => x.value)) * 100) + "%", background: "var(--accent)", opacity: .8 }} />
                  <div className="bar-label">{w.label}</div>
                </div>
                <div className="val">{fmt(w.value)}</div>
              </div>
            ))}
          </div>
        </Card>
        <Card title="Projected line mix" desc="Next-90-day workload apportioned by current on-service share.">
          <div className="rank">
            {lineShare.sort((a, b) => b.s - a.s).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.s / lineShare[0].s * 100) + "%", background: slVar(r.l), opacity: .82 }} />
                  <div className="bar-label"><span className="sw" style={{ background: slVar(r.l) }} />{r.l}</div>
                </div>
                <div className="val">{fmt(Math.round(fw.d90 * r.s / lineTot))}</div>
                <div className="pct">{pct(r.s / lineTot * 100, 0)}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <Card title="How the forecast is built" desc="Calibration parameters, for context.">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: "var(--gap)" }}>
          {[["Active fill rate", "88%", "of on-service due dates convert"],
            ["Lapsed fill rate", "10%", "of lapsed due dates convert"],
            ["Stage-ahead", "−3 days", "refill due sits ahead of run-out"]].map(([l, v, s]) => (
            <div key={l} style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              <span className="sub" style={{ color: "var(--text-2)", fontWeight: 500 }}>{l}</span>
              <span className="mono" style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-.02em" }}>{v}</span>
              <span className="sub">{s}</span>
            </div>
          ))}
        </div>
        <div className="note" style={{ marginTop: 14 }}>{D.forecast_calibration.note}</div>
      </Card>
    </div>
  );
}
Object.assign(window, { Forecast });
