// charts.jsx — benchmark distribution + collection curve

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

  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: "#E1EFFE" },
    { from: D.cohort_p25_pct, to: D.cohort_p50_pct, color: "#C8E9FE" },
    { from: D.cohort_p50_pct, to: D.cohort_p75_pct, color: "#64C5FD" },
    { 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={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: isMobile ? 24 : 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 industry median" : "below industry median"}
          isMobile={isMobile} />
        <BMStat label={isMobile ? "GAP TO P75" : "GAP TO TOP QUARTILE"}
          value={(D.cohort_p75_pct - D.practice_rate_pct).toFixed(1) + "pts"}
          note={`${D.practice_rate_pct}% → ${D.cohort_p75_pct}%`}
          isMobile={isMobile} />
        <BMStat label={isMobile ? "$ LEFT ON TABLE" : "DOLLARS LEFT ON TABLE"}
          value={fmt.usdAbbr(D.gap_to_p75_dollars)} note="vs P75 peers" last warn
          isMobile={isMobile} />
      </div>
    </div>
  );
};

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

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

  const W = 880, H = isMobile ? 320 : 360;
  // On mobile, drop the end-of-line labels (no right pad reserved) — labels move into the chart body instead
  const PAD = { l: isMobile ? 40 : 56, r: isMobile ? 24 : 160, t: 24, b: 48 };
  const innerW = W - PAD.l - PAD.r;
  const innerH = H - PAD.t - PAD.b;

  // x: days 0..120, y: 0..100%
  const xMax = 120;
  const yMax = 100;
  const xS = (d) => PAD.l + (d / xMax) * innerW;
  const yS = (v) => PAD.t + (1 - v / yMax) * innerH;

  const buildPath = (vals) => D.days.map((d, i) => `${i === 0 ? "M" : "L"} ${xS(d)} ${yS(vals[i])}`).join(" ");
  const buildBand = () => {
    const top = D.days.map((d, i) => `${i === 0 ? "M" : "L"} ${xS(d)} ${yS(D.cohort_p75[i])}`).join(" ");
    const bot = [...D.days].reverse().map((d, i) => `L ${xS(d)} ${yS(D.cohort_p25[D.days.length - 1 - i])}`).join(" ");
    return `${top} ${bot} Z`;
  };

  // path lengths for stroke draw — practice path
  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 xTicks = D.days;
  // Superscript overlay — derived from North Shore Gastro (62% D0 upfront), Knownwell, Hudson Medical case studies
  const SS_CURVE = [62, 78, 87, 91, 93, 95]; // D0, D7, D30, D60, D90, D120

  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" }}>
        {/* gridlines */}
        {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"} />
            <text x={PAD.l - 8} y={yS(t) + 3} fontSize="9" fontFamily="Suisse Intl Mono, JetBrains Mono, monospace"
                  fontWeight="700" textAnchor="end" fill="#666">{t}%</text>
          </g>
        ))}
        {xTicks.map(d => (
          <g key={d}>
            <line x1={xS(d)} x2={xS(d)} y1={PAD.t} y2={H - PAD.b}
                  stroke="#F1F1F1" strokeWidth="0.5" />
            <text x={xS(d)} y={H - PAD.b + 18} fontSize="9" fontFamily="Suisse Intl Mono, JetBrains Mono, monospace"
                  fontWeight="700" textAnchor="middle" fill="#666">D{d}</text>
          </g>
        ))}


        {/* practice line — animated draw */}
        <path ref={practiceRef} d={practicePath} fill="none" stroke="#000" strokeWidth="2"
              strokeDasharray={practiceLen}
              strokeDashoffset={practiceLen * (1 - p)} />

        {/* Superscript overlay curve — case-study derived */}
        <path
          d={buildPath(SS_CURVE)}
          fill="none" stroke={THEME.primary} strokeWidth="1.5"
          strokeDasharray="5,3"
          opacity={p > 0.4 ? p : 0}
        />
        {D.days.map((d, i) => (
          <rect key={`ss-${d}`}
            x={xS(d) - 3} y={yS(SS_CURVE[i]) - 3}
            width={p > 0.7 ? 6 : 0} height={p > 0.7 ? 6 : 0}
            fill={THEME.primary}
          />
        ))}

        {/* D0 upfront capture annotation */}
        <g opacity={p > 0.5 ? 1 : 0} style={{ transition: "opacity 0.4s" }}>
          <line x1={xS(0)} x2={xS(0)} y1={yS(SS_CURVE[0]) + 5} y2={yS(D.practice[0]) - 5}
                stroke={THEME.primary} strokeWidth="1" strokeDasharray="2,2" />
          <text x={xS(0) + 10} y={yS(SS_CURVE[0]) + 16} fontSize="7.5"
                fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700"
                fill={THEME.primary}>
            <tspan x={xS(0) + 10} dy="0">WITH SUPERSCRIPT</tspan>
            <tspan x={xS(0) + 10} dy="10">{SS_CURVE[0]}% COLLECTED DAY-OF</tspan>
            <tspan x={xS(0) + 10} dy="10">vs {D.practice[0]}% today</tspan>
          </text>
        </g>

        {/* points */}
        {D.days.map((d, i) => (
          <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={THEME.primary} stroke="#000" strokeWidth="1" />
            <rect x={xS(d) - 24} y={PAD.t} width={48} height={innerH} fill="transparent"
                  onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
                  style={{ cursor: "crosshair" }} />
          </g>
        ))}

        {/* End-of-line labels — desktop only (mobile pulls them into the legend below) */}
        {!isMobile && (
          <g opacity={p > 0.8 ? 1 : 0}>
            <line x1={xS(120) + 6} x2={xS(120) + 16} y1={yS(SS_CURVE[5])} y2={yS(SS_CURVE[5])} stroke={THEME.primary} strokeWidth="1" />
            <text x={xS(120) + 20} y={yS(SS_CURVE[5]) + 4} fontSize="10" fontFamily="Suisse Intl Mono, JetBrains Mono, monospace"
                  fontWeight="700" fill={THEME.primary}>SUPERSCRIPT · {SS_CURVE[5]}%</text>
            <line x1={xS(120) + 6} x2={xS(120) + 16} y1={yS(D.practice[5])} y2={yS(D.practice[5])} stroke="#000" strokeWidth="1" />
            <text x={xS(120) + 20} y={yS(D.practice[5]) + 4} fontSize="10" fontFamily="Suisse Intl Mono, JetBrains Mono, monospace"
                  fontWeight="700" fill="#000">{window.ROI_DATA.practice.split(" ")[0].toUpperCase()} · {D.practice[5]}%</text>
          </g>
        )}
      </svg>

      {/* Static data reference — 3 cols × 2 rows on mobile, 6 cols × 1 row on desktop */}
      <div style={{
        marginTop: 16, display: "grid",
        gridTemplateColumns: isMobile ? "repeat(3, 1fr)" : "repeat(6, 1fr)",
        border: "1px solid #E1E1E1", background: "#fff",
      }}>
        {D.days.map((d, i) => {
          const cols = isMobile ? 3 : 6;
          const colPos = i % cols;
          const rowPos = Math.floor(i / cols);
          const totalRows = Math.ceil(D.days.length / cols);
          return (
            <div key={d} style={{
              padding: isMobile ? "10px 12px" : "10px 14px",
              borderRight: colPos < cols - 1 ? "1px solid #E1E1E1" : "none",
              borderBottom: rowPos < totalRows - 1 ? "1px solid #E1E1E1" : "none",
            }}>
              <Mono color={THEME.primary} size={9} style={{ display: "block" }}>DAY {d}</Mono>
              <Mono size={8} color="#999" style={{ display: "block", marginTop: 4 }}>PRACTICE BASELINE</Mono>
              <div style={{
                fontFamily: "Suisse Intl", fontWeight: 400,
                fontSize: isMobile ? 18 : 20,
                marginTop: 4,
                letterSpacing: "-0.02em", color: "#000",
              }}>{D.practice[i]}%</div>
              <Mono color={THEME.primary} size={8} style={{ display: "block", marginTop: 10 }}>WITH SUPERSCRIPT</Mono>
              <div style={{
                fontFamily: "Suisse Intl", fontWeight: 400,
                fontSize: isMobile ? 18 : 20,
                marginTop: 4,
                letterSpacing: "-0.02em", color: THEME.primary,
              }}>{SS_CURVE[i]}%</div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

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