// apply.jsx — interactive 5-step scholarship application wizard.
const { useState, useEffect, useRef } = React;

const STEPS = ["Eligibility", "About You", "Goals", "Documents", "Review"];
const LS_FORM = "negrete.application.v1";

const BLANK = {
  elig1: false, elig2: false,
  name: "", email: "", phone: "", address: "",
  goals: "", honors: "",
  gpaName: "", acceptName: "",
  signature: "", date: "", consent: false,
};

function loadForm() {
  try { return { ...BLANK, ...JSON.parse(localStorage.getItem(LS_FORM) || "{}") }; }
  catch (e) { return { ...BLANK }; }
}

const isEmail = (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim());

function Field({ label, opt, children, error }) {
  return (
    <div className="field">
      <label>{label}{opt && <span className="opt"> · optional</span>}</label>
      {children}
      {error !== undefined && <div className="msg">{error || ""}</div>}
    </div>
  );
}

function Upload({ label, hint, value, onChange }) {
  const filled = !!value;
  return (
    <div className="field">
      <label>{label}</label>
      <div className={"upload" + (filled ? " filled" : "")}>
        <input type="file" onChange={(e) => onChange(e.target.files[0] ? e.target.files[0].name : "")}
               accept=".pdf,.doc,.docx,.png,.jpg,.jpeg" />
        <div className="ico">{filled ? "✓" : "↑"}</div>
        <div className="t">{filled ? value : "Click to upload or drag a file"}</div>
        <div className="s">{filled ? "Tap to replace" : hint}</div>
      </div>
    </div>
  );
}

function App() {
  const [data, setData] = useState(loadForm);
  const [step, setStep] = useState(0);
  const [submitted, setSubmitted] = useState(false);
  const [touched, setTouched] = useState(false);
  const topRef = useRef(null);

  useEffect(() => {
    try { localStorage.setItem(LS_FORM, JSON.stringify(data)); } catch (e) {}
  }, [data]);

  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));

  // Validation per step → map of field→error (empty object = valid)
  function errorsFor(s) {
    const e = {};
    if (s === 0) {
      if (!data.elig1 || !data.elig2) e._gate = "Please confirm both eligibility statements to continue.";
    }
    if (s === 1) {
      if (!data.name.trim()) e.name = "Please enter your full name.";
      if (!isEmail(data.email)) e.email = "Enter a valid email address.";
      if (!data.phone.trim()) e.phone = "Please enter a phone number.";
      if (!data.address.trim()) e.address = "Please enter your mailing address.";
    }
    if (s === 2) {
      if (data.goals.trim().length < 20) e.goals = "Tell us a little more — at least a sentence or two.";
      if (data.honors.trim().length < 10) e.honors = "Please list at least one honor, award, or way you've been involved.";
    }
    if (s === 4) {
      if (!data.signature.trim()) e.signature = "Please type your full name as your signature.";
      if (!data.date) e.date = "Please add today's date.";
      if (!data.consent) e.consent = "You must affirm the statement to submit.";
    }
    return e;
  }

  const errs = touched ? errorsFor(step) : {};
  const canProceed = Object.keys(errorsFor(step)).length === 0;

  function next() {
    if (Object.keys(errorsFor(step)).length) { setTouched(true); return; }
    setTouched(false);
    setStep((s) => Math.min(STEPS.length - 1, s + 1));
    scrollTop();
  }
  function back() { setTouched(false); setStep((s) => Math.max(0, s - 1)); scrollTop(); }
  function scrollTop() {
    if (!topRef.current) return;
    // Absolute document position of the wizard (offsetTop alone is relative to
    // the positioned section, which lands near the page top). Only scroll up if
    // the wizard's top is above the comfortable view — never jump the page.
    const top = topRef.current.getBoundingClientRect().top + window.scrollY - 96;
    if (window.scrollY > top) window.scrollTo({ top, behavior: "smooth" });
  }

  function submit() {
    if (Object.keys(errorsFor(4)).length) { setTouched(true); return; }
    setSubmitted(true);
    scrollTop();
  }

  function mailtoHref() {
    const body =
`NEGRETE SCHOLARSHIP — 2026 APPLICATION

CONTACT
Name: ${data.name}
Email: ${data.email}
Phone: ${data.phone}
Address: ${data.address}

EDUCATIONAL & PROFESSIONAL GOALS
${data.goals}

HONORS, AWARDS & COMMUNITY INVOLVEMENT
${data.honors}

DOCUMENTS (please attach to this email)
Proof of cumulative GPA: ${data.gpaName || "— to attach —"}
Proof of acceptance: ${data.acceptName || "— to attach if available —"}

STATEMENT OF ACCURACY & CONSENT
I hereby affirm that all the information provided is true and correct to the best of my knowledge. I also consent that my picture may be taken and used for any purpose deemed necessary to promote The Negrete Scholarship Inc.
Signature: ${data.signature}
Date: ${data.date}`;
    return `mailto:negretescholarshipinc@gmail.com?subject=${encodeURIComponent("2026 Negrete Scholarship Application — " + (data.name || ""))}&body=${encodeURIComponent(body)}`;
  }

  if (submitted) {
    return (
      <div ref={topRef} className="wizard">
        <div className="wcard card success step-anim">
          <div className="success__mark">
            <span style={{ fontSize: "2.2rem", color: "var(--eyebrow)" }}>✓</span>
          </div>
          <h2>Your application is ready to send.</h2>
          <p>We've assembled everything you entered. Click below to open a pre-filled email to <b>negretescholarshipinc@gmail.com</b> — then attach your proof of GPA (and proof of acceptance, if available) before sending.</p>
          <div className="success__actions">
            <a className="btn btn--gold btn--lg" href={mailtoHref()}>Open my application email <span className="arrow">→</span></a>
            <button className="btn btn--ghost btn--lg" onClick={() => { setSubmitted(false); setStep(4); }}>Back to review</button>
          </div>
          <p style={{ marginTop: "1.6rem", fontSize: ".88rem" }}>Selections will be announced by email or phone. Proof of acceptance to a program of higher education will be required prior to a scholarship being awarded.</p>
        </div>
      </div>
    );
  }

  return (
    <div ref={topRef} className="wizard">
      <div className="wizard__steps">
        {STEPS.map((label, i) => (
          <div key={label} className={"wstep" + (i === step ? " active" : i < step ? " done" : "")}>
            <div className="wstep__bar"><i></i></div>
            <div className="wstep__lbl">{label}</div>
          </div>
        ))}
      </div>

      <div className="wcard card">
        <div className="step-anim" key={step}>
          {step === 0 && (
            <div>
              <h2>Let's confirm you're eligible.</h2>
              <p className="wcard__sub">The Negrete Scholarship supports graduating California students on their way to higher education. Please confirm the following.</p>
              <div className="consent" style={{ marginBottom: "1rem" }}>
                <input id="e1" type="checkbox" checked={data.elig1} onChange={(e) => set("elig1", e.target.checked)} />
                <label htmlFor="e1">I am graduating from a California high school and applying to an institution of higher education.</label>
              </div>
              <div className="consent">
                <input id="e2" type="checkbox" checked={data.elig2} onChange={(e) => set("elig2", e.target.checked)} />
                <label htmlFor="e2">I can demonstrate a positive impact in my community and at my school.</label>
              </div>
              {errs._gate && <div className="msg" style={{ marginTop: ".8rem" }}>{errs._gate}</div>}
            </div>
          )}

          {step === 1 && (
            <div>
              <h2>About you.</h2>
              <p className="wcard__sub">Your contact information so the committee can reach you.</p>
              <Field label="Full name" error={errs.name}>
                <input type="text" className={errs.name ? "err" : ""} value={data.name}
                       onChange={(e) => set("name", e.target.value)} placeholder="First and last name" />
              </Field>
              <div className="field-row">
                <Field label="Email address" error={errs.email}>
                  <input type="email" className={errs.email ? "err" : ""} value={data.email}
                         onChange={(e) => set("email", e.target.value)} placeholder="you@email.com" />
                </Field>
                <Field label="Phone number" error={errs.phone}>
                  <input type="tel" className={errs.phone ? "err" : ""} value={data.phone}
                         onChange={(e) => set("phone", e.target.value)} placeholder="(559) 000-0000" />
                </Field>
              </div>
              <Field label="Mailing address" error={errs.address}>
                <input type="text" className={errs.address ? "err" : ""} value={data.address}
                       onChange={(e) => set("address", e.target.value)} placeholder="Street, City, State ZIP" />
              </Field>
            </div>
          )}

          {step === 2 && (
            <div>
              <h2>Your goals &amp; impact.</h2>
              <p className="wcard__sub">Help us understand where you're headed and how you've shown up for your community.</p>
              <Field label="What are your educational and professional goals?" error={errs.goals}>
                <textarea className={errs.goals ? "err" : ""} value={data.goals}
                          onChange={(e) => set("goals", e.target.value)}
                          placeholder="Share the path you hope to take and what you want to achieve."></textarea>
              </Field>
              <Field label="Academic honors, awards & community involvement" error={errs.honors}>
                <textarea className={errs.honors ? "err" : ""} value={data.honors}
                          onChange={(e) => set("honors", e.target.value)}
                          placeholder="List your academic honors and awards, and the ways you've been involved in your community."></textarea>
              </Field>
            </div>
          )}

          {step === 3 && (
            <div>
              <h2>Supporting documents.</h2>
              <p className="wcard__sub">Upload what you have now — you can also attach these to your application email at the end.</p>
              <Upload label="Proof of cumulative high school GPA" hint="PDF, image, or document"
                      value={data.gpaName} onChange={(v) => set("gpaName", v)} />
              <Upload label="Proof of acceptance to higher education" hint="Attach if available — required before an award is given"
                      value={data.acceptName} onChange={(v) => set("acceptName", v)} />
            </div>
          )}

          {step === 4 && (
            <div>
              <h2>Review &amp; sign.</h2>
              <p className="wcard__sub">Confirm your details, then affirm the statement of accuracy and consent.</p>
              <div className="review-list" style={{ marginBottom: "1.8rem" }}>
                <Review k="Name" v={data.name} />
                <Review k="Email" v={data.email} />
                <Review k="Phone" v={data.phone} />
                <Review k="Address" v={data.address} />
                <Review k="Goals" v={data.goals} />
                <Review k="Honors & community" v={data.honors} />
                <Review k="GPA document" v={data.gpaName} fallback="To attach to your email" />
                <Review k="Acceptance document" v={data.acceptName} fallback="To attach if available" />
              </div>
              <div className="consent" style={{ marginBottom: "1.3rem" }}>
                <input id="consent" type="checkbox" checked={data.consent} onChange={(e) => set("consent", e.target.checked)} />
                <label htmlFor="consent">I hereby affirm that all the information provided is true and correct to the best of my knowledge. I also consent that my picture may be taken and used for any purpose deemed necessary to promote The Negrete Scholarship Inc.</label>
              </div>
              {errs.consent && <div className="msg" style={{ marginTop: "-.7rem", marginBottom: "1rem" }}>{errs.consent}</div>}
              <div className="field-row">
                <Field label="Signature (type your full name)" error={errs.signature}>
                  <input type="text" className={errs.signature ? "err" : ""} value={data.signature}
                         onChange={(e) => set("signature", e.target.value)}
                         style={{ fontFamily: "var(--font-display)", fontSize: "1.2rem" }} placeholder="Your full name" />
                </Field>
                <Field label="Date" error={errs.date}>
                  <input type="date" className={errs.date ? "err" : ""} value={data.date}
                         onChange={(e) => set("date", e.target.value)} />
                </Field>
              </div>
            </div>
          )}
        </div>

        <div className="wnav">
          {step > 0
            ? <button className="btn btn--ghost" onClick={back}>← Back</button>
            : <a className="btn btn--ghost" href="index.html">← Home</a>}
          {step < STEPS.length - 1
            ? <button className="btn btn--gold" onClick={next} disabled={touched && !canProceed}>Continue <span className="arrow">→</span></button>
            : <button className="btn btn--gold" onClick={submit}>Submit application <span className="arrow">→</span></button>}
        </div>
      </div>

      <p style={{ textAlign: "center", color: "var(--text-soft)", fontSize: ".85rem", marginTop: "1.4rem" }}>
        Your progress is saved automatically on this device.
      </p>
    </div>
  );
}

function Review({ k, v, fallback }) {
  const empty = !v || !v.trim();
  return (
    <div className="review-item">
      <div className="k">{k}</div>
      <div className={"v" + (empty ? " empty" : "")}>{empty ? (fallback || "Not provided") : v}</div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("apply-root")).render(<App />);
