/* ============================================================
   B4IOU — PDF report generation
   Full comprehensive, compliance-corrected report (v2).
   Sections (after cost): Hidden Fee Audit · Corporate Tuition
   Partnerships · Technology + Laptop Access · Accreditation ·
   Credit Transfer · Curriculum · Program Delivery ·
   Professional Affiliations · Career Pathways · State Licensing ·
   Red Flags · Admissions Questions · Financial Aid Questions ·
   Student Consumer Information · Global Disclaimer.
   ============================================================ */

function money(n) {
  if (n == null || isNaN(n)) return "Not reported by institution";
  return "$" + Math.round(n).toLocaleString("en-US");
}
function esc(s) {
  return String(s == null ? "" : s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
}

function buildReportHTML(report, schools, tier) {
  const real = report.schools.filter((s) => s.name);
  const cols = real.map((s) => `<th>${esc(s.name)}<span>${esc(s.program)}</span></th>`).join("");
  const row = (label, fn, cls = "") =>
    `<tr><td class="lbl">${label}</td>${real.map((s) => `<td class="${cls}">${fn(s)}</td>`).join("")}</tr>`;
  const gridClass = real.length === 1 ? "one" : real.length >= 3 ? "three" : "";

  /* ---- Hidden Fee Audit ---- */
  const hiddenFeeBlocks = real.map((s) => {
    const rows = (s.hiddenFees || []).map((f) =>
      `<tr><td class="fee-n">${esc(f.name)}</td><td class="fee-a">${money(f.amount)}${f.period === "year" ? "/yr" : " one-time"}</td><td class="fee-i">${f.included ? "Included" : "Separate"}</td></tr>`
    ).join("");
    return `<div class="scard">
      <h4>${esc(s.name)}</h4>
      <table class="mini"><tr><th>Fee</th><th>Amount</th><th>Status</th></tr>${rows}</table>
      <div class="feetotal">Est. separate fees: <b>${money(s.annualHiddenFees)}/yr</b></div>
      ${s.feesDisclosed ? "" : `<div class="warnline">\u26A0\uFE0F Fee structure not fully publicly disclosed — request a complete itemized fee schedule in writing before enrolling.</div>`}
    </div>`;
  }).join("");

  /* ---- Corporate Tuition Partnerships ---- */
  const partnerBlocks = real.map((s) => {
    const ps = s.corporatePartnerships || [];
    const body = ps.length
      ? `<ul class="plain">${ps.map((p) => `<li><b>${esc(p.partner)}</b> — ${esc(p.benefit)}${p.eligibility ? ` <span class="dim">(${esc(p.eligibility)})</span>` : ""}</li>`).join("")}</ul>`
      : `<p class="body sm">${esc(report.corpPartnershipNone)}</p>`;
    return `<div class="scard"><h4>${esc(s.name)}</h4>${body}</div>`;
  }).join("");

  /* ---- Technology Requirements & Laptop Access ---- */
  const techBlocks = real.map((s) => {
    const t = s.techRequirements || {};
    return `<div class="scard"><h4>${esc(s.name)}</h4>
      <div class="kv"><span>Laptop / tech required</span><b>${t.laptopRequired ? "Yes" : "Recommended"}</b></div>
      <div class="kv"><span>Provided by institution</span><b>${t.providedByInstitution ? "Yes" : "No"}</b></div>
      <div class="kv"><span>Technology fee</span><b>${esc(t.techFee || "—")}</b></div>
      <div class="kv"><span>Min. specs</span><b>${esc(t.minSpecs || "—")}</b></div>
      <div class="kv"><span>Loaner / rental</span><b>${esc(t.loanerProgram || "—")}</b></div>
    </div>`;
  }).join("");
  const laptopRes = (report.laptopResources || []).map((r) =>
    `<li class="${r.warn ? "res-warn" : ""}"><b>${esc(r.name)}</b> — ${esc(r.detail)}</li>`
  ).join("");

  /* ---- Accreditation ---- */
  const accBlock = (info) => {
    if (!info) return "";
    const tag = info.status === "not-required" ? "Not required" : "VERIFY \u2014 not confirmed by B4IOU";
    const link = info.lookupUrl ? `<p class="sm"><a href="${esc(info.lookupUrl)}">${esc(info.lookupLabel)} \u2192</a></p>` : "";
    return `<div class="k">${esc(info.label)}${info.accreditor ? " \u00b7 " + esc(info.accreditor) : ""} <span style="color:#8a5a00;font-weight:700">[${tag}]</span></div><p class="sm">${esc(info.guidance)}</p>${link}`;
  };
  const accBlocks = real.map((s) => {
    const a = s.accreditation || {};
    return `<div class="scard"><h4>${esc(s.name)}</h4>${accBlock(a.institutional)}${accBlock(a.programmatic)}</div>`;
  }).join("");

  /* ---- Admissions Criteria (Correction 11) ---- */
  const admissionsBlocks = real.map((s) => {
    const a = s.admissionsCriteria || {};
    const ps = a.programSpecific || { listed: false };
    const psBody = ps.listed
      ? `<table class="mini"><tr><th>Program requirement</th><th>Status</th></tr>${(ps.items || []).map((it) => `<tr><td>${esc(it.k)}</td><td style="text-align:right">${esc(it.v)}</td></tr>`).join("")}</table>`
      : `<p class="body sm">${esc(ps.note || "")}</p>`;
    return `<div class="scard"><h4>${esc(s.name)} — ${esc(s.program)}</h4>
      <div class="kv"><span>Acceptance rate</span><b>${esc(a.acceptanceRate)}</b></div>
      <div class="kv"><span>Test scores</span><b>${esc(a.testScores)}</b></div>
      <div class="kv"><span>Min GPA</span><b>${esc(a.minGPA)}</b></div>
      <div class="kv"><span>Enrollment</span><b>${esc(a.enrollment)}</b></div>
      <div class="kv"><span>Application deadline</span><b>${esc(a.deadlineType)}</b></div>
      <div class="k" style="margin-top:9px">Program-specific requirements</div>
      ${psBody}
    </div>`;
  }).join("");
  const bgWarning = report.anyBackgroundWarning
    ? `<div class="warnbox"><p>${esc(report.backgroundCheckNotice)}</p></div>`
    : "";

  /* ---- Program Delivery & Structure ---- */
  const deliveryBlocks = real.map((s) => {
    const d = s.delivery || {};
    return `<div class="scard"><h4>${esc(s.name)}</h4>
      <div class="kv"><span>Format</span><b>${esc(d.format)}</b></div>
      <div class="kv"><span>Modality</span><b>${esc(d.modality)}</b></div>
      <div class="kv"><span>Term type</span><b>${esc(d.termType)}</b></div>
      <div class="kv"><span>Course length</span><b>${esc(d.courseLength)}</b></div>
      <div class="kv"><span>Courses / term</span><b>${esc(d.coursesPerTerm)}</b></div>
      <div class="kv"><span>Credit hours</span><b>${esc(String(d.creditHours))}</b></div>
      <div class="kv"><span>Time to finish</span><b>${esc(d.timeFullTime)} FT · ${esc(d.timePartTime)} PT</b></div>
    </div>`;
  }).join("");

  /* ---- Professional Affiliations ---- */
  const affBlocks = real.map((s) => {
    const a = s.affiliations || [];
    const body = a.length
      ? `<ul class="plain">${a.map((x) => `<li><b>${esc(x.name)}</b> <span class="dim">(${esc(x.type)})</span>${x.eligibility ? ` — ${esc(x.eligibility)}` : ""}</li>`).join("")}</ul>`
      : `<p class="body sm">No professional affiliations publicly listed for this program. Ask your admissions representative what student organizations are available to students in this program.</p>`;
    return `<div class="scard"><h4>${esc(s.name)}</h4>${body}</div>`;
  }).join("");

  /* ---- Career Pathways ---- */
  const pathBlocks = real.map((s) => {
    const cp = s.careerPathways || { institutional: [], bls: [] };
    const inst = (cp.institutional || []).map((p) => `<li>${esc(p)}</li>`).join("");
    const bls = (cp.bls || []).map((b) =>
      `<tr><td>${esc(b.occ)}</td><td class="fig">${money(b.wage)}</td><td class="fig">${esc(b.growth)}</td></tr>`
    ).join("");
    return `<div class="scard"><h4>${esc(s.name)} — ${esc(s.program)}</h4>
      <div class="k">Institutional program page</div><ul class="plain tight">${inst}</ul>
      <div class="k" style="margin-top:8px">U.S. Bureau of Labor Statistics — related occupations</div>
      <table class="mini"><tr><th>Occupation</th><th>Median wage</th><th>10-yr growth</th></tr>${bls}</table>
    </div>`;
  }).join("");

  /* ---- State Licensing Board (conditional) ---- */
  let licensingSection = "";
  if (report.licensureRelevant) {
    const licBlocks = real.filter((s) => s.licensingBoard && s.licensingBoard.applies).map((s) =>
      `<div class="warnbox"><b>${esc(s.name)} — ${esc(s.program)}</b><p>${esc(s.licensingBoard.note)}</p></div>`
    ).join("");
    if (licBlocks) {
      licensingSection = `<h2 class="sec">State Licensing Board Approval</h2>${licBlocks}`;
    }
  }

  /* ---- Red Flags ---- */
  const flagsBlocks = real.map((s) => `
    <div class="flagcard"><h4>${esc(s.name)}</h4>
      ${(s.redFlags && s.redFlags.length)
        ? `<ul>${s.redFlags.map((f) => `<li>${esc(f)}</li>`).join("")}</ul>`
        : `<p class="ok">No major red flags detected for this program.</p>`}
    </div>`).join("");

  /* ---- Questions ---- */
  const admissionsQs = (report.questionsToAsk || []).map((q, i) =>
    `<li><span>${String(i + 1).padStart(2, "0")}</span>${esc(q)}</li>`).join("");
  const aidQs = (report.financialAidQuestions || []).map((q, i) =>
    `<li><span>${String(i + 1).padStart(2, "0")}</span>${esc(q)}</li>`).join("");

  /* ---- Consumer Info links ---- */
  const consumerLinks = real.map((s) => {
    const ci = s.consumerInfo || {};
    return `<div class="cilink"><b>${esc(s.name)}</b><br/>
      <a href="${esc(ci.scorecard)}">College Scorecard data \u2192</a>
      <span class="dim sm">${esc(ci.note)}</span></div>`;
  }).join("");

  return `<!DOCTYPE html><html><head><meta charset="utf-8"/>
<link href="https://fonts.googleapis.com/css2?family=Archivo:wght@400;500;600;700;800;900&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet"/>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: 'Archivo', sans-serif; color: #0E1110; background: #fff; }
  .page { max-width: 780px; margin: 0 auto; padding: 40px 44px 56px; }
  .acc { color: #4a6b00; }
  .hdr { display: flex; align-items: center; justify-content: space-between; border-bottom: 3px solid #0E1110; padding-bottom: 16px; }
  .hdr .logo { display: flex; align-items: center; gap: 10px; font-weight: 900; font-size: 22px; letter-spacing: -0.03em; }
  .hdr .mark { width: 30px; height: 30px; border-radius: 8px; background: #CCFF00; color: #0a0e00; display: grid; place-items: center; font-weight: 900; font-size: 14px; }
  .hdr .tag { font-family: 'Space Mono', monospace; font-size: 11px; color: #5b635e; text-transform: uppercase; letter-spacing: 0.08em; }
  h1.big { font-size: 32px; font-weight: 900; letter-spacing: -0.04em; margin: 22px 0 4px; }
  h2.sec { font-size: 12.5px; font-family: 'Space Mono', monospace; letter-spacing: 0.1em; text-transform: uppercase; color: #4a6b00; margin: 32px 0 12px; padding-bottom: 6px; border-bottom: 1px solid #d8ddd2; }
  .lede { color:#414a45; font-size: 14px; line-height: 1.5; }
  p.body { font-size: 13px; line-height: 1.6; color: #2c322e; margin-top: 6px; }
  p.body.sm, .sm { font-size: 12px; line-height: 1.5; }
  .dim { color: #6b736d; }
  table { width: 100%; border-collapse: collapse; margin-top: 6px; }
  th, td { text-align: right; padding: 10px 12px; font-size: 13.5px; border-bottom: 1px solid #e4e8df; }
  th { font-weight: 900; font-size: 14px; letter-spacing: -0.02em; vertical-align: bottom; }
  th span { display: block; font-family: 'Space Mono', monospace; font-weight: 400; font-size: 10px; color: #6b736d; margin-top: 3px; }
  th:first-child, td.lbl { text-align: left; }
  td.lbl { font-family: 'Space Mono', monospace; font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.04em; color: #6b736d; }
  td.fig { font-family: 'Space Mono', monospace; font-weight: 700; }
  td.hl { font-family: 'Space Mono', monospace; font-weight: 700; background: #f6ffd6; color: #3a5500; }
  .winner-note { background: #CCFF00; color: #0a0e00; padding: 14px 18px; border-radius: 10px; font-weight: 700; font-size: 14.5px; margin-top: 14px; line-height: 1.45; }
  /* school card grids */
  .cardgrid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 10px; }
  .cardgrid.one { grid-template-columns: 1fr; }
  .cardgrid.three { grid-template-columns: 1fr 1fr 1fr; }
  .scard { border: 1px solid #d8ddd2; border-radius: 10px; padding: 13px; }
  .scard h4 { font-size: 13.5px; margin-bottom: 9px; letter-spacing: -0.01em; }
  .scard .k { font-family:'Space Mono',monospace; font-size: 9.5px; text-transform: uppercase; letter-spacing: 0.06em; color: #6b736d; margin-bottom: 2px; }
  .scard p.sm { margin-bottom: 8px; }
  .kv { display: flex; justify-content: space-between; gap: 10px; font-size: 12px; padding: 5px 0; border-bottom: 1px solid #eef0ea; }
  .kv span { color: #6b736d; }
  .kv b { text-align: right; font-weight: 700; }
  table.mini th, table.mini td { padding: 6px 7px; font-size: 11.5px; text-align: left; }
  table.mini th { font-family:'Space Mono',monospace; font-size: 9.5px; text-transform: uppercase; color: #6b736d; font-weight: 700; }
  table.mini td.fig { text-align: right; }
  .fee-a { text-align: right; font-family:'Space Mono',monospace; font-weight: 700; }
  .fee-i { text-align: right; color: #6b736d; font-size: 11px; }
  .feetotal { font-size: 12px; margin-top: 8px; }
  .feetotal b { font-family:'Space Mono',monospace; color: #3a5500; }
  .warnline { font-size: 11.5px; line-height: 1.45; color: #8a5a00; background: #fff6e0; border-radius: 7px; padding: 8px 10px; margin-top: 8px; }
  .warnbox { border-left: 3px solid #d99100; background: #fff8e8; padding: 10px 14px; border-radius: 7px; margin: 10px 0; }
  .warnbox b { font-size: 13px; } .warnbox p { font-size: 12px; line-height: 1.5; color: #4a3c1a; margin-top: 4px; }
  .infobox { border-left: 3px solid #4a6b00; background: #f4ffd6; padding: 10px 14px; border-radius: 7px; margin: 10px 0; font-size: 12.5px; line-height: 1.5; color: #2c3a00; }
  ul.plain { margin-left: 16px; margin-top: 4px; } ul.plain li { font-size: 12px; line-height: 1.55; margin: 3px 0; color: #2c322e; }
  ul.plain.tight li { margin: 1px 0; }
  ul.res { margin-left: 16px; margin-top: 6px; } ul.res li { font-size: 12px; line-height: 1.5; margin: 5px 0; color: #2c322e; }
  ul.res li.res-warn { color: #8a5a00; }
  .accexplain { border: 1px solid #d8ddd2; border-radius: 10px; padding: 14px 16px; font-size: 12.5px; line-height: 1.6; color: #2c322e; }
  .flagcard { border-left: 3px solid #FF5A47; padding: 4px 0 4px 14px; margin: 12px 0; }
  .flagcard h4 { font-size: 13.5px; margin-bottom: 4px; } .flagcard ul { margin-left: 16px; }
  .flagcard li { font-size: 12.5px; line-height: 1.5; color: #2c322e; margin: 3px 0; }
  .flagcard .ok { font-size: 12.5px; color: #3a7d52; }
  ol.qs { list-style: none; margin-top: 8px; } 
  ol.qs li { display: flex; gap: 12px; font-size: 13px; line-height: 1.5; padding: 9px 0; border-bottom: 1px solid #eceee7; color:#20262a; }
  ol.qs li span { font-family: 'Space Mono', monospace; color: #4a6b00; font-weight: 700; flex: 0 0 auto; }
  .aidhead { background: #1a1d12; color: #CCFF00; border-radius: 10px 10px 0 0; padding: 13px 16px; font-weight: 800; font-size: 14px; }
  .aidbody { border: 1px solid #d8ddd2; border-top: none; border-radius: 0 0 10px 10px; padding: 4px 16px 12px; }
  .aidintro { font-size: 12px; color: #6b736d; padding: 12px 0 2px; line-height: 1.5; }
  .cilink { padding: 9px 0; border-bottom: 1px solid #eceee7; font-size: 12.5px; }
  .cilink a { color: #2a5d00; font-weight: 700; text-decoration: none; }
  .cilink .dim { display: block; margin-top: 3px; }
  .disclaimer { font-size: 10px; line-height: 1.5; color: #6b736d; margin-top: 14px; }
  .foot { margin-top: 26px; padding-top: 14px; border-top: 3px solid #0E1110; font-family: 'Space Mono', monospace; font-size: 11px; color: #5b635e; text-align: center; }
  @media print {
    .page { padding: 22px 26px; }
    body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
    h2.sec { page-break-after: avoid; }
    table, .flagcard, .scard, .warnbox, .infobox, .accexplain, .aidhead { page-break-inside: avoid; }
    .aidhead { page-break-after: avoid; }
    .savebar { display: none !important; }
  }
  .savebar {
    position: fixed; top: 14px; right: 14px; z-index: 99;
    display: inline-flex; align-items: center; gap: 8px;
    background: #CCFF00; color: #0a0e00; border: 0; cursor: pointer;
    font-family: 'Archivo', sans-serif; font-weight: 800; font-size: 14px;
    padding: 11px 18px; border-radius: 999px;
    box-shadow: 0 8px 28px rgba(0,0,0,0.22);
  }
  .savebar:active { transform: translateY(1px); }
  @media (max-width: 520px) { .savebar { top: auto; bottom: 16px; right: 50%; transform: translateX(50%); } .savebar:active { transform: translateX(50%) translateY(1px); } }
</style></head>
<body><div class="page">

  <button class="savebar" onclick="window.print()">&#x2913; Save as PDF</button>

  <div class="hdr">
    <div class="logo"><span class="mark">B4</span> B4<span class="acc">IOU</span></div>
    <div class="tag">Know before you owe.</div>
  </div>

  <h1 class="big">Your Comparison</h1>
  <p class="lede">${esc(real.map((s) => s.name).join("  vs  "))}</p>

  <div class="warnbox" style="margin-top:14px"><b>\u24D8 Cost figures are official; out-of-pocket is an estimate.</b><p>Tuition, net price, median debt, completion and earnings come directly from the U.S. Dept. of Education College Scorecard. Out-of-pocket combines that tuition with your own estimated federal aid. Any field marked “Not reported by institution” was not reported to the Dept. of Education — it is never estimated. B4IOU has not confirmed each school offers the exact program entered, nor its programmatic accreditation — verify via the official links below.</p></div>

  <h2 class="sec">Cost Breakdown <span style="color:#6b736d;font-weight:400;font-family:Archivo">(U.S. Dept. of Education College Scorecard)</span></h2>
  <table>
    <tr><th>Metric</th>${cols}</tr>
    ${row("Annual tuition", (s) => money(s.annualTuition), "fig")}
    ${row("Annual fees", (s) => s.dataSource === "scorecard" ? "Not reported separately" : money(s.fees), "fig")}
    ${row("Total program (4 yr)", (s) => money(s.totalTuition), "fig")}
  </table>

  <h2 class="sec">What You'll Actually Pay <span style="color:#6b736d;font-weight:400;font-family:Archivo">(after estimated aid)</span></h2>
  <table>
    ${row("Estimated aid / yr", (s) => "\u2212" + money(s.estimatedAid), "fig")}
    ${row("Out of pocket / yr", (s) => money(s.annualOutOfPocket), "hl")}
    ${row("Out of pocket (4 yr)", (s) => money(s.totalOutOfPocket), "fig")}
  </table>
  <div class="winner-note">\u2605 Lowest cost: ${esc(winner_(report))} \u2014 ${esc(report.recommendation)}</div>

  <h2 class="sec">Hidden Fee Audit</h2>
  <div class="cardgrid ${gridClass}">${hiddenFeeBlocks}</div>

  <h2 class="sec">What You'll Owe — 10-Year Loan Projection</h2>
  <table>
    ${row("Est. monthly payment", (s) => money(s.monthlyPayment) + "/mo", "fig")}
    ${row("10-yr total repaid", (s) => money(s.tenYearLoanBurden), "hl")}
    ${row("Interest paid", (s) => money(Math.max(0, s.tenYearLoanBurden - s.totalOutOfPocket)), "fig")}
  </table>

  <h2 class="sec">Corporate Tuition Partnerships</h2>
  <div class="infobox">\uD83D\uDCA1 ${esc(report.corpPartnershipNote)}</div>
  <div class="cardgrid ${gridClass}">${partnerBlocks}</div>

  <h2 class="sec">Technology Requirements & Laptop Access</h2>
  <div class="cardgrid ${gridClass}">${techBlocks}</div>
  <div class="scard" style="margin-top:12px">
    <h4>Laptop Access Resources</h4>
    <ul class="res">${laptopRes}</ul>
    <div class="warnline">\u26A0\uFE0F ${esc(report.rentToOwnWarning)}</div>
  </div>

  <h2 class="sec">Accreditation — In Plain English</h2>
  <div class="accexplain">${esc(report.accreditationExplainer)}</div>
  <div class="cardgrid ${gridClass}" style="margin-top:12px">${accBlocks}</div>

  <h2 class="sec">Credit Transfer</h2>
  <div class="warnbox"><b>\u26A0\uFE0F Credit transfer is never guaranteed</b><p>${esc(report.creditTransferStatement)}</p></div>

  <h2 class="sec">Curriculum Overlap — Are These Degrees Actually The Same?</h2>
  <p class="body">${esc(report.curriculumOverlap || "")}</p>
  ${real.map((s) => `<p class="body sm"><b>${esc(s.name)}:</b> ${esc(s.curriculum || "")}</p>`).join("")}

  <h2 class="sec">Program Delivery & Structure</h2>
  <div class="cardgrid ${gridClass}">${deliveryBlocks}</div>

  <h2 class="sec">Admissions Criteria</h2>
  <div class="cardgrid ${gridClass}">${admissionsBlocks}</div>
  ${bgWarning}

  <h2 class="sec">Professional Affiliations & Organizations</h2>
  <div class="cardgrid ${gridClass}">${affBlocks}</div>

  <h2 class="sec">Career Pathways</h2>
  <div class="cardgrid ${gridClass}">${pathBlocks}</div>
  <p class="disclaimer">${esc(report.careerPathwayNote)}</p>

  ${licensingSection}

  <h2 class="sec">Red Flags</h2>
  ${flagsBlocks}

  <h2 class="sec">Questions To Ask Your Admissions Rep</h2>
  <ol class="qs">${admissionsQs}</ol>

  <h2 class="sec">\u26A0\uFE0F Questions For The Financial Aid Office — Not Your Admissions Rep</h2>
  <div class="aidhead">Contact the Financial Aid office directly</div>
  <div class="aidbody">
    <div class="aidintro">${esc(report.financialAidIntro)}</div>
    <ol class="qs">${aidQs}</ol>
  </div>

  <h2 class="sec">\uD83D\uDCCB Find It Yourself — Student Consumer Information</h2>
  <p class="body sm">${esc(report.consumerInfoIntro)}</p>
  ${consumerLinks}
  <div class="warnline" style="margin-top:10px">\u26A0\uFE0F ${esc(report.consumerInfoWarning)}</div>

  <p class="disclaimer">${esc(report.globalDisclaimer)}</p>
  ${report.dataSource ? `<p class="disclaimer">${esc(report.dataSource)}</p>` : ""}
  <div class="foot">Generated by B4IOU &nbsp;|&nbsp; b4iou.com &nbsp;|&nbsp; Know before you owe.</div>

</div></body></html>`;
}

function winner_(report) { return report.winnerName || (report.schools[0] && report.schools[0].name) || ""; }

/* ============================================================
   Report delivery — reliable in-app preview + save.
   The old hidden-iframe print() silently failed in sandboxed /
   mobile webviews (nothing appeared to happen). Instead we
   render the full report into an on-screen overlay the user can
   read immediately, then Save-as-PDF / open / download from there.
   ============================================================ */

/* Builds the report HTML and opens it for the user.
   Primary path: open the full report in its OWN browser tab — far better on
   mobile than a cramped in-app iframe, and the native browser print/share
   (Save as PDF) works reliably there. If the popup is blocked, fall back to
   the in-app overlay so the user still sees something. */
function openReport(report, schools, tier) {
  const html = buildReportHTML(report, schools, tier);
  let w = null;
  try { w = window.open("", "_blank"); } catch (e) { w = null; }
  if (w && w.document) {
    w.document.open();
    w.document.write(html);
    w.document.close();
    w.document.title = "B4IOU Report";
    return;
  }
  // popup blocked → in-app overlay fallback
  window.dispatchEvent(new CustomEvent("b4iou:preview", { detail: { html } }));
}
/* kept as an alias so existing call sites keep working */
function downloadPDF(report, schools, tier) { openReport(report, schools, tier); }

/* The full-screen report preview overlay (rendered by App). */
function ReportPreview({ html, onClose, toast }) {
  const frameRef = useRef(null);

  useEffect(() => {
    function onKey(e) { if (e.key === "Escape") onClose(); }
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [onClose]);

  function saveAsPdf() {
    const f = frameRef.current;
    try {
      f.contentWindow.focus();
      f.contentWindow.print();
    } catch (e) {
      openInTab();
    }
  }
  function openInTab() {
    const blob = new Blob([html], { type: "text/html" });
    const url = URL.createObjectURL(blob);
    const w = window.open(url, "_blank");
    if (!w) { downloadFile(); return; }
    toast && toast("Opened in a new tab — use your browser to Save as PDF");
    setTimeout(() => URL.revokeObjectURL(url), 60000);
  }
  function downloadFile() {
    const blob = new Blob([html], { type: "text/html" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "B4IOU_Report.html";
    document.body.appendChild(a);
    a.click();
    a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 4000);
    toast && toast("Report file downloaded");
  }

  return (
    <div className="preview-overlay" onMouseDown={onClose}>
      <div className="preview-panel" onMouseDown={(e) => e.stopPropagation()}>
        <div className="preview-bar">
          <div className="preview-title">
            <span className="mono">YOUR REPORT</span>
            <b>B4IOU_Report.pdf</b>
          </div>
          <button className="preview-x" onClick={onClose} aria-label="Close"><Ico.x /></button>
        </div>

        <iframe ref={frameRef} className="preview-frame" title="B4IOU report" srcDoc={html} />

        <div className="preview-actions">
          <button className="btn btn-accent btn-lg" style={{ flex: 1 }} onClick={saveAsPdf}>
            <Ico.download /> Save as PDF
          </button>
          <button className="btn btn-outline btn-lg preview-2nd" onClick={openInTab} title="Open in new tab"><Ico.share /></button>
          <button className="btn btn-outline btn-lg preview-2nd" onClick={downloadFile} title="Download file"><Ico.doc /></button>
        </div>
        <div className="preview-hint mono">
          “Save as PDF” opens your browser’s print dialog — pick <b>Save as PDF</b> as the destination. On phones, tap the share icon to open it in a full tab first.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { buildReportHTML, downloadPDF, openReport, ReportPreview });
