/* ============================================================
   B4IOU — Compliance content engine
   Exact, verified constants + program-aware generators.
   These are deterministic (NOT model-generated) so the
   legally-sensitive language is always correct & compliant.
   ============================================================ */

/* ---------- fixed legal / educational copy (verbatim) ---------- */

const ACCREDITATION_EXPLAINER =
  "INSTITUTIONAL ACCREDITATION evaluates the entire school's quality, financial stability, and academic standards. It determines federal financial aid eligibility and is required for a legitimate degree. PROGRAMMATIC ACCREDITATION evaluates a specific program against industry standards set by a specialized accrediting body. It often determines whether graduates can sit for licensure exams or practice in regulated professions. Any institution still using 'regional' or 'national' accreditation language is using outdated terminology discontinued by the DOE in 2020.";

const CREDIT_TRANSFER_STATEMENT =
  "Transferability of credit is never guaranteed and is always determined by the receiving institution on a case-by-case basis. Formal articulation agreements — written guarantees of credit transfer between specific institutions — are common between community colleges and public universities, particularly within state systems, but are far less common between private institutions. If transfer of prior credits matters to your decision, request a formal written transfer credit evaluation from the registrar's office — not your admissions representative — before enrolling.";

const FINANCIAL_AID_INTRO =
  "The following questions cannot be compliantly answered by admissions representatives. Contact the Financial Aid office directly before making any enrollment decision.";

const FINANCIAL_AID_QUESTIONS = [
  "Does the school offer an institutional grant or scholarship for incoming freshmen this year — what is the amount, and what are the renewal conditions? (These are rarely published in federal data and change often, but most schools have one.)",
  "Is the financial aid package being offered guaranteed for every year of the program — or only the first year?",
  "What happens to my aid eligibility if I drop below full-time enrollment status?",
  "What is my actual net price after all grants and scholarships I personally qualify for — not the published sticker price?",
];

const CORP_PARTNERSHIP_NOTE =
  "Corporate tuition partnerships often extend to immediate family members of employees — even if the student themselves doesn't work there. Check whether a parent, spouse, or guardian works for any partner organization before paying full tuition.";

const CORP_PARTNERSHIP_NONE =
  "No corporate tuition partnerships publicly listed. Ask your admissions representative: \u201CDoes your institution have corporate tuition partnership agreements — and do they extend to immediate family members of employees?\u201D";

const RENT_TO_OWN_WARNING =
  "Rent-to-own total costs significantly exceed retail price. Compare total payment carefully before committing.";

const CAREER_PATHWAY_NOTE =
  "Career pathway data sourced from institutional program pages and U.S. Bureau of Labor Statistics. Individual outcomes vary. Salary figures reflect national medians and are not institution-specific.";

const CONSUMER_INFO_INTRO =
  "Federal law requires every institution to publish Student Consumer Information including graduation rates, placement rates, loan default rates, and financial aid data. Access each school's required disclosures directly:";

const CONSUMER_INFO_WARNING =
  "Salary and placement figures quoted by admissions representatives may not reflect your individual outcome. Always verify independently through BLS.gov or your state's labor department before making enrollment decisions.";

const GLOBAL_DISCLAIMER =
  "All data sourced from U.S. Department of Education public databases, College Scorecard, IPEDS, institutional websites, and Bureau of Labor Statistics. B4IOU is an independent student advocacy tool and is not affiliated with, endorsed by, or acting on behalf of any institution or the U.S. Department of Education. Data reflects publicly available information and may not reflect current pricing or program status. Verify all information directly with institutions and relevant licensing boards before making enrollment decisions. B4IOU does not provide legal, financial, or academic advising. Generated by B4IOU | b4iou.com | Know before you owe.";

const ADMISSIONS_NOT_LISTED =
  "Program-specific admissions requirements not fully listed publicly. Ask your admissions representative: Are there any program-specific admissions requirements — such as minimum GPA, prerequisite courses, background checks, drug screening, entrance exams, or prior certifications — that are not listed in the general institutional admissions requirements?";

const BACKGROUND_CHECK_NOTICE =
  "\u26A0\uFE0F BACKGROUND CHECK NOTICE: Some programs in healthcare, education, and trades require background checks and drug screening for clinical placement or licensure. A prior criminal record may affect eligibility for licensure or employment regardless of program completion. Verify requirements with your state licensing board before enrolling.";

const UNIVERSAL_ADMISSIONS_QUESTION =
  "Are there any program-specific admissions requirements — such as minimum GPA, prerequisite courses, background checks, drug screening, entrance exams, or prior certifications — that are not listed in the general institutional admissions requirements?";

const LAPTOP_ACCESS_RESOURCES = [
  { name: "Federal & state assistance programs", detail: "Affordable Connectivity successor programs, state digital-equity grants, and institutional emergency-aid funds applicable to your situation." },
  { name: "Amazon Renewed", detail: "Certified refurbished laptops with a 90-day guarantee — often 30–50% below retail." },
  { name: "Dell Student Discount Program", detail: "Member Purchase Program pricing + back-to-school coupons for enrolled students." },
  { name: "Apple Education Pricing", detail: "Reduced pricing on Mac/iPad for students and educators, plus occasional gift-card promos." },
  { name: "Carrier financing — Verizon / T-Mobile / AT&T", detail: "0% device payment plans spread monthly; check for student/education plans." },
  { name: "Rent-to-own — Rent-A-Center / Aaron's / FlexShopper", detail: "Available with no credit, but see warning below.", warn: true },
];

/* ---------- Accreditation: verification pointers, never assertions ----------
   B4IOU does NOT claim a given school holds a given accreditation. We name the
   accreditor a field is USUALLY held by, explain why it matters, and link the
   official database so the user verifies THIS program themselves. Every object
   carries a status so the UI can render "verify", never a green "verified" tick.
   On deploy these objects are replaced by rows from the Supabase truth DB
   (school_facts) carrying a real source_url + last_checked_at. */
const PROG_ACCREDITORS = {
  nursing:     { name: "CCNE or ACEN", short: "CCNE / ACEN", url: "https://www.acenursing.org/search-programs/", why: "Required to sit for the NCLEX-RN and for RN licensure in every state." },
  engineering: { name: "ABET",         short: "ABET",        url: "https://amspub.abet.org/aps/category-search", why: "Expected for the Professional Engineer (PE) licensure track." },
  business:    { name: "AACSB or ACBSP", short: "AACSB / ACBSP", url: "https://www.aacsb.edu/accreditation/accredited-schools", why: "Employer-preferred, but not legally required to work in business." },
  education:   { name: "CAEP",         short: "CAEP",        url: "http://caepnet.org/provider-search", why: "Required (with state-board approval) for teacher certification in most states." },
  healthcare:  { name: "a field-specific accreditor", short: "field accreditor", url: "https://ope.ed.gov/dapip/#/home", why: "Often required to sit for a professional licensure exam." },
};

function accreditationFor(name, program) {
  const t = programTypes([program]);

  const institutional = {
    label: "Institutional",
    status: "unverified",
    accreditor: null,
    guidance: "Confirm this school is institutionally accredited AND in good standing — no probation, sanctions, or show-cause orders. This controls federal-aid eligibility and whether the degree is recognized.",
    lookupUrl: "https://ope.ed.gov/dapip/#/home",
    lookupLabel: "Check the U.S. DOE accreditation database",
  };

  let key = null;
  if (/nurs/i.test(program)) key = "nursing";
  else { for (const k of ["engineering", "education", "business", "healthcare"]) { if (t.has(k)) { key = k; break; } } }

  let programmatic;
  if (key) {
    const a = PROG_ACCREDITORS[key];
    programmatic = {
      label: "Programmatic",
      status: "unverified",
      applies: true,
      accreditor: a.short,
      guidance: `${a.why} We have NOT verified that this specific program at ${name} holds ${a.name} accreditation — confirm it is listed in the official database before you enroll.`,
      lookupUrl: a.url,
      lookupLabel: `Search ${a.short.split(" ")[0]}'s official database`,
    };
  } else {
    programmatic = {
      label: "Programmatic",
      status: "not-required",
      applies: false,
      accreditor: null,
      guidance: "No single programmatic accreditor is standard for this field. Ask the program directly whether any specialized accreditation applies to it.",
      lookupUrl: null,
      lookupLabel: null,
    };
  }

  return { institutional, programmatic };
}

Object.assign(window, { accreditationFor });

/* ---------- program-type detection ---------- */

function programTypes(programs) {
  const all = programs.join(" ").toLowerCase();
  const types = new Set();
  if (/nurs|clinic|medical|health|dental|pharm|allied|radiolog|therap|sonograph/.test(all)) types.add("healthcare");
  if (/business|manage|account|finance|\bmba\b|\bbba\b|marketing|economic/.test(all)) types.add("business");
  if (/comput|cyber|\bit\b|information tech|software|data|network|program/.test(all)) types.add("tech");
  if (/psych|communic|liberal|humanit|social|english|history|\bart\b|design|sociolog|political/.test(all)) types.add("liberalarts");
  if (/trade|vocational|cosmetolog|hvac|electric|welding|plumb|automotive|construction|culinary/.test(all)) types.add("trades");
  if (/educat|teach|\bb\.?ed\b/.test(all)) types.add("education");
  if (/engineer/.test(all)) types.add("engineering");
  return types;
}

/* programs that lead to state licensure */
function leadsToLicensure(programs) {
  const t = programTypes(programs);
  return t.has("healthcare") || t.has("trades") || t.has("education") ||
    /cosmetolog|nurs|teach|electric|hvac|welding|dental|pharm/i.test(programs.join(" "));
}

/* ---------- compliant admissions-rep question bank ----------
   Universal first, then ONLY the blocks whose program type is
   present in the comparison. Never asks for outcomes/quality/
   transfer/aid-packaging (those are surfaced or redirected). */

function buildAdmissionsQuestions(programs) {
  const t = programTypes(programs);
  const q = [
    "What is the total cost of attendance for my specific program — including tuition, fees, books, supplies, and any program-specific costs not listed in the catalog?",
    "Is this institution's accreditation current and in good standing? I've reviewed the publicly available status — can you confirm there are no active sanctions, probationary status, or show-cause orders since the last federal reporting period?",
    "Is this specific program accredited by a programmatic accrediting body — and can you confirm the current accreditation status?",
    UNIVERSAL_ADMISSIONS_QUESTION,
  ];
  if (t.has("healthcare")) {
    q.push("Are clinical externships or practicums guaranteed for every student in this program — and are they paid or unpaid?");
    q.push("Are there required certification or licensure exams upon program completion — and are the associated costs covered by the institution or the student?");
    q.push("Are clinical placements arranged locally — and if a local placement is not available, what is the contingency plan?");
  }
  if (t.has("business")) {
    q.push("Does the institution have a dedicated career services department that assists students in this program with job search support — and when does that access begin?");
  }
  if (t.has("tech")) {
    q.push("Does this program include preparation for or coverage of costs for any industry certification exams — and if so, which ones?");
    q.push("Does the institution have a dedicated career services department that assists students in this program — and when does that access begin?");
  }
  if (t.has("liberalarts")) {
    q.push("What career paths are most common for graduates of this specific program — and where is that information publicly documented?");
    q.push("Does the institution have a dedicated academic advisement department available to students in this program — and when does access begin?");
  }
  if (t.has("trades")) {
    q.push("Are tools, equipment, and supply kits required for this program included in tuition — or are they an additional out-of-pocket cost? If separate, what is the estimated total?");
    q.push("Does this program have established relationships with local employers for job placement or hiring — and can you share which employers participate?");
  }
  return q;
}

/* ---------- BLS-style related-occupation data by program type ---------- */
const BLS_TABLE = {
  healthcare: [
    { occ: "Registered Nurses", wage: 86070, growth: "6%" },
    { occ: "Nurse Practitioners", wage: 126260, growth: "46%" },
  ],
  tech: [
    { occ: "Software Developers", wage: 132270, growth: "17%" },
    { occ: "Information Security Analysts", wage: 120360, growth: "32%" },
    { occ: "Data Scientists", wage: 108020, growth: "36%" },
  ],
  business: [
    { occ: "Management Analysts", wage: 99410, growth: "10%" },
    { occ: "Accountants & Auditors", wage: 79880, growth: "4%" },
    { occ: "Financial Analysts", wage: 99890, growth: "8%" },
  ],
  liberalarts: [
    { occ: "Public Relations Specialists", wage: 67440, growth: "6%" },
    { occ: "Substance Abuse / Behavioral Counselors", wage: 53710, growth: "18%" },
  ],
  trades: [
    { occ: "Electricians", wage: 61590, growth: "6%" },
    { occ: "HVAC Mechanics & Installers", wage: 57300, growth: "9%" },
  ],
  education: [
    { occ: "Elementary School Teachers", wage: 63680, growth: "1%" },
    { occ: "Instructional Coordinators", wage: 74620, growth: "2%" },
  ],
  engineering: [
    { occ: "Mechanical Engineers", wage: 99510, growth: "10%" },
    { occ: "Industrial Engineers", wage: 96350, growth: "12%" },
  ],
  general: [
    { occ: "Related professional occupations", wage: 65000, growth: "varies" },
  ],
};

function blsFor(program) {
  const t = programTypes([program]);
  for (const key of ["healthcare", "tech", "engineering", "business", "trades", "education", "liberalarts"]) {
    if (t.has(key)) return BLS_TABLE[key];
  }
  return BLS_TABLE.general;
}

function institutionalPathways(program) {
  const t = programTypes([program]);
  if (t.has("healthcare")) return ["Staff nurse / clinical roles", "Case management", "Public health", "Graduate / advanced practice track"];
  if (t.has("tech")) return ["Software / web development", "Security analysis", "Cloud & systems administration", "Data analytics"];
  if (t.has("business")) return ["Operations & management", "Financial analysis", "Consulting", "Entrepreneurship"];
  if (t.has("trades")) return ["Apprenticeship → journeyman", "Field technician", "Self-employed contractor", "Site supervision"];
  if (t.has("education")) return ["Classroom teaching", "Curriculum support", "Educational administration"];
  if (t.has("engineering")) return ["Design engineering", "Manufacturing & quality", "Project engineering"];
  return ["Program-related professional roles", "Graduate study", "Public & nonprofit sector"];
}

/* ---------- Admissions Criteria (Correction 11) ---------- */
function needsBackgroundWarning(program) {
  const t = programTypes([program]);
  return t.has("healthcare") || t.has("education") || t.has("trades");
}

function buildAdmissionsCriteria(name, program, seed, isFP, isOnline) {
  const r = (n) => seed % n;
  const open = isFP || isOnline;
  const t = programTypes([program]);

  // institutional-level criteria (IPEDS / Scorecard style)
  const acceptanceRate = open ? "Open enrollment (≈100%)" : (55 + r(40)) + "% (selective)";
  const testScores = open ? "Not required" : (["Test-optional / recommended", "Not required", "Recommended"][r(3)]);
  const minGPA = open ? "No minimum (open enrollment)" : "2.5–3.0 (institutional)";
  const enrollment = open ? "Open" : "Selective";
  const deadlineType = open ? "Rolling" : (r(2) === 0 ? "Fixed (priority deadline)" : "Rolling");

  // program-specific requirements — detailed where well-known, else fallback
  let programSpecific = { listed: false, note: ADMISSIONS_NOT_LISTED };
  if (t.has("healthcare") && /nurs/i.test(program)) {
    programSpecific = {
      listed: true,
      items: [
        { k: "Min program GPA", v: "≈2.75 in prerequisites" },
        { k: "Prerequisite courses", v: "Anatomy & Physiology I/II, Microbiology, Chemistry" },
        { k: "Entrance exam", v: "TEAS or HESI A2 required" },
        { k: "Background check", v: "Required for clinical placement" },
        { k: "Drug screening", v: "Required for clinical placement" },
        { k: "Physical / immunizations", v: "Required (CPR, immunization records)" },
        { k: "Interview", v: "Program-dependent" },
      ],
    };
  } else if (t.has("healthcare")) {
    programSpecific = {
      listed: true,
      items: [
        { k: "Prerequisite courses", v: "Science prerequisites typically required" },
        { k: "Entrance exam", v: "Allied-health entrance exam may apply" },
        { k: "Background check", v: "Required for clinical placement" },
        { k: "Drug screening", v: "Required for clinical placement" },
      ],
    };
  }

  return {
    acceptanceRate, testScores, minGPA, enrollment, deadlineType,
    programSpecific,
    backgroundWarning: needsBackgroundWarning(program),
  };
}

Object.assign(window, {
  ACCREDITATION_EXPLAINER, CREDIT_TRANSFER_STATEMENT,
  FINANCIAL_AID_INTRO, FINANCIAL_AID_QUESTIONS,
  CORP_PARTNERSHIP_NOTE, CORP_PARTNERSHIP_NONE, RENT_TO_OWN_WARNING,
  CAREER_PATHWAY_NOTE, CONSUMER_INFO_INTRO, CONSUMER_INFO_WARNING,
  GLOBAL_DISCLAIMER, LAPTOP_ACCESS_RESOURCES,
  ADMISSIONS_NOT_LISTED, BACKGROUND_CHECK_NOTICE, UNIVERSAL_ADMISSIONS_QUESTION,
  programTypes, leadsToLicensure, buildAdmissionsQuestions,
  blsFor, institutionalPathways,
  needsBackgroundWarning, buildAdmissionsCriteria,
});
