// slices.jsx — payer, clinic and denial-reason slices. Added to the canonical template
// 2026-09-18.
//
// DATA CONTRACT. Each component returns null when its key is absent, so the sections can
// be wired optimistically and simply will not render for a report that has no data:
//   payer_families      [{family, responsibility, resp_share_pct, charge_share_pct, rate_pct, uncollected}]
//   payers              [{payer, responsibility, resp_share_pct, vol_share_pct, rate_pct, uncollected,
//                         copay, copay_rate, deductible, deductible_rate, selfpay, selfpay_rate,
//                         ptu, ptu_rate, ptu_share_pct, ptu_uncollected}]
//   clinic_slice        [{name, responsibility, ptu_share_pct, ptu_rate, rest_rate, copay_rate,
//                         deductible_rate, selfpay_rate, medicaid_*}]  NO rate_pct: ClinicSpread
//                         reads the blended rate from `locations` so the two sections cannot drift
//   clinic_spread       {actual_pp, mix_effect_pp, rate_effect_pp, rest_spread_pp, selfpay_min_pct,
//                        selfpay_max_pct, selfpay_spread_pp, ex_medicaid_spread_pp}
//   denial_attribution  {total, parent_total, attributed, attributed_pct, coverage_identity_total,
//                        reasons: [{reason, dollars, rate_pct, uncollected, attributed}]}
//   clinic_payer_leaks  [{clinic, payer, responsibility, rate_pct, ptu, ptu_rate, ptu_uncollected}]

// Colour rule: blue (THEME.proj) is projection only. Nothing in here is projected,
// so nothing in here is blue. Orange (THEME.accent) flags the adjudication-determined
// balances being targeted; red (#FF426F) flags a rate below 60%.

const ORANGE = "#FF8B4A", RED = "#FF426F";
const rateInk = (r) => (r < 40 ? RED : r < 70 ? "#000" : "#000");

// ── Payer families ─────────────────────────────────────────────────────────
const PayerFamilies = () => {
  const D = window.ROI_DATA.payer_families;
  if (!D || !D.length) return null;   // report supplied no payer families
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.15);
  const p = useProgress(1200, seen);
  const isMobile = useIsMobile();
  const maxU = Math.max(...D.map(d => d.uncollected));

  return (
    <div ref={ref} style={{ border: "1px solid #000", background: "#fff" }}>
      <div style={{
        display: "grid", gridTemplateColumns: isMobile ? "1fr 84px" : "1.5fr 110px 90px 90px 1fr",
        padding: "9px 16px", background: "#000", borderBottom: "1px solid #000",
      }}>
        <Mono color={THEME.onDark} size={10}>PAYER FAMILY</Mono>
        {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>RESPONSIBILITY</Mono>}
        {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>SHARE</Mono>}
        <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>RATE</Mono>
        {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>UNCOLLECTED</Mono>}
      </div>
      {D.map((row, i) => {
        const warn = row.rate_pct < 60;
        return (
          <div key={row.family}>
            <div style={{
              display: "grid", gridTemplateColumns: isMobile ? "1fr 84px" : "1.5fr 110px 90px 90px 1fr",
              padding: "12px 16px", alignItems: "baseline",
              borderBottom: i < D.length - 1 ? "1px solid #E1E1E1" : "none",
            }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: "-0.005em" }}>{row.family}</div>
                <Mono size={9} color="#999" style={{ display: "block", marginTop: 3 }}>
                  {row.resp_share_pct}% OF RESPONSIBILITY · {row.charge_share_pct}% OF CHARGES
                </Mono>
              </div>
              {!isMobile && <Mono size={12} color="#000" style={{ textAlign: "right" }}>{fmt.usd(row.responsibility)}</Mono>}
              {!isMobile && <Mono size={12} color="#666" style={{ textAlign: "right" }}>{row.resp_share_pct}%</Mono>}
              <div style={{
                fontFamily: "Suisse Intl", fontWeight: 400, fontSize: 18, letterSpacing: "-0.02em",
                textAlign: "right", color: warn ? RED : "#000",
              }}>{row.rate_pct.toFixed(2)}%</div>
              {!isMobile && (
                <div style={{ textAlign: "right" }}>
                  <Mono size={11} color={warn ? RED : "#666"}>{fmt.usd(row.uncollected)}</Mono>
                  <div style={{ height: 3, marginTop: 4, marginLeft: "auto", background: warn ? ORANGE : THEME.neutral,
                               width: `${(row.uncollected / maxU) * 100 * p}%` }} />
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
};
window.PayerFamilies = PayerFamilies;

// ── Payers ranked by uncollected ───────────────────────────────────────────
const PayerLeaders = () => {
  const D = window.ROI_DATA.payers;
  if (!D || !D.length) return null;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.1);
  const isMobile = useIsMobile();
  const [showAll, setShowAll] = React.useState(false);
  const shown = showAll ? D : D.slice(0, 10);
  const cols = isMobile ? "1fr 70px 70px" : "2fr 100px 70px 90px 80px 70px";

  const cell = (v, align = "right") => (
    <Mono size={11} color="#666" style={{ textAlign: align }}>{v}</Mono>
  );

  return (
    <div ref={ref}>
      <div style={{ border: "1px solid #000", background: "#fff" }}>
        <div style={{ display: "grid", gridTemplateColumns: cols, padding: "9px 16px", background: "#000" }}>
          <Mono color={THEME.onDark} size={10}>PAYER</Mono>
          {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>RESPONSIBILITY</Mono>}
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>RATE</Mono>
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>UNCOLLECTED</Mono>
          {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>PT+UNC</Mono>}
          {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>PT RATE</Mono>}
        </div>
        {shown.map((row, i) => {
          const heavy = row.ptu_share_pct >= 25;
          return (
            <div key={row.payer} style={{
              display: "grid", gridTemplateColumns: cols, padding: "11px 16px", alignItems: "baseline",
              borderBottom: i < shown.length - 1 ? "1px solid #E1E1E1" : "none",
              background: heavy ? "#FFF6F0" : "#fff",
            }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500, letterSpacing: "-0.005em", lineHeight: 1.25 }}>{row.payer}</div>
                <Mono size={9} color="#999" style={{ display: "block", marginTop: 3 }}>
                  {row.vol_share_pct}% OF CHARGES
                  {row.copay_rate != null ? ` · COPAY ${row.copay_rate}%` : ""}
                  {row.deductible_rate != null ? ` · DEDUCT ${row.deductible_rate}%` : ""}
                </Mono>
              </div>
              {!isMobile && cell(fmt.usd(row.responsibility))}
              <div style={{
                fontFamily: "Suisse Intl", fontWeight: 400, fontSize: 16, letterSpacing: "-0.02em",
                textAlign: "right", color: row.rate_pct < 60 ? RED : "#000",
              }}>{row.rate_pct.toFixed(2)}%</div>
              <Mono size={11} color="#000" style={{ textAlign: "right" }}>{fmt.usd(row.uncollected)}</Mono>
              {!isMobile && cell(row.ptu ? `${row.ptu_share_pct}%` : "—")}
              {!isMobile && (
                <Mono size={11} color={heavy ? ORANGE : "#666"} style={{ textAlign: "right" }}>
                  {row.ptu_rate != null ? `${row.ptu_rate}%` : "—"}
                </Mono>
              )}
            </div>
          );
        })}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 10 }}>
        <button type="button" onClick={(e) => { e.preventDefault(); setShowAll(!showAll); }} style={{
          padding: "5px 12px", cursor: "pointer", fontSize: 10, fontWeight: 700,
          fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace", letterSpacing: "-0.03em",
          background: "#fff", color: "#000", border: "1px solid #000",
        }}>{showAll ? "SHOW TOP 10" : `SHOW ALL ${D.length}`}</button>
        <Mono size={9} color="#999">
          SHADED = PATIENT TRANSFER IS 25%+ OF THAT PAYER&#39;S RESPONSIBILITY
        </Mono>
      </div>
    </div>
  );
};
window.PayerLeaders = PayerLeaders;

// ── Clinic spread: what explains it ────────────────────────────────────────
const ClinicSpread = () => {
  const S = window.ROI_DATA.clinic_spread;
  if (!S || !window.ROI_DATA.clinic_slice) return null;
  // The blended clinic rate has exactly one source in this report: `locations`, which
  // section 07 renders. clinic_slice deliberately carries no rate_pct, so the two
  // sections cannot drift. Balance-type and Medicaid columns are charge grain.
  const LOC = {};
  window.ROI_DATA.locations.forEach(l => { LOC[l.name] = l.rate_pct; });
  const C = window.ROI_DATA.clinic_slice
    .filter(c => c.name !== "Telemedicine")
    .map(c => ({ ...c, rate_pct: LOC[c.name] }));
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.15);
  const p = useProgress(1400, seen);
  const isMobile = useIsMobile();
  const sorted = [...C].sort((a, b) => a.rate_pct - b.rate_pct);

  const Bar = ({ label, pp, note }) => (
    <div style={{ marginBottom: 14 }}>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 5 }}>
        <Mono size={10} color={THEME.primary}>{label}</Mono>
        <Mono size={10} color="#000">{pp}pp</Mono>
      </div>
      <div style={{ height: 10, background: "#F1F1F1", border: "1px solid #000" }}>
        <div style={{ height: "100%", width: `${(pp / S.actual_pp) * 100 * p}%`, background: THEME.neutral }} />
      </div>
      <Mono size={9} color="#999" style={{ display: "block", marginTop: 4 }}>{note}</Mono>
    </div>
  );

  return (
    <div ref={ref}>
      <div style={{ marginBottom: 24, maxWidth: 720 }}>
        <Bar label="TOTAL SPREAD ACROSS THE 16 CLINICS" pp={S.actual_pp}
             note={`${sorted[0].rate_pct.toFixed(2)}% AT ${sorted[0].name.toUpperCase()} TO ${sorted[sorted.length-1].rate_pct.toFixed(2)}% AT ${sorted[sorted.length-1].name.toUpperCase()}`} />
        <Bar label="ATTRIBUTABLE TO COLLECTION RATES WITHIN BALANCE TYPES" pp={S.rate_effect_pp}
             note="EACH CLINIC'S OWN RATES APPLIED TO THE GROUP'S BALANCE MIX" />
        <Bar label="ATTRIBUTABLE TO BALANCE MIX" pp={S.mix_effect_pp}
             note="EACH CLINIC'S OWN MIX APPLIED TO THE GROUP'S RATES" />
        <Bar label="REMAINING ONCE MEDICAID IS REMOVED" pp={S.ex_medicaid_spread_pp}
             note="PAYER MIX EXPLAINS PART OF THE SPREAD, NOT ALL OF IT" />
        <div style={{ marginTop: 18, padding: "12px 16px", background: "#F9F9F9", borderLeft: `3px solid ${THEME.primary}` }}>
          <Mono size={10} color={THEME.primary} style={{ display: "block", marginBottom: 6 }}>SELF-PAY IS FLAT ACROSS EVERY CLINIC</Mono>
          <span style={{ fontSize: 14, lineHeight: 1.45, color: "#000" }}>
            Self-pay collects between <strong>{S.selfpay_min_pct.toFixed(2)}%</strong> and <strong>{S.selfpay_max_pct.toFixed(2)}%</strong> at all 16 clinics, a spread of {S.selfpay_spread_pp} points against {S.actual_pp} points on everything else. West Philadelphia collects {sorted[0].rate_pct.toFixed(2)}% overall and {sorted[0].selfpay_rate.toFixed(2)}% of self-pay. The site is held constant, so what moves is whether the amount was set at the time of service or determined by adjudication afterwards.
          </span>
        </div>
      </div>

      <div style={{ border: "1px solid #000", background: "#fff" }}>
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr 60px 60px" : "1.4fr 74px 74px 74px 74px 86px 86px", padding: "9px 16px", background: "#000" }}>
          <Mono color={THEME.onDark} size={10}>CLINIC</Mono>
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>ALL</Mono>
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>SELF-PAY</Mono>
          {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>COPAY</Mono>}
          {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>DEDUCT</Mono>}
          {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>PT+UNC</Mono>}
          {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>MEDICAID</Mono>}
        </div>
        {sorted.map((c, i) => (
          <div key={c.name} style={{
            display: "grid", gridTemplateColumns: isMobile ? "1fr 60px 60px" : "1.4fr 74px 74px 74px 74px 86px 86px",
            padding: "10px 16px", alignItems: "baseline",
            borderBottom: i < sorted.length - 1 ? "1px solid #E1E1E1" : "none",
          }}>
            <div style={{ fontSize: 13, fontWeight: 500, letterSpacing: "-0.005em" }}>{c.name}</div>
            <Mono size={12} color={c.rate_pct < 72 ? RED : "#000"} style={{ textAlign: "right" }}>{c.rate_pct.toFixed(2)}%</Mono>
            <Mono size={12} color="#000" style={{ textAlign: "right" }}>{c.selfpay_rate.toFixed(2)}%</Mono>
            {!isMobile && <Mono size={12} color="#666" style={{ textAlign: "right" }}>{c.copay_rate}%</Mono>}
            {!isMobile && <Mono size={12} color="#666" style={{ textAlign: "right" }}>{c.deductible_rate}%</Mono>}
            {!isMobile && (
              <Mono size={12} color={c.ptu_share_pct >= 20 ? ORANGE : "#666"} style={{ textAlign: "right" }}>
                {c.ptu_share_pct}% @ {c.ptu_rate}%
              </Mono>
            )}
            {!isMobile && (
              <Mono size={12} color={c.medicaid_share_pct >= 7 ? ORANGE : "#666"} style={{ textAlign: "right" }}>
                {c.medicaid_share_pct}% @ {c.medicaid_rate}%
              </Mono>
            )}
          </div>
        ))}
      </div>
      <Mono size={9} color="#999" style={{ display: "block", marginTop: 10 }}>
        PT+UNC AND MEDICAID COLUMNS READ AS "SHARE OF THAT CLINIC&#39;S RESPONSIBILITY @ ITS COLLECTION RATE" · TELEMEDICINE EXCLUDED, 176 CLAIMS
        <br />ALL COLUMN IS THE SECTION 07 FIGURE · BALANCE-TYPE AND MEDICAID COLUMNS ARE CHARGE GRAIN, WHICH DROPS $1,692 OF PAYMENTS CARRYING NO CHARGE ID
      </Mono>
    </div>
  );
};
window.ClinicSpread = ClinicSpread;

// ── Denial-reason attribution ──────────────────────────────────────────────
const DenialReasons = () => {
  const D = window.ROI_DATA.denial_attribution;
  if (!D || !D.reasons) return null;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.15);
  const p = useProgress(1300, seen);
  const isMobile = useIsMobile();
  const maxD = Math.max(...D.reasons.map(r => r.dollars));

  return (
    <div ref={ref}>
      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "repeat(3, 1fr)", border: "1px solid #000", marginBottom: 20 }}>
        {[
          ["TRANSFER BALANCES IN SCOPE", fmt.usd(D.total), `OF THE ${fmt.usd(D.parent_total)} IN SECTION 04`],
          ["CARRIES A DENIAL REASON", `${D.attributed_pct}%`, `${fmt.usd(D.attributed)} OF ${fmt.usd(D.total)}`],
          ["COVERAGE, IDENTITY, ELIGIBILITY AND COB", fmt.usd(D.coverage_identity_total), "THE FOUR CATEGORIES COMBINED"],
        ].map(([label, value, note], i) => (
          <div key={label} style={{ padding: "16px 18px", borderRight: i < 2 && !isMobile ? "1px solid #000" : "none",
                                    borderBottom: isMobile && i < 2 ? "1px solid #000" : "none", background: "#fff" }}>
            <Mono color={THEME.primary} size={10} style={{ display: "block", lineHeight: 1.3 }}>{label}</Mono>
            <div style={{ fontFamily: "Suisse Intl", fontWeight: 400, fontSize: 26, lineHeight: 1, letterSpacing: "-0.02em", margin: "10px 0 6px" }}>{value}</div>
            <Mono size={9} color="#999">{note}</Mono>
          </div>
        ))}
      </div>

      <div style={{ border: "1px solid #000", background: "#fff" }}>
        <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr 70px" : "2fr 110px 70px 110px", padding: "9px 16px", background: "#000" }}>
          <Mono color={THEME.onDark} size={10}>REASON THE BALANCE MOVED TO THE PATIENT</Mono>
          {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>DOLLARS</Mono>}
          <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>RATE</Mono>
          {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>UNCOLLECTED</Mono>}
        </div>
        {D.reasons.map((r, i) => (
          <div key={r.reason} style={{
            display: "grid", gridTemplateColumns: isMobile ? "1fr 70px" : "2fr 110px 70px 110px",
            padding: "11px 16px", alignItems: "baseline",
            borderBottom: i < D.reasons.length - 1 ? "1px solid #E1E1E1" : "none",
            background: r.attributed ? "#fff" : "#F9F9F9",
          }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, letterSpacing: "-0.005em", lineHeight: 1.3,
                            color: r.attributed ? "#000" : "#666" }}>{r.reason}</div>
              {!isMobile && (
                <div style={{ height: 3, marginTop: 5, background: r.attributed ? THEME.neutral : THEME.neutralLight,
                              width: `${(r.dollars / maxD) * 100 * p}%` }} />
              )}
            </div>
            {!isMobile && <Mono size={11} color="#000" style={{ textAlign: "right" }}>{fmt.usd(r.dollars)}</Mono>}
            <Mono size={11} color={r.rate_pct < 40 ? RED : "#000"} style={{ textAlign: "right" }}>{r.rate_pct}%</Mono>
            {!isMobile && <Mono size={11} color="#666" style={{ textAlign: "right" }}>{fmt.usd(r.uncollected)}</Mono>}
          </div>
        ))}
      </div>
      <Mono size={9} color="#999" style={{ display: "block", marginTop: 10 }}>
        SHADED ROW = NO REMITTANCE REASON FOUND ON THE PARENT CHARGE · LARGEST-AMOUNT REASON PER CHARGE ONLY
      </Mono>
    </div>
  );
};
window.DenialReasons = DenialReasons;

// ── Clinic and payer combinations ──────────────────────────────────────────
const ClinicPayerLeaks = () => {
  const D = window.ROI_DATA.clinic_payer_leaks;
  if (!D || !D.length) return null;
  const isMobile = useIsMobile();
  const cols = isMobile ? "1fr 70px" : "1fr 1.4fr 100px 70px 100px";
  return (
    <div style={{ border: "1px solid #000", background: "#fff" }}>
      <div style={{ display: "grid", gridTemplateColumns: cols, padding: "9px 16px", background: "#000" }}>
        <Mono color={THEME.onDark} size={10}>CLINIC</Mono>
        {!isMobile && <Mono color={THEME.onDark} size={10}>PAYER</Mono>}
        {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>PT+UNC</Mono>}
        <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>PT RATE</Mono>
        {!isMobile && <Mono color={THEME.onDark} size={10} style={{ textAlign: "right" }}>UNCOLLECTED</Mono>}
      </div>
      {D.map((r, i) => (
        <div key={r.clinic + r.payer} style={{
          display: "grid", gridTemplateColumns: cols, padding: "11px 16px", alignItems: "baseline",
          borderBottom: i < D.length - 1 ? "1px solid #E1E1E1" : "none",
        }}>
          <div style={{ fontSize: 13, fontWeight: 500 }}>
            {r.clinic}
            {isMobile && <Mono size={9} color="#999" style={{ display: "block", marginTop: 3 }}>{r.payer}</Mono>}
          </div>
          {!isMobile && <div style={{ fontSize: 13, color: "#333", lineHeight: 1.25 }}>{r.payer}</div>}
          {!isMobile && <Mono size={11} color="#000" style={{ textAlign: "right" }}>{fmt.usd(r.ptu)}</Mono>}
          <Mono size={11} color={r.ptu_rate < 40 ? RED : "#000"} style={{ textAlign: "right" }}>{r.ptu_rate}%</Mono>
          {!isMobile && <Mono size={11} color={ORANGE} style={{ textAlign: "right" }}>{fmt.usd(r.ptu_uncollected)}</Mono>}
        </div>
      ))}
    </div>
  );
};
window.ClinicPayerLeaks = ClinicPayerLeaks;
