/* ============================================================
   B4IOU — Step 4 : Free report (Claude-generated)
   ============================================================ */

const LOADER_TICKS = [
  "Pulling tuition + fee data…",
  "Cross-checking accreditation bodies…",
  "Estimating your federal aid…",
  "Modeling 10-year loan burden…",
  "Hunting for red flags…",
  "Ranking the better financial decision…",
];

/* Route the prompt to the right completion source:
   - production (BACKEND=true): our own /api/report endpoint, which calls the
     Anthropic API server-side with YOUR key (billed to your Anthropic account).
   - preview/demo: the in-preview AI binding, if present.
   Throwing here makes the caller fall back to the deterministic estimator. */
async function completePrompt(prompt) {
  const cfg = window.B4IOU_CONFIG || {};
  if (cfg.BACKEND) {
    const r = await fetch("/api/report", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ prompt }),
    });
    if (!r.ok) throw new Error("report endpoint " + r.status);
    const data = await r.json();
    return data.text || "";
  }
  if (window.claude && window.claude.complete) {
    return await window.claude.complete({ messages: [{ role: "user", content: prompt }] });
  }
  throw new Error("no completion source available");
}

async function generateReport(input) {
  const schoolBlocks = input.schools.map((s, i) => {
    const facts = window.scorecardPromptBlock ? window.scorecardPromptBlock(s.scorecard, input.state) : "(no College Scorecard data)";
    return `  ${["A", "B", "C"][i]}. ${s.name} — ${s.program}\n     OFFICIAL COLLEGE SCORECARD DATA: ${facts}`;
  }).join("\n");
  const aidTxt = input.sai != null
    ? `Student Aid Index (SAI): ${input.sai} (from uploaded document)`
    : `Dependency answers: ${JSON.stringify(input.answers || {})}`;

  const prompt = `You are B4IOU, a blunt, pro-student college-cost analyst. You are given ONLY official U.S. Department of Education College Scorecard data for each school below. Use ONLY those numbers. Do NOT invent, estimate, recall, or fill in ANY school fact from your own training knowledge. If a value reads "Not reported by institution", leave it alone — never guess it. Return ONLY compact minified JSON, no markdown, no prose outside JSON.

Student state: ${input.state || "unknown"}
${aidTxt}
Schools:
${schoolBlocks}

Return this exact shape:
{"winnerName":str,"curriculumOverlap":str,"recommendation":str,"schools":[{"name":str,"program":str,"curriculum":str,"redFlags":[str]}]}

RULES:
- winnerName = the school with the lowest avg_net_price; if net price is not reported, use the lowest reported tuition. It MUST be one of the school names above verbatim.
- recommendation = one blunt sentence naming the better financial decision, justified ONLY by the provided numbers.
- curriculum = a neutral one-line description of typical coursework for that program. No school-specific or quality claims.
- redFlags = max 2 per school, each drawn ONLY from the provided data (e.g. net price far above peers, low completion rate, high median debt). If nothing stands out, return [].
- Keep every string under 24 words.

ACCREDITATION (critical): do NOT output accreditation status of any kind. Do not claim a school offers the entered program.

FORBIDDEN — never output any of these in redFlags or anywhere:
- anything implying credits will transfer or asking about transferability
- asking a school to characterize its own curriculum quality, technology currency, or superiority
- the word "guarantee" in relation to employment, placement, or outcomes
- financial-aid packaging / net-price / aid-renewal questions phrased as questions
Do NOT include any questions list — B4IOU generates those separately.`;

  const raw = await completePrompt(prompt);
  let txt = (raw || "").trim();
  const a = txt.indexOf("{"), b = txt.lastIndexOf("}");
  if (a === -1 || b === -1) throw new Error("no json");
  const data = JSON.parse(txt.slice(a, b + 1));
  if (!data.schools || !data.schools.length) throw new Error("empty");

  // deterministic + Scorecard engine owns ALL numbers and structured sections
  const fb = fallbackReport(input);

  // merge: keep EVERY number/section from the verified engine; take only
  // narrative (curriculum + red flags) from Claude.
  data.schools = data.schools.map((s, i) => {
    const base = fb.schools[i] || {};
    const c = clean(s);
    const flags = Array.isArray(c.redFlags) ? c.redFlags.filter(passesRedFlag).map(deRegion) : base.redFlags;
    return { ...base, curriculum: c.curriculum || base.curriculum, redFlags: flags };
  });

  const merged = { ...fb, ...clean(data), _source: "claude" };
  // hard-lock every number + compliance field to the verified copy
  merged.schools = data.schools;
  // winnerName must be a real school; otherwise trust the cost-ranked fallback
  if (!fb.schools.some((s) => s.name === merged.winnerName)) merged.winnerName = fb.winnerName;
  merged.dataSource = fb.dataSource;
  merged.retrievedAt = fb.retrievedAt;
  merged.accreditationExplainer = fb.accreditationExplainer;
  merged.creditTransferStatement = fb.creditTransferStatement;
  merged.questionsToAsk = fb.questionsToAsk;
  merged.financialAidIntro = fb.financialAidIntro;
  merged.financialAidQuestions = fb.financialAidQuestions;
  merged.corpPartnershipNote = fb.corpPartnershipNote;
  merged.corpPartnershipNone = fb.corpPartnershipNone;
  merged.laptopResources = fb.laptopResources;
  merged.rentToOwnWarning = fb.rentToOwnWarning;
  merged.careerPathwayNote = fb.careerPathwayNote;
  merged.consumerInfoIntro = fb.consumerInfoIntro;
  merged.consumerInfoWarning = fb.consumerInfoWarning;
  merged.globalDisclaimer = fb.globalDisclaimer;
  merged.backgroundCheckNotice = fb.backgroundCheckNotice;
  merged.anyBackgroundWarning = fb.anyBackgroundWarning;
  merged.licensureRelevant = fb.licensureRelevant;
  return merged;
}

/* strip discontinued regional/national accreditation language */
function deRegion(str) {
  return String(str)
    .replace(/\bregionally\s+accredited\b/gi, "institutionally accredited")
    .replace(/\bnationally\s+accredited\b/gi, "institutionally accredited")
    .replace(/\bregional\s+accreditation\b/gi, "institutional accreditation")
    .replace(/\bnational\s+accreditation\b/gi, "institutional accreditation")
    .replace(/\bregionally\b/gi, "institutionally")
    .replace(/\bregional\b/gi, "institutional");
}

/* reject any red flag that violates the forbidden-question rules */
function passesRedFlag(f) {
  return !/transfer|guarantee|graduat\w* rate|default rate|placement rate|salary|pass rate/i.test(String(f));
}

function clean(o) {
  const out = {};
  for (const k in o) if (o[k] !== null && o[k] !== undefined && o[k] !== "") out[k] = o[k];
  return out;
}

/* cost display: a real number renders as money; a null renders the
   honest "Not reported by institution" — never an invented figure. */
function isNum(v) { return typeof v === "number" && !isNaN(v); }
function CostCell({ value, className }) {
  if (isNum(value)) return <span className={"v " + (className || "")}>{fmt(value)}</span>;
  return <span className={"v nr " + (className || "")}>Not reported by institution</span>;
}

function Loader() {
  const [i, setI] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setI((x) => (x + 1) % LOADER_TICKS.length), 1100);
    return () => clearInterval(t);
  }, []);
  return (
    <div className="loader-wrap">
      <div className="spinner" />
      <div>
        <div style={{ fontWeight: 900, fontSize: 26, letterSpacing: "-0.03em" }}>Running your numbers… 🔍</div>
        <div className="loader-tick" style={{ marginTop: 12 }}>{LOADER_TICKS[i]}</div>
      </div>
      <div className="mono" style={{ fontSize: 11, color: "var(--text-3)" }}>Powered by B4IOU AI</div>
    </div>
  );
}

/* ---- the on-screen free report ---- */
function FreeReport({ report, schools, onUpgrade, onBack }) {
  const winnerIdx = report.schools.findIndex((s) => s.name === report.winnerName);

  return (
    <div className="screen">
      <div className="report-head fade-up">
        <span className="eyebrow"><Ico.spark /> Step 3 of 3 · Your free report</span>
        <h2 className="title" style={{ marginTop: 12 }}>Here's the damage.</h2>
        <p className="lede" style={{ marginTop: 8 }}>{report.recommendation}</p>
      </div>

      <div className="pad" style={{ paddingTop: 4 }}>
        <div className="verify-banner fade-up">
          <span className="vb-ic"><Ico.shield /></span>
          <div>
            <div className="vb-h">Official figures + one estimate — still verify program &amp; accreditation</div>
            <p>Tuition and outcome figures come straight from the <b>U.S. Dept. of Education College Scorecard</b>. Out-of-pocket combines that tuition with your <b>own estimated</b> federal aid. Anything marked <b>"Not reported by institution"</b> wasn't reported to the Dept. of Education — never guessed. We haven't confirmed each school offers the exact program you entered or holds the accreditation its field usually requires — use the official links to verify.</p>
          </div>
        </div>
      </div>

      <div className="pad stack" style={{ gap: 14, paddingTop: 12 }}>
        {/* side by side */}
        <div className="cmp-grid">
          {report.schools.map((s, i) => (
            <div className={`school-col fade-up d${Math.min(i + 1, 4)} ${i === winnerIdx ? "winner" : ""}`} key={i}>
              <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 10, marginBottom: 8 }}>
                <div>
                  <div style={{ fontWeight: 800, fontSize: 16, letterSpacing: "-0.02em", lineHeight: 1.1 }}>{s.name}</div>
                  <div className="mono" style={{ fontSize: 11.5, color: "var(--text-3)", marginTop: 3 }}>{s.program}</div>
                </div>
                <span style={{ width: 24, height: 24, flex: "0 0 24px", borderRadius: 7, background: i === winnerIdx ? "var(--accent)" : "var(--surface-3)", color: i === winnerIdx ? "var(--accent-ink)" : "var(--text-2)", display: "grid", placeItems: "center", fontWeight: 900, fontSize: 12 }}>{["A", "B", "C"][i]}</span>
              </div>
              {i === winnerIdx && <div style={{ marginBottom: 10 }}><Pill kind="accent"><Ico.bolt /> Best value</Pill></div>}

              <div className="metric-row"><span className="k">Annual tuition + fees {s.dataSource !== "scorecard" && <span className="est-tag">est.</span>}</span>{isNum(s.annualTuition) ? <span className="v">{fmt(s.annualTuition + s.fees)}</span> : <span className="v nr">Not reported by institution</span>}</div>
              <div className="metric-row"><span className="k">Est. aid / year</span><span className="v pos">−{fmt(s.estimatedAid)}</span></div>
              <div className="metric-row"><span className="k">Out of pocket / yr <span className="est-tag">est.</span></span><CostCell value={s.annualOutOfPocket} className="big accent" /></div>
              <div className="metric-row"><span className="k">4-yr out of pocket <span className="est-tag">est.</span></span><CostCell value={s.totalOutOfPocket} /></div>
              <div className="grant-note"><Ico.flag /> <span>Institutional grants aren't in federal data and most schools have one for incoming freshmen — <b>ask admissions</b>. It could lower this number.</span></div>
              {s.scorecardUrl && <a className="scorecard-link" href={s.scorecardUrl} target="_blank" rel="noopener noreferrer">See {s.name.split(" ").slice(0,2).join(" ")}'s full record on College Scorecard →</a>}

              <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--line)" }}>
                <AccredLine info={s.accreditation && s.accreditation.institutional} />
                <AccredLine info={s.accreditation && s.accreditation.programmatic} />
              </div>

              {s.ownershipOverride && (
                <div className="own-override">
                  <div className="own-override-h">Now classified <b>{s.ownership}</b></div>
                  <p>{s.ownershipOverride.note}</p>
                  {s.ownershipOverride.sourceUrl && (
                    <a href={s.ownershipOverride.sourceUrl} target="_blank" rel="noopener noreferrer">
                      Verify via {s.ownershipOverride.sourceName} →
                    </a>
                  )}
                </div>
              )}

              <CorrectionLink school={s} />
            </div>
          ))}
        </div>

        {/* accreditation explainer */}
        <div className="card card-2 fade-up" style={{ borderColor: "var(--accent-line)" }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}><Ico.shield /> Accreditation, in plain English</div>
          <p style={{ fontSize: 13, lineHeight: 1.6, color: "var(--text-2)" }}>{report.accreditationExplainer}</p>
        </div>

        {/* credit transfer protective callout */}
        <div className="callout warn fade-up">
          <div className="callout-h"><Ico.flag /> Credit transfer — read this</div>
          <p>{report.creditTransferStatement}</p>
        </div>

        {/* background check notice (healthcare/education/trades) */}
        {report.anyBackgroundWarning && (
          <div className="callout danger fade-up">
            <div className="callout-h"><Ico.shield /> Background check notice</div>
            <p>{report.backgroundCheckNotice}</p>
          </div>
        )}

        {/* locked preview */}
        <div className="locked fade-up">
          <div className="blurred">
            <div style={{ fontWeight: 800, marginBottom: 8 }}>Your full report goes deep</div>
            <div className="metric-row"><span className="k">Hidden fee audit</span><span className="v">per school</span></div>
            <div className="metric-row"><span className="k">10-yr loan burden</span><span className="v">$XX,XXX</span></div>
            <div className="metric-row"><span className="k">Tech + laptop access</span><span className="v">resources</span></div>
            <div className="metric-row"><span className="k">Career pathways + BLS</span><span className="v">wages</span></div>
            <div className="metric-row"><span className="k">Licensing board check</span><span className="v">by state</span></div>
          </div>
          <div className="lock-over">
            <div>
              <div style={{ color: "var(--accent)", marginBottom: 8, display: "flex", justifyContent: "center" }}><Ico.lock /></div>
              <div className="lk">The deep stuff is locked</div>
              <div className="lk-sub">Hidden fees · loan projection · delivery · pathways · licensing · the right questions</div>
            </div>
          </div>
        </div>

        {/* what's inside the full report */}
        <div className="card fade-up">
          <div className="eyebrow dim" style={{ marginBottom: 12 }}><Ico.doc /> Inside the full PDF</div>
          <div className="inside-grid">
            {["Hidden Fee Audit", "Corporate Tuition Partnerships", "Technology + Laptop Access", "Program Delivery & Structure", "Admissions Criteria", "Professional Affiliations", "Career Pathways + BLS wages", report.licensureRelevant ? "State Licensing Board check" : "Accreditation deep-dive", "Questions for Admissions", "Questions for Financial Aid", "Student Consumer Info links"].map((t) => (
              <div className="inside-item" key={t}><span className="ck"><Ico.check /></span>{t}</div>
            ))}
          </div>
        </div>

        {/* watermark */}
        <div className="watermark fade-up">🔒 Unlock your full report + PDF at b4iou.com</div>

        {/* upgrade buttons */}
        <div className="stack" style={{ gap: 10, marginTop: 4 }}>
          <Btn kind="accent" size="lg" arrow onClick={onUpgrade}>Unlock full report — from $9.99</Btn>
          <div style={{ textAlign: "center" }}><BackBtn onClick={onBack} label="Edit my schools" /></div>
        </div>

        {report.dataSource && <div className="data-source-note mono">{report.dataSource}</div>}
      </div>
    </div>
  );
}

function AccredLine({ info }) {
  if (!info) return null;
  const notReq = info.status === "not-required";
  return (
    <div className="accred-line">
      <span className="accred-ic" data-status={info.status}>
        {notReq ? <Ico.flag /> : <Ico.search />}
      </span>
      <div style={{ minWidth: 0 }}>
        <div className="accred-head">
          <span className="accred-label">{info.label}</span>
          {info.accreditor && <span className="accred-acc">{info.accreditor}</span>}
          <span className={`accred-badge ${notReq ? "muted" : ""}`}>{notReq ? "Not required" : "Verify"}</span>
        </div>
        <div className="accred-guide">{info.guidance}</div>
        {info.lookupUrl && (
          <a className="accred-link" href={info.lookupUrl} target="_blank" rel="noopener noreferrer">
            {info.lookupLabel} →
          </a>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { generateReport, Loader, FreeReport, AccredLine });
