/* EmploymentApplication.jsx -- full online employment application (CR #198 v2).
   Mirrors the City of Philadelphia Application for Temporary Employment.
   Sensitive fields (SSN, DOB, address) are sent server-side, written into
   the city's official PDF, emailed to JJ as the only persistent record.
   They are NOT stored in our database.

   Reuses Field (Camps.jsx) + the loadSigPad signature_pad CDN loader pattern
   from Registration.jsx -- both are in window scope by the time this loads. */

const POSITIONS = [
  "", "Camp Counselor", "Teaching Artist", "Front Desk / Admin",
  "Production Assistant", "Music Director", "Choreographer", "Other"
];

const STATES = [
  "", "AL","AK","AZ","AR","CA","CO","CT","DE","DC","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","PR"
];

function EmploymentApplicationPage() {
  const blank = {
    // Personal (CR #222: name split into 3 fields; first + last required, middle optional)
    first_name: "", middle_name: "", last_name: "",
    birthdate: "", ssn: "", email: "",
    address: "", city: "", state: "PA", zip: "",
    home_phone: "", cell_phone: "",
    sex: "", marital_status: "",
    other_names: "",
    // Citizenship + license
    us_citizen: "yes", work_authority_id: "",
    drivers_license: "", license_state: "PA",
    // Tax
    exemptions: "", dependents: "",
    // Demographics (optional)
    hispanic_surnames: "",
    // Military
    military_status: "no_service",
    // Prior city employment
    prior_city_employment: "no", prior_city_dept: "", prior_city_payroll: "",
    // Education -- HS
    hs_school_name: "", hs_school_city_state: "", hs_grade_completed: "12",
    hs_last_year_attended: "", ged: false, hs_graduated: "",
    // College 1
    college1_name: "", college1_city_state: "",
    college1_last_year: "", college1_credits: "", college1_degree: "", college1_major: "", college1_graduated: "",
    // College 2
    college2_name: "", college2_city_state: "",
    college2_last_year: "", college2_credits: "", college2_degree: "", college2_major: "", college2_graduated: "",
    // Graduate / other
    grad_name: "", grad_city_state: "",
    grad_last_year: "", grad_credits: "", grad_degree: "", grad_major: "", grad_graduated: "",
    // Employment job 1
    job1_company: "", job1_business_type: "", job1_address: "",
    job1_from: "", job1_to: "", job1_salary: "",
    job1_position: "", job1_supervisor: "", job1_duties: "",
    // Employment job 2
    job2_company: "", job2_business_type: "", job2_address: "",
    job2_from: "", job2_to: "", job2_salary: "",
    job2_position: "", job2_supervisor: "", job2_duties: "",
    // Emergency contact
    emergency_name: "", emergency_relationship: "",
    emergency_address: "", emergency_city: "", emergency_state: "PA", emergency_zip: "",
    emergency_phone: "",
    // Nepotism disclosure (PDF page 6) -- "Are you related to a current
    // PPR employee?" If yes, applicant lists up to 4 related employees.
    nepotism_related: "no",
    nepotism: [
      { name: "", relationship: "", division: "" },
      { name: "", relationship: "", division: "" },
      { name: "", relationship: "", division: "" },
      { name: "", relationship: "", division: "" },
    ],
    // What position are you applying for?
    position: "",
    // Pre-employment medical-history release + drug-testing consent
    // (PDF page 7). Required for offer of employment.
    medical_release_consent: false,
    medical_release_physician_name: "",
    // Sign + attest
    attestation: false,
  };

  const [data, setData] = React.useState(() => {
    // Restore from localStorage if present (autosave). Skip SSN -- never persist locally.
    try {
      const raw = window.localStorage.getItem("ppr-employment-application-draft");
      if (raw) {
        const parsed = JSON.parse(raw);
        // CR #222 migration: old drafts stored a single full_name string in
        // "Last, First Middle" order. Split it so existing in-progress
        // applicants don't lose their name on this deploy.
        if (parsed.full_name && !parsed.first_name && !parsed.last_name) {
          const m = String(parsed.full_name).match(/^\s*([^,]+),\s*(\S+)(?:\s+(.*))?$/);
          if (m) {
            parsed.last_name = m[1].trim();
            parsed.first_name = (m[2] || "").trim();
            parsed.middle_name = (m[3] || "").trim();
          } else {
            // No comma -- best-effort: first token = first, rest = last.
            const parts = String(parsed.full_name).trim().split(/\s+/);
            parsed.first_name = parts[0] || "";
            parsed.last_name = parts.slice(1).join(" ");
          }
          delete parsed.full_name;
        }
        return { ...blank, ...parsed, ssn: "" };
      }
    } catch (_) {}
    return blank;
  });
  const [submitted, setSubmitted] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");
  const [showSsn, setShowSsn] = React.useState(false);
  const [sigReady, setSigReady] = React.useState(false);
  const canvasRef = React.useRef(null);
  const padRef = React.useRef(null);

  const update = (k, v) => setData(d => ({ ...d, [k]: v }));
  const updateNep = (i, k, v) => setData(d => {
    const next = d.nepotism.slice();
    next[i] = { ...next[i], [k]: v };
    return { ...d, nepotism: next };
  });

  // Autosave to localStorage on every change EXCEPT SSN.
  React.useEffect(() => {
    try {
      const { ssn, ...safe } = data;
      window.localStorage.setItem("ppr-employment-application-draft", JSON.stringify(safe));
    } catch (_) {}
  }, [data]);

  // Lazy-load signature_pad from CDN. loadSigPad is a global from Registration.jsx.
  React.useEffect(() => {
    let cancelled = false;
    if (typeof window.loadSigPad !== "function") {
      // Fallback: load directly if Registration.jsx wasn't loaded for some reason.
      const s = document.createElement("script");
      s.src = "https://cdn.jsdelivr.net/npm/signature_pad@4/dist/signature_pad.umd.min.js";
      s.async = true;
      s.onload = () => initPad();
      s.onerror = () => setError("Couldn't load signature pad — please refresh.");
      document.head.appendChild(s);
      return;
    }
    window.loadSigPad().then(() => { if (!cancelled) initPad(); }).catch(() => setError("Couldn't load signature pad — please refresh."));
    function initPad() {
      const canvas = canvasRef.current;
      if (!canvas || padRef.current) return;
      const ratio = Math.max(window.devicePixelRatio || 1, 1);
      canvas.width = canvas.offsetWidth * ratio;
      canvas.height = canvas.offsetHeight * ratio;
      canvas.getContext("2d").scale(ratio, ratio);
      padRef.current = new window.SignaturePad(canvas, {
        backgroundColor: "rgba(255,255,255,0)",
        penColor: "#2A1820",
      });
      setSigReady(true);
    }
    return () => { cancelled = true; };
  }, []);

  const clearSig = () => { if (padRef.current) padRef.current.clear(); };

  const onSubmit = async (e) => {
    e.preventDefault();
    setError("");
    if (!data.attestation) { setError("You must check the attestation box to submit."); return; }
    if (!data.medical_release_consent) { setError("You must check the medical-history release & drug-testing consent box to submit."); return; }
    if (!padRef.current || padRef.current.isEmpty()) { setError("Please sign the form before submitting."); return; }

    const signatureDataUrl = padRef.current.toDataURL("image/png");

    setSubmitting(true);
    try {
      // CR #222: reconstruct full_name from the split fields in the order
      // the PDF expects: "Last, First Middle". Middle is optional.
      const fullName = [
        `${(data.last_name || "").trim()},`,
        (data.first_name || "").trim(),
        (data.middle_name || "").trim(),
      ].filter(p => p && p !== ",").join(" ");

      // CR #244: the medical-release overlay shows the applicant's name in
      // natural order ("First [Middle] Last") rather than the City form's
      // "Last, First Middle". Middle name is optional.
      const medicalName = [
        (data.first_name || "").trim(),
        (data.middle_name || "").trim(),
        (data.last_name || "").trim(),
      ].filter(Boolean).join(" ");

      // Server expects a single object per the API contract -- map our form
      // shape to the AcroForm-friendly keys the PDF filler uses.
      const payload = {
        type: "employment-application",
        position: data.position,
        // Personal
        full_name: fullName,
        birthdate: data.birthdate,
        ssn: data.ssn,
        email: data.email,
        address_csz: [data.address, data.city, data.state, data.zip].filter(Boolean).join(", "),
        home_phone: data.home_phone,
        cell_phone: data.cell_phone,
        sex: data.sex,
        marital_status: data.marital_status,
        other_names: data.other_names,
        us_citizen: data.us_citizen,
        work_authority_id: data.us_citizen === "no" ? data.work_authority_id : "",
        drivers_license: data.drivers_license + (data.license_state ? " (" + data.license_state + ")" : ""),
        exemptions: data.exemptions,
        dependents: data.dependents,
        hispanic_surnames: data.hispanic_surnames,
        military_no_service:     data.military_status === "no_service",
        military_active_reserve: data.military_status === "active_reserve",
        military_completed:      data.military_status === "completed",
        prior_city_employment: data.prior_city_employment,
        prior_city_dept: data.prior_city_dept,
        prior_city_payroll: data.prior_city_payroll,
        // Education
        hs_name: data.hs_school_name,
        hs_name_2: data.hs_school_city_state,
        hs_grade_completed: data.hs_grade_completed,
        hs_last_year: data.hs_last_year_attended,
        ged: data.ged,
        college1_name: data.college1_name, college1_name_2: data.college1_city_state,
        college1_last_year: data.college1_last_year, college1_credits: data.college1_credits,
        college1_degree: data.college1_degree,
        college2_name: data.college2_name, college2_name_2: data.college2_city_state,
        college2_last_year: data.college2_last_year, college2_credits: data.college2_credits,
        college2_degree: data.college2_degree,
        grad_name: data.grad_name, grad_name_2: data.grad_city_state,
        grad_last_year: data.grad_last_year, grad_credits: data.grad_credits,
        grad_degree: data.grad_degree,
        // Employment
        job1_company: data.job1_company, job1_business_type: data.job1_business_type,
        job1_address: data.job1_address, job1_from: data.job1_from, job1_to: data.job1_to,
        job1_salary: data.job1_salary, job1_position: data.job1_position,
        job1_supervisor: data.job1_supervisor, job1_duties: data.job1_duties,
        job2_company: data.job2_company, job2_business_type: data.job2_business_type,
        job2_address: data.job2_address, job2_from: data.job2_from, job2_to: data.job2_to,
        job2_salary: data.job2_salary, job2_position: data.job2_position,
        job2_supervisor: data.job2_supervisor, job2_duties: data.job2_duties,
        // Emergency
        emergency_name: data.emergency_name,
        emergency_relationship: data.emergency_relationship,
        emergency_address: data.emergency_address,
        emergency_csz: [data.emergency_city, data.emergency_state, data.emergency_zip].filter(Boolean).join(", "),
        emergency_phone: data.emergency_phone,
        // Nepotism disclosure (PDF page 6)
        nepotism_yes: data.nepotism_related === "yes",
        nepotism_no:  data.nepotism_related === "no",
        nep1_name: data.nepotism[0].name, nep1_relationship: data.nepotism[0].relationship, nep1_division: data.nepotism[0].division,
        nep2_name: data.nepotism[1].name, nep2_relationship: data.nepotism[1].relationship, nep2_division: data.nepotism[1].division,
        nep3_name: data.nepotism[2].name, nep3_relationship: data.nepotism[2].relationship, nep3_division: data.nepotism[2].division,
        nep4_name: data.nepotism[3].name, nep4_relationship: data.nepotism[3].relationship, nep4_division: data.nepotism[3].division,
        // Medical-history release & drug-testing consent (PDF page 7)
        medical_release_consent: data.medical_release_consent === true,
        medical_release_applicant_name: medicalName,
        medical_release_physician_name: data.medical_release_physician_name,
        // Sign
        applicant_print_name: fullName,
        signature_data_url: signatureDataUrl,
        attestation: true,
      };

      const res = await fetch("/api/intake", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || !json.ok) throw new Error(json.error || `error_${res.status}`);
      // Wipe the localStorage draft after successful submit.
      try { window.localStorage.removeItem("ppr-employment-application-draft"); } catch (_) {}
      setSubmitted({ ref: json.ref, firstName: (data.first_name || "").trim() });
    } catch (err) {
      setError("Couldn't submit right now. Please try again, or email Joseph.J.Pospiech@phila.gov.");
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <section className="section" style={{ background: "var(--c-cream)", minHeight: "60vh", display: "flex", alignItems: "center" }}>
        <div className="container" style={{ maxWidth: 720, textAlign: "center" }}>
          <div style={{ fontSize: 80, marginBottom: 18 }}>✦</div>
          <h2 className="display" style={{ fontSize: "clamp(40px, 7vw, 80px)", marginBottom: 18 }}>
            {submitted.firstName ? `Application submitted, ${submitted.firstName}.` : "Application submitted."}
          </h2>
          <p style={{ fontSize: 18, color: "var(--c-ink-soft)", lineHeight: 1.55, maxWidth: 600, margin: "0 auto 16px" }}>
            JJ has your application. You'll get a confirmation email shortly with your
            filled-out PDF, the FBI Clearance instructions, and the Medical Examination
            form (PDF) for your physician to complete.
          </p>
          <p style={{ fontSize: 14, color: "var(--c-ink-soft)", margin: "0 auto 28px" }}>
            Reference: {submitted.ref}
          </p>
          {/* CR #202 + CR #222: post-submit step cards. Medical first, then FBI
              (which is now the final step per CR #222). */}
          <div className="card" style={{ background: "var(--c-cream-deep)", padding: 20, maxWidth: 560, margin: "0 auto 18px", textAlign: "left" }}>
            <div className="eyebrow">Next step</div>
            <div className="display" style={{ fontSize: 22, marginTop: 6 }}>Bring this to your physician.</div>
            <p style={{ fontSize: 14, color: "var(--c-ink-soft)", marginTop: 8, lineHeight: 1.55 }}>
              The City requires a completed Medical Examination form from your physician
              before your first shift. Download it here, or check your email — we sent a
              copy along with the application confirmation.
            </p>
            <div style={{ marginTop: 12 }}>
              <a
                href="/forms/employment-medical-form.pdf"
                target="_blank"
                rel="noopener"
                className="btn small ochre"
              >
                Download Medical Form ↗
              </a>
            </div>
          </div>
          {/* CR #222: FBI Instructions promoted to a styled final step card,
              matching the medical form box above. */}
          <div className="card" style={{ background: "var(--c-cream-deep)", padding: 20, maxWidth: 560, margin: "0 auto 24px", textAlign: "left" }}>
            <div className="eyebrow">Final step</div>
            <div className="display" style={{ fontSize: 22, marginTop: 6 }}>Schedule your FBI fingerprinting.</div>
            <p style={{ fontSize: 14, color: "var(--c-ink-soft)", marginTop: 8, lineHeight: 1.55 }}>
              Pre-register at{" "}
              <a href="https://uenroll.identogo.com" target="_blank" rel="noopener" style={{ color: "var(--c-primary-deep)" }}>
                uenroll.identogo.com
              </a>{" "}
              with service code <strong>1KG756</strong> and pick a Philadelphia
              fingerprinting location. Full instructions are in the PDF below.
            </p>
            <div style={{ marginTop: 12 }}>
              <a
                href="/forms/employment-fbi-instructions.pdf"
                target="_blank"
                rel="noopener"
                className="btn small ochre"
              >
                Download FBI instructions ↗
              </a>
            </div>
          </div>
          <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap", marginTop: 14 }}>
            <a href="#employment" onClick={(e) => { e.preventDefault(); window.location.hash = '#employment'; }} className="btn small">
              Back to Employment Resources
            </a>
          </div>
        </div>
      </section>
    );
  }

  return (
    <div>
      {/* Hero — CR #246: Philadelphia City Hall photo, framed Venice-style */}
      <section style={{ background: "var(--c-cream)", borderBottom: "2px solid var(--c-ink)" }}>
        <div className="container" style={{ padding: "64px 0 40px" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 40, alignItems: "center" }} className="employment-apply-hero">
            <div>
              <div className="eyebrow">Employment Application</div>
              <h1 className="display" style={{ fontSize: "clamp(40px, 6vw, 84px)", margin: "10px 0 16px", lineHeight: 1 }}>
                City of Philadelphia<br />Application for<br /><span style={{ fontStyle: "italic", color: "var(--c-primary)" }}>Temporary Employment</span>
              </h1>
              <p style={{ fontSize: 17, lineHeight: 1.55, color: "var(--c-ink)", maxWidth: 720 }}>
                Fill out the form below and sign at the bottom. We'll generate the official PDF and email it to JJ Pospiech (PPR Performing Arts Coordinator) along with a copy to you.
              </p>
              <div style={{ marginTop: 16, padding: 14, background: "#FFEED9", border: "1px solid var(--c-accent)", borderRadius: 8, fontSize: 13.5, color: "var(--c-ink)", maxWidth: 720, lineHeight: 1.55 }}>
                <strong>Privacy:</strong> Sensitive fields (SSN, date of birth, full address) are written into the official PDF and emailed only to JJ. They are <strong>never stored</strong> in our website's database. Your draft autosaves to your own browser as you type — except your SSN, which is only kept in memory while this page is open.
              </div>
            </div>
            <div style={{
              aspectRatio: "4/5", borderRadius: 22, overflow: "hidden",
              border: "2px solid var(--c-ink)", boxShadow: "var(--shadow-lift)"
            }}>
              <img
                src="/img/cr-246-city-hall.jpg"
                alt="Philadelphia City Hall"
                style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
                loading="lazy"
              />
            </div>
          </div>
        </div>
        <style>{`
          @media (max-width: 800px) {
            .employment-apply-hero { grid-template-columns: 1fr !important; gap: 24px !important; }
            .employment-apply-hero > div:last-child { max-width: 240px !important; margin: 0 auto !important; }
          }
        `}</style>
      </section>

      <section className="section">
        <div className="container" style={{ maxWidth: 920 }}>
          <form onSubmit={onSubmit}>
            {/* ============ Personal ============ */}
            <FormSection number="01" title="Personal information">
              <Row>
                <Field label="First name" value={data.first_name} onChange={v => update("first_name", v)} required />
                <Field label="Middle name (optional)" value={data.middle_name} onChange={v => update("middle_name", v)} />
                <Field label="Last name" value={data.last_name} onChange={v => update("last_name", v)} required />
              </Row>
              <Row>
                <Field
                  label="Birthdate (MM/DD/YYYY)"
                  value={data.birthdate}
                  onChange={v => update("birthdate", v)}
                  required
                  placeholder="MM/DD/YYYY"
                  inputMode="numeric"
                  maxLength={10}
                  pattern="\d{2}/\d{2}/\d{4}"
                  title="Use MM/DD/YYYY format, e.g. 04/15/1990"
                  formatter={window.formatDateMDY}
                />
                <SsnField value={data.ssn} reveal={showSsn} setReveal={setShowSsn} onChange={v => update("ssn", v)} />
                <Field
                  label="Sex"
                  type="select"
                  options={["", "female", "male", "non_binary", "trans_female", "trans_male", "prefer_not", "self_describe"]}
                  optionLabels={["—", "Female", "Male", "Non-binary", "Transgender female", "Transgender male", "Prefer not to say", "Prefer to self-describe"]}
                  value={data.sex}
                  onChange={v => update("sex", v)}
                />
              </Row>
              <Row>
                <Field label="Email" type="email" value={data.email} onChange={v => update("email", v)} required />
                <Field
                  label="Cell phone"
                  type="tel"
                  value={data.cell_phone}
                  onChange={v => update("cell_phone", v)}
                  required
                  placeholder="215-555-0100"
                  inputMode="tel"
                  maxLength={12}
                  pattern="\d{3}-\d{3}-\d{4}"
                  title="Use XXX-XXX-XXXX format"
                  formatter={window.formatPhone}
                />
              </Row>
              <Row>
                <Field
                  label="Home phone (optional)"
                  type="tel"
                  value={data.home_phone}
                  onChange={v => update("home_phone", v)}
                  placeholder="215-555-0100"
                  inputMode="tel"
                  maxLength={12}
                  pattern="\d{3}-\d{3}-\d{4}"
                  title="Use XXX-XXX-XXXX format"
                  formatter={window.formatPhone}
                />
                <Field
                  label="Marital status"
                  type="select"
                  options={["", "single", "married", "domestic_partner", "divorced", "widowed", "separated", "prefer_not"]}
                  optionLabels={["—", "Single", "Married", "Domestic partner", "Divorced", "Widowed", "Separated", "Prefer not to say"]}
                  value={data.marital_status}
                  onChange={v => update("marital_status", v)}
                  required
                />
              </Row>
              <Field label="Address (street)" value={data.address} onChange={v => update("address", v)} required />
              <Row>
                <Field label="City" value={data.city} onChange={v => update("city", v)} required />
                <Field label="State" type="select" options={STATES} value={data.state} onChange={v => update("state", v)} required />
                <Field
                  label="ZIP"
                  value={data.zip}
                  onChange={v => update("zip", v)}
                  required
                  placeholder="19102"
                  inputMode="numeric"
                  maxLength={5}
                  pattern="\d{5}"
                  title="5-digit ZIP code"
                />
              </Row>
              <Field label="Other names used for employment or education (optional)" value={data.other_names} onChange={v => update("other_names", v)} />
            </FormSection>

            {/* ============ Citizenship + license ============ */}
            <FormSection number="02" title="Citizenship & license">
              <Row>
                <Field label="U.S. citizen?" type="select" options={["yes", "no"]} optionLabels={["Yes", "No"]} value={data.us_citizen} onChange={v => update("us_citizen", v)} required />
                {data.us_citizen === "no" && (
                  <Field label="Work Authority ID #" value={data.work_authority_id} onChange={v => update("work_authority_id", v)} required />
                )}
              </Row>
              <Row>
                <Field label="Driver's license number (optional)" value={data.drivers_license} onChange={v => update("drivers_license", v)} />
                <Field label="Issuing state" type="select" options={STATES} value={data.license_state} onChange={v => update("license_state", v)} />
              </Row>
              <Row>
                <Field label="No. of exemptions (tax, optional)" value={data.exemptions} onChange={v => update("exemptions", v)} />
                <Field label="No. of dependents (optional)" value={data.dependents} onChange={v => update("dependents", v)} />
              </Row>
            </FormSection>

            {/* ============ Demographics + military ============ */}
            <FormSection number="03" title="Demographics & military">
              <Field label="Hispanic surnames — provide mother's maiden name / place of birth (optional)" value={data.hispanic_surnames} onChange={v => update("hispanic_surnames", v)} />
              <div>
                <label style={{ display: "block", fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--c-ink-soft)", marginBottom: 8 }}>Military status</label>
                <div style={{ display: "flex", gap: 18, flexWrap: "wrap" }}>
                  {[["no_service", "No service"], ["active_reserve", "Active Reserve"], ["completed", "Obligation Completed"]].map(([val, label]) => (
                    <label key={val} style={{ fontSize: 14, display: "flex", gap: 6, alignItems: "center" }}>
                      <input type="radio" name="military_status" value={val} checked={data.military_status === val} onChange={() => update("military_status", val)} />
                      {label}
                    </label>
                  ))}
                </div>
              </div>
              <Row>
                <Field label="Have you ever been employed by the City of Philadelphia?" type="select" options={["no", "yes"]} optionLabels={["No", "Yes"]} value={data.prior_city_employment} onChange={v => update("prior_city_employment", v)} />
                {data.prior_city_employment === "yes" && (
                  <Field label="If yes — Department" value={data.prior_city_dept} onChange={v => update("prior_city_dept", v)} />
                )}
              </Row>
              {data.prior_city_employment === "yes" && (
                <Field label="Payroll #" value={data.prior_city_payroll} onChange={v => update("prior_city_payroll", v)} />
              )}
            </FormSection>

            {/* ============ Education ============ */}
            <FormSection number="04" title="Education">
              <div className="display" style={{ fontSize: 18, marginBottom: 6 }}>High school</div>
              <Row>
                <Field label="School name" value={data.hs_school_name} onChange={v => update("hs_school_name", v)} />
                <Field label="City, State" value={data.hs_school_city_state} onChange={v => update("hs_school_city_state", v)} />
              </Row>
              <Row>
                <Field label="Highest grade completed" type="select" options={["", "K", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]} value={data.hs_grade_completed} onChange={v => update("hs_grade_completed", v)} />
                <Field
                  label="Last year attended"
                  value={data.hs_last_year_attended}
                  onChange={v => update("hs_last_year_attended", v)}
                  placeholder="2005"
                  inputMode="numeric"
                  maxLength={4}
                  pattern="(19|20)\d{2}"
                  title="4-digit year, e.g. 2005"
                />
                <Field
                  label="Graduated"
                  type="select"
                  options={["", "yes", "no"]}
                  optionLabels={["—", "Yes", "No"]}
                  value={data.hs_graduated}
                  onChange={v => update("hs_graduated", v)}
                  required
                />
              </Row>
              <div style={{ marginTop: 6 }}>
                <label style={{ fontSize: 14, display: "flex", gap: 6, alignItems: "center" }}>
                  <input type="checkbox" checked={data.ged} onChange={e => update("ged", e.target.checked)} />
                  GED instead of high school diploma
                </label>
              </div>

              <CollegeBlock label="College / University 1 (optional)" prefix="college1" data={data} update={update} />
              <CollegeBlock label="College / University 2 (optional)" prefix="college2" data={data} update={update} />
              <CollegeBlock label="Graduate / other training (optional)" prefix="grad" data={data} update={update} />
            </FormSection>

            {/* ============ Employment history ============ */}
            <FormSection number="05" title="Employment history (most recent first)">
              <JobBlock label="Most recent" prefix="job1" data={data} update={update} />
              <JobBlock label="Previous" prefix="job2" data={data} update={update} />
            </FormSection>

            {/* ============ Emergency contact ============ */}
            <FormSection number="06" title="Emergency contact">
              <Row>
                <Field label="Contact name" value={data.emergency_name} onChange={v => update("emergency_name", v)} required />
                <Field label="Relationship" value={data.emergency_relationship} onChange={v => update("emergency_relationship", v)} required />
              </Row>
              <Field label="Address" value={data.emergency_address} onChange={v => update("emergency_address", v)} required />
              <Row>
                <Field label="City" value={data.emergency_city} onChange={v => update("emergency_city", v)} required />
                <Field label="State" type="select" options={STATES} value={data.emergency_state} onChange={v => update("emergency_state", v)} />
                <Field
                  label="ZIP"
                  value={data.emergency_zip}
                  onChange={v => update("emergency_zip", v)}
                  required
                  placeholder="19102"
                  inputMode="numeric"
                  maxLength={5}
                  pattern="\d{5}"
                  title="5-digit ZIP code"
                />
              </Row>
              <Field
                label="Phone"
                type="tel"
                value={data.emergency_phone}
                onChange={v => update("emergency_phone", v)}
                required
                placeholder="215-555-0100"
                inputMode="tel"
                maxLength={12}
                pattern="\d{3}-\d{3}-\d{4}"
                title="Use XXX-XXX-XXXX format"
                formatter={window.formatPhone}
              />
            </FormSection>

            {/* ============ Nepotism disclosure (PDF page 6) ============ */}
            <FormSection number="07" title="Nepotism disclosure">
              <p style={{ fontSize: 14, color: "var(--c-ink)", lineHeight: 1.55, margin: 0 }}>
                Executive Order No. 1-11 ("Prohibition of Nepotism") requires the City to disclose any familial relationships between hires and current employees. <strong>Are you related to any permanent or temporary employee working for the Philadelphia Department of Parks &amp; Recreation?</strong>
              </p>
              <div style={{ display: "flex", gap: 18, flexWrap: "wrap" }}>
                {[["no", "No"], ["yes", "Yes"]].map(([val, label]) => (
                  <label key={val} style={{ fontSize: 14, display: "flex", gap: 6, alignItems: "center" }}>
                    <input type="radio" name="nepotism_related" value={val} checked={data.nepotism_related === val} onChange={() => update("nepotism_related", val)} />
                    {label}
                  </label>
                ))}
              </div>
              {data.nepotism_related === "yes" && (
                <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 6 }}>
                  <p style={{ fontSize: 13, color: "var(--c-ink-soft)", margin: 0 }}>
                    List up to 4 related PPR employees. Leave the extra rows blank if you don't need them.
                  </p>
                  {data.nepotism.map((r, i) => (
                    <div key={i} style={{ border: "1px solid var(--c-ink-soft)", borderRadius: 12, padding: 16, background: "var(--c-paper)" }}>
                      <div style={{ fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--c-ink-soft)", marginBottom: 10 }}>
                        Related employee {i + 1}
                      </div>
                      <Row>
                        <Field label="Name" value={r.name} onChange={v => updateNep(i, "name", v)} />
                        <Field label="Relationship" value={r.relationship} onChange={v => updateNep(i, "relationship", v)} />
                        <Field label="Division / department" value={r.division} onChange={v => updateNep(i, "division", v)} />
                      </Row>
                    </div>
                  ))}
                </div>
              )}
            </FormSection>

            {/* ============ Position interest ============ */}
            <FormSection number="08" title="Position you're applying for">
              <Field label="Position" type="select" options={POSITIONS} value={data.position} onChange={v => update("position", v)} />
            </FormSection>

            {/* ============ Medical-history release & drug-testing consent (PDF page 7) ============ */}
            <FormSection number="09" title="Medical-history release & drug-testing consent">
              <p style={{ fontSize: 14, color: "var(--c-ink)", lineHeight: 1.55, margin: 0 }}>
                As a condition of employment with the Philadelphia Department of Parks &amp; Recreation, you must consent to release medical-history information to your prospective employer (where relevant to job fitness) and to a drug/alcohol screening if requested.
              </p>
              <Field
                label="Your physician's name (if known — leave blank if you don't have a current PCP)"
                value={data.medical_release_physician_name}
                onChange={v => update("medical_release_physician_name", v)}
              />
              <label style={{ fontSize: 14, display: "flex", gap: 8, alignItems: "flex-start" }}>
                <input
                  type="checkbox"
                  checked={data.medical_release_consent}
                  onChange={e => update("medical_release_consent", e.target.checked)}
                  required
                />
                <span>
                  I consent to release the content of my medical history to my prospective employer as it relates to my fitness to perform the duties associated with the position for which I have applied. I also consent to undergo drug/alcohol screening as requested and to provide a urine sample for that purpose.
                </span>
              </label>
            </FormSection>

            {/* ============ Sign + attest ============ */}
            <FormSection number="10" title="Signature & attestation">
              <p style={{ fontSize: 14, color: "var(--c-ink)", lineHeight: 1.55, marginBottom: 16 }}>
                I certify that the answers given above are true and complete to the best of my knowledge. I understand that any false statement may disqualify me from employment or be cause for dismissal if I am hired.
              </p>
              <div style={{ marginBottom: 14 }}>
                <label style={{ fontSize: 14, display: "flex", gap: 8, alignItems: "flex-start" }}>
                  <input
                    type="checkbox"
                    checked={data.attestation}
                    onChange={e => update("attestation", e.target.checked)}
                    required
                  />
                  <span>I attest the above is true and accurate, and I authorize the Philadelphia Department of Parks &amp; Recreation to verify the information I've provided.</span>
                </label>
              </div>
              <div style={{ marginTop: 10 }}>
                <label style={{ display: "block", fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--c-ink-soft)", marginBottom: 8 }}>
                  Signature
                </label>
                <div style={{ position: "relative", border: "2px solid var(--c-ink)", borderRadius: 12, height: 160, background: "var(--c-paper)" }}>
                  <canvas ref={canvasRef} style={{ width: "100%", height: "100%", touchAction: "none" }} />
                </div>
                <div style={{ marginTop: 8, display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" }}>
                  <button type="button" className="btn small ghost" onClick={clearSig} disabled={!sigReady}>Clear</button>
                  <span style={{ fontSize: 12, color: "var(--c-ink-soft)" }}>
                    {sigReady ? "Use a finger or stylus on touch devices, or click and drag with a mouse." : "Loading signature pad…"}
                  </span>
                </div>
              </div>
            </FormSection>

            {error && (
              <div style={{ marginTop: 24, padding: 14, background: "#FBE4DC", border: "2px solid var(--c-primary)", borderRadius: 12, fontSize: 14, color: "var(--c-ink)" }}>
                {error}
              </div>
            )}

            <div className="card" style={{ background: "var(--c-cream-deep)", marginTop: 32, display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 14 }}>
              <div>
                <div className="display" style={{ fontSize: 22 }}>Submit your application.</div>
                <div style={{ fontSize: 13, color: "var(--c-ink-soft)" }}>You'll get a confirmation email — JJ will follow up.</div>
              </div>
              <button type="submit" className="btn" disabled={submitting}>
                {submitting ? "Submitting…" : "Submit application →"}
              </button>
            </div>
          </form>
        </div>
      </section>
    </div>
  );
}

function SsnField({ value, reveal, setReveal, onChange }) {
  return (
    <div>
      <label style={{ display: "block", fontFamily: "var(--f-mono)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--c-ink-soft)", marginBottom: 8 }}>
        Social Security Number<span style={{ color: "var(--c-primary)" }}> *</span>
      </label>
      <div style={{ position: "relative" }}>
        <input
          type={reveal ? "text" : "password"}
          value={value}
          onChange={e => onChange(window.formatSSN ? window.formatSSN(e.target.value) : e.target.value)}
          placeholder="XXX-XX-XXXX"
          required
          autoComplete="off"
          inputMode="numeric"
          maxLength={11}
          pattern="\d{3}-\d{2}-\d{4}"
          title="Use XXX-XX-XXXX format (9 digits)"
          style={{
            width: "100%", padding: "12px 60px 12px 14px",
            border: "2px solid var(--c-ink)", borderRadius: 12,
            background: "var(--c-paper)", fontSize: 15,
            fontFamily: "ui-monospace, monospace",
          }}
        />
        <button
          type="button"
          onClick={() => setReveal(!reveal)}
          style={{
            position: "absolute", right: 6, top: "50%", transform: "translateY(-50%)",
            padding: "4px 10px", fontSize: 11, background: "transparent",
            border: "1px solid var(--c-ink-soft)", borderRadius: 6, cursor: "pointer",
          }}
        >
          {reveal ? "Hide" : "Show"}
        </button>
      </div>
      <div style={{ fontSize: 11, color: "var(--c-ink-soft)", marginTop: 6 }}>
        Encrypted in transit, written to the PDF only, never saved on our servers.
      </div>
    </div>
  );
}

function FormSection({ number, title, children }) {
  return (
    <div style={{ borderTop: "2px solid var(--c-ink)", paddingTop: 32, marginTop: 32 }}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 22 }}>
        <span className="display" style={{ fontSize: 32, color: "var(--c-primary)" }}>{number}</span>
        <span className="display" style={{ fontSize: 28 }}>{title}</span>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>{children}</div>
    </div>
  );
}

function CollegeBlock({ label, prefix, data, update }) {
  // The school field carries the block: if it's filled in, treat the
  // graduated answer as required (CR #202 -- "require graduated button for
  // for both high school and/or college experience").
  const hasData = !!(data[`${prefix}_name`] || "").trim();
  return (
    <div style={{ marginTop: 18, paddingTop: 14, borderTop: "1px dashed var(--c-line)" }}>
      <div className="display" style={{ fontSize: 18, marginBottom: 6 }}>{label}</div>
      <Row>
        <Field label="School name" value={data[`${prefix}_name`]} onChange={v => update(`${prefix}_name`, v)} />
        <Field label="City, State" value={data[`${prefix}_city_state`]} onChange={v => update(`${prefix}_city_state`, v)} />
      </Row>
      <Row>
        <Field
          label="Last year attended"
          value={data[`${prefix}_last_year`]}
          onChange={v => update(`${prefix}_last_year`, v)}
          placeholder="2010"
          inputMode="numeric"
          maxLength={4}
          pattern="(19|20)\d{2}"
          title="4-digit year, e.g. 2010"
        />
        <Field label="Credits" value={data[`${prefix}_credits`]} onChange={v => update(`${prefix}_credits`, v)} />
        <Field label="Degree" value={data[`${prefix}_degree`]} onChange={v => update(`${prefix}_degree`, v)} />
      </Row>
      <Row>
        <Field label="Major / course of study" value={data[`${prefix}_major`]} onChange={v => update(`${prefix}_major`, v)} />
        <Field
          label="Graduated"
          type="select"
          options={["", "yes", "no"]}
          optionLabels={["—", "Yes", "No"]}
          value={data[`${prefix}_graduated`] || ""}
          onChange={v => update(`${prefix}_graduated`, v)}
          required={hasData}
        />
      </Row>
    </div>
  );
}

function JobBlock({ label, prefix, data, update }) {
  return (
    <div style={{ marginTop: 18, paddingTop: 14, borderTop: "1px dashed var(--c-line)" }}>
      <div className="display" style={{ fontSize: 18, marginBottom: 6 }}>{label}</div>
      <Row>
        <Field label="Company name" value={data[`${prefix}_company`]} onChange={v => update(`${prefix}_company`, v)} />
        <Field label="Type of business" value={data[`${prefix}_business_type`]} onChange={v => update(`${prefix}_business_type`, v)} />
      </Row>
      <Field label="Address" value={data[`${prefix}_address`]} onChange={v => update(`${prefix}_address`, v)} />
      <Row>
        <Field
          label="From (MM/YY)"
          value={data[`${prefix}_from`]}
          onChange={v => update(`${prefix}_from`, v)}
          placeholder="05/26"
          inputMode="numeric"
          maxLength={5}
          pattern="\d{2}/\d{2}"
          title="Use MM/YY format, e.g. 05/26"
          formatter={window.formatMonthYear}
        />
        <Field
          label="To (MM/YY)"
          value={data[`${prefix}_to`]}
          onChange={v => update(`${prefix}_to`, v)}
          placeholder="05/26"
          inputMode="numeric"
          maxLength={5}
          pattern="\d{2}/\d{2}"
          title="Use MM/YY format, e.g. 05/26"
          formatter={window.formatMonthYear}
        />
        <Field label="Salary" value={data[`${prefix}_salary`]} onChange={v => update(`${prefix}_salary`, v)} />
      </Row>
      <Row>
        <Field label="Position held" value={data[`${prefix}_position`]} onChange={v => update(`${prefix}_position`, v)} />
        <Field label="Immediate supervisor (name + title)" value={data[`${prefix}_supervisor`]} onChange={v => update(`${prefix}_supervisor`, v)} />
      </Row>
      <Field label="Briefly describe primary duties and responsibilities" type="textarea" value={data[`${prefix}_duties`]} onChange={v => update(`${prefix}_duties`, v)} />
    </div>
  );
}

Object.assign(window, { EmploymentApplicationPage });
