// breakdowns.jsx — cost share + balance buckets

// ── Rate Ladder ─────────────────────────────────────────────────────────────
// Visualizes the spread between best- and worst-collecting cost categories.
const RateLadder = () => {
  const D = window.ROI_DATA.cost_share;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.2);
  const p = useProgress(1500, seen);

  // Sorted by rate desc so the spread is visible top-to-bottom
  const sorted = [...D].sort((a, b) => b.rate_pct - a.rate_pct);
  const best = sorted[0], worst = sorted[sorted.length - 1];
  const spread = best.rate_pct - worst.rate_pct;

  return (
    <div ref={ref} style={{ border: "1px solid #000", background: "#fff", padding: "20px 24px 16px", marginBottom: 24 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16 }}>
        <Mono color={THEME.primary} size={10}>COLLECTION RATE LADDER · BY COST CATEGORY</Mono>
        <Mono color="#999" size={9}>
          BEST ({best.type.toUpperCase()}) – WORST ({worst.type.toUpperCase()}) SPREAD: {spread.toFixed(1)} PTS
        </Mono>
      </div>

      {/* Horizontal rate bars with category labels */}
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {sorted.map((row, i) => {
          const barW = row.rate_pct * p;
          const isBest = i === 0;
          const isWorst = i === sorted.length - 1;
          const color = isBest ? THEME.neutral : isWorst ? "#FF426F" : "#D4D4D4";
          return (
            <div key={row.type} style={{ display: "grid", gridTemplateColumns: "180px 1fr 110px", alignItems: "center", gap: 14 }}>
              <div>
                <span style={{ fontSize: 14, fontWeight: 500, letterSpacing: "-0.01em" }}>{row.type}</span>
                <Mono size={9} color="#666" style={{ display: "block", marginTop: 2 }}>
                  {fmt.usdAbbr(row.collectable)} POOL · {row.share}% OF BOOK
                </Mono>
              </div>
              <div style={{ position: "relative", height: 22, background: "#F1F1F1" }}>
                <div style={{
                  height: 22, width: `${barW}%`,
                  background: color,
                  transition: "width 600ms cubic-bezier(0.2,0.7,0.2,1)",
                  borderRight: barW > 5 ? `2px solid ${isBest ? "#000" : color}` : "none",
                }} />
                <span style={{
                  position: "absolute", left: barW > 10 ? 8 : `calc(${barW}% + 8px)`,
                  top: "50%", transform: "translateY(-50%)",
                  fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace",
                  fontWeight: 700, fontSize: 11,
                  color: barW > 10 ? "#fff" : "#000",
                }}>{row.rate_pct.toFixed(2)}%</span>
              </div>
              <Mono size={11} color={isWorst ? "#FF426F" : "#666"} style={{ textAlign: "right" }}>
                {fmt.usd(row.uncollected)} LEAK
              </Mono>
            </div>
          );
        })}
      </div>

      {/* Spread callout */}
      <div style={{
        marginTop: 18, padding: "12px 16px",
        background: "rgba(0,163,255,0.06)", borderLeft: `3px solid ${THEME.proj}`,
      }}>
        <Mono size={10} color={THEME.proj} style={{ display: "block", marginBottom: 6 }}>POINT-OF-SERVICE LIFT</Mono>
        <span style={{ fontSize: 14, lineHeight: 1.45, color: "#000" }}>
          Copay (predictable at check-in) collects at <strong>{best.rate_pct.toFixed(1)}%</strong>. Deductible and coinsurance (post-adjudication) collect at <strong>{D.find(d => d.type === "Deductible")?.rate_pct.toFixed(1)}% and {D.find(d => d.type === "Coinsurance")?.rate_pct.toFixed(1)}%</strong>. The {(best.rate_pct - (D.find(d => d.type === "Deductible")?.rate_pct ?? 0)).toFixed(1)}-point gap is the dollar value of pricing transparency at point of service — about <strong>${Math.round((best.rate_pct/100 - (D.find(d => d.type === "Deductible")?.rate_pct ?? 0)/100) * (D.find(d => d.type === "Deductible")?.collectable ?? 0)).toLocaleString()} of recoverable deductible alone</strong>.
        </span>
      </div>
    </div>
  );
};

window.RateLadder = RateLadder;

const CostShare = () => {
  const D = window.ROI_DATA.cost_share;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.2);
  const p = useProgress(1500, seen);
  const [hover, setHover] = React.useState(null);
  const isMobile = useIsMobile();

  const maxCol = Math.max(...D.map(d => d.collectable));
  const cols = isMobile ? "1fr 90px" : "180px 1fr 90px 110px 110px";

  return (
    <div ref={ref} style={{ border: "1px solid #000", background: "#fff" }}>
      {!isMobile && (
        <div style={{
          display: "grid", gridTemplateColumns: cols,
          padding: "10px 16px", borderBottom: "1px solid #000",
          background: "#000", color: "#fff",
        }}>
          <Mono color={THEME.onDark} size={10}>COST TYPE</Mono>
          <Mono color={THEME.onDark} size={10}>COLLECTABLE / COLLECTED</Mono>
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>SHARE</Mono>
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>RATE</Mono>
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>UNCOLLECTED</Mono>
        </div>
      )}
      {D.map((row, i) => {
        const colW = (row.collectable / maxCol) * 100 * p;
        const fillW = (row.collected / row.collectable) * colW;
        const isHover = hover === i;
        const warn = row.rate_pct < 60;
        // Orange marks the adjudication-determined balances being targeted. Deductible is
        // flagged on size even when its rate clears the warn threshold, so the bar
        // highlights without the rate reading as critical-red.
        const flagged = warn || row.type === "Deductible";

        /* Mechanism-only copy, computed from the row. Practice-specific analytical
           claims (what patient transfer actually IS at a given account, whether the
           payer adjudicated, write-off shares) MUST be measured per account and
           overridden in that report's own copy of this file. Do not hardcode
           numbers from another practice here: that shipped MSPB's figures into a
           later report before it was caught. */
        const annotation = row.type === "Patient Transfer"
          ? `Balances that move to the patient after the payer processes the claim. They collect ${row.rate_pct.toFixed(2)}% of ${fmt.usd(row.collectable)}, leaving ${fmt.usd(row.uncollected)} uncollected. Whether the payer paid a share or nothing at all is account-specific and worth measuring before making a claim about it.`
          : row.type === "Self-pay"
          ? `Charges with no insurer on file, where the amount is set before the visit rather than after adjudication. They collect ${row.rate_pct.toFixed(2)}% of ${fmt.usd(row.collectable)}, leaving ${fmt.usd(row.uncollected)} uncollected.`
          : row.type === "Copay"
          ? `A fixed amount the front desk can read off the card, so the price is known before the patient leaves. It collects ${row.rate_pct.toFixed(2)}% of ${fmt.usd(row.collectable)}.`
          : null;

        return (
          <React.Fragment key={row.type}>
            {isMobile ? (
              <div
                 onClick={() => setHover(hover === i ? null : i)}
                 style={{
                   padding: "14px 16px",
                   borderBottom: annotation ? "none" : (i < D.length - 1 ? "1px solid #E1E1E1" : "none"),
                   background: isHover ? "#F1F1F1" : "#fff",
                 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <div style={{ fontSize: 16, fontWeight: 500, letterSpacing: "-0.01em" }}>{row.type}</div>
                  <span style={{
                    fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 20, letterSpacing: "-0.02em",
                    color: warn ? "#FF426F" : "#000",
                  }}>{row.rate_pct}%</span>
                </div>
                <Mono size={10} color="#666" style={{ display: "block", marginTop: 2 }}>{fmt.usdAbbr(row.collectable)} POOL · {row.share}% OF BOOK</Mono>
                <div style={{ position: "relative", height: 28, marginTop: 10 }}>
                  <div style={{
                    position: "absolute", left: 0, top: 0, height: 28,
                    width: `${colW}%`, background: "#EDEDED", border: `1px solid ${THEME.neutralLight}`,
                    transition: "width 200ms linear",
                  }} />
                  <div style={{
                    position: "absolute", left: 0, top: 0, height: 28,
                    width: `${fillW}%`, background: flagged ? THEME.accent : THEME.neutral,
                    transition: "width 200ms linear",
                  }} />
                </div>
                <Mono size={10} color={warn ? "#FF426F" : "#666"} style={{ display: "block", marginTop: 6 }}>
                  {fmt.usdAbbr(row.collected)} of {fmt.usdAbbr(row.collectable)} · {fmt.usdAbbr(row.uncollected)} uncollected
                </Mono>
              </div>
            ) : (
              <div
                 onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
                 style={{
                   display: "grid", gridTemplateColumns: cols,
                   padding: "16px",
                   borderBottom: annotation ? "none" : (i < D.length - 1 ? "1px solid #E1E1E1" : "none"),
                   background: isHover ? "#F1F1F1" : "#fff",
                   alignItems: "center", transition: "background 120ms",
                 }}>
                <div>
                  <div style={{ fontSize: 17, fontWeight: 500, letterSpacing: "-0.01em" }}>{row.type}</div>
                  <Mono size={10} color="#666" style={{ marginTop: 4 }}>{fmt.usdAbbr(row.collectable)} POOL</Mono>
                </div>
                <div style={{ position: "relative", height: 32 }}>
                  <div style={{
                    position: "absolute", left: 0, top: 0, height: 32,
                    width: `${colW}%`, background: "#EDEDED", border: `1px solid ${THEME.neutralLight}`,
                    transition: "width 200ms linear",
                  }} />
                  <div style={{
                    position: "absolute", left: 0, top: 0, height: 32,
                    width: `${fillW}%`, background: flagged ? THEME.accent : THEME.neutral,
                    transition: "width 200ms linear",
                  }} />
                  <div style={{
                    position: "absolute", left: 8, top: "50%", transform: "translateY(-50%)",
                    color: "#fff",
                    fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace",
                    fontWeight: 700, fontSize: 11, letterSpacing: "-0.02em",
                  }}>{fmt.usdAbbr(row.collected)} of {fmt.usdAbbr(row.collectable)}</div>
                </div>
                <Mono size={12} color="#000" style={{ textAlign: "right" }}>{row.share}%</Mono>
                <div style={{ textAlign: "right" }}>
                  <span style={{
                    fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 22, letterSpacing: "-0.02em",
                    color: warn ? "#FF426F" : "#000",
                  }}>{row.rate_pct}%</span>
                </div>
                <Mono size={11} color={warn ? "#FF426F" : "#666"} style={{ textAlign: "right" }}>
                  {fmt.usdAbbr(row.uncollected)}
                </Mono>
              </div>
            )}
            {annotation && (
              <div style={{
                padding: isMobile ? "0 16px 14px" : "0 16px 14px",
                borderBottom: i < D.length - 1 ? "1px solid #E1E1E1" : "none",
                background: "#fff",
              }}>
                <div style={{
                  borderLeft: `3px solid ${row.type === "Patient Transfer" ? "#FF426F" : THEME.primary}`,
                  paddingLeft: 12,
                  fontSize: 13,
                  lineHeight: 1.55,
                  letterSpacing: "-0.005em",
                  color: "#444",
                  maxWidth: 760,
                }}>{annotation}</div>
              </div>
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
};

const BalanceBuckets = () => {
  const D = window.ROI_DATA.balance_buckets;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.2);
  const p = useProgress(1500, seen);

  return (
    <div ref={ref} style={{
      display: "grid", gridTemplateColumns: "repeat(6, 1fr)",
      border: "1px solid #000", background: "#fff",
    }}>
      {D.map((row, i) => {
        const fill = row.rate_pct * p;
        const warn = row.rate_pct < 50;
        return (
          <div key={row.bucket} style={{
            padding: "16px 14px 18px",
            borderRight: i < D.length - 1 ? "1px solid #000" : "none",
            display: "flex", flexDirection: "column", gap: 12,
            background: warn ? "#FFF6F0" : "#fff",
            minHeight: 240,
          }}>
            <div>
              <Mono color={THEME.primary} size={10}>BAND {String(i + 1).padStart(2, "0")}</Mono>
              <div style={{ fontSize: 18, fontWeight: 500, marginTop: 6, letterSpacing: "-0.01em" }}>{row.bucket}</div>
              <Mono size={10} color="#666" style={{ marginTop: 4 }}>{fmt.num(row.claims)} CLAIMS</Mono>
            </div>
            {/* vertical fill bar */}
            <div style={{
              flex: 1, position: "relative", border: "1px solid #000", background: "#F9F9F9",
              minHeight: 90,
            }}>
              <div style={{
                position: "absolute", left: 0, right: 0, bottom: 0,
                height: `${fill}%`,
                background: warn ? "#FF426F" : THEME.neutral,
                transition: "height 200ms linear",
              }} />
              <span style={{
                position: "absolute", top: 6, left: 6,
                fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 22,
                letterSpacing: "-0.02em",
                color: warn ? "#FF426F" : "#000"
              }}>{row.rate_pct}%</span>
            </div>
            <div>
              <Mono size={10} color="#666">AVG · {row.avg_days}d</Mono>
            </div>
          </div>
        );
      })}
    </div>
  );
};

window.CostShare = CostShare;
window.BalanceBuckets = BalanceBuckets;
