/* ============================================================
   B4IOU — static data + fallback estimator
   ============================================================ */

const SCHOOLS = [
  /* Large public universities */
  { name: "Arizona State University", meta: "Public · AZ" },
  { name: "Penn State University", meta: "Public · PA" },
  { name: "Ohio State University", meta: "Public · OH" },
  { name: "University of Texas at Austin", meta: "Public · TX" },
  { name: "University of Florida", meta: "Public · FL" },
  { name: "University of Central Florida", meta: "Public · FL" },
  { name: "Florida International University", meta: "Public · FL" },
  { name: "Michigan State University", meta: "Public · MI" },
  { name: "University of Michigan", meta: "Public · MI" },
  { name: "University of California, Los Angeles", meta: "Public · CA" },
  { name: "University of California, Berkeley", meta: "Public · CA" },
  { name: "San Diego State University", meta: "Public · CA" },
  { name: "California State University, Fullerton", meta: "Public · CA" },
  { name: "University of Washington", meta: "Public · WA" },
  { name: "University of Wisconsin–Madison", meta: "Public · WI" },
  { name: "University of Minnesota", meta: "Public · MN" },
  { name: "Indiana University Bloomington", meta: "Public · IN" },
  { name: "Purdue University", meta: "Public · IN" },
  { name: "University of Illinois Urbana–Champaign", meta: "Public · IL" },
  { name: "Texas A&M University", meta: "Public · TX" },
  { name: "University of Houston", meta: "Public · TX" },
  { name: "University of Georgia", meta: "Public · GA" },
  { name: "Georgia State University", meta: "Public · GA" },
  { name: "University of North Carolina at Chapel Hill", meta: "Public · NC" },
  { name: "North Carolina State University", meta: "Public · NC" },
  { name: "Rutgers University", meta: "Public · NJ" },
  { name: "University of Maryland", meta: "Public · MD" },
  { name: "Virginia Tech", meta: "Public · VA" },
  { name: "University of Virginia", meta: "Public · VA" },
  { name: "University of Arizona", meta: "Public · AZ" },
  { name: "University of Colorado Boulder", meta: "Public · CO" },
  { name: "University of Tennessee", meta: "Public · TN" },
  { name: "University of Alabama", meta: "Public · AL" },
  { name: "Louisiana State University", meta: "Public · LA" },
  { name: "University of Oregon", meta: "Public · OR" },
  { name: "University of Utah", meta: "Public · UT" },
  { name: "University of Nevada, Las Vegas", meta: "Public · NV" },
  { name: "CUNY — Hunter College", meta: "Public · NY" },
  { name: "SUNY University at Buffalo", meta: "Public · NY" },

  /* Private nonprofit */
  { name: "New York University", meta: "Private · NY" },
  { name: "Southern New Hampshire University", meta: "Private · NH" },
  { name: "Liberty University", meta: "Private · VA" },
  { name: "Grand Canyon University", meta: "Private · AZ" },
  { name: "Western Governors University", meta: "Private · UT" },
  { name: "Boston University", meta: "Private · MA" },
  { name: "Northeastern University", meta: "Private · MA" },
  { name: "Syracuse University", meta: "Private · NY" },
  { name: "DePaul University", meta: "Private · IL" },
  { name: "Drexel University", meta: "Private · PA" },
  { name: "Pepperdine University", meta: "Private · CA" },
  { name: "Baylor University", meta: "Private · TX" },
  { name: "Howard University", meta: "Private · DC" },
  { name: "University of Southern California", meta: "Private · CA" },

  /* For-profit */
  { name: "University of Phoenix", meta: "For-profit · AZ" },
  { name: "Full Sail University", meta: "For-profit · FL" },
  { name: "DeVry University", meta: "For-profit · IL" },
  { name: "Capella University", meta: "For-profit · MN" },
  { name: "Walden University", meta: "For-profit · MN" },
  { name: "Strayer University", meta: "For-profit · DC" },
  { name: "Colorado Technical University", meta: "For-profit · CO" },
  { name: "American InterContinental University", meta: "For-profit · GA" },
  { name: "Keiser University", meta: "For-profit · FL" },
  { name: "Purdue University Global", meta: "For-profit · IN" },

  /* Community & two-year colleges */
  { name: "Community College of Denver", meta: "Public 2-yr · CO" },
  { name: "Miami Dade College", meta: "Public 2-yr · FL" },
  { name: "Houston Community College", meta: "Public 2-yr · TX" },
  { name: "Santa Monica College", meta: "Public 2-yr · CA" },
  { name: "Maricopa Community Colleges", meta: "Public 2-yr · AZ" },
  { name: "Northern Virginia Community College", meta: "Public 2-yr · VA" },
  { name: "Valencia College", meta: "Public 2-yr · FL" },
  { name: "Ivy Tech Community College", meta: "Public 2-yr · IN" },
];

const PROGRAMS = [
  { name: "Nursing (BSN)", meta: "Healthcare" },
  { name: "Computer Science (BS)", meta: "STEM" },
  { name: "Business Administration (BBA)", meta: "Business" },
  { name: "Psychology (BA)", meta: "Social Science" },
  { name: "Mechanical Engineering (BS)", meta: "Engineering" },
  { name: "Graphic Design (BFA)", meta: "Arts" },
  { name: "Criminal Justice (BS)", meta: "Public Service" },
  { name: "Education (B.Ed)", meta: "Education" },
  { name: "Cybersecurity (BS)", meta: "STEM" },
  { name: "Communications (BA)", meta: "Humanities" },
  { name: "Accounting (BS)", meta: "Business" },
  { name: "Data Science (BS)", meta: "STEM" },
];

const STATES = ["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"];

/* studentaid.gov-style dependency / aid questions */
const AID_QUESTIONS = [
  {
    id: "status", q: "Are you a dependent or independent student?",
    hint: "Independent if 24+, married, a veteran, or supporting your own kids.",
    opts: [
      { v: "dependent", t: "Dependent (under 24, supported by parents)" },
      { v: "independent", t: "Independent (on my own)" },
    ],
  },
  {
    id: "household", q: "How many people are in your household?",
    hint: "Include yourself, parents (if dependent), and any dependents.",
    opts: [
      { v: "1-2", t: "1–2 people" },
      { v: "3-4", t: "3–4 people" },
      { v: "5+", t: "5 or more people" },
    ],
  },
  {
    id: "income", q: "What's your household's annual income range?",
    hint: "Adjusted gross income from your most recent tax return.",
    opts: [
      { v: "under30", t: "Under $30,000" },
      { v: "30-60", t: "$30,000 – $60,000" },
      { v: "60-100", t: "$60,000 – $100,000" },
      { v: "over100", t: "Over $100,000" },
    ],
  },
  {
    id: "college", q: "How many in your household will be in college this year?",
    hint: "More students in college can increase your aid eligibility.",
    opts: [
      { v: "1", t: "Just me" },
      { v: "2", t: "2 of us" },
      { v: "3+", t: "3 or more" },
    ],
  },
  {
    id: "assets", q: "Do you (or your parents) have significant savings or assets?",
    hint: "Excludes retirement accounts and primary home.",
    opts: [
      { v: "low", t: "Under $10,000" },
      { v: "mid", t: "$10,000 – $50,000" },
      { v: "high", t: "Over $50,000" },
    ],
  },
  {
    id: "firstgen", q: "Will you be the first in your family to earn a degree?",
    hint: "First-generation students may qualify for extra grants.",
    opts: [
      { v: "yes", t: "Yes, first-generation" },
      { v: "no", t: "No" },
    ],
  },
];

/* deterministic estimate the moment we need numbers without the API */
function hashStr(s) { let h = 0; for (let i = 0; i < s.length; i++) { h = (h * 31 + s.charCodeAt(i)) >>> 0; } return h; }

function estimateSAI(answers) {
  // very rough proxy of a Student Aid Index from the dependency answers
  let sai = 8000;
  const inc = answers.income;
  if (inc === "under30") sai = -1500;
  else if (inc === "30-60") sai = 2500;
  else if (inc === "60-100") sai = 9000;
  else if (inc === "over100") sai = 22000;
  if (answers.household === "5+") sai -= 3000;
  else if (answers.household === "3-4") sai -= 1200;
  if (answers.college === "2") sai = Math.round(sai / 1.6);
  else if (answers.college === "3+") sai = Math.round(sai / 2.2);
  if (answers.assets === "high") sai += 5000;
  else if (answers.assets === "mid") sai += 1500;
  if (answers.status === "independent" && inc === "under30") sai -= 1000;
  return sai;
}

function pellFromSAI(sai) {
  const MAX_PELL = 7395;
  if (sai <= 0) return MAX_PELL;
  if (sai >= 7000) return 0;
  return Math.max(0, Math.round((MAX_PELL - (sai / 7000) * MAX_PELL) / 50) * 50);
}

const ONLINE_RE = /phoenix|snhu|southern new hampshire|western governors|wgu|liberty|grand canyon|full sail|devry|capella|strayer|online/i;

/* deterministic per-school detail sections (Hidden fees, tech, delivery, etc.) */
function buildSchoolSections(s, seed, isFP, isOnline, state) {
  const r = (n) => seed % n;
  const techFee = 250 + r(450);
  const labApplies = /nurs|clinic|health|comput|cyber|data|engineer|lab|science|trade|hvac|weld/i.test(s.program);
  const labFee = 180 + r(420);
  const hiddenFees = [
    { name: "Technology fee", amount: techFee, period: "year", included: false },
    { name: "Student services fee", amount: 120 + r(280), period: "year", included: !isFP && r(2) === 0 },
    { name: "Graduation / commencement fee", amount: 60 + r(120), period: "one-time", included: false },
    { name: "Application fee", amount: 25 + r(60), period: "one-time", included: false },
  ];
  if (labApplies) hiddenFees.splice(1, 0, { name: "Lab / studio fee", amount: labFee, period: "year", included: false });
  const annualHidden = hiddenFees.filter((f) => !f.included && f.period === "year").reduce((a, b) => a + b.amount, 0);

  const licensure = leadsToLicensure([s.program]);

  return {
    accreditation: accreditationFor(s.name, s.program),
    programVerified: false, // we have NOT confirmed this school offers this exact program
    hiddenFees,
    annualHiddenFees: annualHidden,
    feesDisclosed: !isFP,
    corporatePartnerships: [], // none verified -> renders the compliant "ask" fallback
    techRequirements: {
      laptopRequired: isOnline || /comput|cyber|data|design|engineer|business/i.test(s.program),
      providedByInstitution: false,
      techFee: hiddenFees[0].included ? "Included in tuition" : `$${techFee}/yr (separate)`,
      minSpecs: (isOnline || /comput|cyber|data|design/i.test(s.program))
        ? "Modern 64-bit OS, 8GB+ RAM, webcam, reliable broadband"
        : "Not publicly specified",
      loanerProgram: !isFP ? "Library / IT loaner laptops typically available" : "Not publicly confirmed — ask directly",
    },
    affiliations: [], // none verified -> renders the compliant "ask" fallback
    delivery: {
      format: isOnline ? "Fully online" : "In-person (hybrid options available)",
      modality: isOnline ? "Asynchronous (some synchronous sessions)" : "In-person, synchronous",
      termType: /western governors|wgu/i.test(s.name) ? "Competency-based (6-month terms)"
        : isFP ? "Accelerated sessions (5\u20136 weeks)" : "Semester (16 weeks)",
      courseLength: /western governors|wgu/i.test(s.name) ? "Self-paced" : isFP ? "5\u20136 weeks/course" : "16 weeks/course",
      coursesPerTerm: isFP ? "1\u20132 at a time" : "4\u20135",
      creditHours: 120,
      timeFullTime: "~4 years",
      timePartTime: "~5\u20136 years",
    },
    careerPathways: {
      institutional: institutionalPathways(s.program),
      bls: blsFor(s.program),
    },
    licensingBoard: {
      applies: licensure,
      verified: false,
      note: licensure
        ? `State licensing board approval status could not be independently verified for this program in ${state || "your state"}. Verify directly with your state licensing board before enrolling — graduation from an unapproved program may disqualify you from licensure.`
        : "This program does not lead to a state-issued license.",
    },
    consumerInfo: {
      scorecard: "https://collegescorecard.ed.gov/search/?search=" + encodeURIComponent(s.name),
      note: "Find this school's required \u201CStudent Consumer Information\u201D / \u201CRight-to-Know\u201D disclosures page on its official .edu site, or review federal data via College Scorecard.",
    },
    admissionsCriteria: buildAdmissionsCriteria(s.name, s.program, seed, isFP, isOnline),
  };
}

/* Build a complete fallback report so the UI never breaks */
const NOT_REPORTED_TXT = "Not reported by institution";

function fallbackReport(input) {
  const sai = input.sai != null ? input.sai : estimateSAI(input.answers || {});
  const pell = pellFromSAI(sai);
  const forprofit = (n) => /phoenix|devry|full sail|grand canyon|for-profit/i.test(n);
  const state = input.state;
  const scEnabled = !!(window.B4IOU_CONFIG && window.B4IOU_CONFIG.SCORECARD && window.B4IOU_CONFIG.SCORECARD.enabled);

  const schools = input.schools.map((s) => {
    const seed = hashStr(s.name + s.program);
    const isFP = forprofit(s.name);
    const isOnline = ONLINE_RE.test(s.name);
    const sc = (scEnabled && s.scorecard && window.scorecardToFields) ? window.scorecardToFields(s.scorecard, state) : null;
    const years = 4;
    const loanRate = 0.0653;
    const monthlyOf = (oop) => oop > 0 ? (oop * (loanRate / 12)) / (1 - Math.pow(1 + loanRate / 12, -120)) : 0;

    let core;
    if (scEnabled) {
      // ---- LIVE: every cost fact comes from College Scorecard; null ⇒ Not reported ----
      const tuition = sc ? sc.tuition : null;            // residency-correct tuition or null
      const fees = 0;                                    // Scorecard has no separate required-fee line
      const stateGrant = Math.round((pell ? 1500 : 600) + (seed % 800));
      const aid = pell + stateGrant;                     // student's own federal aid estimate (not a school fact)
      const reported = tuition != null;
      const annualOOP = reported ? Math.max(0, tuition + fees - aid) : null;
      const oop = annualOOP != null ? annualOOP * years : null;
      const monthly = annualOOP != null ? monthlyOf(oop) : null;
      core = {
        annualTuition: reported ? tuition : null,
        fees,
        totalTuition: reported ? (tuition + fees) * years : null,
        estimatedAid: aid,
        annualOutOfPocket: annualOOP,
        totalOutOfPocket: oop,
        tenYearLoanBurden: monthly != null ? Math.round(monthly * 120) : null,
        monthlyPayment: monthly != null ? Math.round(monthly) : null,
        tuitionReported: reported,
        costStatus: "scorecard",
        // real Scorecard facts surfaced on the school object (null ⇒ Not reported)
        netPrice: sc ? sc.netPrice : null,
        medianDebt: sc ? sc.medianDebt : null,
        completionRate: sc ? sc.completionRate : null,
        medianEarnings: sc ? sc.medianEarnings : null,
        admissionRate: sc ? sc.admissionRate : null,
        pellRate: sc ? sc.pellRate : null,
        federalLoanRate: sc ? sc.federalLoanRate : null,
        ownership: sc ? sc.ownership : NOT_REPORTED_TXT,
        ownershipOverride: sc ? sc.ownershipOverride : null,
        institutionalAccreditor: sc ? sc.accreditor : NOT_REPORTED_TXT,
        enrollmentSize: sc ? sc.size : null,
        scorecardId: sc ? sc.scorecardId : (s.scorecardId || null),
        dataSource: "scorecard",
      };
    } else {
      // ---- legacy deterministic estimate (only if Scorecard is disabled in config) ----
      const base = isFP ? 16500 : 11000;
      const annual = base + (seed % 9000);
      const fees = 1200 + (seed % 1400);
      const totalTuition = (annual + fees) * years;
      const stateGrant = Math.round((pell ? 1500 : 600) + (seed % 800));
      const aid = pell + stateGrant;
      const annualOOP = Math.max(0, annual + fees - aid);
      const oop = annualOOP * years;
      const monthly = monthlyOf(oop);
      core = {
        annualTuition: annual, fees, totalTuition,
        estimatedAid: aid, annualOutOfPocket: annualOOP, totalOutOfPocket: oop,
        tenYearLoanBurden: Math.round(monthly * 120), monthlyPayment: Math.round(monthly),
        tuitionReported: true, costStatus: "estimate", dataSource: "estimate",
      };
    }

    return {
      name: s.name, program: s.program,
      ...core,
      scorecardUrl: "https://collegescorecard.ed.gov/search/?search=" + encodeURIComponent(s.name),
      curriculum: `${s.program} core: ~40 credits major coursework, general education, and a capstone (120 total credits).`,
      redFlags: isFP
        ? ["Tuition runs well above the public-school median for this degree", "Fee structure may not be fully disclosed up front — request an itemized schedule in writing"]
        : ((core.annualTuition || 0) > 16000 ? ["Tuition is on the higher end — ask the Financial Aid office about institutional grants"] : []),
      ...buildSchoolSections(s, seed, isFP, isOnline, state),
    };
  });

  // cheapest by out-of-pocket; schools with unreported cost sort last
  const rank = (v) => (v == null ? Number.MAX_SAFE_INTEGER : v);
  const cheapest = [...schools].sort((a, b) => rank(a.totalOutOfPocket) - rank(b.totalOutOfPocket))[0];
  const programs = schools.map((s) => s.program);
  const recHasCost = cheapest && cheapest.totalOutOfPocket != null;
  return {
    schools,
    sai, pell, state,
    winnerName: cheapest.name,
    dataSource: schools.some((s) => s.dataSource === "scorecard")
      ? "Data sourced from U.S. Department of Education College Scorecard. Retrieved at time of report generation."
      : null,
    retrievedAt: new Date().toISOString(),
    accreditationExplainer: ACCREDITATION_EXPLAINER,
    creditTransferStatement: CREDIT_TRANSFER_STATEMENT,
    curriculumOverlap: schools.length >= 2
      ? `${schools[0].program} and ${schools[1].program} share most core coursework. The real difference is delivery, support, and total cost — not the diploma itself.`
      : "",
    recommendation: recHasCost
      ? `Based on cost after estimated aid, ${cheapest.name} is the stronger financial decision — roughly ${fmt(cheapest.totalOutOfPocket)} out of pocket over 4 years.`
      : `Tuition isn't reported by these institutions in the federal data — confirm published prices with each school's financial aid office before deciding.`,
    questionsToAsk: buildAdmissionsQuestions(programs),
    financialAidIntro: FINANCIAL_AID_INTRO,
    financialAidQuestions: FINANCIAL_AID_QUESTIONS,
    corpPartnershipNote: CORP_PARTNERSHIP_NOTE,
    corpPartnershipNone: CORP_PARTNERSHIP_NONE,
    laptopResources: LAPTOP_ACCESS_RESOURCES,
    rentToOwnWarning: RENT_TO_OWN_WARNING,
    careerPathwayNote: CAREER_PATHWAY_NOTE,
    consumerInfoIntro: CONSUMER_INFO_INTRO,
    consumerInfoWarning: CONSUMER_INFO_WARNING,
    globalDisclaimer: GLOBAL_DISCLAIMER,
    backgroundCheckNotice: BACKGROUND_CHECK_NOTICE,
    anyBackgroundWarning: programs.some((p) => needsBackgroundWarning(p)),
    licensureRelevant: leadsToLicensure(programs),
    _source: "estimate",
  };
}

Object.assign(window, { SCHOOLS, PROGRAMS, STATES, AID_QUESTIONS, estimateSAI, pellFromSAI, fallbackReport });
