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

const CATEGORY_COLORS = {
  "E&M":       THEME.primary,
  "Injection":  "#64C5FD",
  "Surgery":    "#FF426F",
};

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

  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",
      color: sort === key ? THEME.primary : "#666",
      border: "1px solid #000", marginRight: -1,
    }}>{label}</button>
  );

  return (
    <div ref={ref}>
      <div style={{
        display: "flex",
        flexDirection: isMobile ? "column" : "row",
        alignItems: isMobile ? "flex-start" : "center",
        gap: isMobile ? 10 : 16,
        marginBottom: 16,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
          <Mono size={10} color="#666">SORT BY</Mono>
          <div style={{ display: "flex", flexWrap: "wrap" }}>
            {sortBtn("leakage", isMobile ? "LEAKAGE" : "DOLLAR LEAKAGE")}
            {sortBtn("rate",    isMobile ? "RATE" : "COLLECTION RATE")}
            {sortBtn("volume",  isMobile ? "VOLUME" : "BILLING VOLUME")}
          </div>
        </div>
        <div style={{ display: "flex", gap: 12, marginLeft: isMobile ? 0 : "auto", flexWrap: "wrap" }}>
          {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>

      {/* Mobile: card layout per code */}
      {isMobile ? (
        <div style={{ border: "1px solid #000", background: "#fff" }}>
          {sorted.map((row, i) => {
            const catColor = CATEGORY_COLORS[row.category] || THEME.primary;
            const isWarn = row.rate_pct < 65;
            const barW = row.rate_pct * p;
            return (
              <div key={row.code} style={{
                padding: "14px 14px 16px",
                borderBottom: i < sorted.length - 1 ? "1px solid #E1E1E1" : "none",
                background: isWarn ? "rgba(255,66,111,0.03)" : "#fff",
              }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8, gap: 12 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 7, minWidth: 0 }}>
                    <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>
                  <span style={{
                    fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 18,
                    letterSpacing: "-0.02em",
                    color: isWarn ? "#FF426F" : "#000",
                    whiteSpace: "nowrap",
                  }}>{fmt.usdAbbr(row.leakage)}</span>
                </div>
                <div style={{ fontSize: 13, letterSpacing: "-0.005em", color: "#333", marginBottom: 10, lineHeight: 1.4 }}>
                  {row.desc}
                </div>
                <div style={{ position: "relative", height: 22, background: "#F1F1F1", marginBottom: 8 }}>
                  <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}% RATE</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between" }}>
                  <Mono size={10} color="#666">{row.billed.toLocaleString()} BILLED</Mono>
                  <Mono size={10} color="#666">AVG ${row.avg_balance >= 1000 ? (row.avg_balance / 1000).toFixed(1) + "K" : row.avg_balance}</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.primary} size={10}>CODE</Mono>
            <Mono color={THEME.primary} size={10}>DESCRIPTION</Mono>
            <Mono color={THEME.primary} size={10} style={{ textAlign: "right" }}>BILLED</Mono>
            <Mono color={THEME.primary} size={10}>COLLECTION RATE</Mono>
            <Mono color={THEME.primary} size={10} style={{ textAlign: "right" }}>AVG BAL</Mono>
            <Mono color={THEME.primary} 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);
  const p = useProgress(750, 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 (55..100)
  const rMin = 55, 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 ? THEME.primary : 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 */}
        {[60, 70, 80, 90, 100].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={Math.max(PAD.t + 14, 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="#64C5FD" strokeWidth="2" strokeDasharray="4,3"
              opacity={p} />

        {/* Rate dots. label sits above the dot so it cannot overlap an adjacent dot. */}
        {ratePoints.map(pt => (
          <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" />
            <text
              x={pt.x}
              y={pt.y - 11}
              fontSize="9"
              textAnchor="middle"
              fontFamily="Suisse Intl Mono, JetBrains Mono, monospace" fontWeight="700"
              fill={rateColor(pt.code.rate_pct)} opacity={p}>{pt.code.rate_pct}%</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 #64C5FD", display: "inline-block" }} />
          <Mono size={10} color="#666">COLLECTION RATE: NEW PATIENT</Mono>
        </div>
        {[["≥88%", "#01CE91"], ["75–87%", THEME.primary], ["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>
  );
};

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