/* ============================================================
   B4IOU — Step 5 : Paywall   Step 6 : Post-payment
   ============================================================ */

const TIERS = {
  full: {
    id: "full", price: "19.99", name: "Full Report", tagline: "2 schools · everything unlocked", schools: 2, pdf: true, feat: true,
    feats: [
      "Full report for 2 schools",
      "Complete PDF download",
      "All report sections included",
      "Shareable link generated",
      "Verified question bank",
      "Student Consumer Information links",
    ],
  },
  full3: {
    id: "full3", price: "34.99", name: "Full Report + 3rd School", tagline: "3 schools · ranked best value", schools: 3, pdf: true, best: true,
    feats: [
      "Everything in Full Report",
      "Adds a 3rd school to compare",
      "Value ranking — best financial decision",
      "Corporate partnership deep dive",
      "10-year loan projection comparison",
      "Priority report generation",
    ],
  },
  quick: {
    id: "quick", price: "9.99", name: "Quick Check", tagline: "Both schools · screen-only", schools: 2, pdf: false,
    feats: [
      "Both schools — full side-by-side",
      "Accreditation status check",
      "Hidden fee audit, per school",
      "10-year loan projection",
      "On screen only — no PDF or share link",
    ],
  },
};
const TIER_ORDER = ["full", "full3", "quick"];

/* Consent-gated email capture — writes a real lead via captureLead(),
   and (when sendReport) actually emails the comparison via Resend. */
function EmailCapture({ title, sub, leadExtra, report, schools, tier, sendReport }) {
  const [email, setEmail] = useState("");
  const [consent, setConsent] = useState(false);
  const [saved, setSaved] = useState(false);
  const [msg, setMsg] = useState("Saved — check your inbox.");
  const cfg = window.B4IOU_CONFIG || {};
  const ok = /.+@.+\..+/.test(email) && consent;
  async function save() {
    if (!ok) return;
    if (window.captureLead) window.captureLead(Object.assign({ lead_type: "email", email, consent: true }, leadExtra || {}));
    setSaved(true);
    if (sendReport && window.sendEmail) {
      setMsg("Sending your report…");
      const summary = window.buildEmailSummary ? window.buildEmailSummary(report, schools, tier) : null;
      const res = await window.sendEmail({ mode: "report", to: email, summary });
      if (res && res.simulated) setMsg("Saved — your report emails the moment delivery goes live.");
      else if (res && res.ok) setMsg("Sent! Check your inbox for your comparison.");
      else setMsg("Saved — we couldn’t email it just now. We’ll retry.");
    }
  }
  return (
    <div className="card fade-up d3" style={{ borderColor: "var(--accent-line)" }}>
      <div style={{ fontWeight: 800, fontSize: 14.5, marginBottom: 4 }}>{title}</div>
      <div className="mono" style={{ fontSize: 11.5, color: "var(--text-3)", marginBottom: 12 }}>{sub}</div>
      {saved ? (
        <div style={{ display: "flex", gap: 8, alignItems: "center", color: "var(--accent)" }}><Ico.check /> <span style={{ fontWeight: 700, fontSize: 14 }}>{msg}</span></div>
      ) : (
        <>
          <div style={{ display: "flex", gap: 8 }}>
            <input className="input" type="email" placeholder="you@email.com" value={email} onChange={(e) => setEmail(e.target.value)} style={{ flex: 1 }} />
            <button className="btn btn-accent btn-md" disabled={!ok} onClick={save}>Save</button>
          </div>
          <label className="consent">
            <input type="checkbox" checked={consent} onChange={(e) => setConsent(e.target.checked)} />
            <span>I agree to be contacted by B4IOU about my comparison and accept the <a href={cfg.PRIVACY_URL || "#"} target="_blank" rel="noopener noreferrer">privacy policy</a>.</span>
          </label>
        </>
      )}
    </div>
  );
}

function Paywall({ schools, setSchools, onPay, onBack }) {
  const [tier, setTier] = useState("full");
  const [paying, setPaying] = useState(false);
  const needThird = tier === "full3";
  const third = schools[2] || { name: "", program: "" };
  function setThird(key, val) {
    setSchools((prev) => {
      const next = [...prev];
      next[2] = { ...(next[2] || { name: "", program: "" }), [key]: val };
      return next;
    });
  }
  function setThirdMany(obj) {
    setSchools((prev) => {
      const next = [...prev];
      next[2] = { ...(next[2] || { name: "", program: "" }), ...obj };
      return next;
    });
  }
  async function pickThird(school) {
    setThirdMany({ name: school.name, scorecardId: school.id, schoolState: school.state, scorecard: null, programsMerged: null, programNote: null, scLoading: true, program: "" });
    let raw = null;
    try { const res = await window.scorecardFetch(school.id, school.name); raw = res && res.data; } catch (e) { raw = null; }
    setThirdMany({ scorecard: raw, scLoading: false });
    try {
      const agg = await window.scorecardAggregatePrograms(school.id, school.name);
      if (agg && agg.programs.length) {
        const own = (raw && window.scorecardPrograms) ? window.scorecardPrograms(raw).length : 0;
        const note = agg.programs.length > own
          ? (agg.onlineDivision
              ? `Includes programs from ${agg.onlineDivision} and ${agg.siblingCount - 1} other ${school.name.split(/\s*[-–]\s*/)[0]} division${agg.siblingCount - 1 === 1 ? "" : "s"}.`
              : `Pooled across ${agg.siblingCount} ${school.name.split(/\s*[-–]\s*/)[0]} campuses (some delivered online or at another location).`)
          : null;
        setThirdMany({ programsMerged: agg.programs, programNote: note });
      }
    } catch (e) {}
  }
  const thirdReady = !needThird || (third.name.trim() && third.program.trim());

  function pay() {
    setPaying(true);
    const cfg = window.B4IOU_CONFIG || {};
    if (cfg.BACKEND) {
      onPay(tier);                          // redirects to Stripe (or toasts on error)
      setTimeout(() => setPaying(false), 8000); // safety reset if redirect didn't fire
      return;
    }
    setTimeout(() => { setPaying(false); onPay(tier); }, 1600);
  }

  return (
    <div className="screen">
      <div className="pad grow stack" style={{ gap: 16 }}>
        <div className="fade-up">
          <span className="eyebrow"><Ico.lock /> One unlock. Zero subscriptions.</span>
          <h2 className="title" style={{ marginTop: 12 }}>Get the whole picture.</h2>
          <p className="lede" style={{ marginTop: 8 }}>A $50K decision deserves more than a sticker price. Pick your report.</p>
        </div>

        {/* tiers */}
        <div className="stack fade-up d1" style={{ gap: 14, marginTop: 4 }}>
          {TIER_ORDER.map((id) => {
            const t = TIERS[id];
            const sel = tier === id;
            return (
              <div key={id} className={`tier ${sel ? "sel" : ""} ${t.best ? "feat" : ""}`} onClick={() => setTier(id)}>
                {t.best && <span className="badge">Best value</span>}
                {t.feat && <span className="badge alt">Most popular</span>}
                <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
                  <div>
                    <div className="mono" style={{ fontSize: 11, color: sel ? "var(--accent)" : "var(--text-3)", letterSpacing: "0.06em", textTransform: "uppercase" }}>{t.name}</div>
                    <div className="price" style={{ marginTop: 6 }}>
                      <span className="cur">$</span><span className="amt">{t.price.split(".")[0]}</span>
                      <span className="cur" style={{ fontSize: 18 }}>.{t.price.split(".")[1]}</span>
                    </div>
                    <div className="mono" style={{ fontSize: 10.5, color: "var(--text-3)", marginTop: 4 }}>{t.tagline}</div>
                  </div>
                  <span className="radio-dot" style={{ marginTop: 4, borderColor: sel ? "var(--accent)" : "var(--line-2)" }}>
                    {sel && <span style={{ width: 10, height: 10, borderRadius: "50%", background: "var(--accent)" }} />}
                  </span>
                </div>
                <ul className="feat-list">
                  {t.feats.map((f, i) => (
                    <li key={i}><span className={id === "full3" && i > 0 ? "plus" : "ck"}>{id === "full3" && i > 0 ? "+" : <Ico.check />}</span>{f}</li>
                  ))}
                </ul>
              </div>
            );
          })}
        </div>

        {/* 3rd school input for Tier 2 */}
        {needThird && (
          <div className="card fade-up" style={{ borderColor: "var(--accent-line)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 12 }}>
              <span style={{ width: 26, height: 26, borderRadius: 8, background: "#FF9F6E", color: "var(--accent-ink)", display: "grid", placeItems: "center", fontWeight: 900, fontSize: 13 }}>C</span>
              <span className="mono" style={{ fontSize: 12, color: "var(--text-2)" }}>ADD YOUR 3RD SCHOOL</span>
            </div>
            <div className="stack" style={{ gap: 12 }}>
              <SchoolPicker
                value={third.name}
                loading={third.scLoading}
                picked={!!third.scorecard}
                onType={(v) => setThirdMany({ name: v, scorecard: null, scorecardId: null, scLoading: false })}
                onPick={(school) => pickThird(school)}
              />
              <Combo label="Program / Degree" value={third.program} onChange={(v) => setThird("program", v)} placeholder={third.scorecard ? "Pick from this school's programs" : "e.g. Computer Science (BS)"} options={programOptionsFor(third)} />
              {third.programNote && <div className="prog-note mono"><Ico.shield /> {third.programNote}</div>}
            </div>
          </div>
        )}

        {/* Quick Check scope note */}
        {tier === "quick" && (
          <div className="callout accent fade-up">
            <div className="callout-h"><Ico.bolt /> Quick Check — both schools, screen only</div>
            <p>You'll get the hidden-fee audit and 10-year loan projection for <b style={{ color: "var(--text)" }}>both schools</b> on screen — everything in the free comparison, plus the cost deep-dive. No PDF or shareable link.</p>
          </div>
        )}

        {/* stripe placeholder */}
        <div className="fade-up">
          <div className="kicker-bar" style={{ marginBottom: 12 }}>
            <span className="ln" />
            <span className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", color: "var(--text-3)", textTransform: "uppercase" }}>Secure checkout</span>
            <span className="ln" />
          </div>
          <div className="stripe-box">
            <div className="stripe-field"><span>Card number</span><span style={{ letterSpacing: 2 }}>•••• •••• •••• ••••</span></div>
            <div style={{ display: "flex", gap: 10 }}>
              <div className="stripe-field" style={{ flex: 1 }}><span>MM / YY</span><span>••/••</span></div>
              <div className="stripe-field" style={{ flex: 1 }}><span>CVC</span><span>•••</span></div>
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7, color: "var(--text-3)" }}>
              <Ico.lock /><span className="mono" style={{ fontSize: 11 }}>Stripe placeholder — connects live at launch</span>
            </div>
          </div>
        </div>
      </div>

      <div className="sticky-cta">
        {needThird && !thirdReady && !paying && (
          <div style={{ textAlign: "center", marginBottom: 8, fontSize: 12.5, fontWeight: 700, color: "var(--accent)", lineHeight: 1.4 }}>
            ↑ Add your 3rd school’s name &amp; program above to continue
          </div>
        )}
        <Btn kind="accent" size="lg" arrow={!paying && thirdReady} disabled={!thirdReady || paying} onClick={pay}>
          {paying ? "Processing…"
            : (needThird && !thirdReady) ? "Add your 3rd school to continue"
            : tier === "quick" ? "Pay $9.99 — Quick Check"
            : `Pay $${TIERS[tier].price} & unlock`}
        </Btn>
        <div style={{ textAlign: "center", marginTop: 6 }}><BackBtn onClick={onBack} label="Back to report" /></div>
      </div>
    </div>
  );
}

/* ---------------- Step 6 : Post-payment ---------------- */
function PostPayment({ report, schools, tier, onDownload, onUpgrade, toast }) {
  if (tier === "quick") return <QuickCheckResult report={report} onUpgrade={onUpgrade} toast={toast} />;
  return <FullPostPayment report={report} schools={schools} tier={tier} onDownload={onDownload} toast={toast} />;
}

/* Reusable share + referral block (social post / text a friend / email a friend).
   Used on EVERY paid tier so buyers can drive referrals. */
function ShareReferral({ report, schools, tier, toast, refUrl: refUrlProp }) {
  const genUrl = useMemo(() => `https://b4iou.com/r/${Math.random().toString(36).slice(2, 8)}`, []);
  const refUrl = refUrlProp || genUrl;
  const [refMode, setRefMode] = useState("social"); // social | text | email
  const [friendEmail, setFriendEmail] = useState("");
  const [sent, setSent] = useState(false);
  const [refMsg, setRefMsg] = useState("");
  const sharePost = "I used B4IOU before picking my school 👀 First comparison is free → b4iou.com #B4IOU";
  const smsBody = `You should run your school through B4IOU before you owe anything — see the real cost after aid. First comparison's free: ${refUrl}`;
  const smsHref = "sms:?&body=" + encodeURIComponent(smsBody);

  function copy(text, label) {
    navigator.clipboard?.writeText(text);
    toast(label || "Copied!");
  }

  async function emailFriend() {
    if (!/.+@.+\..+/.test(friendEmail)) return;
    const step = tier === "quick" ? "post-quick-referral" : "post-full-referral";
    if (window.captureLead) window.captureLead({ lead_type: "referral", referred_email: friendEmail, source_step: step });
    setSent(true);
    setRefMsg("Sending the invite…");
    const summary = window.buildEmailSummary ? window.buildEmailSummary(report, schools, tier) : { link: refUrl };
    if (summary) summary.link = refUrl;
    const res = window.sendEmail ? await window.sendEmail({ mode: "referral", to: friendEmail, summary }) : { ok: false };
    if (res && res.simulated) setRefMsg("Logged — the invite sends the moment email delivery goes live. You both get a free report.");
    else if (res && res.ok) setRefMsg("Sent! Your friend just got the invite — you both earned a free report.");
    else setRefMsg("Saved — we couldn’t send it just now. We’ll retry. You both still get a free report.");
  }

  return (
    <div className="fade-up d2" style={{ marginTop: 6 }}>
      <div className="kicker-bar" style={{ marginBottom: 14 }}>
        <span className="ln" />
        <span className="mono" style={{ fontSize: 10, letterSpacing: "0.14em", color: "var(--accent)", textTransform: "uppercase" }}>Help a friend avoid the debt trap</span>
        <span className="ln" />
      </div>

      <div style={{ display: "flex", gap: 8, marginBottom: 14, background: "var(--surface)", padding: 5, borderRadius: "var(--r-md)", border: "1px solid var(--line)" }}>
        {[["social", "Social post"], ["text", "Text a friend"], ["email", "Email a friend"]].map(([v, t]) => (
          <button key={v} className="btn btn-sm" style={{ flex: 1, background: refMode === v ? "var(--accent)" : "transparent", color: refMode === v ? "var(--accent-ink)" : "var(--text-2)" }} onClick={() => setRefMode(v)}>{t}</button>
        ))}
      </div>

      {refMode === "social" ? (
        <div className="card" style={{ padding: 16 }}>
          <p style={{ fontSize: 14, lineHeight: 1.5, color: "var(--text)" }}>{sharePost}</p>
          <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
            <button className="btn btn-accent btn-md" style={{ flex: 1 }} onClick={() => copy(sharePost, "Post copied — go drop it 🔥")}><Ico.copy /> Copy post</button>
            <button className="btn btn-outline btn-md" onClick={() => copy(refUrl, "Link copied!")}><Ico.share /></button>
          </div>
        </div>
      ) : refMode === "text" ? (
        <div className="card" style={{ padding: 16 }}>
          <p style={{ fontSize: 13, color: "var(--text-2)", marginBottom: 12 }}>Opens your phone’s <b style={{ color: "var(--text)" }}>Messages app</b> with the note pre-written — just pick a contact and hit send. <b style={{ color: "var(--accent)" }}>You both get a free future report.</b></p>
          <div style={{ display: "flex", gap: 8 }}>
            <a className="btn btn-accent btn-md" href={smsHref} style={{ flex: 1, textDecoration: "none", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8 }}><Ico.mail /> Open Messages</a>
            <button className="btn btn-outline btn-md" onClick={() => copy(smsBody, "Message copied!")}><Ico.copy /></button>
          </div>
          <p className="mono" style={{ fontSize: 10.5, color: "var(--text-3)", marginTop: 10 }}>On a computer? Tap copy and paste it into your messages.</p>
        </div>
      ) : (
        <div className="card" style={{ padding: 16 }}>
          <p style={{ fontSize: 13, color: "var(--text-2)", marginBottom: 12 }}>Enter a friend's email — we'll send them an invite. <b style={{ color: "var(--accent)" }}>You both get a free future report.</b></p>
          {sent ? (
            <div style={{ display: "flex", gap: 8, alignItems: "center", color: "var(--accent)" }}><Ico.check /> <span style={{ fontWeight: 700, fontSize: 14 }}>{refMsg}</span></div>
          ) : (
            <div style={{ display: "flex", gap: 8 }}>
              <input className="input" type="email" placeholder="friend@email.com" value={friendEmail} onChange={(e) => setFriendEmail(e.target.value)} style={{ flex: 1 }} />
              <button className="btn btn-accent btn-md" disabled={!/.+@.+\..+/.test(friendEmail)} onClick={emailFriend}><Ico.mail /></button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* Quick Check ($9.99) — both schools, screen-only: accreditation + hidden fees + loan projection */
function QuickCheckResult({ report, onUpgrade, toast }) {
  const [myEmail, setMyEmail] = useState("");
  const [emailSaved, setEmailSaved] = useState(false);
  const schools = (report.schools || []).filter((s) => s.name);
  return (
    <div className="screen">
      <div className="pad-lg grow stack" style={{ gap: 16 }}>
        <div className="fade-up" style={{ textAlign: "center", marginTop: 8 }}>
          <div style={{ width: 60, height: 60, margin: "0 auto 14px", borderRadius: 16, background: "var(--accent)", color: "var(--accent-ink)", display: "grid", placeItems: "center", boxShadow: "0 0 40px rgba(204,255,0,0.4)" }}>
            <Ico.bolt style={{ width: 26, height: 26 }} />
          </div>
          <h2 className="title">Quick Check ⚡</h2>
          <p className="lede" style={{ marginTop: 8 }}>The fast read on both schools — on screen, no PDF.</p>
        </div>

        {/* per-school: accreditation + hidden fees */}
        {schools.map((s, i) => (
          <div className="card fade-up d1" key={i}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 12 }}>
              <span style={{ width: 24, height: 24, flex: "0 0 24px", borderRadius: 7, background: i === 0 ? "var(--accent)" : "#7CC6FF", color: "var(--accent-ink)", display: "grid", placeItems: "center", fontWeight: 900, fontSize: 12 }}>{["A", "B"][i]}</span>
              <div>
                <div style={{ fontWeight: 800, fontSize: 15, letterSpacing: "-0.02em", lineHeight: 1.1 }}>{s.name}</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--text-3)", marginTop: 2 }}>{s.program}</div>
              </div>
            </div>

            <div className="eyebrow" style={{ marginBottom: 8 }}><Ico.shield /> Accreditation</div>
            <AccredLine info={s.accreditation && s.accreditation.institutional} />
            <AccredLine info={s.accreditation && s.accreditation.programmatic} />

            <div className="eyebrow" style={{ margin: "14px 0 8px" }}><Ico.flag /> Hidden fee audit</div>
            {(s.hiddenFees || []).map((f, k) => (
              <div className="metric-row" key={k}>
                <span className="k">{f.name}</span>
                <span className="v" style={{ fontSize: 14 }}>{f.included ? "Included" : fmt(f.amount) + (f.period === "year" ? "/yr" : "")}</span>
              </div>
            ))}
            <div className="metric-row"><span className="k">Est. separate fees</span><span className="v accent">{fmt(s.annualHiddenFees)}/yr</span></div>
            {!s.feesDisclosed && (
              <div className="callout warn" style={{ marginTop: 12 }}>
                <div className="callout-h"><Ico.flag /> Fees not fully disclosed</div>
                <p>Request a complete itemized fee schedule in writing before enrolling.</p>
              </div>
            )}
          </div>
        ))}

        {/* 10-year loan projection comparison */}
        <div className="card card-2 fade-up d2">
          <div className="eyebrow" style={{ marginBottom: 12 }}><Ico.bolt /> 10-year loan projection</div>
          <div style={{ display: "grid", gridTemplateColumns: `repeat(${schools.length}, 1fr)`, gap: 12 }}>
            {schools.map((s, i) => (
              <div key={i} style={{ padding: 12, border: "1px solid var(--line-2)", borderRadius: "var(--r-md)", background: "var(--surface)" }}>
                <div className="mono" style={{ fontSize: 10.5, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>{["A", "B"][i]} · {s.name.split(" ").slice(0, 2).join(" ")}</div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)" }}>Est. monthly</div>
                <div style={{ fontWeight: 900, fontSize: 19, letterSpacing: "-0.02em" }}>{fmt(s.monthlyPayment)}<span style={{ fontSize: 12, color: "var(--text-3)", fontWeight: 600 }}>/mo</span></div>
                <div style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 8 }}>10-yr total repaid</div>
                <div style={{ fontWeight: 800, fontSize: 15, color: "var(--accent)" }}>{fmt(s.tenYearLoanBurden)}</div>
              </div>
            ))}
          </div>
        </div>

        {/* upsell */}
        <div className="card fade-up d2" style={{ borderColor: "var(--accent)", background: "var(--accent-soft)", marginTop: 4 }}>
          <div style={{ fontWeight: 900, fontSize: 19, letterSpacing: "-0.02em" }}>Take it off the screen.</div>
          <p style={{ fontSize: 13.5, color: "var(--text-2)", margin: "8px 0 16px", lineHeight: 1.5 }}>
            Quick Check is screen-only. Unlock the <b style={{ color: "var(--accent)" }}>full report + downloadable PDF</b> — curriculum, career pathways, licensing checks, the right questions to ask, plus a shareable link for parents and counselors.
          </p>
          <Btn kind="accent" size="lg" arrow onClick={onUpgrade}>Unlock the full report + PDF</Btn>
        </div>

        {/* share + referral — available on every paid tier */}
        <ShareReferral report={report} schools={schools} tier="quick" toast={toast} />

        {/* email capture */}
        <EmailCapture
          title="Want this saved + tips as you decide?"
          sub="We'll email your Quick Check + a short decision guide. No spam."
          report={report}
          schools={report.schools}
          tier="quick"
          sendReport
          leadExtra={{ source_step: "quickcheck", home_state: report.state, sai_estimate: report.sai, schools: (report.schools || []).filter((s) => s.name).map((s) => ({ name: s.name, program: s.program })) }}
        />

        <div className="fade-up d3" style={{ textAlign: "center", marginTop: 4 }}>
          {report.dataSource && <div className="data-source-note mono" style={{ marginBottom: 8 }}>{report.dataSource}</div>}
          <div className="mono" style={{ fontSize: 10.5, color: "var(--text-3)" }}>© 2026 B4IOU — All rights reserved.</div>
        </div>
      </div>
    </div>
  );
}

function FullPostPayment({ report, schools, tier, onDownload, toast }) {
  const link = useMemo(() => `b4iou.com/r/${Math.random().toString(36).slice(2, 8)}`, []);
  const refUrl = "https://" + link;

  function copy(text, label) {
    navigator.clipboard?.writeText(text);
    toast(label || "Copied!");
  }

  return (
    <div className="screen">
      <div className="pad-lg grow stack" style={{ gap: 18 }}>
        <div className="fade-up" style={{ textAlign: "center", marginTop: 8 }}>
          <div style={{ width: 64, height: 64, margin: "0 auto 16px", borderRadius: 18, background: "var(--accent)", color: "var(--accent-ink)", display: "grid", placeItems: "center", boxShadow: "0 0 40px rgba(204,255,0,0.4)" }}>
            <Ico.check style={{ width: 30, height: 30 }} />
          </div>
          <h2 className="title">You're armed. 🔥</h2>
          <p className="lede" style={{ marginTop: 8 }}>Your full B4IOU report is ready. Open it below to save or print as a PDF.</p>
        </div>

        {/* PDF download */}
        <div className="card fade-up d1" style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <span style={{ width: 44, height: 44, flex: "0 0 44px", borderRadius: 12, background: "var(--accent-soft)", color: "var(--accent)", display: "grid", placeItems: "center" }}><Ico.doc /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 800, fontSize: 14.5 }}>B4IOU_Report.pdf</div>
            <div className="mono" style={{ fontSize: 11, color: "var(--text-3)" }}>{schools.filter(s=>s.name).length} schools · full analysis</div>
          </div>
          <button className="btn btn-accent btn-sm" onClick={onDownload}><Ico.download /> Open</button>
        </div>

        {/* shareable link */}
        <div className="card card-2 fade-up d1">
          <div className="eyebrow dim" style={{ marginBottom: 8 }}><Ico.share /> Your shareable link</div>
          <p style={{ fontSize: 12.5, color: "var(--text-2)", lineHeight: 1.5, marginBottom: 12 }}>
            Send this to a parent, partner, or counselor. They open a <b style={{ color: "var(--text)" }}>read-only view</b> of this comparison — cost after aid, out-of-pocket, and accreditation — no login, nothing to pay. The full PDF and deep sections stay yours.
          </p>
          <div style={{ display: "flex", gap: 8 }}>
            <div className="input" style={{ flex: 1, display: "flex", alignItems: "center", fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--accent)", overflow: "hidden" }}>{link}</div>
            <button className="btn btn-ghost btn-md" onClick={() => copy(refUrl, "Link copied!")}><Ico.copy /></button>
          </div>
        </div>

        {/* share + referral — shared component, same as Quick Check */}
        <ShareReferral report={report} schools={schools} tier={tier} toast={toast} refUrl={refUrl} />

        {/* email capture */}
        <EmailCapture
          title="Want this report saved + tips as you decide?"
          sub="We'll email your report + a short decision guide. No spam."
          report={report}
          schools={schools}
          tier={tier}
          sendReport
          leadExtra={{ source_step: "post-full", home_state: report.state, sai_estimate: report.sai, tier, schools: (schools || []).filter((s) => s.name).map((s) => ({ name: s.name, program: s.program })) }}
        />

        <div className="fade-up d3" style={{ textAlign: "center", marginTop: 6 }}>
          {report.dataSource && <div className="data-source-note mono" style={{ marginBottom: 8 }}>{report.dataSource}</div>}
          <div className="mono" style={{ fontSize: 10.5, color: "var(--text-3)" }}>Generated by B4IOU · b4iou.com · Share this with someone who needs it</div>
          <div className="mono" style={{ fontSize: 10.5, color: "var(--text-3)", marginTop: 6 }}>© 2026 B4IOU — All rights reserved.</div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Paywall, PostPayment, TIERS });
