/* ============================================================
   Registration — multi-step form for Delegates and Observers.
   Submits to Firebase Cloud Firestore › registrations (create-only).
   ============================================================ */
const { useState: useStateR, useEffect: useEffectR, useRef: useRefR } = React;

const DELEGATE_STEPS = ["Details", "Preferences", "Review"];
const OBSERVER_STEPS = ["Details", "Review"];
const STORE_KEY = "bmun_reg_v3";

/* Pass tiers — keep fee + inclusions in one place so the aside and review stay in sync. */
const PASSES = {
  delegate: {
    type: "Delegate",
    pass: "Delegate Pass",
    eyebrow: "Delegate Pass",
    fee: 4000,
    headline: <>One pass.<br />Three days.</>,
    note: "per delegate · all three days included",
    incl: [
      "Committee placement & study guides",
      "Delegate ID card & certificate",
      "Refreshments across all 3 days",
      "Formal dinner & Social Event",
      "Pre-conference workshop",
      "Awards & closing ceremony",
    ],
  },
  observer: {
    type: "Observer",
    pass: "Observer Pass",
    eyebrow: "Observer Pass",
    fee: 2000,
    headline: <>Watch it<br />unfold.</>,
    note: "per observer · all three days included",
    incl: [
      "Observer seating in every committee",
      "Watch all six committees debate",
      "Refreshments across all 3 days",
      "Formal dinner & Social Event",
      "Certificate of attendance",
      "Entry to the closing ceremony",
    ],
  },
};

const blankForm = {
  type: "delegate",
  fullName: "",
  email: "",
  phone: "",
  age: "",
  grade: "",
  institution: "",
  city: "",
  experience: "",
  pref1: "",
  pref2: "",
  pref3: "",
  heard: "",
  payment: "",
  consent: false,
};

const PAY = [
  { id: "bank", label: "Bank Transfer", desc: "Direct deposit / IBFT to our account." },
  { id: "jazzcash", label: "JazzCash", desc: "Mobile wallet transfer." },
  { id: "easypaisa", label: "EasyPaisa", desc: "Mobile wallet transfer." },
];

/* Reject if a Firebase call neither resolves nor rejects in time, so the
   Submit button can never get stuck on "Submitting…". */
const withTimeout = (promise, ms, label) => Promise.race([
  promise,
  new Promise((_, reject) => setTimeout(() => reject(new Error(`${label} timed out`)), ms)),
]);

/* ---- Age document → embedded in the registration (no Cloud Storage needed) ----
   We compress photos in the browser and store them as a data URL on the
   Firestore document. Firestore caps a document at ~1 MB, so we keep the
   encoded image comfortably under that. */
const readAsDataURL = (file) => new Promise((res, rej) => {
  const r = new FileReader();
  r.onload = () => res(r.result);
  r.onerror = () => rej(new Error("read failed"));
  r.readAsDataURL(file);
});
const loadImage = (src) => new Promise((res, rej) => {
  const i = new Image();
  i.onload = () => res(i);
  i.onerror = () => rej(new Error("decode failed"));
  i.src = src;
});
const dataUrlBytes = (u) => Math.ceil((u.length - (u.indexOf(",") + 1)) * 0.75);

async function buildAgeProof(file) {
  if (!file) throw new Error("NO_FILE");
  // PDFs can't be recompressed  keep small ones as-is, otherwise ask for a photo.
  if (file.type === "application/pdf") {
    if (file.size > 850 * 1024) throw new Error("PDF_TOO_LARGE");
    const dataUrl = await readAsDataURL(file);
    return { url: dataUrl, name: file.name, contentType: file.type, size: file.size };
  }
  // Images: downscale + JPEG-compress until under the size budget.
  const img = await loadImage(await readAsDataURL(file));
  const LIMIT = 650 * 1024;
  let best = null;
  for (const maxDim of [1500, 1200, 950, 750]) {
    const scale = Math.min(1, maxDim / Math.max(img.width, img.height));
    const w = Math.max(1, Math.round(img.width * scale));
    const h = Math.max(1, Math.round(img.height * scale));
    const cv = document.createElement("canvas");
    cv.width = w; cv.height = h;
    const ctx = cv.getContext("2d");
    ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, w, h);
    ctx.drawImage(img, 0, 0, w, h);
    for (const q of [0.75, 0.6, 0.45]) {
      const out = cv.toDataURL("image/jpeg", q);
      const sz = dataUrlBytes(out);
      if (!best || sz < best.size) best = { url: out, size: sz };
      if (sz <= LIMIT) {
        return { url: out, name: (file.name || "document").replace(/\.[^.]+$/, "") + ".jpg", contentType: "image/jpeg", size: sz };
      }
    }
  }
  if (best) return { url: best.url, name: "document.jpg", contentType: "image/jpeg", size: best.size };
  throw new Error("COMPRESS_FAILED");
}

/* Friendlier message for the most common setup mistakes. */
const friendlyError = (err, kind) => {
  const code = (err && (err.code || err.message)) || "";
  if (/permission|unauthor|denied|insufficient/i.test(code)) {
    return kind === "upload"
      ? "Your document couldn't be saved,  uploads are currently blocked. Please contact us so we can fix it."
      : "Your registration couldn't be saved,  submissions are currently blocked. Please contact us so we can fix it.";
  }
  if (/timed out|network|unavailable|offline/i.test(code)) {
    return "The connection timed out. Please check your internet and try again.";
  }
  return kind === "upload"
    ? "We couldn't upload your age document just now. Please try again."
    : "We couldn't submit your registration just now. Please try again.";
};

function Registration({ innerRef }) {
  const [form, setForm] = useStateR(() => {
    try {
      const saved = localStorage.getItem(STORE_KEY);
      return saved ? { ...blankForm, ...JSON.parse(saved) } : blankForm;
    } catch { return blankForm; }
  });
  const [step, setStep] = useStateR(0);
  const [errors, setErrors] = useStateR({});
  const [done, setDone] = useStateR(false);
  const [code, setCode] = useStateR("");
  const [submitting, setSubmitting] = useStateR(false);
  const [submitErr, setSubmitErr] = useStateR("");
  // Age-proof document is held in memory only (File objects can't be persisted to localStorage).
  const [ageProof, setAgeProof] = useStateR(null);
  const topRef = useRefR(null);

  const MAX_PROOF_BYTES = 8 * 1024 * 1024; // 8 MB

  const isObserver = form.type === "observer";
  const STEPS = isObserver ? OBSERVER_STEPS : DELEGATE_STEPS;
  const pass = PASSES[form.type] || PASSES.delegate;
  const stepName = STEPS[step];

  useEffectR(() => {
    try { localStorage.setItem(STORE_KEY, JSON.stringify(form)); } catch {}
  }, [form]);

  const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); setErrors(e => ({ ...e, [k]: undefined })); };

  const onProofPick = (file) => {
    if (!file) { setAgeProof(null); return; }
    const okType = /^(image\/|application\/pdf)/.test(file.type);
    if (!okType) { setErrors(e => ({ ...e, ageProof: "Upload an image or PDF." })); setAgeProof(null); return; }
    if (file.size > MAX_PROOF_BYTES) { setErrors(e => ({ ...e, ageProof: "File must be under 8 MB." })); setAgeProof(null); return; }
    setAgeProof(file);
    setErrors(e => ({ ...e, ageProof: undefined }));
  };

  /* Switching pass type restarts the flow so step indices never fall out of range. */
  const setType = (t) => {
    if (t === form.type) return;
    setForm(f => ({ ...f, type: t }));
    setStep(0);
    setErrors({});
    setSubmitErr("");
  };

  const validate = (name) => {
    const e = {};
    const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const phoneRe = /^[0-9+\s\-()]{7,}$/;
    if (name === "Details") {
      if (!form.fullName.trim()) e.fullName = "Required.";
      if (!emailRe.test(form.email)) e.email = "Enter a valid email.";
      if (!phoneRe.test(form.phone)) e.phone = "Enter a valid phone number.";
      if (!form.age || +form.age < 10 || +form.age > 19) e.age = "BMUN is open to ages 19 and below.";
      if (!form.grade.trim()) e.grade = "Required.";
      if (!form.institution.trim()) e.institution = "Required.";
      if (!ageProof) e.ageProof = "Please upload a document to verify your age.";
      // Observers have no Preferences step, so collect "how did you hear" here.
      if (isObserver && !form.heard) e.heard = "Let us know how you heard about us.";
    }
    if (name === "Preferences") {
      if (!form.experience) e.experience = "Pick your experience level.";
      if (!form.pref1) e.pref1 = "Choose a first preference.";
      if (!form.pref2) e.pref2 = "Choose a second preference.";
      if (!form.pref3) e.pref3 = "Choose a third preference.";
      const prefs = [form.pref1, form.pref2, form.pref3].filter(Boolean);
      if (new Set(prefs).size !== prefs.length) e.pref3 = "Pick three different committees.";
      if (!form.heard) e.heard = "Let us know how you heard about us.";
    }
    if (name === "Review") {
      if (!form.payment) e.payment = "Select a payment method.";
      if (!form.consent) e.consent = "Please confirm to continue.";
    }
    return e;
  };

  const next = () => {
    const e = validate(stepName);
    setErrors(e);
    if (Object.keys(e).length) return;
    if (step < STEPS.length - 1) { setStep(step + 1); window.scrollTo({ top: window.scrollY }); }
    else submit();
  };
  const back = () => { if (step > 0) { setStep(step - 1); window.scrollTo({ top: window.scrollY }); } };

  const submit = async () => {
    if (submitting) return;
    setSubmitErr("");
    setSubmitting(true);
    const prefix = isObserver ? "BMUN-OBS-" : "BMUN-DEL-";
    const c = prefix + Math.random().toString(36).slice(2, 6).toUpperCase();
    const expLabel = (EXPERIENCE.find(x => x.id === form.experience) || {}).label || form.experience;
    const payLabel = (PAY.find(x => x.id === form.payment) || {}).label || form.payment;

    // Compress + embed the age document in the registration record (no Cloud Storage).
    let ageProofMeta = null;
    try {
      ageProofMeta = await buildAgeProof(ageProof);
    } catch (err) {
      console.error("BMUN age-proof processing failed", err);
      setSubmitErr(
        err.message === "PDF_TOO_LARGE"
          ? "Your PDF is too large to attach. Please upload a clear photo of your document instead."
          : "We couldn't process your document. Please upload a clear photo (JPG or PNG) and try again."
      );
      setSubmitting(false);
      return;
    }

    const payload = {
      ref: c,
      event: "BMUN 2026",
      registrationType: pass.type,
      passType: pass.pass,
      fee: pass.fee,
      fullName: form.fullName.trim(),
      email: form.email.trim(),
      phone: form.phone.trim(),
      age: form.age,
      grade: form.grade.trim(),
      institution: form.institution.trim(),
      city: form.city.trim(),
      experience: isObserver ? "" : expLabel,
      committeePreferences: isObserver ? [] : [form.pref1, form.pref2, form.pref3].filter(Boolean),
      heardFrom: form.heard,
      paymentMethod: payLabel,
      consent: !!form.consent,
      ageVerified: false, // set true by an organiser after they review the document
      ageProof: ageProofMeta,
    };
    try {
      let saver = window.bmunSaveRegistration;
      if (typeof saver !== "function") {
        await new Promise(r => setTimeout(r, 900));
        saver = window.bmunSaveRegistration;
      }
      if (typeof saver !== "function") throw new Error("Firebase not ready");
      await withTimeout(saver(payload), 30000, "Save");
      setCode(c);
      setDone(true);
      try { localStorage.removeItem(STORE_KEY); } catch {}
    } catch (err) {
      console.error("BMUN registration failed", err);
      setSubmitErr(friendlyError(err, "save"));
    } finally {
      setSubmitting(false);
    }
  };

  const resetAll = () => { setForm(blankForm); setStep(0); setDone(false); setErrors({}); setSubmitErr(""); setAgeProof(null); };

  const roleWord = isObserver ? "observer" : "delegate";

  return (
    <section className="section register" id="register" ref={innerRef}>
      <div className="wrap">
        <Reveal>
          <SectionHead center
            eyebrow="Registration"
            title="Claim your seat at the table."
            sub="Takes about three minutes. Your progress saves automatically, you can come back any time."
          />
        </Reveal>
        <Reveal>
          <div className="reg-shell" ref={topRef}>
            {/* ---- Aside ---- */}
            <aside className="reg-aside">
              <span className="eyebrow" style={{ color: "var(--gold-soft)" }}>{pass.eyebrow}</span>
              <h3 style={{ marginTop: 16 }}>{pass.headline}</h3>
              <div className="price">
                <span className="amt">{pass.fee.toLocaleString()}</span>
                <span className="cur">PKR</span>
              </div>
              <div className="price-note">{pass.note}</div>
              <ul className="reg-incl">
                {pass.incl.map(t => (
                  <li key={t}><Icon name="check" size={17} /> {t}</li>
                ))}
              </ul>
              <div className="pay-methods">
                <div className="label">Pay your way</div>
                <div className="pay-row">
                  <span className="pay-pill">Bank Transfer</span>
                  <span className="pay-pill">JazzCash</span>
                  <span className="pay-pill">EasyPaisa</span>
                </div>
                <p style={{ fontSize: 12.5, color: "#c9b08c", marginTop: 16, lineHeight: 1.5 }}>
                  Account details are shared after you submit. Your seat is confirmed once payment is verified.
                </p>
              </div>
            </aside>

            {/* ---- Form ---- */}
            <div className="reg-form">
              {done ? (
                <div className="reg-success">
                  <div className="seal"><Icon name="check" size={44} stroke={2.4} /></div>
                  <h3>You&rsquo;re on the list!</h3>
                  <p className="lead" style={{ marginTop: 14 }}>
                    Thank you, {form.fullName.split(" ")[0] || roleWord}. We&rsquo;ve recorded your {pass.pass.toLowerCase()} registration.
                    Our Delegate Affairs team will email you payment details and next steps shortly.
                  </p>
                  <div className="code">{code}</div>
                  <p className="hint" style={{ marginTop: 14 }}>NOTE THIS REFERENCE NUMBER, quote it when sending your payment receipt.</p>
                  <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 28, flexWrap: "wrap" }}>
                    <a className="btn btn-gold" href="https://wa.me/923063934558" target="_blank" rel="noopener">
                      <Icon name="whatsapp" size={18} /> Message us on WhatsApp
                    </a>
                    <button className="btn btn-ghost" onClick={resetAll}>Register someone else</button>
                  </div>
                </div>
              ) : (
                <>
                  {/* Pass-type selector */}
                  <div className="reg-type" role="tablist" aria-label="Choose a pass">
                    <button type="button" role="tab" aria-selected={!isObserver}
                      className={`reg-type-btn ${!isObserver ? "on" : ""}`} onClick={() => setType("delegate")}>
                      <Icon name="gavel" size={20} />
                      <span><strong>Delegate</strong><small>Debate &amp; represent · PKR 4,000</small></span>
                    </button>
                    <button type="button" role="tab" aria-selected={isObserver}
                      className={`reg-type-btn ${isObserver ? "on" : ""}`} onClick={() => setType("observer")}>
                      <Icon name="users" size={20} />
                      <span><strong>Observer</strong><small>Watch &amp; learn · PKR 2,000</small></span>
                    </button>
                  </div>

                  {/* Stepper */}
                  <div className="stepper">
                    {STEPS.map((s, i) => (
                      <React.Fragment key={s}>
                        <div className={`step-node ${i === step ? "active" : ""} ${i < step ? "done" : ""}`}>
                          <span className="step-dot">{i < step ? <Icon name="check" size={15} stroke={2.4} /> : i + 1}</span>
                          <span className="step-name">{s}</span>
                        </div>
                        {i < STEPS.length - 1 && <span className={`step-line ${i < step ? "filled" : ""}`} />}
                      </React.Fragment>
                    ))}
                  </div>

                  {/* STEP — DETAILS */}
                  {stepName === "Details" && (
                    <div>
                      <h3 className="display h-md" style={{ marginBottom: 6 }}>Your details</h3>
                      <p className="muted" style={{ fontSize: 15, marginBottom: 22 }}>
                        {isObserver
                          ? "Observers get a front-row seat to every committee, no preparation required. Just bring your curiosity."
                          : "First time at an MUN? No worries, every committee welcomes beginners, and you’ll get study guides plus a workshop before the conference."}
                      </p>
                      <div className="field">
                        <label>Full name <span className="req">*</span></label>
                        <input className={`input ${errors.fullName ? "err" : ""}`} placeholder="e.g. Ayesha Baloch"
                          value={form.fullName} onChange={e => set("fullName", e.target.value)} />
                        {errors.fullName && <div className="err-msg">{errors.fullName}</div>}
                      </div>
                      <div className="field-row">
                        <div className="field">
                          <label>Email <span className="req">*</span></label>
                          <input className={`input ${errors.email ? "err" : ""}`} type="email" placeholder="you@email.com"
                            value={form.email} onChange={e => set("email", e.target.value)} />
                          {errors.email && <div className="err-msg">{errors.email}</div>}
                        </div>
                        <div className="field">
                          <label>Phone / WhatsApp <span className="req">*</span></label>
                          <input className={`input ${errors.phone ? "err" : ""}`} placeholder="+92 3xx xxxxxxx"
                            value={form.phone} onChange={e => set("phone", e.target.value)} />
                          {errors.phone && <div className="err-msg">{errors.phone}</div>}
                        </div>
                      </div>
                      <div className="field-row">
                        <div className="field">
                          <label>Age <span className="req">*</span></label>
                          <input className={`input ${errors.age ? "err" : ""}`} type="number" min="10" max="19" placeholder="e.g. 17"
                            value={form.age} onChange={e => set("age", e.target.value)} />
                          {errors.age && <div className="err-msg">{errors.age}</div>}
                        </div>
                        <div className="field">
                          <label>Grade / Year <span className="req">*</span></label>
                          <input className={`input ${errors.grade ? "err" : ""}`} placeholder="e.g. Grade 11 / 1st year"
                            value={form.grade} onChange={e => set("grade", e.target.value)} />
                          {errors.grade && <div className="err-msg">{errors.grade}</div>}
                        </div>
                      </div>
                      <div className="field-row">
                        <div className="field">
                          <label>School / Institution <span className="req">*</span></label>
                          <input className={`input ${errors.institution ? "err" : ""}`} placeholder="e.g. TCS Quetta Campus"
                            value={form.institution} onChange={e => set("institution", e.target.value)} />
                          {errors.institution && <div className="err-msg">{errors.institution}</div>}
                        </div>
                        <div className="field">
                          <label>City</label>
                          <input className="input" placeholder="e.g. Quetta"
                            value={form.city} onChange={e => set("city", e.target.value)} />
                        </div>
                      </div>

                      {/* Age-verification document — BMUN is open to ages 20 and below. */}
                      <div className="field">
                        <label>Age verification document <span className="req">*</span></label>
                        <p className="hint" style={{ marginTop: -2, marginBottom: 12 }}>
                          BMUN is open to participants aged 19 and below. Upload your CNIC, B-Form, or passport
                          (image or PDF, up to 8&nbsp;MB) so our team can verify your age. University Students are not allowed even if below age limit.
                        </p>
                        <label className={`upload ${errors.ageProof ? "err" : ""} ${ageProof ? "has-file" : ""}`}>
                          <input type="file" accept="image/*,application/pdf" hidden
                            onChange={e => onProofPick(e.target.files && e.target.files[0])} />
                          <span className="upload-ic"><Icon name={ageProof ? "check" : "plus"} size={20} stroke={2.2} /></span>
                          <span className="upload-text">
                            {ageProof
                              ? <><strong>{ageProof.name}</strong><small>{(ageProof.size / 1024 / 1024).toFixed(2)} MB · tap to replace</small></>
                              : <><strong>Choose a file</strong><small>CNIC · B-Form · Passport image or PDF</small></>}
                          </span>
                        </label>
                        {errors.ageProof && <div className="err-msg">{errors.ageProof}</div>}
                      </div>

                      {isObserver && (
                        <div className="field" style={{ marginTop: 4 }}>
                          <label>How did you hear about BMUN? <span className="req">*</span></label>
                          <select className={`select ${errors.heard ? "err" : ""}`} value={form.heard} onChange={e => set("heard", e.target.value)}>
                            <option value="">Select one…</option>
                            {HEARD.map(h => <option key={h} value={h}>{h}</option>)}
                          </select>
                          {errors.heard && <div className="err-msg">{errors.heard}</div>}
                        </div>
                      )}
                    </div>
                  )}

                  {/* STEP — PREFERENCES (delegates only) */}
                  {stepName === "Preferences" && (
                    <div>
                      <h3 className="display h-md" style={{ marginBottom: 18 }}>Committee preferences</h3>
                      <div className="field">
                        <label>MUN experience <span className="req">*</span></label>
                        <div className="choice-grid">
                          {EXPERIENCE.map(x => (
                            <button key={x.id} className={`choice ${form.experience === x.id ? "on" : ""}`} onClick={() => set("experience", x.id)}>
                              <span className="radio" />
                              <span className="ctext"><h5>{x.label}</h5><p>{x.desc}</p></span>
                            </button>
                          ))}
                        </div>
                        {errors.experience && <div className="err-msg">{errors.experience}</div>}
                      </div>
                      <div className="field" style={{ marginTop: 26 }}>
                        <label>Rank your top three committees <span className="req">*</span></label>
                        <p className="hint" style={{ marginTop: -2, marginBottom: 14 }}>Pick three different committees. We place every delegate in one of their choices wherever possible.</p>
                        {[["pref1", "1st"], ["pref2", "2nd"], ["pref3", "3rd"]].map(([k, rank]) => (
                          <div className="pref-row" key={k}>
                            <span className="rank">{rank} choice</span>
                            <select className={`select ${errors[k] ? "err" : ""}`} value={form[k]} onChange={e => set(k, e.target.value)}>
                              <option value="">Select a committee…</option>
                              {COMMITTEES.map(c => <option key={c.abbr} value={c.abbr}>{c.abbr} — {c.name}</option>)}
                            </select>
                          </div>
                        ))}
                        {(errors.pref1 || errors.pref2 || errors.pref3) && (
                          <div className="err-msg">{errors.pref3 || errors.pref1 || errors.pref2}</div>
                        )}
                      </div>
                      <div className="field" style={{ marginTop: 26 }}>
                        <label>How did you hear about BMUN? <span className="req">*</span></label>
                        <select className={`select ${errors.heard ? "err" : ""}`} value={form.heard} onChange={e => set("heard", e.target.value)}>
                          <option value="">Select one…</option>
                          {HEARD.map(h => <option key={h} value={h}>{h}</option>)}
                        </select>
                        {errors.heard && <div className="err-msg">{errors.heard}</div>}
                      </div>
                    </div>
                  )}

                  {/* STEP — REVIEW */}
                  {stepName === "Review" && (
                    <div>
                      <h3 className="display h-md" style={{ marginBottom: 18 }}>Review &amp; confirm</h3>
                      <div className="review-list">
                        <div className="review-item"><span className="k">Pass</span><span className="v">{pass.pass}</span></div>
                        <div className="review-item"><span className="k">Name</span><span className="v">{form.fullName}</span></div>
                        <div className="review-item"><span className="k">Email</span><span className="v">{form.email}</span></div>
                        <div className="review-item"><span className="k">Phone</span><span className="v">{form.phone}</span></div>
                        <div className="review-item"><span className="k">Age / Grade</span><span className="v">{form.age} · {form.grade}</span></div>
                        <div className="review-item"><span className="k">Institution</span><span className="v">{form.institution}{form.city ? ` · ${form.city}` : ""}</span></div>
                        <div className="review-item"><span className="k">Age document</span><span className="v">{ageProof ? ageProof.name : "—"}</span></div>
                        {!isObserver && (
                          <div className="review-item"><span className="k">Committee choices</span><span className="v">{[form.pref1, form.pref2, form.pref3].filter(Boolean).join(" · ")}</span></div>
                        )}
                        <div className="review-item"><span className="k">Fee due</span><span className="v">PKR {pass.fee.toLocaleString()}</span></div>
                      </div>

                      <div className="field" style={{ marginTop: 26 }}>
                        <label>Preferred payment method <span className="req">*</span></label>
                        <div className="choice-grid c2">
                          {PAY.map(p => (
                            <button key={p.id} className={`choice ${form.payment === p.id ? "on" : ""}`} onClick={() => set("payment", p.id)}>
                              <span className="radio" />
                              <span className="ctext"><h5>{p.label}</h5><p>{p.desc}</p></span>
                            </button>
                          ))}
                        </div>
                        {errors.payment && <div className="err-msg">{errors.payment}</div>}
                      </div>

                      <label className="consent">
                        <input type="checkbox" checked={form.consent} onChange={e => set("consent", e.target.checked)} />
                        <span>I confirm the information above is accurate and I agree to abide by the BMUN Code of Conduct throughout the conference.</span>
                      </label>
                      {errors.consent && <div className="err-msg" style={{ marginTop: 8 }}>{errors.consent}</div>}
                      {submitErr && <div className="err-msg" style={{ marginTop: 12 }}>{submitErr}</div>}
                    </div>
                  )}

                  {/* Nav */}
                  <div className="form-nav">
                    {step > 0
                      ? <button className="btn btn-ghost" onClick={back} disabled={submitting}><Icon name="arrowLeft" size={18} /> Back</button>
                      : <span style={{ fontSize: 13.5, color: "var(--muted-2)" }}>Step {step + 1} of {STEPS.length}</span>}
                    <button className="btn btn-primary" onClick={next} disabled={submitting}>
                      {step === STEPS.length - 1 ? (submitting ? "Submitting…" : "Submit Registration") : "Continue"} <Icon name="arrowRight" size={18} />
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

window.Registration = Registration;

/* ============================================================
   Pay Fee portal — a delegate enters their reference code; we look the
   registration up in Firestore and only reveal payment details once an
   organiser has flipped `ageVerified` to true. Until then we show the
   "wait for verification" message.
   ============================================================ */
function PaymentPortal({ innerRef }) {
  const [codeIn, setCodeIn] = useStateR("");
  // status: idle | loading | verified | pending | notfound | error
  const [status, setStatus] = useStateR("idle");
  const [reg, setReg] = useStateR(null);
  const [errMsg, setErrMsg] = useStateR("");
  // On-site payment submission (only shown once age is verified).
  const [payFile, setPayFile] = useStateR(null);
  const [payMethod, setPayMethod] = useStateR("");
  const [paySubmitting, setPaySubmitting] = useStateR(false);
  const [paySubmitErr, setPaySubmitErr] = useStateR("");
  const [payDone, setPayDone] = useStateR(false);
  const PAY_MAX_BYTES = 8 * 1024 * 1024; // 8 MB

  const check = async () => {
    const code = codeIn.trim().toUpperCase();
    if (!code) { setStatus("error"); setErrMsg("Enter the reference code from your registration (e.g. BMUN-DEL-AB12)."); return; }
    setStatus("loading");
    setErrMsg("");
    setReg(null);
    try {
      let fetcher = window.bmunFetchRegistration;
      if (typeof fetcher !== "function") {
        await new Promise(r => setTimeout(r, 900));
        fetcher = window.bmunFetchRegistration;
      }
      if (typeof fetcher !== "function") throw new Error("Lookup not ready");
      const record = await withTimeout(fetcher(code), 30000, "Lookup");
      if (!record) { setStatus("notfound"); return; }
      setReg(record);
      setStatus(record.ageVerified ? "verified" : "pending");
    } catch (err) {
      console.error("BMUN payment lookup failed", err);
      setStatus("error");
      setErrMsg(
        /timed out|network|unavailable|offline/i.test(err.message || "")
          ? "The connection timed out. Please check your internet and try again."
          : "We couldn't look up your registration just now. Please try again in a moment."
      );
    }
  };

  const onKey = (e) => { if (e.key === "Enter") check(); };
  const resetPay = () => { setPayFile(null); setPayMethod(""); setPaySubmitErr(""); setPayDone(false); };
  const reset = () => { setStatus("idle"); setReg(null); setErrMsg(""); resetPay(); };

  const onPayPick = (file) => {
    if (!file) { setPayFile(null); return; }
    const okType = /^(image\/|application\/pdf)/.test(file.type);
    if (!okType) { setPaySubmitErr("Upload an image or PDF of your payment screenshot."); setPayFile(null); return; }
    if (file.size > PAY_MAX_BYTES) { setPaySubmitErr("File must be under 8 MB."); setPayFile(null); return; }
    setPayFile(file);
    setPaySubmitErr("");
  };

  const submitPayment = async () => {
    if (paySubmitting || !reg) return;
    if (!payFile) { setPaySubmitErr("Please attach a screenshot of your payment."); return; }
    setPaySubmitErr("");
    setPaySubmitting(true);
    // Reuse the registration image compressor so the screenshot fits in one doc.
    let proof;
    try {
      proof = await buildAgeProof(payFile);
    } catch (err) {
      console.error("BMUN payment-proof processing failed", err);
      setPaySubmitErr(
        err.message === "PDF_TOO_LARGE"
          ? "Your PDF is too large to attach. Please upload a clear screenshot instead."
          : "We couldn't process that file. Please upload a clear screenshot (JPG or PNG) and try again."
      );
      setPaySubmitting(false);
      return;
    }
    const methodLabel = (PAY.find(x => x.id === payMethod) || {}).label || payMethod || "";
    const payload = {
      ref: reg.ref,
      registrationId: reg.id || "",
      fullName: reg.fullName || "",
      email: reg.email || "",
      passType: reg.passType || "",
      fee: typeof reg.fee !== "undefined" ? reg.fee : "",
      paymentMethod: methodLabel,
      paymentProof: proof,
      status: "submitted", // organiser flips this once they confirm the payment
    };
    try {
      let saver = window.bmunSavePayment;
      if (typeof saver !== "function") {
        await new Promise(r => setTimeout(r, 900));
        saver = window.bmunSavePayment;
      }
      if (typeof saver !== "function") throw new Error("Firebase not ready");
      await withTimeout(saver(payload), 30000, "Payment save");
      setPayDone(true);
    } catch (err) {
      console.error("BMUN payment submission failed", err);
      setPaySubmitErr(friendlyError(err, "save"));
    } finally {
      setPaySubmitting(false);
    }
  };

  const waLink = reg
    ? `https://wa.me/${PAYMENT_RECEIPT_WHATSAPP}?text=${encodeURIComponent(
        `Hi BMUN, I'm sending my payment receipt for registration ${reg.ref} (${reg.fullName || ""}).`)}`
    : `https://wa.me/${PAYMENT_RECEIPT_WHATSAPP}`;

  return (
    <section className="section pay-portal" id="payment" ref={innerRef}>
      <div className="wrap">
        <Reveal>
          <SectionHead center
            eyebrow="Pay Fee"
            title="Already registered? Pay your fee here."
            sub="Enter the reference code you received when you registered. Once our team has verified your age, your payment details appear here."
          />
        </Reveal>
        <Reveal>
          <div className="pay-card">
            {/* ---- Lookup ---- */}
            <div className="pay-lookup">
              <div className="field" style={{ marginBottom: 0, flex: 1 }}>
                <label>Registration reference code <span className="req">*</span></label>
                <input
                  className={`input ${status === "error" ? "err" : ""}`}
                  placeholder="BMUN-DEL-AB12"
                  value={codeIn}
                  onChange={e => { setCodeIn(e.target.value); if (status !== "idle" && status !== "loading") reset(); }}
                  onKeyDown={onKey}
                  autoComplete="off"
                  spellCheck="false"
                />
              </div>
              <button className="btn btn-primary" onClick={check} disabled={status === "loading"}>
                {status === "loading" ? "Checking…" : <>Check status <Icon name="arrowRight" size={18} /></>}
              </button>
            </div>
            {status === "error" && errMsg && <div className="err-msg" style={{ marginTop: 12 }}>{errMsg}</div>}

            {/* ---- Not found ---- */}
            {status === "notfound" && (
              <div className="pay-state pay-state--warn">
                <span className="pay-state-ic"><Icon name="plus" size={26} stroke={2.2} style={{ transform: "rotate(45deg)" }} /></span>
                <div>
                  <h4>No registration found</h4>
                  <p>We couldn&rsquo;t find a registration with that reference code. Double-check the code from your confirmation, or reach out on WhatsApp if you think this is a mistake.</p>
                  <a className="btn btn-ghost" href={`https://wa.me/${PAYMENT_RECEIPT_WHATSAPP}`} target="_blank" rel="noopener" style={{ marginTop: 14 }}>
                    <Icon name="whatsapp" size={18} /> Message us
                  </a>
                </div>
              </div>
            )}

            {/* ---- Pending age verification ---- */}
            {status === "pending" && reg && (
              <div className="pay-state pay-state--pending">
                <span className="pay-state-ic"><Icon name="clock" size={26} /></span>
                <div>
                  <h4>Hang tight, {(reg.fullName || "delegate").split(" ")[0]} — your age isn&rsquo;t verified yet</h4>
                  <p>
                    Wait for your age to be verified. <strong>You&rsquo;ll receive an email once it is</strong>, and then
                    you can come back here to view your payment details and complete your registration.
                  </p>
                </div>
              </div>
            )}

            {/* ---- Verified → show details + payment ---- */}
            {status === "verified" && reg && (
              <div className="pay-result">
                <div className="pay-verified-banner">
                  <span className="pay-state-ic ok"><Icon name="check" size={24} stroke={2.4} /></span>
                  <div>
                    <h4>Age verified - you&rsquo;re cleared to pay</h4>
                    <p>Welcome back, {(reg.fullName || "delegate").split(" ")[0]}. Here are your details and how to send your fee.</p>
                  </div>
                </div>

                <div className="review-list" style={{ marginTop: 22 }}>
                  <div className="review-item"><span className="k">Reference</span><span className="v">{reg.ref}</span></div>
                  <div className="review-item"><span className="k">Name</span><span className="v">{reg.fullName}</span></div>
                  {reg.passType && <div className="review-item"><span className="k">Pass</span><span className="v">{reg.passType}</span></div>}
                  {reg.institution && <div className="review-item"><span className="k">Institution</span><span className="v">{reg.institution}</span></div>}
                  {Array.isArray(reg.committeePreferences) && reg.committeePreferences.length > 0 && (
                    <div className="review-item"><span className="k">Committee choices</span><span className="v">{reg.committeePreferences.join(" · ")}</span></div>
                  )}
                  {typeof reg.fee !== "undefined" && (
                    <div className="review-item"><span className="k">Fee due</span><span className="v">PKR {Number(reg.fee).toLocaleString()}</span></div>
                  )}
                </div>

                <h5 className="pay-subhead">Send your fee to any one of these</h5>
                <div className="pay-accounts">
                  {(window.PAYMENT_ACCOUNTS || []).map(acc => (
                    <div className="pay-acc" key={acc.method}>
                      <div className="pay-acc-head">
                        <span className="pay-acc-ic"><Icon name={acc.icon || "book"} size={18} /></span>
                        <strong>{acc.title}</strong>
                      </div>
                      <dl className="pay-acc-lines">
                        {acc.lines.map(([k, v]) => (
                          <div key={k}><dt>{k}</dt><dd>{v}</dd></div>
                        ))}
                      </dl>
                    </div>
                  ))}
                </div>

                {payDone ? (
                  <div className="pay-submitted">
                    <span className="pay-state-ic ok"><Icon name="check" size={24} stroke={2.4} /></span>
                    <div>
                      <h4>Payment submitted - thank you!</h4>
                      <p>
                        We&rsquo;ve received your payment for reference <strong>{reg.ref}</strong>. Our team will
                        verify it and confirm your seat shortly. You can close this page.
                      </p>
                      <button className="btn btn-ghost" style={{ marginTop: 14 }} onClick={() => { setCodeIn(""); reset(); }}>
                        Submit for another code
                      </button>
                    </div>
                  </div>
                ) : (
                  <div className="pay-submit">
                    <h5 className="pay-subhead">Submit your payment</h5>
                    <p className="pay-note" style={{ marginTop: 0 }}>
                      Once you&rsquo;ve paid, upload a screenshot of your receipt here. It&rsquo;s linked to your
                      reference <strong>{reg.ref}</strong>, and your seat is confirmed once we verify it.
                    </p>

                    <div className="field" style={{ marginTop: 18 }}>
                      <label>Payment method used</label>
                      <div className="choice-grid c2">
                        {PAY.map(p => (
                          <button key={p.id} type="button" className={`choice ${payMethod === p.id ? "on" : ""}`} onClick={() => setPayMethod(p.id)}>
                            <span className="radio" />
                            <span className="ctext"><h5>{p.label}</h5><p>{p.desc}</p></span>
                          </button>
                        ))}
                      </div>
                    </div>

                    <div className="field">
                      <label>Payment screenshot <span className="req">*</span></label>
                      <label className={`upload ${paySubmitErr && !payFile ? "err" : ""} ${payFile ? "has-file" : ""}`}>
                        <input type="file" accept="image/*,application/pdf" hidden
                          onChange={e => onPayPick(e.target.files && e.target.files[0])} />
                        <span className="upload-ic"><Icon name={payFile ? "check" : "plus"} size={20} stroke={2.2} /></span>
                        <span className="upload-text">
                          {payFile
                            ? <><strong>{payFile.name}</strong><small>{(payFile.size / 1024 / 1024).toFixed(2)} MB · tap to replace</small></>
                            : <><strong>Choose a file</strong><small>Receipt / transfer confirmation image or PDF</small></>}
                        </span>
                      </label>
                    </div>

                    {paySubmitErr && <div className="err-msg" style={{ marginTop: 4 }}>{paySubmitErr}</div>}

                    <div className="pay-actions">
                      <button className="btn btn-primary" onClick={submitPayment} disabled={paySubmitting}>
                        {paySubmitting ? "Submitting…" : <>Submit payment <Icon name="arrowRight" size={18} /></>}
                      </button>
                      <button className="btn btn-ghost" onClick={() => { setCodeIn(""); reset(); }} disabled={paySubmitting}>Check another code</button>
                    </div>
                    <p className="pay-help">
                      Trouble uploading? <a href={waLink} target="_blank" rel="noopener">Send it on WhatsApp instead</a>.
                    </p>
                  </div>
                )}
              </div>
            )}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

window.PaymentPortal = PaymentPortal;
