// breakdowns.jsx. cost share + balance buckets

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

  const maxCol = Math.max(...D.map(d => d.collectable));

  // Mobile: card layout. type/rate header, bar, then a stat row
  if (isMobile) {
    return (
      <div ref={ref} style={{ border: "1px solid #000", background: "#fff" }}>
        {D.map((row, i) => {
          const colW = (row.collectable / maxCol) * 100 * p;
          const fillW = (row.collected / row.collectable) * colW;
          const warn = row.rate_pct < 60;
          const annotation = row.type === "Patient Transfer"
            ? "These balances originate from primary insurer denials and non-covered service transfers. Patients believe insurance should have covered it, and most never pay."
            : row.type === "Self-pay"
            ? "Claims with no insurer on file. These patients agreed to their financial responsibility upfront, which is why this category collects over 3× better than patient transfer."
            : null;
          return (
            <div key={row.type} style={{
              padding: "16px",
              borderBottom: i < D.length - 1 ? "1px solid #E1E1E1" : "none",
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
                <div>
                  <div style={{ fontSize: 16, fontWeight: 500, letterSpacing: "-0.01em" }}>{row.type}</div>
                  <Mono size={10} color="#666" style={{ marginTop: 4 }}>{fmt.usdAbbr(row.collectable)} POOL · {row.share}% SHARE</Mono>
                </div>
                <span style={{
                  fontFamily: "Suisse Intl", fontWeight: 500, fontSize: 24, letterSpacing: "-0.02em",
                  color: warn ? "#FF426F" : "#000",
                }}>{row.rate_pct}%</span>
              </div>
              <div style={{ position: "relative", height: 26, marginBottom: 8 }}>
                <div style={{
                  position: "absolute", left: 0, top: 0, height: 26,
                  width: `${colW}%`, background: "#E1EFFE", border: `1px solid ${THEME.primary}`,
                  transition: "width 200ms linear",
                }} />
                <div style={{
                  position: "absolute", left: 0, top: 0, height: 26,
                  width: `${fillW}%`, background: warn ? THEME.accent : THEME.primary,
                  transition: "width 200ms linear",
                }} />
              </div>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <Mono size={10} color="#666">COLLECTED {fmt.usdAbbr(row.collected)}</Mono>
                <Mono size={10} color={warn ? "#FF426F" : "#666"}>UNCOLLECTED {fmt.usdAbbr(row.uncollected)}</Mono>
              </div>
              {annotation && (
                <div style={{
                  marginTop: 12,
                  borderLeft: `3px solid ${row.type === "Patient Transfer" ? "#FF426F" : THEME.primary}`,
                  paddingLeft: 10,
                  fontSize: 12,
                  lineHeight: 1.55,
                  letterSpacing: "-0.005em",
                  color: "#444",
                }}>{annotation}</div>
              )}
            </div>
          );
        })}
      </div>
    );
  }

  return (
    <div ref={ref} style={{ border: "1px solid #000", background: "#fff" }}>
      <div style={{
        display: "grid", gridTemplateColumns: "180px 1fr 90px 110px 110px",
        padding: "10px 16px", borderBottom: "1px solid #000",
        background: "#000", color: "#fff",
      }}>
        <Mono color={THEME.primary} size={10}>COST TYPE</Mono>
        <Mono color={THEME.primary} size={10}>COLLECTABLE / COLLECTED</Mono>
        <Mono color={THEME.primary} size={10} style={{ textAlign: "right" }}>SHARE</Mono>
        <Mono color={THEME.primary} size={10} style={{ textAlign: "right" }}>RATE</Mono>
        <Mono color={THEME.primary} 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;

        const annotation = row.type === "Patient Transfer"
          ? "These balances originate from primary insurer denials and non-covered service transfers. The payer pushed the balance to the patient after claim processing. Patients receiving a surprise post-denial bill have the lowest payment intent in the dataset: they believe insurance should have covered it, and most never pay."
          : row.type === "Self-pay"
          ? "Claims with no insurer on file at time of service. These patients agreed to their financial responsibility upfront, which is why this category collects over 3× better than patient transfer despite similar average balance size. The gap illustrates the direct value of price clarity at the point of care."
          : null;

        return (
          <React.Fragment key={row.type}>
            <div
               onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
               style={{
                 display: "grid", gridTemplateColumns: "180px 1fr 90px 110px 110px",
                 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: "#E1EFFE", border: `1px solid ${THEME.primary}`,
                  transition: "width 200ms linear",
                }} />
                <div style={{
                  position: "absolute", left: 0, top: 0, height: 32,
                  width: `${fillW}%`, background: warn ? THEME.accent : THEME.primary,
                  transition: "width 200ms linear",
                }} />
                <div style={{
                  position: "absolute", left: 8, top: "50%", transform: "translateY(-50%)",
                  color: "#000",
                  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={{
                gridColumn: "1 / -1",
                padding: "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);
  const p = useProgress(700, seen);
  const isMobile = useIsMobile();
  const cols = isMobile ? 2 : 6;

  return (
    <div ref={ref} style={{
      display: "grid",
      gridTemplateColumns: `repeat(${cols}, 1fr)`,
      border: "1px solid #000", background: "#fff",
    }}>
      {D.map((row, i) => {
        const fill = row.rate_pct * p;
        const warn = row.rate_pct < 50;
        const colPos = i % cols;
        const rowPos = Math.floor(i / cols);
        const totalRows = Math.ceil(D.length / cols);
        return (
          <div key={row.bucket} style={{
            padding: isMobile ? "14px 12px 16px" : "16px 14px 18px",
            borderRight: colPos < cols - 1 ? "1px solid #000" : "none",
            borderBottom: rowPos < totalRows - 1 ? "1px solid #000" : "none",
            display: "flex", flexDirection: "column", gap: isMobile ? 10 : 12,
            background: warn ? "#FFF6F0" : "#fff",
            minHeight: isMobile ? 180 : 240,
          }}>
            <div>
              <Mono color={THEME.primary} size={10}>BAND {String(i + 1).padStart(2, "0")}</Mono>
              <div style={{
                fontSize: isMobile ? 15 : 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: isMobile ? 70 : 90,
            }}>
              <div style={{
                position: "absolute", left: 0, right: 0, bottom: 0,
                height: `${fill}%`,
                background: warn ? "#FF426F" : THEME.primary,
                transition: "height 200ms linear",
              }} />
              <span style={{
                position: "absolute", top: 6, left: 6,
                fontFamily: "Suisse Intl", fontWeight: 500,
                fontSize: isMobile ? 18 : 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;
