/* ============================================================
   B4IOU — School-admin corrections + B2B verified-listing capture
   ------------------------------------------------------------
   A school staffer can propose a correction to their listing.
   Every submission does THREE things:
     1. Files a PENDING correction (school_corrections table) — never
        goes live until you review it; shown alongside federal data,
        never silently replacing it.
     2. Captures the institution as a B2B lead (captureLead type
        "institution") — the start of the verified-listing pipeline.
     3. Queues an outreach flag so admissions/marketing can be
        introduced to the paid verified-listing program.

   Trust rule: a source URL is REQUIRED. We surface school-submitted
   facts as "School-verified · sourced", reviewed, with provenance —
   so this improves data integrity instead of becoming marketing spin.
   ============================================================ */

const CORRECTION_FIELDS = [
  { key: "cost", label: "Tuition, fees & net price" },
  { key: "programs", label: "Program offerings" },
  { key: "accreditation", label: "Accreditation status" },
  { key: "ownership", label: "Ownership / nonprofit status" },
  { key: "grants", label: "Institutional grants & scholarships" },
  { key: "outcomes", label: "Completion / earnings / outcomes" },
  { key: "other", label: "Something else" },
];

async function submitCorrection(data) {
  const cfg = window.B4IOU_CONFIG || {};
  const SB = cfg.SUPABASE || {};
  const row = {
    scorecard_id: data.scorecardId != null ? data.scorecardId : null,
    school_name: data.schoolName || null,
    field: data.field || "other",
    current_value: data.currentValue || null,
    proposed_value: data.proposedValue || null,
    source_url: data.sourceUrl || null,
    explanation: data.explanation || null,
    submitter_name: data.name || null,
    submitter_email: data.email || null,
    submitter_title: data.title || null,
    submitter_department: data.department || null,
    status: "pending",
    outreach_status: "queued",
    created_at: new Date().toISOString(),
  };

  // 2 + 3: capture the institution as a B2B lead + queue outreach (never blocks UI)
  try {
    if (window.captureLead) window.captureLead({
      lead_type: "institution",
      email: data.email,
      name: data.name,
      schools: [{ name: data.schoolName, scorecard_id: data.scorecardId }],
      source_step: "school-correction",
      institution_role: [data.title, data.department].filter(Boolean).join(" · ") || null,
      verified_listing_interest: true,
    });
  } catch (e) {}

  // 1: file the pending correction
  if (!SB.enabled || !SB.url || !SB.anonKey) return { ok: true, stored: "local" };
  try {
    const r = await fetch(SB.url.replace(/\/$/, "") + "/rest/v1/" + (SB.correctionsTable || "school_corrections"), {
      method: "POST",
      headers: {
        "content-type": "application/json",
        apikey: SB.anonKey,
        authorization: "Bearer " + SB.anonKey,
        prefer: "return=minimal",
      },
      body: JSON.stringify(row),
    });
    if (!r.ok) throw new Error("corrections " + r.status);
    return { ok: true, stored: "remote" };
  } catch (e) {
    return { ok: false, error: String((e && e.message) || e), stored: "local" };
  }
}

/* small input used inside the modal */
function CField({ label, children, hint }) {
  return (
    <label className="cf">
      <span className="cf-l">{label}</span>
      {children}
      {hint && <span className="cf-h">{hint}</span>}
    </label>
  );
}

function CorrectionModal({ school, onClose }) {
  const [field, setField] = useState("cost");
  const [proposedValue, setProposedValue] = useState("");
  const [sourceUrl, setSourceUrl] = useState("");
  const [explanation, setExplanation] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [title, setTitle] = useState("");
  const [department, setDepartment] = useState("");
  const [sending, setSending] = useState(false);
  const [done, setDone] = useState(false);

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

  const urlOk = /^https?:\/\/.+\..+/.test(sourceUrl.trim());
  const emailOk = /.+@.+\..+/.test(email.trim());
  const eduEmail = /\.edu(\.|$|\/)/i.test(email.trim()) || /\.edu$/i.test((email.split("@")[1] || ""));
  const ready = proposedValue.trim() && urlOk && emailOk && name.trim() && !sending;

  async function send() {
    if (!ready) return;
    setSending(true);
    await submitCorrection({
      scorecardId: school.scorecardId, schoolName: school.name,
      field, proposedValue, sourceUrl, explanation,
      name, email, title, department,
    });
    setSending(false);
    setDone(true);
  }

  return (
    <div className="cm-overlay" onMouseDown={onClose}>
      <div className="cm" onMouseDown={(e) => e.stopPropagation()}>
        <button className="cm-x" onClick={onClose} aria-label="Close">✕</button>

        {done ? (
          <div className="cm-done">
            <div className="cm-done-ic"><Ico.check /></div>
            <h3>Thank you — submitted for review.</h3>
            <p>Your correction for <b>{school.name}</b> is queued. Once we verify it against your source, it appears as <b>“School-verified · sourced”</b> alongside the federal data — never replacing it silently.</p>
            <div className="cm-vl">
              <div className="cm-vl-h"><Ico.shield /> Want your full listing verified?</div>
              <p>B4IOU offers a <b>Verified Listing</b> program — your programs, real costs, grants, and accreditation kept current and badged. We'll email {email ? <b>{email}</b> : "your team"} with details.</p>
            </div>
            <button className="btn btn-accent btn-md" onClick={onClose}>Done</button>
          </div>
        ) : (
          <>
            <div className="cm-head">
              <div className="cm-eyebrow mono"><Ico.shield /> School correction</div>
              <h3>Improve {school.name}'s listing</h3>
              <p className="cm-sub">Spotted something the federal data gets wrong or misses? Tell us — with a source — and we'll review it. This is how schools keep their B4IOU listing accurate.</p>
            </div>

            <div className="cm-body">
              <CField label="What needs correcting?">
                <select className="input" value={field} onChange={(e) => setField(e.target.value)}>
                  {CORRECTION_FIELDS.map((f) => <option key={f.key} value={f.key}>{f.label}</option>)}
                </select>
              </CField>

              <CField label="The correct information" hint="e.g. “In-state tuition is $14,200/yr for 2025–26” or “We offer a BSN, not just an ADN.”">
                <textarea className="input cm-ta" value={proposedValue} onChange={(e) => setProposedValue(e.target.value)} placeholder="State the accurate fact plainly." rows={3} />
              </CField>

              <CField label="Source link (required)" hint={urlOk ? "" : "A public URL we can verify — your tuition page, catalog, 990, or accreditor listing."}>
                <input className={`input ${sourceUrl && !urlOk ? "cm-bad" : ""}`} value={sourceUrl} onChange={(e) => setSourceUrl(e.target.value)} placeholder="https://yourschool.edu/tuition" />
              </CField>

              <CField label="Anything else? (optional)">
                <input className="input" value={explanation} onChange={(e) => setExplanation(e.target.value)} placeholder="Context that helps us review faster." />
              </CField>

              <div className="cm-divider"><span>About you</span></div>

              <div className="cm-row">
                <CField label="Your name"><input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="Jordan Lee" /></CField>
                <CField label="Work email" hint={email && !emailOk ? "Enter a valid email." : (emailOk && eduEmail ? "✓ School email — speeds verification." : "A .edu email speeds review.")}>
                  <input className={`input ${email && !emailOk ? "cm-bad" : ""}`} value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@yourschool.edu" />
                </CField>
              </div>
              <div className="cm-row">
                <CField label="Title (optional)"><input className="input" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Director of Admissions" /></CField>
                <CField label="Department (optional)"><input className="input" value={department} onChange={(e) => setDepartment(e.target.value)} placeholder="Enrollment / Marketing" /></CField>
              </div>

              <button className="btn btn-accent btn-lg" disabled={!ready} onClick={send}>
                {sending ? "Submitting…" : "Submit correction for review"}
              </button>
              <p className="cm-fine">Reviewed before anything changes. We may contact you to verify and to introduce B4IOU's Verified Listing program.</p>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

/* the entry-point link shown on each school card in the report */
function CorrectionLink({ school }) {
  const [open, setOpen] = useState(false);
  const short = (school.name || "").split(/\s*[-–]\s*/)[0];
  return (
    <>
      <button className="correction-link" onClick={() => setOpen(true)}>
        <Ico.shield /> Work at {short}? Suggest a correction
      </button>
      {open && <CorrectionModal school={school} onClose={() => setOpen(false)} />}
    </>
  );
}

Object.assign(window, { submitCorrection, CorrectionModal, CorrectionLink });
