// charts.jsx — benchmark distribution + collection curve

const BenchmarkChart = () => {
  const D = window.ROI_DATA.benchmark;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.2);
  // 900ms total fill, then practice marker
  const p = useProgress(900, seen);

  const X0 = D.cohort_min_pct, X1 = D.cohort_max_pct;
  const xScale = (v) => ((v - X0) / (X1 - X0)) * 100;

  const segs = [
    { from: D.cohort_min_pct, to: D.cohort_p25_pct,    color: "#EDEDED" },
    { from: D.cohort_p25_pct, to: D.cohort_p50_pct, color: "#E4E4E4" },
    { from: D.cohort_p50_pct, to: D.cohort_p75_pct, color: "#9A9A9A" },
    { from: D.cohort_p75_pct, to: D.cohort_max_pct,    color: THEME.primary },
  ];
  const N = segs.length; // 4
  // Each segment fills sequentially: seg i animates when p is in [i/N, (i+1)/N]
  const segP = (i) => Math.min(1, Math.max(0, (p - i / N) * N));
  const practiceX = xScale(D.practice_rate_pct);
  // Practice marker only appears after all segments complete
  const showMarker = p >= 0.98;

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <div style={{ position: "relative", height: 240, padding: "60px 0 60px" }}>
        {/* track */}
        <div style={{ position: "absolute", left: 0, right: 0, top: "50%", height: 56, transform: "translateY(-50%)" }}>
          {/* outer border */}
          <div style={{ position: "absolute", inset: 0, border: "1px solid #000" }} />
          {segs.map((s, i) => {
            const w = ((s.to - s.from) / (X1 - X0)) * 100;
            const left = ((s.from - X0) / (X1 - X0)) * 100;
            return (
              <div key={i} style={{
                position: "absolute", left: `${left}%`, width: `${w * segP(i)}%`,
                top: 0, bottom: 0, background: s.color,
              }} />
            );
          })}
        </div>

        {/* tick markers — stagger P25/P75 (odd indices) lower to avoid label collision */}
        {[D.cohort_min_pct, D.cohort_p25_pct, D.cohort_p50_pct, D.cohort_p75_pct, D.cohort_max_pct].map((v, i) => {
          const labels = ["MIN", "P25", "MEDIAN", "P75", "MAX"];
          const stagger = i % 2 === 1; // P25 and P75 drop lower
          return (
            <div key={i} style={{
              position: "absolute", left: `${xScale(v)}%`, top: "calc(50% + 32px)",
              transform: "translateX(-50%)", display: "flex", flexDirection: "column",
              alignItems: "center", gap: 4,
              opacity: showMarker ? 1 : 0, transition: "opacity 0.4s",
            }}>
              <div style={{ width: 1, height: stagger ? 32 : 12, background: "#000" }} />
              <Mono size={10} color="#000">{v.toFixed(1)}%</Mono>
              <Mono size={9} color="#666">{labels[i]}</Mono>
            </div>
          );
        })}

        {/* practice marker — appears after all bars */}
        <div style={{
          position: "absolute", left: `${practiceX}%`, top: 0, bottom: 0,
          transform: "translateX(-50%)",
          display: "flex", flexDirection: "column", alignItems: "center",
          opacity: showMarker ? 1 : 0, transition: "opacity 0.4s 0.1s",
        }}>
          <div style={{
            background: "#000", color: "#fff", padding: "6px 10px",
            display: "flex", flexDirection: "column", gap: 4, marginBottom: 4
          }}>
            <Mono color={THEME.accent} size={9}>{window.ROI_DATA.practice.toUpperCase()}</Mono>
            <span style={{ fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 22, lineHeight: 1, letterSpacing: "-0.02em" }}>
              {D.practice_rate_pct}%
            </span>
          </div>
          <div style={{ width: 0, height: 0, borderLeft: "6px solid transparent", borderRight: "6px solid transparent", borderTop: "8px solid #000" }} />
          <div style={{ width: 1, flex: 1, background: "#000", borderLeft: "1px dashed #000" }} />
        </div>
      </div>

      {/* Gap callout */}
      <div style={{
        marginTop: 32, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 0,
        border: "1px solid #000",
      }}>
        <BMStat label="QUARTILE"
          value={D.practice_rate_pct >= D.cohort_p75_pct ? "Q1" : D.practice_rate_pct >= D.cohort_p50_pct ? "Q2" : D.practice_rate_pct >= D.cohort_p25_pct ? "Q3" : "Q4"}
          note={D.practice_rate_pct >= D.cohort_p50_pct ? "above cohort median" : "below cohort median"} />
        <BMStat label="GAP TO TOP QUARTILE"
          value={(D.cohort_p75_pct - D.practice_rate_pct).toFixed(1) + "pts"}
          note={`from ${D.practice_rate_pct}% → ${D.cohort_p75_pct}%`} />
        <BMStat label="ADDITIONAL COLLECTIONS AT P75" value={fmt.usdAbbr(D.gap_to_p75_dollars)} note="vs the P75 cohort rate" last warn />
      </div>
    </div>
  );
};

const BMStat = ({ label, value, note, last = false, warn = false }) => (
  <div style={{
    padding: "20px 22px", borderRight: last ? "none" : "1px solid #000",
    minHeight: 110, display: "flex", flexDirection: "column", justifyContent: "space-between"
  }}>
    <Mono color={THEME.primary} size={10}>{label}</Mono>
    <div>
      <div style={{
        fontFamily: "Suisse Intl", fontWeight: 400, fontSize: 32, lineHeight: 1,
        letterSpacing: "-0.025em", marginBottom: 6,
        color: warn ? "#FF426F" : "#000"
      }}>{value}</div>
      <Mono color="#666" size={11}>{note}</Mono>
    </div>
  </div>
);

// ---------- Collection Curve ----------
const CollectionCurve = () => {
  const D = window.ROI_DATA.collection_curve;
  const H = window.ROI_DATA.headline;
  const P = window.ROI_DATA.projection;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.2);
  const p = useProgress(1800, seen);
  const [hover, setHover] = React.useState(null);
  const isMobile = useIsMobile();

  // Three levels, all on the SAME denominator (total patient responsibility), so they
  // sit on one y-axis legitimately. Only the numerator's time window changes:
  //   d120Rate  = collected within 120 days of service   (the curve's endpoint)
  //   toDateRate= collected through the data cutoff       (section 01's headline)
  //   projRate  = where the projection puts it            (section 08)
  const projCurve  = P.projected_curve || null;   // null => level-only render
  const d120Rate   = D.practice[D.practice.length - 1];
  const toDateRate = H.collection_rate_pct;
  const projRate   = P.projected_rate_pct;
  const upliftPts  = P.uplift_pts;

  const W = 880, H_ = 360;
  const PAD = { l: 56, r: 190, t: 24, b: 56 };
  const innerW = W - PAD.l - PAD.r;
  const innerH = H_ - PAD.t - PAD.b;

  const xMax = Math.max(...D.days);
  const xS = (d) => PAD.l + (d / xMax) * innerW * 0.78;  // curve occupies left 78%
  const xToDate = PAD.l + innerW;                         // "to date" column, right of D120
  const yS = (v) => PAD.t + (1 - v / 100) * innerH;

  const buildPath = (vals) => {
    let started = false;
    return D.days.map((d, i) => {
      if (vals[i] == null) return null;
      const cmd = started ? "L" : "M";
      started = true;
      return `${cmd} ${xS(d)} ${yS(vals[i])}`;
    }).filter(Boolean).join(" ");
  };

  const practicePath = buildPath(D.practice);
  const [practiceLen, setPracticeLen] = React.useState(2000);
  const practiceRef = React.useRef(null);
  React.useEffect(() => {
    if (practiceRef.current) setPracticeLen(practiceRef.current.getTotalLength());
  }, []);

  const yTicks = [0, 25, 50, 75, 100];
  const MonoTxt = (props) => (
    <text fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" {...props} />
  );

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <svg viewBox={`0 0 ${W} ${H_}`} width="100%" overflow="visible" style={{ display: "block", border: "1px solid #000", background: "#fff" }}>
        {yTicks.map(t => (
          <g key={t}>
            <line x1={PAD.l} x2={W - PAD.r} y1={yS(t)} y2={yS(t)}
                  stroke="#E1E1E1" strokeWidth="0.5" strokeDasharray={t === 0 ? "" : "2,3"} />
            <MonoTxt x={PAD.l - 8} y={yS(t) + 3} fontSize="9" textAnchor="end" fill="#666">{t}%</MonoTxt>
          </g>
        ))}
        {D.days.map(d => (
          <g key={d}>
            <line x1={xS(d)} x2={xS(d)} y1={PAD.t} y2={H_ - PAD.b} stroke="#F1F1F1" strokeWidth="0.5" />
            <MonoTxt x={xS(d)} y={H_ - PAD.b + 18} fontSize="9" textAnchor="middle" fill="#666">D{d}</MonoTxt>
          </g>
        ))}

        {/* separator between the 120-day curve and the to-date / projected column */}
        <line x1={xS(xMax) + 26} x2={xS(xMax) + 26} y1={PAD.t} y2={H_ - PAD.b} stroke="#D4D4D4" strokeWidth="0.5" strokeDasharray="1,3" />
        <MonoTxt x={xToDate} y={H_ - PAD.b + 18} fontSize="9" textAnchor="middle" fill="#666">TO DATE</MonoTxt>

        {/* measured curve, D0 to D120 */}
        <path ref={practiceRef} d={practicePath} fill="none" stroke="#000" strokeWidth="2"
              strokeDasharray={practiceLen} strokeDashoffset={practiceLen * (1 - p)} />

        {/* measured continuation from D120 to the to-date figure */}
        <path d={`M ${xS(xMax)} ${yS(d120Rate)} L ${xToDate} ${yS(toDateRate)}`}
              fill="none" stroke="#000" strokeWidth="1.5" strokeDasharray="4,3" opacity={p > 0.6 ? 1 : 0} />

        {/* projected level. Blue, and the only blue in this chart. */}
        <g opacity={p > 0.75 ? 1 : 0} style={{ transition: "opacity 0.4s" }}>
          {/* Projected trajectory when the report supplies projection.projected_curve,
              otherwise a level drawn only from D120 rightward. Either way it is dashed,
              because it is projected rather than measured. */}
          {projCurve ? (
            <>
              <path d={D.days.map((d, i) => `${i === 0 ? "M" : "L"} ${xS(d)} ${yS(projCurve[i])}`).join(" ")}
                    fill="none" stroke={THEME.proj} strokeWidth="2" strokeDasharray="6,4" />
              <path d={`M ${xS(xMax)} ${yS(projCurve[projCurve.length - 1])} L ${xToDate} ${yS(projRate)}`}
                    fill="none" stroke={THEME.proj} strokeWidth="1.5" strokeDasharray="4,3" />
              {D.days.map((d, i) => (
                <rect key={`pj-${d}`} x={xS(d) - 3} y={yS(projCurve[i]) - 3} width={6} height={6} fill={THEME.proj} />
              ))}
            </>
          ) : (
            <line x1={xS(xMax)} x2={xToDate} y1={yS(projRate)} y2={yS(projRate)}
                  stroke={THEME.proj} strokeWidth="1.5" strokeDasharray="6,4" />
          )}
          <rect x={xToDate - 4} y={yS(projRate) - 4} width={8} height={8} fill={THEME.proj} />
          {/* the gap we project to close */}
          <line x1={xToDate} x2={xToDate} y1={yS(toDateRate)} y2={yS(projRate)} stroke={THEME.proj} strokeWidth="1" />
          <line x1={xToDate - 5} x2={xToDate + 5} y1={yS(toDateRate)} y2={yS(toDateRate)} stroke={THEME.proj} strokeWidth="1" />
          <MonoTxt x={xToDate + 10} y={(yS(toDateRate) + yS(projRate)) / 2 + 3} fontSize="9" fill={THEME.proj}>+{upliftPts}PP</MonoTxt>
        </g>

        {/* measured points on the curve */}
        {D.days.map((d, i) => D.practice[i] == null ? null : (
          <g key={d}>
            <rect x={xS(d) - 3} y={yS(D.practice[i]) - 3} width={p > 0.7 ? 6 : 0} height={p > 0.7 ? 6 : 0} fill="#000" stroke="#000" strokeWidth="1" />
            {hover === i && (
              <line x1={xS(d)} x2={xS(d)} y1={PAD.t} y2={H_ - PAD.b} stroke="#000" strokeWidth="0.5" strokeDasharray="2,2" />
            )}
            <rect x={xS(d) - 20} y={PAD.t} width={40} height={innerH} fill="transparent"
                  onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
                  style={{ cursor: "crosshair" }} />
          </g>
        ))}
        <rect x={xToDate - 3} y={yS(toDateRate) - 3} width={6} height={6} fill="#000" opacity={p > 0.6 ? 1 : 0} />

        {/* right-hand labels */}
        <g opacity={p > 0.85 ? 1 : 0}>
          <MonoTxt x={xToDate + 10} y={yS(projRate) + 3} fontSize="10" fill={THEME.proj}>PROJECTED · {projRate.toFixed(2)}%</MonoTxt>
          <MonoTxt x={xToDate + 10} y={yS(toDateRate) + 14} fontSize="10" fill="#000">TODAY · {toDateRate.toFixed(2)}%</MonoTxt>
        </g>
      </svg>

      {/* Measured points, then the projected level as the last cell */}
      {/* days + TO DATE + PROJECTED is 8 columns. The mobile CSS in index.html only
          collapses repeat(2..6, 1fr) grids, so an 8-column grid slips through and the
          values crush at 375px. Emitting repeat(2, 1fr) on mobile makes it match that
          rule and collapse to a single column like every other grid in the report. */}
      <div style={{
        marginTop: 16, display: "grid",
        gridTemplateColumns: isMobile ? "repeat(2, 1fr)" : `repeat(${D.days.length + 2}, 1fr)`,
        border: "1px solid #E1E1E1", background: "#fff",
      }}>
        {D.days.map((d, i) => (
          <div key={d} style={{ padding: "10px 12px", borderRight: "1px solid #E1E1E1", borderBottom: isMobile ? "1px solid #E1E1E1" : "none" }}>
            <Mono color={THEME.primary} size={9}>DAY {d}</Mono>
            <div style={{ fontFamily: "Suisse Intl", fontWeight: 400, fontSize: 20, marginTop: 6, letterSpacing: "-0.02em", color: "#000" }}>{D.practice[i]}%</div>
            {projCurve && (
              <Mono size={9} color={THEME.proj} style={{ display: "block", marginTop: 3 }}>→ {projCurve[i]}%</Mono>
            )}
          </div>
        ))}
        <div style={{ padding: "10px 12px", borderRight: "1px solid #E1E1E1", borderBottom: isMobile ? "1px solid #E1E1E1" : "none" }}>
          <Mono color={THEME.primary} size={9}>TO DATE</Mono>
          <div style={{ fontFamily: "Suisse Intl", fontWeight: 400, fontSize: 20, marginTop: 6, letterSpacing: "-0.02em", color: "#000" }}>{toDateRate.toFixed(2)}%</div>
        </div>
        <div style={{ padding: "10px 12px", background: "#F4FAFF" }}>
          <Mono color={THEME.proj} size={9}>PROJECTED</Mono>
          <div style={{ fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 20, marginTop: 6, letterSpacing: "-0.02em", color: THEME.proj }}>{projRate.toFixed(2)}%</div>
        </div>
      </div>
    </div>
  );
};

window.BenchmarkChart = BenchmarkChart;
window.CollectionCurve = CollectionCurve;
