/* fillers.jsx — Fillers department: who fills, when. Date filter only —
   downstream of intake, every script gets filled regardless of payer/product. */
const { D, fmt, pct, fmtMonthLong, monthLabelShort } = window.RX;

const DOW7 = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const dowOf = (iso) => (new Date(iso + "T00:00:00").getDay() + 6) % 7; // Mon=0

function fillerData(from, to) {
  const byTech = {};
  const months = new Set();
  for (const [d, tech, n] of D.filler_daily) {
    if (d < from || d > to) continue;
    const t = (byTech[tech] = byTech[tech] || { total: 0, dow: [0, 0, 0, 0, 0, 0, 0], mon: {} });
    t.total += n;
    t.dow[dowOf(d)] += n;
    const m = d.slice(0, 7);
    t.mon[m] = (t.mon[m] || 0) + n;
    months.add(m);
  }
  const fillers = Object.entries(byTech).sort((a, b) => b[1].total - a[1].total);
  return { fillers, months: [...months].sort() };
}

function FillerHeat({ fillers, cols, cellVal, colLabel, colTitle }) {
  const max = Math.max(1, ...fillers.flatMap(([, t]) => cols.map(c => cellVal(t, c))));
  return (
    <div className="heat" style={{ gridTemplateColumns: "44px repeat(" + cols.length + ",1fr)", "--hc": "22px" }}>
      <div className="hlab" />
      {cols.map(c => <div key={c} className="hlab" style={{ justifyContent: "center" }}>{colLabel(c)}</div>)}
      {fillers.map(([tech, t]) => (
        <React.Fragment key={tech}>
          <div className="hlab">{tech}</div>
          {cols.map(c => {
            const v = cellVal(t, c);
            const a = v ? 0.12 + 0.88 * Math.sqrt(v / max) : 0;
            return <div key={c} className="hcell" title={tech + " · " + colTitle(c) + " · " + fmt(v)}
              style={{ background: v ? "color-mix(in srgb, var(--accent) " + (a * 100).toFixed(0) + "%, var(--panel-2))" : "var(--panel-2)", color: a > 0.55 ? "#fff" : "var(--text-3)" }}>
              {v >= max * 0.5 ? fmt(v) : ""}
            </div>;
          })}
        </React.Fragment>
      ))}
    </div>
  );
}

function Fillers({ filter }) {
  const [mode, setMode] = useLS("rx_filler_mode", "weekday");
  const { fillers, months } = useMemo(() => fillerData(filter.from, filter.to), [filter.from, filter.to]);
  const shown = fillers.slice(0, 16);
  const total = fillers.reduce((a, [, t]) => a + t.total, 0);
  const maxTotal = shown.length ? shown[0][1].total : 1;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>Fillers</h1>
          <p>The filling team's output, from the Entered By column of the dispensed data. Date filter only — payer and product don't change who fills what.</p>
        </div>
        <div className="lens-flag"><b>{fmt(total)}</b> scripts in range</div>
      </div>

      <Card title="Filler productivity" desc="Scripts entered per filler. Darker = busier. Toggle the columns between weekday rhythm and monthly trend."
        meta={`${shown.length} of ${fillers.length} fillers`}
        right={<Segmented value={mode} options={[{ value: "weekday", label: "Weekday" }, { value: "month", label: "Month" }]} onChange={setMode} />}
        style={{ marginBottom: "var(--gap)" }}>
        {shown.length ? (mode === "weekday"
          ? <FillerHeat fillers={shown} cols={[0, 1, 2, 3, 4, 5, 6]} cellVal={(t, c) => t.dow[c]} colLabel={c => DOW7[c]} colTitle={c => DOW7[c]} />
          : <FillerHeat fillers={shown} cols={months} cellVal={(t, c) => t.mon[c] || 0} colLabel={c => monthLabelShort(c)} colTitle={c => fmtMonthLong(c)} />)
          : <div className="empty">No fills in the selected range.</div>}
        {fillers.length > shown.length && <div className="note">Showing the top {shown.length} fillers by volume in range; {fillers.length - shown.length} more fall below the fold.</div>}
      </Card>

      <Card title="Output by filler" desc="Scripts entered in the selected range. De-identified to initials." meta={`${fmt(total)} total`}>
        <div className="rank" style={{ maxHeight: 380, overflowY: "auto" }}>
          {shown.map(([tech, t], i) => (
            <div className="rank-row" key={tech} style={{ gridTemplateColumns: "1fr auto auto" }}>
              <div className="bar-track">
                <div className="bar-fill" style={{ width: (t.total / maxTotal * 100) + "%", background: i < 3 ? "var(--accent)" : "var(--sl-acc)", opacity: i < 3 ? .85 : .6 }} />
                <div className="bar-label">{tech}</div>
              </div>
              <div className="val">{fmt(t.total)}</div>
              <div className="pct">{total ? pct(t.total / total * 100, 1) : "—"}</div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}
Object.assign(window, { Fillers });
