/* MedBridge — Attribution, Benchmarking, ROI */

/* ===================== ATTRIBUTION ===================== */
function VBars({ bands }) {
  const max = Math.max(...bands.map((b) => b.rate)) * 1.15;
  const [grow, setGrow] = useStateMB(false);
  useEffectMB(() => { const t = setTimeout(() => setGrow(true), 80); return () => clearTimeout(t); }, []);
  return (
    <div style={{ display: "grid", gridTemplateColumns: `repeat(${bands.length},1fr)`, gap: 18, alignItems: "end", height: 240, padding: "10px 6px 0" }}>
      {bands.map((b) => (
        <div key={b.band} className="col" style={{ alignItems: "center", justifyContent: "flex-end", height: "100%" }}>
          <div className="mono fw7" style={{ fontSize: 18, color: b.color, marginBottom: 6 }}>{b.rate}%</div>
          <div style={{ width: "100%", maxWidth: 92, height: grow ? `${(b.rate / max) * 180}px` : 0, background: `linear-gradient(180deg, ${b.color}, color-mix(in srgb, ${b.color} 65%, white))`, borderRadius: "8px 8px 0 0", transition: "height .9s cubic-bezier(.2,.8,.2,1)" }} />
          <div className="fw6" style={{ fontSize: 12, marginTop: 9, textAlign: "center", whiteSpace: "nowrap" }}>{b.band}</div>
          <div className="muted mono" style={{ fontSize: 10.5, marginTop: 2 }}>n = {b.n.toLocaleString()}</div>
        </div>
      ))}
    </div>
  );
}

function Attribution() {
  const a = window.MB.attribution;
  return (
    <div className="content"><div className="pad" style={{ maxWidth: 1200, margin: "0 auto" }}>
      <div className="page-head">
        <div><h1>Complication Attribution</h1><div className="ph-sub">30-day complication outcomes correlated with information completeness at transfer · {a.period}</div></div>
        <button className="btn btn-ghost"><Icon name="print" size={15} />Export ({a.confidence})</button>
      </div>

      <div className="row gap10" style={{ padding: "14px 18px", borderRadius: 12, background: "var(--mb-crit-bg)", border: "1px solid #F0C9C4", marginBottom: 16 }}>
        <Icon name="alert" size={22} style={{ color: "var(--mb-crit)", flexShrink: 0 }} />
        <div style={{ fontSize: 14.5, fontWeight: 600 }}>{a.headline}</div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 16, alignItems: "start" }}>
        <Card title="30-day complication rate by completeness band" icon="chart"
          action={<span className="muted" style={{ fontSize: 11.5 }}>{a.sample.toLocaleString()} transfers</span>}>
          <VBars bands={a.bands} />
          <div className="muted" style={{ fontSize: 12, marginTop: 14, textAlign: "center" }}>
            A clear dose–response: as handoff completeness falls, the downstream complication rate rises <b style={{ color: "var(--mb-crit)" }}>3.4×</b>.
          </div>
        </Card>

        <Card title="Risk by missing field" icon="filter">
          <div className="muted" style={{ fontSize: 11.5, marginBottom: 8 }}>Adjusted odds ratio for a 30-day complication when each field is absent</div>
          {a.byField.map((f) => (
            <BarRow key={f.field} label={f.field} sub={f.complication} value={f.or} max={3} suffix="×" color={f.color} />
          ))}
        </Card>
      </div>

      <div className="kpi-row" style={{ marginTop: 16 }}>
        <Kpi label="Transfers analyzed" icon="send" value={a.sample.toLocaleString()} sub={a.period} />
        <Kpi label="With critical gap" icon="alert" value="1,438" sub="10.1% of transfers" accent="var(--mb-crit)" />
        <Kpi label="Excess complications" icon="activity" value="284" sub="attributable / quarter" accent="var(--mb-warn)" />
        <Kpi label="Statistical confidence" icon="check" value={a.confidence} sub="logistic regression" accent="var(--mb-good)" />
      </div>
    </div></div>
  );
}

/* ===================== BENCHMARKING ===================== */
function Benchmark() {
  const { hospitals, jurisdictions } = window.MB;
  const [juris, setJuris] = useStateMB("All");
  const provAvg = 81;
  let rows = hospitals.filter((h) => juris === "All" || h.juris === juris).sort((a, b) => b.score - a.score);

  return (
    <div className="content"><div className="pad" style={{ maxWidth: 1300, margin: "0 auto" }}>
      <div className="page-head">
        <div><h1>Hospital Benchmarking</h1><div className="ph-sub">Completeness performance ranked across {hospitals.length} connected sites · Atlantic provincial average {provAvg}%</div></div>
        <div className="row gap6">
          {["All", "NS", "NB", "PE", "NT", "NU"].map((j) => (
            <button key={j} onClick={() => setJuris(j)} className="btn btn-sm" style={{ background: juris === j ? "var(--primary)" : "var(--surface)", color: juris === j ? "#fff" : "var(--text-2)", border: "1px solid " + (juris === j ? "var(--primary)" : "var(--border)") }}>{j === "All" ? "All Atlantic + North" : j}</button>
          ))}
        </div>
      </div>

      <div className="card" style={{ overflow: "hidden" }}>
        <table className="tbl">
          <thead><tr><th>Rank</th><th>Hospital</th><th>EMR</th><th>Completeness vs provincial avg</th><th>Trend</th><th style={{ textAlign: "right" }}>Transfers/mo</th><th style={{ textAlign: "right" }}>Complication</th></tr></thead>
          <tbody>
            {rows.map((h, i) => (
              <tr key={h.name}>
                <td className="mono fw7" style={{ fontSize: 14, color: i === 0 ? "var(--mb-good)" : i === rows.length - 1 ? "var(--mb-crit)" : "var(--text-3)" }}>{i + 1}</td>
                <td><div className="fw6" style={{ fontSize: 13 }}>{h.name}</div><div className="muted" style={{ fontSize: 11 }}>{h.city} · {h.juris} · {h.beds} beds</div></td>
                <td style={{ fontSize: 12 }} className="t2">{h.emr.split(" (")[0]}</td>
                <td style={{ minWidth: 240 }}>
                  <div className="row gap10">
                    <div className="hbar-track" style={{ position: "relative" }}>
                      <div className="hbar-fill" style={{ width: h.score + "%", background: scoreColor(h.score) }} />
                      <span style={{ position: "absolute", left: provAvg + "%", top: -3, bottom: -3, width: 2, background: "var(--text-2)", opacity: .5 }} title={`Prov avg ${provAvg}%`} />
                    </div>
                    <ScorePill score={h.score} />
                  </div>
                </td>
                <td><Sparkline data={h.trend} color={scoreColor(h.score)} w={72} h={24} /></td>
                <td className="mono" style={{ textAlign: "right" }}>{h.transfersMo}</td>
                <td className="mono fw6" style={{ textAlign: "right", color: h.complicationRate > 18 ? "var(--mb-crit)" : h.complicationRate > 15 ? "var(--mb-warn)" : "var(--text)" }}>{h.complicationRate}%</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="legend" style={{ marginTop: 12 }}>
        <span><i style={{ width: 2, height: 12, background: "var(--text-2)", borderRadius: 0 }} />Provincial average ({provAvg}%)</span>
        <span><i style={{ background: "var(--mb-good)" }} />≥88</span><span><i style={{ background: "var(--mb-warn)" }} />62–87</span><span><i style={{ background: "var(--mb-crit)" }} />&lt;62</span>
      </div>
    </div></div>
  );
}

/* ===================== ROI ===================== */
function Roi() {
  const r = window.MB.roi.NS;
  const savings = useCountUp(r.annualSavings, 1100, 1);
  const avoided = useCountUp(r.complicationsAvoided, 1100);
  const ratio = useCountUp(r.roiRatio, 1100, 1);

  const w = 560, h = 240, pad = { l: 44, r: 16, t: 16, b: 28 };
  const iw = w - pad.l - pad.r, ih = h - pad.t - pad.b;
  const maxY = 52;
  const x = (i) => pad.l + (i / (r.years.length - 1)) * iw;
  const y = (v) => pad.t + ih - (v / maxY) * ih;
  const line = (arr) => arr.map((v, i) => (i ? "L" : "M") + x(i) + " " + y(v)).join(" ");
  const beIdx = r.breakEvenYear - 1;

  return (
    <div className="content"><div className="pad" style={{ maxWidth: 1200, margin: "0 auto" }}>
      <div className="page-head">
        <div><h1>Ministry ROI &amp; Savings</h1><div className="ph-sub">Nova Scotia · health budget ${r.budget}B · model per Alberta Health Services 2024 complication costing</div></div>
        <div className="juris"><span className="flag">🇨🇦</span> Nova Scotia</div>
      </div>

      <div className="kpi-row" style={{ marginBottom: 16 }}>
        <Kpi label="Est. annual savings" icon="chart" value={`$${savings}`} unit="M" sub={`range $${r.annualSavingsLo}–${r.annualSavingsHi}M`} accent="var(--mb-good)" />
        <Kpi label="Return on investment" icon="arrowUp" value={ratio} unit="×" sub="per $1 invested" accent="var(--mb-good)" />
        <Kpi label="Complications avoided" icon="shield" value={avoided.toLocaleString()} sub="projected / year" />
        <Kpi label="Break-even" icon="clock" value={`Year ${r.breakEvenYear}`} sub={`platform cost $${r.platformCost}M`} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }}>
        <Card title="Cumulative cost vs. avoided complication cost" icon="chart">
          <svg width="100%" viewBox={`0 0 ${w} ${h}`}>
            {[0, 13, 26, 39, 52].map((v) => (<g key={v}><line x1={pad.l} y1={y(v)} x2={w - pad.r} y2={y(v)} stroke="var(--hairline)" /><text x={pad.l - 8} y={y(v) + 3} textAnchor="end" fontSize="10" fill="var(--text-3)" className="mono">${v}M</text></g>))}
            {r.years.map((yr, i) => <text key={yr} x={x(i)} y={h - 9} textAnchor="middle" fontSize="10.5" fill="var(--text-3)">{yr}</text>)}
            {/* savings area */}
            <path d={line(r.cumSavings) + ` L${x(r.years.length - 1)} ${y(0)} L${x(0)} ${y(0)} Z`} fill="var(--mb-good)" opacity="0.1" />
            <path d={line(r.cumSavings)} fill="none" stroke="var(--mb-good)" strokeWidth="2.6" strokeLinejoin="round" />
            <path d={line(r.cumCost)} fill="none" stroke="var(--mb-crit)" strokeWidth="2.6" strokeDasharray="5 4" strokeLinejoin="round" />
            {r.cumSavings.map((v, i) => <circle key={i} cx={x(i)} cy={y(v)} r="3.5" fill="#fff" stroke="var(--mb-good)" strokeWidth="2" />)}
            {/* break-even marker */}
            <line x1={x(beIdx)} y1={pad.t} x2={x(beIdx)} y2={pad.t + ih} stroke="var(--primary)" strokeWidth="1.5" strokeDasharray="3 3" opacity=".6" />
            <text x={x(beIdx)} y={pad.t + 2} textAnchor="middle" fontSize="10" fontWeight="700" fill="var(--primary)">break-even</text>
          </svg>
          <div className="legend" style={{ justifyContent: "center", marginTop: 6 }}>
            <span><i style={{ background: "var(--mb-good)" }} />Avoided complication cost</span>
            <span><i style={{ background: "var(--mb-crit)" }} />Platform cost</span>
          </div>
        </Card>

        <Card title="How the savings are calculated" icon="info">
          <div className="col">
            {[
              ["NS hospital admissions / yr", "≈ 95,000", "var(--text)"],
              ["× 24% with a complication", "22,800 complications", "var(--text)"],
              ["× 10% attributable to info gaps", "2,280 preventable", "var(--mb-warn)"],
              ["× $10,866 avg cost / complication", "$24.8M exposure", "var(--mb-crit)"],
              ["× conservative reduction achieved", "$21.4M saved / yr", "var(--mb-good)"],
            ].map(([k, v, c], i, arr) => (
              <div key={k}>
                <div className="row" style={{ justifyContent: "space-between", padding: "9px 0", gap: 12 }}>
                  <span className="t2" style={{ fontSize: 12.5, flex: 1 }}>{k}</span>
                  <span className="mono fw7" style={{ fontSize: 13, color: c, whiteSpace: "nowrap", flexShrink: 0 }}>{v}</span>
                </div>
                {i < arr.length - 1 && <div className="divider" />}
              </div>
            ))}
          </div>
          <div className="row gap10" style={{ marginTop: 12, padding: "11px 13px", background: "var(--mb-good-bg)", borderRadius: 9 }}>
            <Icon name="check" size={18} style={{ color: "var(--mb-good)", flexShrink: 0 }} />
            <div style={{ fontSize: 12.5, fontWeight: 600 }}>Every $1 invested in MedBridge returns <b style={{ color: "var(--mb-good)" }}>${r.roiRatio}</b> in avoided complication cost within {r.breakEvenYear} years — measurable and reportable to the Legislature.</div>
          </div>
        </Card>
      </div>
    </div></div>
  );
}

Object.assign(window, { Attribution, Benchmark, Roi });
