// hero.jsx — top of report
const Hero = () => {
  const D = window.ROI_DATA;
  const H = D.headline;
  const P = D.projection;
  const ref = React.useRef(null);
  const seen = useInView(ref, 0.05);

  const collectedCounter   = useCounter(H.total_collected, 1800, seen);
  const rateCounter        = useCounter(H.collection_rate_pct, 1500, seen, 2);
  const daysCounter        = useCounter(H.avg_days_to_payment, 1500, seen, 1);
  const upliftCounter      = P ? useCounter(P.gross_annual_uplift, 1800, seen) : 0;
  const netUpliftCounter   = P && P.fee ? useCounter(P.fee.net_uplift_after_fees, 1800, seen) : 0;
  const cashForwardCounter = P && P.cash_moved_forward ? useCounter(P.cash_moved_forward, 1800, seen) : 0;
  const isMobile = useIsMobile();

  return (
    <section ref={ref} style={{
      position: "relative",
      background: "#F9F9F9",
      padding: "32px 56px 80px",
      borderBottom: "1px solid #000",
      overflow: "hidden",
    }}>
      {/* Top chyron meta-line */}
      <div style={{
        display: "flex", alignItems: "center", gap: 16,
        paddingBottom: 16, marginBottom: 56, borderBottom: `1px dashed ${THEME.primary}`,
      }}>
        <img src="assets/superscript-logo-blue.svg" alt="Superscript" style={{ height: 18 }} />
        <Mono color={THEME.primary}>[01] HEADLINE</Mono>
        <Mono color={THEME.primary} style={{ opacity: 0.6 }}>·</Mono>
        <Mono color={THEME.primary} style={{ opacity: 0.6 }}>PATIENT COLLECTIONS ROI</Mono>
        <span style={{ flex: 1, height: 1, background: THEME.primary, opacity: 0.4 }} />
      </div>

      {/* Practice header */}
      <div style={{ marginBottom: 32 }}>
        <div>
          <Mono color={THEME.primary} size={11} style={{ display: "block", marginBottom: 24 }}>PRACTICE</Mono>
          <h1 style={{
            fontFamily: "Suisse Intl", fontWeight: 300, fontSize: 72, lineHeight: 0.98,
            letterSpacing: "-0.03em", margin: 0,
          }}>
            {D.practice}
          </h1>
          <div style={{ display: "flex", gap: 32, marginTop: 32, flexWrap: "wrap" }}>
            <div>
              <Mono color={THEME.primary} size={10} style={{ display: "block", marginBottom: 6, opacity: 0.6 }}>SPECIALTY</Mono>
              <span style={{ fontSize: 16, fontWeight: 400 }}>{D.specialty}</span>
            </div>
            <div>
              <Mono color={THEME.primary} size={10} style={{ display: "block", marginBottom: 6, opacity: 0.6 }}>LOCATION</Mono>
              <span style={{ fontSize: 16, fontWeight: 400 }}>{D.location}</span>
            </div>
            <div>
              <Mono color={THEME.primary} size={10} style={{ display: "block", marginBottom: 6, opacity: 0.6 }}>PERIOD</Mono>
              <span style={{ fontSize: 16, fontWeight: 400 }}>{D.period}</span>
            </div>
            {D.report_date && (
              <div>
                <Mono color={THEME.primary} size={10} style={{ display: "block", marginBottom: 6, opacity: 0.6 }}>DATA AS OF</Mono>
                <span style={{ fontSize: 16, fontWeight: 400 }}>{(() => {
                  const parts = D.report_date.split("-");
                  if (parts.length !== 3) return D.report_date;
                  const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
                  const m = parseInt(parts[1], 10) - 1;
                  const d = parseInt(parts[2], 10);
                  return `${months[m]} ${d}, ${parts[0]}`;
                })()}</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Headline metric grid — uplift combo takes 2 columns, rest are single tiles */}
      {P && P.fee ? (
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 0,
          border: "1px solid #000",
        }}>
          {isMobile ? (
            <>
              <Metric label="PROJECTED UPLIFT" value={fmt.usd(upliftCounter)} note={`pure lift, pre-fee · ${P.fee.gross_roi_multiple.toFixed(1)}x gross ROI`} square />
              <Metric label="NET AFTER FEES" value={fmt.usd(netUpliftCounter)} note={`after ${P.fee.fee_pct}% fee, excl. card processing · ${P.fee.net_roi_multiple.toFixed(1)}x net ROI`} accent square />
            </>
          ) : (
            <UpliftCombo gross={upliftCounter} net={netUpliftCounter} fee={P.fee} />
          )}
          <Metric
            label="TOTAL UNCOLLECTED 2025"
            definition="Gross patient responsibility for CY2025 not yet collected as of the data cutoff."
            value={<span style={{ whiteSpace: "nowrap" }}>{fmt.usd(H.total_uncollected)} <span style={{ fontSize: "0.5em", fontWeight: 400, color: "#999" }}>uncollected</span></span>}
            valueSize={22}
            note={`of ${fmt.usd(H.total_collectable)} collectable`}
            square
          />
          <Metric
            label="COLLECTION RATE"
            definition="Total patient payments collected divided by total gross patient responsibility for CY2025."
            value={`${rateCounter.toFixed(2)}%`}
            note={`→ ${P.projected_rate_pct.toFixed(2)}% w/ Superscript`}
            square
          />
          <Metric
            label="AVG DAYS TO PAY"
            definition="Weighted average days from patient liability posting to patient payment posting."
            value={`${daysCounter.toFixed(1)}d`}
            note={`→ ~${P.projected_avg_days_to_payment}d w/ Superscript`}
            square
          />
          <Metric
            label="CASH MOVED FORWARD"
            definition="Working-capital value of collecting the same dollars ~32 days sooner, independent of the uplift."
            value={fmt.usd(cashForwardCounter)}
            note="sooner, not new"
            last
            square
          />
        </div>
      ) : P ? (
        /* Projection present without fee math (pure collections lift, the current
           methodology). Uplift tile stays leftmost and black; rate and days carry arrows. */
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 0,
          border: "1px solid #000",
        }}>
          <Metric
            label="PROJECTED UPLIFT"
            definition={P.basis ? `Additional patient dollars collected each year: ${P.basis}.` : "Additional patient dollars collected each year at the modelled rate."}
            value={fmt.usd(upliftCounter)}
            note="pure collections lift · no fees or labor savings"
            accent
          />
          <Metric
            label="COLLECTION RATE"
            definition="Total patient payments collected divided by total gross patient responsibility for CY2025."
            value={`${rateCounter.toFixed(2)}%`}
            note={`\u2192 ${P.projected_rate_pct.toFixed(2)}% with Superscript`}
          />
          <Metric
            label="AVG DAYS TO PAY"
            definition="Weighted average days from patient liability posting to patient payment posting."
            value={`${daysCounter.toFixed(1)}d`}
            note={`\u2192 ~${P.projected_avg_days_to_payment}d with Superscript`}
          />
          <Metric
            label="TOTAL UNCOLLECTED"
            definition="Gross patient responsibility for CY2025 that has not yet been collected as of the data cutoff."
            value={fmt.usd(H.total_uncollected)}
            note={`${fmt.num(H.total_claims)} claims \u00b7 CY2025`}
            last
          />
        </div>
      ) : (
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 0,
          border: "1px solid #000",
        }}>
          <Metric
            label="COLLECTION RATE"
            definition="Total patient payments collected divided by total gross patient responsibility for CY2025."
            value={`${rateCounter.toFixed(2)}%`}
            note={`${fmt.usd(H.total_collected)} of ${fmt.usd(H.total_collectable)} owed`}
          />
          <Metric
            label="AVG DAYS TO PAY"
            definition="Weighted average days from patient liability posting to patient payment posting."
            value={`${daysCounter.toFixed(1)}d`}
            note="across all patient-liability claims"
          />
          <Metric
            label="TOTAL UNCOLLECTED"
            definition="Gross patient responsibility for CY2025 that has not yet been collected as of the data cutoff."
            value={fmt.usd(H.total_uncollected)}
            note={`${fmt.num(H.total_claims)} claims · CY2025`}
            last
          />
        </div>
      )}

      {H.curve_narrative && <PullQuote>{H.curve_narrative}</PullQuote>}
    </section>
  );
};

const Metric = ({ label, definition, secondary, value, valueSize, note, projNote = false, last = false, accent = false, warn = false, square = false }) => (
  <div style={{
    padding: square ? "18px 16px" : "20px 22px 22px",
    borderRight: last ? "none" : "1px solid #000",
    background: accent ? "#000" : warn ? "#fff" : "#fff",
    color: accent ? "#fff" : "#000",
    height: square ? 220 : undefined,
    minHeight: square ? undefined : 168,
    display: "flex", flexDirection: "column", justifyContent: "space-between",
    position: "relative",
    gap: 12,
  }}>
    <div>
      <Mono color={accent ? THEME.proj : THEME.primary} size={square ? 11 : 10} style={square ? { display: "block", lineHeight: 1.3 } : undefined}>{label}</Mono>
      {definition && (
        <div style={{
          marginTop: 8,
          fontFamily: "Suisse Intl",
          fontWeight: 400, fontSize: square ? 13 : 12, lineHeight: 1.35,
          letterSpacing: "-0.005em",
          color: accent ? "rgba(255,255,255,0.85)" : "#444",
          maxWidth: square ? undefined : 320,
        }}>{definition}</div>
      )}
    </div>
    <div>
      {secondary && (
        <div style={{ marginBottom: 8 }}>
          <Mono size={9} color={accent ? "rgba(255,255,255,0.6)" : "#999"}>{secondary.label}</Mono>
          <div style={{
            fontFamily: "Suisse Intl", fontWeight: 500, fontSize: square ? 14 : 16,
            letterSpacing: "-0.01em", marginTop: 2,
            color: accent ? "rgba(255,255,255,0.85)" : "#444",
          }}>{secondary.value}</div>
        </div>
      )}
      <div style={{
        fontFamily: "Suisse Intl", fontWeight: 400, fontSize: valueSize || (square ? 26 : 38), lineHeight: 1,
        letterSpacing: "-0.025em", marginBottom: 8,
        color: warn ? "#FF426F" : (accent ? "#fff" : "#000"),
      }}>{value}</div>
      <div style={{
        fontFamily: "Suisse Intl Mono, JetBrains Mono, monospace",
        fontWeight: 500, fontSize: square ? 10 : 11, letterSpacing: "-0.02em",
        // blue only when the note states a projected improvement
        color: accent ? "rgba(255,255,255,0.85)" : (projNote ? THEME.proj : "#666")
      }}>{note}</div>
    </div>
  </div>
);

// Wide combo tile spanning 2 grid columns: gross uplift above net-after-fees
// on the left, gross and net ROI on fees on the right. Fees exclude card
// processing (see projection.fee in data.js).
const ComboNum = ({ value, note, color = "#fff" }) => (
  <div>
    <div style={{ fontFamily: "Suisse Intl", fontWeight: 400, fontSize: 30, lineHeight: 1, letterSpacing: "-0.025em", marginBottom: 4, color }}>{value}</div>
    <Mono size={10} color="rgba(255,255,255,0.6)">{note}</Mono>
  </div>
);
const UpliftCombo = ({ gross, net, fee }) => (
  <div style={{
    gridColumn: "span 2", height: 220, background: "#000", color: "#fff",
    padding: "18px 16px", borderRight: "1px solid #000",
    display: "flex", flexDirection: "column", justifyContent: "space-between",
  }}>
    <Mono color={THEME.proj} size={9} style={{ display: "block", lineHeight: 1.3 }}>PROJECTED UPLIFT · ROI ON FEES</Mono>
    <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", columnGap: 16 }}>
      <ComboNum value={fmt.usd(gross)} note="pure lift, pre-fee" />
      <ComboNum value={`${fee.gross_roi_multiple.toFixed(1)}x`} note="gross ROI" />
    </div>
    <div style={{ borderTop: "1px solid rgba(255,255,255,0.2)", paddingTop: 12, display: "grid", gridTemplateColumns: "1.4fr 1fr", columnGap: 16 }}>
      <ComboNum value={fmt.usd(net)} note={`net after ${fee.fee_pct}% fee`} color={THEME.proj} />
      <ComboNum value={`${fee.net_roi_multiple.toFixed(1)}x`} note="net ROI" color={THEME.proj} />
    </div>
  </div>
);

window.Hero = Hero;
