// trends.jsx — monthly rate + AR days dual chart

const MonthlyTrend = () => {
  const D1 = window.ROI_DATA.monthly_rate;
  const D2 = window.ROI_DATA.monthly_ar;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0);
  const p = useProgress(800, seen);
  const [hover, setHover] = React.useState(null);

  const W = 880, H = 360;
  const PAD = { l: 56, r: 56, t: 24, b: 56 };
  const innerW = W - PAD.l - PAD.r;
  const innerH = H - PAD.t - PAD.b;
  const N = D1.length;
  const colW = innerW / N;

  // Left axis: dynamic min, always 100% max
  const rates = D1.map(d => d.rate);
  const rMinRaw = Math.min(...rates);
  const rMin = Math.floor((rMinRaw - 5) / 10) * 10;
  const rMax = 100;
  const rTicks = [];
  for (let t = rMin; t <= rMax; t += 10) rTicks.push(t);
  const yR = (v) => PAD.t + (1 - (v - rMin) / (rMax - rMin)) * innerH;

  // Right axis: dynamic range from AR data, padded by 5d, snapped to 10s
  const arVals = D2.map(d => d.avg);
  const aMaxRaw = Math.max(...arVals);
  const aMin = 0;
  const aMax = Math.ceil((aMaxRaw + 5) / 10) * 10;
  const aTicks = [];
  for (let t = 0; t <= aMax; t += Math.ceil(aMax / 5 / 10) * 10) aTicks.push(t);
  const yA = (v) => PAD.t + (1 - (v - aMin) / (aMax - aMin)) * innerH;
  const xS = (i) => PAD.l + colW * i + colW / 2;

  // Use cohort median as the under/above threshold, not a hardcoded value
  const industryMedian = window.ROI_DATA.benchmark.cohort_p50_pct;

  // animated path for AR days
  const arPath = D2.map((m, i) => `${i === 0 ? "M" : "L"} ${xS(i)} ${yA(m.avg)}`).join(" ");
  const arRef = React.useRef(null);
  const [arLen, setArLen] = React.useState(2000);
  React.useEffect(() => { if (arRef.current) setArLen(arRef.current.getTotalLength()); }, []);

  return (
    <div ref={ref}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block", border: "1px solid #000", background: "#fff" }}>
        {/* y-grid — dynamic ticks */}
        {rTicks.map(t => (
          <g key={t}>
            <line x1={PAD.l} x2={W - PAD.r} y1={yR(t)} y2={yR(t)} stroke="#F1F1F1" strokeWidth="0.5" />
            <text x={PAD.l - 8} y={yR(t) + 3} fontSize="9" textAnchor="end"
                  fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#666">{t}%</text>
          </g>
        ))}
        {/* right axis labels — dynamic */}
        {aTicks.map(t => (
          <text key={t} x={W - PAD.r + 8} y={yA(t) + 3} fontSize="9"
                fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill={THEME.accent}>{t}d</text>
        ))}

        {/* Cohort median baseline (real Superscript-customer p50, not industry) */}
        <line x1={PAD.l} x2={W - PAD.r} y1={yR(industryMedian)} y2={yR(industryMedian)} stroke="#64C5FD" strokeWidth="1" strokeDasharray="3,3" opacity={p} />
        <text x={W - PAD.r - 4} y={yR(industryMedian) - 4} fontSize="9" textAnchor="end"
              fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#64C5FD" opacity={p}>COHORT MEDIAN {industryMedian.toFixed(1)}%</text>

        {/* bars: monthly rate */}
        {D1.map((m, i) => {
          const h = (yR(rMin) - yR(m.rate));
          const x = xS(i) - 14;
          const isH = hover === i;
          return (
            <g key={m.m}>
              <rect x={x} y={yR(m.rate)} width={28} height={h * p}
                    fill={m.rate < industryMedian ? THEME.accent : THEME.primary} opacity={isH ? 1 : 0.92}
                    style={{ transition: "opacity 120ms" }} />
              <text x={xS(i)} y={H - PAD.b + 16} fontSize="10" textAnchor="middle"
                    fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700"
                    fill={isH ? "#000" : "#666"}>{m.m}</text>
              {isH && (
                <text x={xS(i)} y={yR(m.rate) - 6} fontSize="10" textAnchor="middle"
                      fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#000">{m.rate}%</text>
              )}
              <rect x={x} y={PAD.t} width={28} height={innerH} fill="transparent"
                    onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)} />
            </g>
          );
        })}

        {/* AR days line */}
        <path ref={arRef} d={arPath} fill="none" stroke={THEME.accent} strokeWidth="2"
              strokeDasharray={arLen} strokeDashoffset={arLen * (1 - p)} />
        {D2.map((m, i) => (
          <circle key={m.m} cx={xS(i)} cy={yA(m.avg)} r={p > 0.7 ? 3.5 : 0}
                  fill="#fff" stroke={THEME.accent} strokeWidth="1.5" />
        ))}

        {/* hover crosshair */}
        {hover !== null && (
          <line x1={xS(hover)} x2={xS(hover)} y1={PAD.t} y2={H - PAD.b}
                stroke="#000" strokeWidth="0.5" strokeDasharray="2,3" opacity={0.4} />
        )}
      </svg>

      {/* legend */}
      <div style={{ display: "flex", gap: 16, marginTop: 16, alignItems: "center", flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 16, height: 12, background: THEME.primary }} />
          <Mono size={11} color="#000">COLLECTION RATE %</Mono>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 16, height: 12, background: THEME.accent }} />
          <Mono size={11} color="#000">UNDER-MEDIAN MONTHS</Mono>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 20, height: 2, background: THEME.accent }} />
          <Mono size={11} color="#000">AVG DAYS TO PAYMENT</Mono>
        </div>
      </div>

    </div>
  );
};

window.MonthlyTrend = MonthlyTrend;

// Sub-component so useCounter is called at component level (not inside map)
const LeakageCard = ({ yr, val, color, subtext, borderRight, seen }) => {
  const counted = useCounter(val, 700, seen);
  const isMobile = useIsMobile();
  return (
    <div style={{
      padding: isMobile ? "16px 14px" : "24px 28px",
      borderRight: borderRight ? "1px solid #000" : "none",
    }}>
      <Mono color={THEME.primary} size={isMobile ? 9 : 10}>{yr} TOTAL LEAKAGE</Mono>
      <div style={{
        fontFamily: "Suisse Intl", fontWeight: 300,
        fontSize: isMobile ? 30 : 64,
        lineHeight: 1,
        letterSpacing: "-0.035em",
        marginTop: isMobile ? 8 : 12,
        color,
      }}>
        {isMobile ? fmt.usdAbbr(counted) : "$" + counted.toLocaleString()}
      </div>
      <Mono size={isMobile ? 9 : 10} color="#666" style={{ display: "block", marginTop: 8, lineHeight: 1.4 }}>{subtext}</Mono>
    </div>
  );
};

// ── YoY Trends ──────────────────────────────────────────────────────────────
// For each type: positive rate delta = good (blue bar), negative = bad (red bar + row tint)
// For leakage: positive delta = bad (leakage grew, red), negative = good (leakage shrank, green)
const YOY_TYPES = [
  { key: "COPAY",           label: "Copay",            color: THEME.primary },
  { key: "COINSURANCE",     label: "Coinsurance",      color: "#0089E5" },
  { key: "DEDUCTIBLE",      label: "Deductible",       color: "#64C5FD" },
  { key: "SELFPAY",         label: "Self-pay",         color: THEME.accent },
  { key: "PATIENTTRANSFER", label: "Patient Transfer", color: "#FF426F" },
];

const YearlyTrends = () => {
  const yoy = window.ROI_DATA.yoy.filter(y => !y.partial); // 2024 + 2025 only
  const ref = React.useRef(null);
  const seen = useInView(ref, 0);
  const p = useProgress(750, seen); // 3.6s: 6 bars × 500ms each + 600ms for tick reveal
  const [activeTab, setActiveTab] = React.useState("rate"); // "rate" | "leakage" | "days"
  const isMobile = useIsMobile();

  const tabStyle = (t) => ({
    padding: isMobile ? "8px 10px" : "8px 18px",
    fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace",
    fontWeight: 700,
    fontSize: isMobile ? 10 : 11,
    letterSpacing: "-0.03em",
    cursor: "pointer", border: "1px solid #000",
    marginRight: -1,
    background: activeTab === t ? "#000" : "#fff",
    color: activeTab === t ? THEME.primary : "#666",
    flex: isMobile ? 1 : "0 0 auto",
  });

  // Grid template for the rate table — desktop uses fixed columns, mobile uses an inline-stacked card layout
  const RATE_GRID = "160px 1fr 110px 90px";

  return (
    <div ref={ref}>
      {/* Tab bar */}
      <div style={{ display: "flex", marginBottom: 24 }}>
        <button style={tabStyle("rate")}    onClick={() => setActiveTab("rate")}>{isMobile ? "RATE" : "COLLECTION RATE"}</button>
        <button style={tabStyle("leakage")} onClick={() => setActiveTab("leakage")}>{isMobile ? "LEAKAGE" : "REVENUE LEAKAGE"}</button>
        <button style={tabStyle("days")}    onClick={() => setActiveTab("days")}>{isMobile ? "DAYS" : "DAYS TO PAYMENT"}</button>
      </div>

      {/* ── COLLECTION RATE BY TYPE ── */}
      {activeTab === "rate" && (() => {
        const r24Overall = yoy[0].rate_pct;
        const r25Overall = yoy[1].rate_pct;
        const overallDelta = r25Overall - r24Overall;
        const overallNeg = overallDelta <= -2;
        const p75 = window.ROI_DATA.benchmark.cohort_p75_pct;
        const gapToP75 = (p75 - r25Overall).toFixed(1);

        // Sequential: each bar gets 1/6 of total 3.6s = 600ms window
        const N = YOY_TYPES.length + 1; // 5 types + 1 overall = 6
        const barWindow = 1 / N;
        const barP = (idx) => Math.min(1, Math.max(0, (p - idx * barWindow) / barWindow));
        const overallBarP = barP(YOY_TYPES.length);
        // Tick marks only after all bars done (p ≥ 5/6 ≈ 0.83), plus a short delay
        const showTick = p >= (N - 1) / N + 0.05;

        // Mobile row renderer — stacked card with a single bar + delta on right, 24/25 readout below
        const MobileRateRow = ({ label, r24, r25, delta, barP_, isLast, isMeaningfulDrop, isFlat, barColor, isOverall = false }) => {
          const tickPct = r24;
          return (
            <div style={{
              padding: "14px 14px 16px",
              borderBottom: isLast ? "none" : "1px solid #E1E1E1",
              background: isMeaningfulDrop
                ? "rgba(255,66,111,0.03)"
                : (isOverall ? "#F9F9F9" : "#fff"),
              borderTop: isOverall ? "1px solid #000" : "none",
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14, gap: 12 }}>
                <div style={{
                  fontSize: isOverall ? 13 : 15,
                  fontFamily: isOverall ? "Suisse Intl Mono, JetBrains Mono, monospace" : "Suisse Intl",
                  fontWeight: isOverall ? 700 : 500,
                  letterSpacing: "-0.01em",
                  color: isMeaningfulDrop ? "#FF426F" : "#000",
                }}>{isOverall ? "OVERALL" : label}</div>
                <span style={{
                  fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 18,
                  letterSpacing: "-0.02em",
                  color: isMeaningfulDrop ? "#FF426F" : (isFlat ? "#999" : "#01CE91"),
                  whiteSpace: "nowrap",
                }}>{delta > 0 ? "+" : ""}{delta.toFixed(1)}pp</span>
              </div>
              <div style={{ position: "relative", height: 22 }}>
                <div style={{ position: "absolute", inset: 0, background: isOverall ? "#E1E1E1" : "#F1F1F1" }} />
                <div style={{
                  position: "absolute", left: 0, top: 0, bottom: 0,
                  width: `${r25 * barP_}%`, background: barColor,
                }} />
                <div style={{
                  position: "absolute", top: -12, bottom: -4,
                  left: `${tickPct}%`, width: 1.5, background: "#000",
                  opacity: showTick ? 1 : 0, transition: "opacity 0.3s",
                }} />
                <Mono size={9} color="#000" style={{
                  position: "absolute", top: -20,
                  left: `${tickPct}%`, transform: "translateX(-50%)",
                  whiteSpace: "nowrap",
                  background: isOverall ? "#F9F9F9" : "#fff",
                  padding: "0 2px",
                  opacity: showTick ? 1 : 0, transition: "opacity 0.3s",
                }}>{r24}%</Mono>
                <Mono size={10} color="#fff" style={{
                  position: "absolute", left: 7, top: "50%", transform: "translateY(-50%)",
                  opacity: showTick ? 1 : 0, transition: "opacity 0.3s",
                }}>{r25}%</Mono>
              </div>
              <Mono size={10} color="#999" style={{ display: "block", marginTop: 8 }}>
                {r24}% → {r25}%
                {isMeaningfulDrop && <span style={{ color: "#FF426F", marginLeft: 8 }}>▼ DECLINED</span>}
                {isFlat && <span style={{ color: "#999", marginLeft: 8 }}>FLAT</span>}
              </Mono>
            </div>
          );
        };

        return (
          <div>
            <div style={{ border: "1px solid #000", background: "#fff" }}>
              {/* Header */}
              <div style={{
                display: isMobile ? "block" : "grid",
                gridTemplateColumns: isMobile ? undefined : RATE_GRID,
                padding: isMobile ? "10px 14px" : "10px 16px 26px",
                borderBottom: "1px solid #000",
                background: "#000",
              }}>
                {isMobile ? (
                  <Mono color={THEME.primary} size={10}>COST TYPE  ·  2025 RATE  ·  CHANGE FROM 2024</Mono>
                ) : (
                  <>
                    <Mono color={THEME.primary} size={10}>COST TYPE</Mono>
                    <Mono color={THEME.primary} size={10}>2025 RATE  ·  2024 BENCHMARK</Mono>
                    <Mono color={THEME.primary} size={10} style={{ textAlign: "center" }}>2024 → 2025</Mono>
                    <Mono color={THEME.primary} size={10} style={{ textAlign: "right" }}>CHANGE</Mono>
                  </>
                )}
              </div>

              {YOY_TYPES.map((t, i) => {
                const r24 = yoy[0].types[t.key].rate_pct;
                const r25 = yoy[1].types[t.key].rate_pct;
                const delta = r25 - r24;
                const isMeaningfulDrop = delta <= -2;
                const isFlat = Math.abs(delta) < 2;
                const barColor = isMeaningfulDrop ? "#FF426F" : (isFlat ? "#AAAAAA" : t.color);
                const tickPct = r24;

                if (isMobile) {
                  return (
                    <MobileRateRow key={t.key}
                      label={t.label} r24={r24} r25={r25} delta={delta}
                      barP_={barP(i)} isLast={false}
                      isMeaningfulDrop={isMeaningfulDrop} isFlat={isFlat} barColor={barColor} />
                  );
                }

                return (
                  <div key={t.key} style={{
                    display: "grid", gridTemplateColumns: RATE_GRID,
                    padding: "16px 16px 14px", alignItems: "center",
                    borderBottom: i < YOY_TYPES.length - 1 ? "1px solid #E1E1E1" : "none",
                    background: isMeaningfulDrop ? "rgba(255,66,111,0.03)" : "#fff",
                  }}>
                    <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: "-0.01em", color: isMeaningfulDrop ? "#FF426F" : "#000" }}>
                      {t.label}
                    </div>

                    {/* Single bar: fills to 2025 rate; vertical tick shows 2024 */}
                    <div style={{ paddingRight: 20, paddingTop: 14 }}>
                      <div style={{ position: "relative", height: 26 }}>
                        {/* track */}
                        <div style={{ position: "absolute", inset: 0, background: "#F1F1F1" }} />
                        {/* 2025 fill — sequential, no CSS transition (React drives it frame by frame) */}
                        <div style={{
                          position: "absolute", left: 0, top: 0, bottom: 0,
                          width: `${r25 * barP(i)}%`, background: barColor,
                        }} />
                        {/* 2024 tick mark — appears after all bars complete */}
                        <div style={{
                          position: "absolute", top: -14, bottom: -4,
                          left: `${tickPct}%`, width: 1.5,
                          background: "#000",
                          opacity: showTick ? 1 : 0,
                          transition: "opacity 0.3s",
                        }} />
                        {/* 2024 label above tick — appears with tick */}
                        <Mono size={9} color="#000" style={{
                          position: "absolute", top: -22,
                          left: `${tickPct}%`, transform: "translateX(-50%)",
                          whiteSpace: "nowrap", background: "#fff",
                          padding: "0 2px",
                          opacity: showTick ? 1 : 0,
                          transition: "opacity 0.3s",
                        }}>{r24}%</Mono>
                        {/* 2025 rate inside bar — appears with tick */}
                        <Mono size={10} color="#fff" style={{
                          position: "absolute", left: 7, top: "50%", transform: "translateY(-50%)",
                          opacity: showTick ? 1 : 0,
                          transition: "opacity 0.3s",
                        }}>{r25}%</Mono>
                      </div>
                    </div>

                    {/* 2024 → 2025 */}
                    <div style={{ textAlign: "center" }}>
                      <Mono size={10} color="#999">{r24}% → {r25}%</Mono>
                    </div>

                    {/* Delta */}
                    <div style={{ textAlign: "right", display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 2 }}>
                      <span style={{
                        fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 18,
                        letterSpacing: "-0.02em",
                        color: isMeaningfulDrop ? "#FF426F" : (isFlat ? "#999" : "#01CE91"),
                      }}>
                        {delta > 0 ? "+" : ""}{delta.toFixed(1)}pp
                      </span>
                      {isMeaningfulDrop && <Mono size={9} color="#FF426F">▼ DECLINED</Mono>}
                      {isFlat && <Mono size={9} color="#999">FLAT</Mono>}
                    </div>
                  </div>
                );
              })}

              {/* Overall row */}
              {isMobile ? (
                <MobileRateRow
                  label="OVERALL" r24={r24Overall} r25={r25Overall} delta={overallDelta}
                  barP_={overallBarP} isLast={true}
                  isMeaningfulDrop={overallNeg}
                  isFlat={Math.abs(overallDelta) < 2}
                  barColor={overallNeg ? "#FF426F" : THEME.primary}
                  isOverall />
              ) : (
                <div style={{
                  display: "grid", gridTemplateColumns: RATE_GRID,
                  padding: "16px 16px 14px", alignItems: "center",
                  background: "#F9F9F9", borderTop: "1px solid #000",
                }}>
                  <Mono color="#000" size={11}>OVERALL</Mono>
                  <div style={{ paddingRight: 20, paddingTop: 14 }}>
                    <div style={{ position: "relative", height: 26 }}>
                      <div style={{ position: "absolute", inset: 0, background: "#E1E1E1" }} />
                      <div style={{
                        position: "absolute", left: 0, top: 0, bottom: 0,
                        width: `${r25Overall * overallBarP}%`,
                        background: overallNeg ? "#FF426F" : THEME.primary,
                        transition: "width 300ms linear",
                      }} />
                      <div style={{
                        position: "absolute", top: -14, bottom: -4,
                        left: `${r24Overall}%`, width: 1.5, background: "#000",
                        opacity: showTick ? 1 : 0, transition: "opacity 0.3s",
                      }} />
                      <Mono size={9} color="#000" style={{
                        position: "absolute", top: -22,
                        left: `${r24Overall}%`, transform: "translateX(-50%)",
                        whiteSpace: "nowrap", background: "#F9F9F9", padding: "0 2px",
                        opacity: showTick ? 1 : 0, transition: "opacity 0.3s",
                      }}>{r24Overall}%</Mono>
                      <Mono size={10} color="#fff" style={{
                        position: "absolute", left: 7, top: "50%", transform: "translateY(-50%)",
                        opacity: showTick ? 1 : 0, transition: "opacity 0.3s",
                      }}>
                        {r25Overall}%
                      </Mono>
                    </div>
                  </div>
                  <div style={{ textAlign: "center" }}>
                    <Mono size={10} color="#999">{r24Overall}% → {r25Overall}%</Mono>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <span style={{
                      fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 18,
                      letterSpacing: "-0.02em",
                      color: overallNeg ? "#FF426F" : (Math.abs(overallDelta) < 2 ? "#999" : "#01CE91"),
                    }}>
                      {overallDelta > 0 ? "+" : ""}{overallDelta.toFixed(1)}pp
                    </span>
                  </div>
                </div>
              )}
            </div>

            {/* Legend + dynamic caption */}
            <div style={{ marginTop: 12, display: "flex", alignItems: "center", gap: isMobile ? 12 : 20, flexWrap: "wrap" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <div style={{ width: 14, height: 14, border: "1.5px solid #000", position: "relative" }}>
                  <div style={{ position: "absolute", left: "65%", top: -4, bottom: -4, width: 1.5, background: "#000" }} />
                </div>
                <Mono size={10} color="#666">VERTICAL TICK = 2024 RATE</Mono>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <div style={{ width: 14, height: 14, background: "#FF426F", opacity: 0.85 }} />
                <Mono size={10} color="#666">DECLINED ≥2pp</Mono>
              </div>
              <div style={{ marginLeft: isMobile ? 0 : "auto", display: "flex", alignItems: "center", gap: 8, flexBasis: isMobile ? "100%" : "auto" }}>
                <div style={{ width: 24, height: 1, borderTop: "1px dashed #64C5FD", flexShrink: 0 }} />
                <Mono size={10} color="#64C5FD" style={{ lineHeight: 1.4 }}>
                  {isMobile
                    ? `COHORT P50 ${window.ROI_DATA.benchmark.cohort_p50_pct.toFixed(1)}% · P75 ${p75}% · GAP ${gapToP75}pts`
                    : `COHORT MEDIAN ${window.ROI_DATA.benchmark.cohort_p50_pct.toFixed(1)}% · P75 ${p75}% · GAP TO TOP QUARTILE: ${gapToP75}pts`}
                </Mono>
              </div>
            </div>
          </div>
        );
      })()}

      {/* ── REVENUE LEAKAGE ── */}
      {activeTab === "leakage" && (
        <div>
          <div style={{
            display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 0,
            border: "1px solid #000", marginBottom: 24,
          }}>
            <LeakageCard
              yr={yoy[0].year}
              val={yoy[0].total_leakage}
              color="#000"
              subtext={`of ${fmt.usdAbbr(yoy[0].total_collectable)} collectable`}
              borderRight
              seen={seen}
            />
            <LeakageCard
              yr={yoy[1].year}
              val={yoy[1].total_leakage}
              color={THEME.primary}
              subtext={`of ${fmt.usdAbbr(yoy[1].total_collectable)} collectable · ${yoy[1].total_leakage > yoy[0].total_leakage ? "+" : "−"}${fmt.usdAbbr(Math.abs(yoy[1].total_leakage - yoy[0].total_leakage))} vs ${yoy[0].year}`}
              seen={seen}
            />
          </div>

          {/* By type stacked comparison */}
          <div style={{ border: "1px solid #000", background: "#fff" }}>
            {!isMobile && (
              <div style={{
                display: "grid", gridTemplateColumns: "180px 1fr 1fr 90px",
                padding: "10px 16px", borderBottom: "1px solid #000", background: "#000",
              }}>
                <Mono color={THEME.primary} size={10}>TYPE</Mono>
                <Mono color={THEME.primary} size={10}>2024 LEAKAGE</Mono>
                <Mono color={THEME.primary} size={10}>2025 LEAKAGE</Mono>
                <Mono color={THEME.primary} size={10} style={{ textAlign: "right" }}>CHANGE</Mono>
              </div>
            )}
            {isMobile && (
              <div style={{ padding: "10px 14px", borderBottom: "1px solid #000", background: "#000" }}>
                <Mono color={THEME.primary} size={10}>TYPE  ·  2024 vs 2025 LEAKAGE  ·  CHANGE</Mono>
              </div>
            )}
            {YOY_TYPES.map((t, i) => {
              const l24 = yoy[0].types[t.key].leakage;
              const l25 = yoy[1].types[t.key].leakage;
              const maxL = Math.max(...YOY_TYPES.map(tt => Math.max(yoy[0].types[tt.key].leakage, yoy[1].types[tt.key].leakage)));
              const delta = l25 - l24;
              const isWorse = delta > 1000; // leakage grew = bad
              const barColor25 = isWorse ? "#FF426F" : "#01CE91";

              if (isMobile) {
                return (
                  <div key={t.key} style={{
                    padding: "14px 14px",
                    borderBottom: i < YOY_TYPES.length - 1 ? "1px solid #E1E1E1" : "none",
                    background: isWorse ? "rgba(255,66,111,0.04)" : "#fff",
                  }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10, gap: 8 }}>
                      <div style={{ fontSize: 15, fontWeight: 500, color: isWorse ? "#FF426F" : "#000" }}>{t.label}</div>
                      <span style={{
                        fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 16, letterSpacing: "-0.02em",
                        color: isWorse ? "#FF426F" : "#01CE91", whiteSpace: "nowrap",
                      }}>
                        {delta > 0 ? "+" : ""}${Math.abs(Math.round(delta / 1000))}K
                        {isWorse && <span style={{ marginLeft: 6, fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace", fontSize: 9 }}>▼</span>}
                      </span>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                      <Mono size={9} color="#999" style={{ width: 32, flexShrink: 0 }}>2024</Mono>
                      <div style={{ flex: 1, position: "relative", height: 18, background: "#F9F9F9", border: "1px solid #E1E1E1" }}>
                        <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${(l24 / maxL) * 100 * p}%`, background: "#CCCCCC", transition: "width 200ms linear" }} />
                      </div>
                      <Mono size={10} color="#333" style={{ width: 44, flexShrink: 0, textAlign: "right" }}>${Math.round(l24 / 1000)}K</Mono>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <Mono size={9} color={isWorse ? "#FF426F" : "#01CE91"} style={{ width: 32, flexShrink: 0 }}>2025</Mono>
                      <div style={{ flex: 1, position: "relative", height: 18, background: isWorse ? "rgba(255,66,111,0.06)" : "#F6FDF9", border: `1px solid ${barColor25}` }}>
                        <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${(l25 / maxL) * 100 * p}%`, background: barColor25, transition: "width 200ms linear" }} />
                      </div>
                      <Mono size={10} color={isWorse ? "#FF426F" : "#01CE91"} style={{ width: 44, flexShrink: 0, textAlign: "right" }}>${Math.round(l25 / 1000)}K</Mono>
                    </div>
                  </div>
                );
              }

              return (
                <div key={t.key} style={{
                  display: "grid", gridTemplateColumns: "180px 1fr 1fr 90px",
                  padding: "14px 16px", alignItems: "center",
                  borderBottom: i < YOY_TYPES.length - 1 ? "1px solid #E1E1E1" : "none",
                  background: isWorse ? "rgba(255,66,111,0.04)" : "#fff",
                }}>
                  <div style={{ fontSize: 15, fontWeight: 500, color: isWorse ? "#FF426F" : "#000" }}>{t.label}</div>
                  <div style={{ paddingRight: 16 }}>
                    <div style={{ position: "relative", height: 24, background: "#F9F9F9", border: "1px solid #E1E1E1" }}>
                      <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${(l24 / maxL) * 100 * p}%`, background: "#CCCCCC", transition: "width 200ms linear" }} />
                      <Mono size={10} color="#333" style={{ position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)" }}>${Math.round(l24 / 1000)}K</Mono>
                    </div>
                  </div>
                  <div style={{ paddingRight: 16 }}>
                    <div style={{ position: "relative", height: 24, background: isWorse ? "rgba(255,66,111,0.06)" : "#F6FDF9", border: `1px solid ${barColor25}` }}>
                      <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${(l25 / maxL) * 100 * p}%`, background: barColor25, transition: "width 200ms linear" }} />
                      <Mono size={10} color="#fff" style={{ position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)",  }}>${Math.round(l25 / 1000)}K</Mono>
                    </div>
                  </div>
                  <div style={{ textAlign: "right", display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 2 }}>
                    <span style={{ fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 16, letterSpacing: "-0.02em", color: isWorse ? "#FF426F" : "#01CE91" }}>
                      {delta > 0 ? "+" : ""}${Math.abs(Math.round(delta / 1000))}K
                    </span>
                    {isWorse && <Mono size={9} color="#FF426F">▼ GREW</Mono>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ── DAYS TO PAYMENT ── */}
      {activeTab === "days" && (() => {
        const W = 880, H = 240;
        const PAD = { l: 56, r: 56, t: 24, b: 48 };
        const innerW = W - PAD.l - PAD.r;
        const innerH = H - PAD.t - PAD.b;
        const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
        const d24 = [19.4,25.5,30.7,28.1,29.6,31.3,36.9,43.9,34.0,27.2,23.0,17.6];
        const d25 = window.ROI_DATA.monthly_ar.map(m => m.avg);
        const peakVal = Math.max(...d25, ...d24);
        const yMax = Math.ceil((peakVal + 4) / 10) * 10;
        const yTicks = Array.from({ length: Math.floor(yMax / 10) + 1 }, (_, i) => i * 10);
        const avg24 = (d24.reduce((a, b) => a + b, 0) / d24.length).toFixed(1);
        const avg25 = (d25.reduce((a, b) => a + b, 0) / d25.length).toFixed(1);
        const peak25i = d25.indexOf(Math.max(...d25));
        const peak24i = d24.indexOf(Math.max(...d24));
        const xS = (i) => PAD.l + (i / 11) * innerW;
        const yS = (v) => PAD.t + (1 - v / yMax) * innerH;
        const mkPath = (arr) => arr.map((v, i) => `${i===0?"M":"L"} ${xS(i)} ${yS(v)}`).join(" ");
        const path24 = mkPath(d24);
        const path25 = mkPath(d25);

        return (
          <div>
            <svg viewBox={`0 0 ${W} ${H}`} width="100%" 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="#F1F1F1" strokeWidth="0.5" />
                  <text x={PAD.l-8} y={yS(t)+3} fontSize="9" textAnchor="end"
                        fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#666">{t}d</text>
                </g>
              ))}
              {months.map((m, i) => (
                <text key={m} x={xS(i)} y={H-8} fontSize="9" textAnchor="middle"
                      fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#666">{m}</text>
              ))}
              {/* Superscript baseline */}
              <line x1={PAD.l} x2={W-PAD.r} y1={yS(1.2)} y2={yS(1.2)} stroke="rgba(1,206,145,0.4)" strokeWidth="1" strokeDasharray="3,3" />
              <text x={W-PAD.r-4} y={yS(1.2)-4} fontSize="9" textAnchor="end"
                    fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="rgba(1,206,145,0.8)">SUPERSCRIPT 1.2d</text>
              {/* 2024 line */}
              <path d={path24} fill="none" stroke="#CCCCCC" strokeWidth="2" strokeDasharray="4,3" opacity={p} />
              {/* 2025 line */}
              <path d={path25} fill="none" stroke={THEME.primary} strokeWidth="2.5"
                    strokeDasharray="1500" strokeDashoffset={1500*(1-p)} />
              {d25.map((v, i) => (
                <circle key={i} cx={xS(i)} cy={yS(v)} r={p > 0.7 ? 3.5 : 0} fill={THEME.primary} stroke="#fff" strokeWidth="1" />
              ))}
              {/* annotations — both anchored at peak month, vertically staggered */}
              <g opacity={p}>
                <text x={xS(peak25i)+8} y={yS(d25[peak25i])-10} fontSize="9"
                      fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700"
                      fill={THEME.primary}>2025 {months[peak25i].toUpperCase()} {d25[peak25i]}d</text>
                <text x={xS(peak24i)+8} y={yS(d24[peak24i])-10} fontSize="9"
                      fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700"
                      fill="#AAAAAA">2024 {months[peak24i].toUpperCase()} {d24[peak24i]}d</text>
              </g>
            </svg>
            <div style={{ display: "flex", gap: 16, marginTop: 12, alignItems: "center", flexWrap: "wrap" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 20, height: 2, background: "#CCCCCC", display: "inline-block", borderTop: "2px dashed #CCCCCC" }} />
                <Mono size={11} color="#666">2024 (avg {avg24}d)</Mono>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 20, height: 2.5, background: THEME.primary, display: "inline-block" }} />
                <Mono size={11} color="#000">2025 (avg {avg25}d)</Mono>
              </div>
            </div>
            {/* stat callout */}
            <div style={{
              marginTop: 16, display: "grid",
              gridTemplateColumns: "repeat(3, 1fr)",
              border: "1px solid #000",
            }}>
              {[
                { label: isMobile ? "2024" : "2024 AVG", value: avg24 + "d", color: "#666" },
                { label: isMobile ? "2025" : "2025 AVG", value: avg25 + "d", color: THEME.primary },
                { label: isMobile ? "W/ SS" : "WITH SUPERSCRIPT", value: "1.2d", color: "#01CE91" }
              ].map((s, i) => (
                <div key={s.label} style={{
                  padding: isMobile ? "12px 10px" : "16px 20px",
                  borderRight: i < 2 ? "1px solid #000" : "none",
                }}>
                  <Mono color={THEME.primary} size={isMobile ? 9 : 10}>{s.label}</Mono>
                  <div style={{
                    fontFamily: "Suisse Intl", fontWeight: 400,
                    fontSize: isMobile ? 22 : 36,
                    letterSpacing: "-0.03em",
                    marginTop: isMobile ? 6 : 8,
                    color: s.color
                  }}>{s.value}</div>
                </div>
              ))}
            </div>
          </div>
        );
      })()}
    </div>
  );
};

window.YearlyTrends = YearlyTrends;
