/* projects.jsx — transient initiatives: TSP funnel + CGM Service scaffold */
const { D, fmt, pct, monthLabel, monthLabelShort, slVar } = window.RX;

const usd = (n) => (n < 0 ? "−$" : "$") + Math.abs(Math.round(n)).toLocaleString("en-US");

function Funnel({ steps }) {
  const max = steps[0].v;
  const cols = ["var(--accent)", "color-mix(in srgb,var(--accent) 78%,#000)", "color-mix(in srgb,var(--accent) 60%,#000)"];
  return (
    <div>
      {steps.map((s, i) => (
        <div className="funnel-step" key={i}>
          <div style={{ width: 150, flex: "none" }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{s.label}</div>
            <div className="sub" style={{ color: "var(--text-3)", fontSize: 11.5 }}>{s.note}</div>
          </div>
          <div style={{ flex: 1 }}>
            <div className="funnel-bar" style={{ width: Math.max(8, s.v / max * 100) + "%", background: cols[i] || cols[2] }}>{fmt(s.v)}</div>
          </div>
          <div style={{ width: 64, textAlign: "right", fontVariantNumeric: "tabular-nums", fontFamily: "Geist Mono, monospace", fontWeight: 600, color: i === 0 ? "var(--text-3)" : "var(--text)" }}>
            {i === 0 ? "100%" : pct(s.v / max * 100, 1)}
          </div>
        </div>
      ))}
    </div>
  );
}

function TSP() {
  const t = D.tsp;
  return (
    <div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(5,1fr)", marginBottom: "var(--gap)" }}>
        <KPI feature label="Referrals" value={fmt(t.total)} sub="TruSteel placeholders" />
        <KPI label="Converted" value={fmt(t.converted)} accentBar="var(--pos)" sub="billed to real insurance" />
        <KPI label="Conversion rate" value={pct(t.rate * 100, 1)} accentBar="var(--sl-cgm)" sub="of all referrals" />
        <KPI label="Pending" value={fmt(t.pending)} accentBar="var(--warn)" sub="awaiting a real Rx" />
        <KPI label="Realized profit" value={usd(t.net_profit_realized)} accentBar="var(--sl-supplies)" sub={`on ${fmt(t.converted)} conversions`} />
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1.15fr 1fr", marginBottom: "var(--gap)" }}>
        <Card title="Conversion funnel" desc="From placeholder referral to a billed prescription.">
          {/* Funnel is on a profile basis (Referrals, Converted). "Released" is a
              script count — a different unit — so it lives in the note below, not as
              a bar (a 902-of-904 scripts figure against ~1,600 profiles read >100%). */}
          <Funnel steps={[
            { label: "Referrals", note: "TruSteel placeholders", v: t.total },
            { label: "Converted", note: "billed to real insurance", v: t.converted },
          ]} />
          <div className="note">
            <b>{fmt(t.on_hold)}</b> entries still on hold · <b>{fmt(t.already_active)}</b> were already active before referral. Released Rx: <b>{fmt(t.released)}</b> of {fmt(t.rx_count)} scripts in the program. Realized net profit from conversions: <b>{usd(t.net_profit_realized)}</b> (placeholder book value {usd(t.net_profit_total)}).
            {t.matched_in_data != null && <> {fmt(t.matched_in_data)} of {fmt(t.total)} referrals appear in the dispensed data so far.</>}
            {" "}TSP patients stay out of the organic on-service numbers until they convert.
          </div>
        </Card>
        <Card title="Templates & conversions by month" desc="New TSP templates created, conversions landed, and referrals still pending at each month-end.">
          <div className="matrix-wrap" style={{ maxHeight: 320, border: "1px solid var(--border)" }}>
            <table>
              <thead><tr><th>Month</th><th className="num">New templates</th><th className="num">Converted</th><th className="num">Pending at month-end</th></tr></thead>
              <tbody>
                {t.by_month.filter(m => m.templates_new >= 10 || m.converted > 0).map(m => (
                  <tr key={m.month}>
                    <td>{window.RX.fmtMonthLong(m.month)}</td>
                    <td className="num">{fmt(m.templates_new)}</td>
                    <td className="num" style={{ color: "var(--pos)" }}>{fmt(m.converted)}</td>
                    <td className="num" style={{ color: "var(--warn)" }}>{fmt(m.pending_eom)}</td>
                  </tr>))}
              </tbody>
            </table>
          </div>
          <div className="note">Months with fewer than 10 new templates and no conversions are folded out of view, as on the production chart.</div>
        </Card>
      </div>

      <Card title="Program economics" desc="TSP is an up-front investment: placeholders are billed at a loss until they convert to real coverage.">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: "var(--gap)" }}>
          {[["Rx in program", fmt(t.rx_count), "scripts touched"],
            ["Released", fmt(t.released), "moved to active"],
            ["Realized profit", usd(t.net_profit_realized), "from conversions"],
            ["Carried investment", usd(t.net_profit_total), "until conversion"]].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: 21, fontWeight: 600, letterSpacing: "-.02em", color: v.startsWith("−") ? "var(--neg)" : "var(--text)" }}>{v}</span>
              <span className="sub">{s}</span>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

function CGMService() {
  const c = D.cgm_outreach;                       // base keys (toggle-free tab)
  if (!c) return <Card><Unavail what="CGM outreach metrics" /></Card>;
  const workable = c.eligible_no_cgm + c.pending_fill + c.converted_ytd;
  const trend = Array.isArray(c.trend) ? c.trend : [];
  return (
    <div>
      <div className="grid" style={{ gridTemplateColumns: "repeat(5,1fr)", marginBottom: "var(--gap)" }}>
        <KPI feature label="Eligible, not yet on a CGM" value={fmt(c.eligible_no_cgm)} accentBar="var(--sl-cgm)" sub="Medi-Cal Rx pump patients, no CGM (of the workable cohort)" />
        <KPI label="Rx received — pending" value={fmt(c.pending_fill)} accentBar="var(--warn)" sub="CGM Rx on hold, too soon to fill" />
        <KPI label="Converted (2026)" value={fmt(c.converted_ytd)} accentBar="var(--pos)" sub="pump → CGM this year" />
        <KPI label="Conversion rate" value={pct(c.conversion_rate * 100, 1)} accentBar="var(--sl-cgm)" sub="of the workable cohort" />
        <KPI label="Incoming on CGM (2026)" value={fmt(c.incoming_ytd)} sub="arrived already on a CGM — not a conversion" />
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1.15fr 1fr", marginBottom: "var(--gap)" }}>
        <Card title="Conversion funnel" desc="Medi-Cal Rx pump-supply patients moving onto a continuous glucose monitor (any brand), 2026.">
          <Funnel steps={[
            { label: "Workable cohort", note: "eligible + pending + converted", v: workable },
            { label: "Rx received", note: "on hold or filled", v: c.pending_fill + c.converted_ytd },
            { label: "Converted", note: "CGM dispensed (2026)", v: c.converted_ytd },
          ]} />
          <div className="note">
            Already on a CGM before 2026: <b>{fmt(c.pre_2026_on_cgm)}</b> (not counted). On a CGM now: <b>{fmt(c.on_cgm_now)}</b> (of which Dexcom: <b>{fmt(c.on_dexcom_now)}</b>).
            {" "}Dispensing-derived · 2026 year-to-date · won't match the call tracker to the unit.
          </div>
        </Card>
        <Card title="Conversions & pending by month" desc="Cumulative pump→CGM conversions, CGM Rx pending fill, and patients on a CGM at each 2026 month-end.">
          <div className="matrix-wrap" style={{ maxHeight: 320, border: "1px solid var(--border)" }}>
            <table>
              <thead><tr><th>Month</th><th className="num">Converted (cum.)</th><th className="num">Pending</th><th className="num">On a CGM</th></tr></thead>
              <tbody>
                {trend.map(m => (
                  <tr key={m.month}>
                    <td>{window.RX.fmtMonthLong(m.month)}</td>
                    <td className="num" style={{ color: "var(--pos)" }}>{fmt(m.converted_cum)}</td>
                    <td className="num" style={{ color: "var(--warn)" }}>{fmt(m.pending)}</td>
                    <td className="num">{fmt(m.on_cgm)}</td>
                  </tr>))}
              </tbody>
            </table>
          </div>
          <div className="note">A fixed Medi-Cal Rx cohort tracked by supply coverage — same patients as the call tracker, a different lens.</div>
        </Card>
      </div>
    </div>
  );
}

function Projects() {
  const [tab, setTab] = useLS("rx_project_tab", "tsp");
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>Projects</h1>
          <p>Transient initiatives tracked while in progress. Completed projects can later be filed into an Archive tab.</p>
        </div>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <Segmented value={tab} options={[{ value: "tsp", label: "TruSteel (TSP)" }, { value: "cgm", label: "CGM Service" }]} onChange={setTab} />
          <span className="ctrl ghost" style={{ cursor: "default", opacity: .6 }} title="Completed projects will move here">Archive</span>
        </div>
      </div>
      {tab === "tsp" ? (D.tsp ? <TSP /> : <Card><Unavail what="TSP metrics" /></Card>) : <CGMService />}
    </div>
  );
}
Object.assign(window, { Projects });
