// 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: rate 60..85
  const rMin = 60, rMax = 85;
  const yR = (v) => PAD.t + (1 - (v - rMin) / (rMax - rMin)) * innerH;
  // right axis: AR days 0..50
  const aMin = 0, aMax = 50;
  const yA = (v) => PAD.t + (1 - (v - aMin) / (aMax - aMin)) * innerH;
  const xS = (i) => PAD.l + colW * i + colW / 2;

  // 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 */}
        {[60, 65, 70, 75, 80, 85].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 */}
        {[0, 10, 20, 30, 40, 50].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="#FF8B4A">{t}d</text>
        ))}

        {/* P75 industry baseline at 87% would be off-scale top. Show median 80.3 */}
        <line x1={PAD.l} x2={W - PAD.r} y1={yR(80.3)} y2={yR(80.3)} stroke="#64C5FD" strokeWidth="1" strokeDasharray="3,3" opacity={p} />
        <text x={W - PAD.r - 4} y={yR(80.3) - 4} fontSize="9" textAnchor="end"
              fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#64C5FD" opacity={p}>INDUSTRY MEDIAN 80.3%</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 < 75 ? "#FF8B4A" : "#00A3FF"} 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="#FF8B4A" 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="#FF8B4A" 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: 24, marginTop: 16, alignItems: "center" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 16, height: 12, background: "#00A3FF" }} />
          <Mono size={11} color="#000">COLLECTION RATE %</Mono>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 16, height: 12, background: "#FF8B4A" }} />
          <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: "#FF8B4A" }} />
          <Mono size={11} color="#000">AVG DAYS TO PAYMENT</Mono>
        </div>
      </div>

      {/* readout */}
      {hover !== null && (
        <div style={{
          marginTop: 12, padding: "12px 16px", border: "1px solid #000",
          display: "grid", gridTemplateColumns: "100px 1fr 1fr 1fr", gap: 24, background: "#000", color: "#fff",
        }}>
          <Mono color="#00A3FF" size={11}>{D1[hover].m.toUpperCase()} 2024</Mono>
          <div><Mono color="rgba(255,255,255,0.5)" size={9}>RATE</Mono><div style={{ fontSize: 18, marginTop: 2 }}>{D1[hover].rate}%</div></div>
          <div><Mono color="rgba(255,255,255,0.5)" size={9}>COLLECTED</Mono><div style={{ fontSize: 18, marginTop: 2 }}>{fmt.usdAbbr(D1[hover].collected)}</div></div>
          <div><Mono color="rgba(255,255,255,0.5)" size={9}>AVG DAYS</Mono><div style={{ fontSize: 18, marginTop: 2, color: "#FF8B4A" }}>{D2[hover].avg.toFixed(1)}d</div></div>
        </div>
      )}
    </div>
  );
};

window.MonthlyTrend = MonthlyTrend;

// ── 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: "#00A3FF" },
  { key: "DEDUCTIBLE",      label: "Deductible",       color: "#64C5FD" },
  { key: "COINSURANCE",     label: "Coinsurance",      color: "#0089E5" },
  { key: "SELFPAY",         label: "Self-pay",         color: "#FF8B4A" },
  { 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);
  const leakage24 = useCounter(yoy[0].total_leakage, 1600, seen);
  const leakage25 = useCounter(yoy[1].total_leakage, 1600, seen);

  return (
    <div ref={ref}>
      {/* ── COLLECTION RATE BY TYPE ── */}
      <div>
        <div style={{ border: "1px solid #000", background: "#fff" }}>
            {/* Header */}
            <div style={{
              display: "grid", gridTemplateColumns: "180px repeat(2, 1fr) 80px",
              padding: "10px 16px", borderBottom: "1px solid #000",
              background: "#000",
            }}>
              <Mono color="#00A3FF" size={10}>COST TYPE</Mono>
              <Mono color="#00A3FF" size={10}>2024</Mono>
              <Mono color="#00A3FF" size={10}>2025</Mono>
              <Mono color="#00A3FF" 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 isNeg = delta < -0.4;
              const barColor25 = isNeg ? "#FF426F" : t.color;
              const borderColor25 = isNeg ? "#FF426F" : t.color;
              return (
                <div key={t.key} style={{
                  display: "grid", gridTemplateColumns: "180px repeat(2, 1fr) 80px",
                  padding: "14px 16px", alignItems: "center",
                  borderBottom: i < YOY_TYPES.length - 1 ? "1px solid #E1E1E1" : "none",
                  background: isNeg ? "rgba(255,66,111,0.04)" : "#fff",
                }}>
                  <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: "-0.01em", color: isNeg ? "#FF426F" : "#000" }}>{t.label}</div>
                  {/* 2024 bar */}
                  <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: `${r24 * p}%`, background: "#CCCCCC", transition: "width 200ms linear" }} />
                      <Mono size={10} color="#333" style={{ position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)" }}>{r24}%</Mono>
                    </div>
                  </div>
                  {/* 2025 bar */}
                  <div style={{ paddingRight: 16 }}>
                    <div style={{ position: "relative", height: 24, background: isNeg ? "rgba(255,66,111,0.06)" : "#F9F9F9", border: `1px solid ${borderColor25}` }}>
                      <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${r25 * p}%`, background: barColor25, transition: "width 200ms linear" }} />
                      <Mono size={10} color="#fff" style={{ position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)",  }}>{r25}%</Mono>
                    </div>
                  </div>
                  <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: isNeg ? "#FF426F" : (delta > 0 ? "#01CE91" : "#999") }}>
                      {delta > 0 ? "+" : ""}{delta.toFixed(1)}pp
                    </span>
                    {isNeg && <Mono size={9} color="#FF426F">▼ DECLINED</Mono>}
                  </div>
                </div>
              );
            })}
            {/* Overall row */}
            <div style={{
              display: "grid", gridTemplateColumns: "180px repeat(2, 1fr) 80px",
              padding: "14px 16px", alignItems: "center",
              background: "#F9F9F9", borderTop: "1px solid #000",
            }}>
              <Mono color="#000" size={11}>OVERALL</Mono>
              <div style={{ paddingRight: 16 }}>
                <div style={{ position: "relative", height: 28, background: "#E1E1E1", border: "1px solid #000" }}>
                  <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${75.8 * p}%`, background: "#000", transition: "width 200ms linear" }} />
                  <Mono size={11} color="#fff" style={{ position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)" }}>75.8%</Mono>
                </div>
              </div>
              <div style={{ paddingRight: 16 }}>
                <div style={{ position: "relative", height: 28, background: "#E1EFFE", border: "1px solid #00A3FF" }}>
                  <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${77.0 * p}%`, background: "#00A3FF", transition: "width 200ms linear" }} />
                  <Mono size={11} color="#fff" style={{ position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)" }}>77.0%</Mono>
                </div>
              </div>
              <div style={{ textAlign: "right" }}>
                <span style={{ fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 18, letterSpacing: "-0.02em", color: "#01CE91" }}>+1.2pp</span>
              </div>
            </div>
          </div>
          {/* Industry median reference */}
          <div style={{ marginTop: 12, display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 24, height: 1, borderTop: "1px dashed #64C5FD" }} />
            <Mono size={10} color="#64C5FD">INDUSTRY MEDIAN 80.3% — Allied is 3.3pts below; gap to P75 is 10pts</Mono>
          </div>
        </div>

      {/* ── REVENUE LEAKAGE ── */}
      <div style={{ marginTop: 64 }}>
          <div style={{
            display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 0,
            border: "1px solid #000", marginBottom: 24,
          }}>
            {[{ yr: "2024", val: 1844666, color: "#000" }, { yr: "2025", val: 1674830, color: "#00A3FF" }].map((y, i) => (
              <div key={y.yr} style={{
                padding: "24px 28px",
                borderRight: i === 0 ? "1px solid #000" : "none",
              }}>
                <Mono color="#00A3FF" size={10}>{y.yr} TOTAL LEAKAGE</Mono>
                <div style={{
                  fontFamily: "Suisse Intl", fontWeight: 300, fontSize: 64, lineHeight: 1,
                  letterSpacing: "-0.035em", marginTop: 12, color: y.color,
                }}>
                  {"$" + Math.round(i === 0 ? leakage24 : leakage25).toLocaleString()}
                </div>
                <Mono size={10} color="#666" style={{ display: "block", marginTop: 8 }}>
                  {y.yr === "2024" ? "of $7.62M collectable" : "of $7.29M collectable · −$170K vs 2024"}
                </Mono>
              </div>
            ))}
          </div>

          {/* By type stacked comparison */}
          <div style={{ border: "1px solid #000", background: "#fff" }}>
            <div style={{
              display: "grid", gridTemplateColumns: "180px 1fr 1fr 90px",
              padding: "10px 16px", borderBottom: "1px solid #000", background: "#000",
            }}>
              <Mono color="#00A3FF" size={10}>TYPE</Mono>
              <Mono color="#00A3FF" size={10}>2024 LEAKAGE</Mono>
              <Mono color="#00A3FF" size={10}>2025 LEAKAGE</Mono>
              <Mono color="#00A3FF" size={10} style={{ textAlign: "right" }}>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";
              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 ── */}
      <div style={{ marginTop: 64 }}>
        {(() => {
        const W = 880, H = 240;
        const PAD = { l: 56, r: 24, 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 = window.ROI_DATA.yoy[1] ? [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 yMax = 50;
        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" }}>
              {[0,10,20,30,40,50].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="#00A3FF" strokeWidth="1.5" strokeDasharray="3,3" opacity={p} />
              <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="#00A3FF" opacity={p}>SUPERSCRIPT 1.2d</text>
              {/* 2024 line */}
              <path d={path24} fill="none" stroke="#CCCCCC" strokeWidth="2" strokeDasharray="4,3" opacity={p} />
              {/* 2025 line — dashed green */}
              <path d={path25} fill="none" stroke="#01CE91" strokeWidth="2.5"
                    strokeDasharray="6,3" opacity={p} />
              {d25.map((v, i) => (
                <circle key={i} cx={xS(i)} cy={yS(v)} r={p > 0.7 ? 3.5 : 0} fill="#01CE91" stroke="#fff" strokeWidth="1" />
              ))}
              {/* annotations */}
              <g opacity={p}>
                <text x={xS(7)+6} y={yS(43.9)-8} fontSize="9" fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#AAAAAA">2024 AUG 43.9d</text>
                <text x={xS(11)-6} y={yS(9.1)-8} fontSize="9" textAnchor="end" fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#01CE91">2025 DEC 9.1d</text>
              </g>
            </svg>
            <div style={{ display: "flex", gap: 24, marginTop: 12, alignItems: "center" }}>
              <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 28.6d)</Mono>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 20, height: 2.5, background: "#01CE91", display: "inline-block", borderTop: "2px dashed #01CE91" }} />
                <Mono size={11} color="#000">2025 (avg 15.6d)</Mono>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 20, height: 1.5, background: "#00A3FF", display: "inline-block", borderTop: "1.5px dashed #00A3FF" }} />
                <Mono size={11} color="#00A3FF">SUPERSCRIPT (1.2d)</Mono>
              </div>
            </div>
            {/* stat callout */}
            <div style={{
              marginTop: 16, display: "grid", gridTemplateColumns: "repeat(3, 1fr)",
              border: "1px solid #000",
            }}>
              {[
                { label: "2024 AVG", value: "28.6d", color: "#666" },
                { label: "2025 AVG", value: "15.6d", color: "#01CE91" },
                { label: "SUPERSCRIPT", value: "1.2d",  color: "#00A3FF" }
              ].map((s, i) => (
                <div key={s.label} style={{
                  padding: "16px 20px",
                  borderRight: i < 2 ? "1px solid #000" : "none",
                }}>
                  <Mono color="#00A3FF" size={10}>{s.label}</Mono>
                  <div style={{
                    fontFamily: "Suisse Intl", fontWeight: 400, fontSize: 36,
                    letterSpacing: "-0.03em", marginTop: 8, color: s.color
                  }}>{s.value}</div>
                </div>
              ))}
            </div>
          </div>
        );
        })()}
      </div>
    </div>
  );
};

window.YearlyTrends = YearlyTrends;
