// codes.jsx — procedure code breakdown + E&M severity chart

// Derived from the categories actually present in data.js, so the legend can never
// advertise categories the report does not contain. Add a category to a report by
// setting procedure_codes[].category — no edit here required.
// No blue: blue marks projected improvement only, and these are measured categories.
// All values stay dark enough to carry white bold text on a bar, and all are distinct
// (the old palette repeated #9A9A9A at slots 2 and 5, so two categories collided).
const CATEGORY_PALETTE = ["#2E2E2E", "#5A5A5A", "#FF8B4A", "#8A8A8A", "#B8A6E8", "#FF426F", "#A8A8A8"];
const CATEGORY_COLORS = (() => {
  const rows = (window.ROI_DATA && window.ROI_DATA.procedure_codes) || [];
  const cats = [...new Set(rows.map(r => r.category).filter(Boolean))];
  const map = {};
  cats.forEach((c, i) => { map[c] = CATEGORY_PALETTE[i % CATEGORY_PALETTE.length]; });
  return map;
})();

// ── CPT Code Table ──────────────────────────────────────────────────────────
const ProcedureCodes = () => {
  const D = window.ROI_DATA.procedure_codes;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.15);
  const p = useProgress(1400, seen);
  const [sort, setSort] = React.useState("leakage"); // leakage | rate | volume
  const [hover, setHover] = React.useState(null);

  const sorted = [...D].sort((a, b) => {
    if (sort === "leakage") return b.leakage - a.leakage;
    if (sort === "rate")    return a.rate_pct - b.rate_pct;
    return b.billed - a.billed;
  });

  const maxLeakage = Math.max(...D.map(d => d.leakage));
  const maxBilled  = Math.max(...D.map(d => d.billed));

  const sortBtn = (key, label) => (
    <button type="button" onClick={(e) => { e.preventDefault(); setSort(key); }} style={{
      padding: "5px 12px", cursor: "pointer", fontSize: 10, fontWeight: 700,
      fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace",
      letterSpacing: "-0.03em",
      background: sort === key ? "#000" : "#fff",
      // White on the active (black) tab. This used to be THEME.primary, which was legible
      // only while primary was blue; near-black on black disappeared.
      color: sort === key ? "#fff" : "#666",
      border: "1px solid #000", marginRight: -1,
    }}>{label}</button>
  );

  return (
    <div ref={ref}>
      <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 16 }}>
        <Mono size={10} color="#666">SORT BY</Mono>
        <div style={{ display: "flex" }}>
          {sortBtn("leakage", "DOLLAR LEAKAGE")}
          {sortBtn("rate",    "COLLECTION RATE")}
          {sortBtn("volume",  "BILLING VOLUME")}
        </div>
        <div style={{ display: "flex", gap: 16, marginLeft: "auto" }}>
          {Object.entries(CATEGORY_COLORS).map(([cat, col]) => (
            <div key={cat} style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 8, height: 8, borderRadius: "50%", background: col, display: "inline-block" }} />
              <Mono size={10} color="#666">{cat.toUpperCase()}</Mono>
            </div>
          ))}
        </div>
      </div>

      <div style={{ border: "1px solid #000", background: "#fff" }}>
        {/* Header */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "90px 1fr 90px 180px 80px 110px", columnGap: 16,
          padding: "9px 16px", background: "#000", borderBottom: "1px solid #000",
        }}>
          <Mono color={THEME.onDark} size={10}>CODE</Mono>
          <Mono color={THEME.onDark} size={10}>DESCRIPTION</Mono>
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>BILLED</Mono>
          <Mono color={THEME.onDark} size={10}>COLLECTION RATE</Mono>
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>AVG BAL</Mono>
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>LEAKAGE</Mono>
        </div>

        {sorted.map((row, i) => {
          const catColor = CATEGORY_COLORS[row.category] || THEME.primary;
          const isWarn = row.rate_pct < 65;
          const isHover = hover === row.code;
          const barW = row.rate_pct * p;

          return (
            <div key={row.code}
                 onMouseEnter={() => setHover(row.code)}
                 onMouseLeave={() => setHover(null)}
                 style={{
                   display: "grid",
                   gridTemplateColumns: "90px 1fr 90px 180px 80px 110px", columnGap: 16,
                   padding: "13px 16px", alignItems: "center",
                   borderBottom: i < sorted.length - 1 ? "1px solid #E1E1E1" : "none",
                   background: isHover ? "#F9F9F9" : (isWarn ? "rgba(255,66,111,0.03)" : "#fff"),
                   transition: "background 120ms",
                 }}>
              {/* Code + category dot */}
              <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                <span style={{ width: 7, height: 7, borderRadius: "50%", background: catColor, flexShrink: 0 }} />
                <span style={{
                  fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace",
                  fontWeight: 700, fontSize: 13, letterSpacing: "-0.02em",
                  color: "#000",
                }}>{row.code}</span>
              </div>
              {/* Description */}
              <div style={{ fontSize: 13, letterSpacing: "-0.005em", color: "#333", paddingRight: 12 }}>
                {row.desc}
              </div>
              {/* Billed */}
              <div style={{ textAlign: "right" }}>
                <div style={{
                  fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace",
                  fontWeight: 700, fontSize: 13, color: "#000",
                }}>{row.billed.toLocaleString()}</div>
                {/* volume sparklet */}
                <div style={{
                  height: 3, marginTop: 4,
                  width: `${(row.billed / maxBilled) * 80}px`,
                  background: "#E1E1E1", borderRadius: 2, marginLeft: "auto",
                  transition: "width 600ms",
                }} />
              </div>
              {/* Rate bar */}
              <div style={{ paddingRight: 8 }}>
                <div style={{ position: "relative", height: 22, background: "#F1F1F1" }}>
                  <div style={{
                    position: "absolute", left: 0, top: 0, bottom: 0,
                    width: `${barW}%`,
                    background: isWarn ? "#FF426F" : catColor,
                    transition: "width 200ms linear",
                  }} />
                  <span style={{
                    position: "absolute", left: 6, top: "50%", transform: "translateY(-50%)",
                    fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace",
                    fontWeight: 700, fontSize: 10, color: "#fff",
                  }}>{row.rate_pct}%</span>
                </div>
              </div>
              {/* Avg balance */}
              <div style={{
                textAlign: "right",
                fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace",
                fontWeight: 700, fontSize: 13, color: "#333",
              }}>${row.avg_balance >= 1000 ? (row.avg_balance / 1000).toFixed(1) + "K" : row.avg_balance}</div>
              {/* Leakage */}
              <div style={{ textAlign: "right" }}>
                <span style={{
                  fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 15,
                  letterSpacing: "-0.02em",
                  color: isWarn ? "#FF426F" : "#000",
                }}>{fmt.usdAbbr(row.leakage)}</span>
              </div>
            </div>
          );
        })}
      </div>

      <div style={{ marginTop: 12, display: "flex", gap: 32, flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 10, height: 10, background: "rgba(255,66,111,0.15)", border: "1px solid #FF426F", display: "inline-block" }} />
          <Mono size={10} color="#666">COLLECTION RATE BELOW 65%</Mono>
        </div>
        <Mono size={10} color="#666">SOURCE: ATHENA EHR TRANSACTION DATA · CY2025 · PATIENT BUCKET ONLY</Mono>
      </div>
    </div>
  );
};

// ── E&M Severity Chart ──────────────────────────────────────────────────────
const EMSeverity = () => {
  const D = window.ROI_DATA.em_codes;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.2);
  const p = useProgress(1600, seen);
  const [hover, setHover] = React.useState(null);

  const established = D.filter(d => d.type === "Established");
  const newPt       = D.filter(d => d.type === "New Patient");

  const W = 880, H = 320;
  const PAD = { l: 56, r: 56, t: 32, b: 56 };
  const innerW = W - PAD.l - PAD.r;
  const innerH = H - PAD.t - PAD.b;

  // Two groups: established (5 codes) + new patient (4 codes), with gap between
  const allCodes = [...established, null, ...newPt]; // null = gap divider
  const slots = allCodes.length;
  const slotW = innerW / slots;

  // Y left: billing volume (0..maxBilled)
  const maxBilled = Math.max(...D.map(d => d.billed));
  const yVol = (v) => PAD.t + (1 - v / maxBilled) * innerH;

  // Y right: collection rate. Auto-fit min so low rates don't drop below chart.
  const rateMin = Math.min(...D.map(d => d.rate_pct));
  const rMin = Math.max(0, Math.floor((rateMin - 5) / 10) * 10);
  const rMax = 100;
  const yRate = (v) => PAD.t + (1 - (v - rMin) / (rMax - rMin)) * innerH;

  // Rate line points (skip the null gap)
  let ratePoints = [];
  let xi = 0;
  for (const c of allCodes) {
    if (c) ratePoints.push({ x: PAD.l + xi * slotW + slotW / 2, y: yRate(c.rate_pct), code: c });
    xi++;
  }
  // Split into two segments at the gap
  const estPts  = ratePoints.filter(pt => pt.code.type === "Established");
  const newPts  = ratePoints.filter(pt => pt.code.type === "New Patient");
  const mkLine  = pts => pts.map((pt, i) => `${i === 0 ? "M" : "L"} ${pt.x} ${pt.y}`).join(" ");

  // Rate color: green→red by rate
  const rateColor = (r) => r >= 88 ? "#01CE91" : r >= 75 ? "#6A6A6A" : r >= 65 ? THEME.accent : "#FF426F";

  return (
    <div ref={ref}>
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block", border: "1px solid #000", background: "#fff" }}>
        {/* Y-grid for volume */}
        {[0, 5000, 10000, 15000, 20000].map(t => (
          <g key={t}>
            <line x1={PAD.l} x2={W - PAD.r} y1={yVol(t)} y2={yVol(t)} stroke="#F1F1F1" strokeWidth="0.5" />
            <text x={PAD.l - 8} y={yVol(t) + 3} fontSize="9" textAnchor="end"
                  fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#999">
              {t === 0 ? "0" : (t / 1000) + "K"}
            </text>
          </g>
        ))}
        {/* Y-axis right: rate (dynamic range based on rMin) */}
        {Array.from({length: Math.floor((rMax - rMin) / 10) + 1}, (_, i) => rMin + i * 10).filter(t => t > rMin).map(t => (
          <text key={t} x={W - PAD.r + 8} y={yRate(t) + 3} fontSize="9"
                fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill={THEME.primary}>{t}%</text>
        ))}

        {/* Group labels */}
        <text x={PAD.l + slotW * 2} y={PAD.t - 12} fontSize="9" textAnchor="middle"
              fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#666">ESTABLISHED PATIENTS</text>
        <text x={PAD.l + slotW * 7.5} y={PAD.t - 12} fontSize="9" textAnchor="middle"
              fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#666">NEW PATIENTS</text>

        {/* Divider gap */}
        <line x1={PAD.l + slotW * 5} x2={PAD.l + slotW * 5} y1={PAD.t} y2={H - PAD.b}
              stroke="#E1E1E1" strokeWidth="1" strokeDasharray="3,3" />

        {/* Bars */}
        {allCodes.map((c, i) => {
          if (!c) return null;
          const x = PAD.l + i * slotW;
          const cx = x + slotW / 2;
          const barW = slotW * 0.55;
          const h = (c.billed / maxBilled) * innerH * p;
          const isH = hover === c.code;
          const col = rateColor(c.rate_pct);

          return (
            <g key={c.code}>
              <rect x={cx - barW / 2} y={yVol(c.billed)} width={barW} height={h * 0}
                    style={{ display: "none" }} />
              <rect x={cx - barW / 2} y={H - PAD.b - h} width={barW} height={h}
                    fill={isH ? "#BBBBBB" : "#E1E1E1"}
                    onMouseEnter={() => setHover(c.code)}
                    onMouseLeave={() => setHover(null)}
                    style={{ cursor: "default", transition: "fill 120ms" }} />
              {/* code label */}
              <text x={cx} y={H - PAD.b + 14} fontSize="9" textAnchor="middle"
                    fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700"
                    fill="#666">{c.code}</text>
              <text x={cx} y={H - PAD.b + 24} fontSize="8" textAnchor="middle"
                    fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700"
                    fill="#999">{c.label}</text>
              {/* volume label: only show if bar is tall enough not to collide with group headers */}
              {isH && h > 60 && <text x={cx} y={H - PAD.b - h - 8} fontSize="9" textAnchor="middle"
                    fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700"
                    fill="#666">{c.billed.toLocaleString()}</text>}
            </g>
          );
        })}

        {/* Rate lines */}
        <path d={mkLine(estPts)} fill="none" stroke={THEME.primary} strokeWidth="2"
              strokeDasharray="1200" strokeDashoffset={1200 * (1 - p)} />
        <path d={mkLine(newPts)} fill="none" stroke="#9A9A9A" strokeWidth="2" strokeDasharray="4,3"
              opacity={p} />

        {/* Rate dots — labels above dots to avoid x-axis label collision; white halo handles line crossing */}
        {ratePoints.map(pt => {
          const labelY = pt.y - 12;
          const labelText = `${pt.code.rate_pct}%`;
          const labelW = labelText.length * 6 + 6;
          return (
            <g key={pt.code.code}>
              <circle cx={pt.x} cy={pt.y} r={p > 0.7 ? 5 : 0}
                      fill={rateColor(pt.code.rate_pct)} stroke="#fff" strokeWidth="1.5" />
              {/* white halo so the line never bleeds through the label */}
              <rect x={pt.x - labelW / 2} y={labelY - 8} width={labelW} height={11}
                    fill="#fff" opacity={p} />
              <text x={pt.x} y={labelY} fontSize="9" textAnchor="middle"
                    fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700"
                    fill={rateColor(pt.code.rate_pct)} opacity={p}>{labelText}</text>
            </g>
          );
        })}

        {/* Axis labels */}
        <text x={PAD.l - 40} y={PAD.t + innerH / 2} fontSize="9" textAnchor="middle"
              fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill="#999"
              transform={`rotate(-90, ${PAD.l - 40}, ${PAD.t + innerH / 2})`}>CLAIMS BILLED</text>
        <text x={W - PAD.r + 42} y={PAD.t + innerH / 2} fontSize="9" textAnchor="middle"
              fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700" fill={THEME.primary}
              transform={`rotate(90, ${W - PAD.r + 42}, ${PAD.t + innerH / 2})`}>COLLECTION RATE</text>
      </svg>

      {/* Legend */}
      <div style={{ display: "flex", gap: 24, marginTop: 12, flexWrap: "wrap", alignItems: "center" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 20, height: 10, background: "#E1E1E1", display: "inline-block" }} />
          <Mono size={10} color="#666">BILLING VOLUME (CLAIMS)</Mono>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 20, height: 2, background: THEME.primary, display: "inline-block" }} />
          <Mono size={10} color="#666">COLLECTION RATE · ESTABLISHED</Mono>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 20, height: 2, borderTop: "2px dashed #9A9A9A", display: "inline-block" }} />
          <Mono size={10} color="#666">COLLECTION RATE · NEW PATIENT</Mono>
        </div>
        {[["≥88%", "#01CE91"], ["75–87%", "#6A6A6A"], ["65–74%", THEME.accent], ["<65%", "#FF426F"]].map(([label, col]) => (
          <div key={label} style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: "50%", background: col, display: "inline-block" }} />
            <Mono size={10} color="#666">{label}</Mono>
          </div>
        ))}
      </div>
    </div>
  );
};

// ── Procedure Treemap ───────────────────────────────────────────────────────
// Squarified-style layout: each procedure's rectangle area is proportional to
// its dollar leakage; colors match the category palette used in the table.
const ProcedureTreemap = () => {
  const D = window.ROI_DATA.procedure_codes;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.15);
  const p = useProgress(1400, seen);

  // Pre-compute layout in a stable order (by leakage desc).
  const sorted = React.useMemo(() =>
    [...D].sort((a, b) => b.leakage - a.leakage), [D]);

  // Pack into rows where each row's items roughly fill the container width
  // while keeping aspect ratios sensible. Greedy row-packing.
  const W = 760, H = 340;
  const totalLeakage = sorted.reduce((s, d) => s + d.leakage, 0);
  const rows = [];
  let cur = [], curSum = 0;
  const targetRowCount = Math.ceil(Math.sqrt(sorted.length));
  const targetPerRow = Math.ceil(sorted.length / targetRowCount);
  sorted.forEach((d, i) => {
    cur.push(d); curSum += d.leakage;
    if (cur.length >= targetPerRow || i === sorted.length - 1) {
      rows.push({ items: cur, sum: curSum });
      cur = []; curSum = 0;
    }
  });
  // Each row's height is proportional to its leakage share
  let yCursor = 0;
  const cells = [];
  rows.forEach(row => {
    const rowH = (row.sum / totalLeakage) * H;
    let xCursor = 0;
    row.items.forEach(d => {
      const cellW = (d.leakage / row.sum) * W;
      cells.push({ d, x: xCursor, y: yCursor, w: cellW, h: rowH });
      xCursor += cellW;
    });
    yCursor += rowH;
  });

  return (
    <div ref={ref} style={{ border: "1px solid #000", background: "#fff", padding: "20px 24px 16px", marginBottom: 32 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 12 }}>
        <Mono color={THEME.primary} size={10}>LEAKAGE TREEMAP · TOP 12 PROCEDURES</Mono>
        <Mono color="#999" size={9}>RECTANGLE AREA = APRIL UNCOLLECTED $ · COLOR = CATEGORY</Mono>
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", display: "block" }}>
        {cells.map((c, i) => {
          const col = CATEGORY_COLORS[c.d.category] || "#999";
          // Reveal animation: stagger scale from top-left
          const reveal = Math.min(1, Math.max(0, (p - i * 0.04) / 0.5));
          const showText = c.w > 70 && c.h > 38;
          const showSmallText = c.w > 44 && c.h > 22 && !showText;
          return (
            <g key={c.d.code} style={{ opacity: reveal, transition: "opacity 400ms" }}>
              <rect
                x={c.x + 1} y={c.y + 1}
                width={Math.max(0, c.w - 2)} height={Math.max(0, c.h - 2)}
                fill={col} fillOpacity={c.d.rate_pct < 30 ? 0.95 : c.d.rate_pct < 60 ? 0.75 : 0.55}
                stroke="#fff" strokeWidth="2"
              />
              {showText && (
                <>
                  <text x={c.x + 10} y={c.y + 20} fill="#fff"
                        fontFamily="Suisse Intl Mono, JetBrains Mono, monospace"
                        fontWeight="700" fontSize="13">{c.d.code}</text>
                  <text x={c.x + 10} y={c.y + c.h - 26} fill="#fff" fillOpacity="0.9"
                        fontFamily="Suisse Intl" fontWeight="400" fontSize="11">
                    {c.d.desc.length > Math.floor(c.w / 7) ? c.d.desc.slice(0, Math.floor(c.w / 7) - 1) + "…" : c.d.desc}
                  </text>
                  <text x={c.x + 10} y={c.y + c.h - 10} fill="#fff"
                        fontFamily="Suisse Intl Mono, JetBrains Mono, monospace"
                        fontWeight="700" fontSize="11">
                    ${c.d.leakage.toLocaleString()} · {c.d.rate_pct.toFixed(1)}%
                  </text>
                </>
              )}
              {showSmallText && (
                <text x={c.x + 6} y={c.y + 16} fill="#fff"
                      fontFamily="Suisse Intl Mono, JetBrains Mono, monospace"
                      fontWeight="700" fontSize="11">{c.d.code}</text>
              )}
            </g>
          );
        })}
      </svg>

      {/* Legend strip */}
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10, padding: "8px 0", borderTop: "1px solid #E1E1E1" }}>
        <div style={{ display: "flex", gap: 18 }}>
          {Object.entries(CATEGORY_COLORS).map(([cat, col]) => (
            <div key={cat} style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 10, height: 10, background: col, display: "inline-block" }} />
              <Mono size={9} color="#666">{cat.toUpperCase()}</Mono>
            </div>
          ))}
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{ width: 10, height: 10, background: "#999", display: "inline-block" }} />
            <Mono size={9} color="#666">OTHER</Mono>
          </div>
        </div>
        <Mono size={9} color="#666">SATURATION ↑ = LOWER COLLECTION RATE</Mono>
      </div>
    </div>
  );
};

window.ProcedureTreemap = ProcedureTreemap;
window.ProcedureCodes = ProcedureCodes;
window.EMSeverity = EMSeverity;
