/* DOMINANCE — Page: Apply (mobile-first full-page application flow).
   Lives at hash route #/apply. Same questions and submit logic as the VSL
   modal, but rendered as a normal scrollable document — no modal overlay,
   no body scroll-lock, no sticky positioning, no 100dvh tricks. The mobile
   pop-up was unfixable; this replaces it with a plain page so iOS Safari
   handles viewport, keyboard, and back button naturally. */

function ApplyPage({ navigate }) {
  const QUESTIONS = window.APPLY_QUESTIONS || [];
  const [step, setStep] = useState(0);
  const [answers, setAnswers] = useState({});
  const [contact, setContact] = useState({ firstName: "", email: "", company: "", website: "" });
  const [contactErrors, setContactErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [direction, setDirection] = useState(1);

  const totalQ = QUESTIONS.length;
  const isContact = step === totalQ;
  const currentQ = !isContact ? QUESTIONS[step] : null;

  // Browser back button → previous step instead of leaving the page entirely.
  // We tag the current history entry as step 0, then pushState on each forward.
  // On popstate we read the target step from event.state and rewind.
  useEffect(() => {
    if (window.history.state == null || typeof window.history.state.applyStep !== "number") {
      window.history.replaceState({ applyStep: 0 }, "");
    }
    const onPop = (e) => {
      if (e.state && typeof e.state.applyStep === "number") {
        setDirection(-1);
        setStep(e.state.applyStep);
      }
    };
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  // Scroll to top whenever step changes — the form stays visually anchored.
  useEffect(() => { window.scrollTo({ top: 0, behavior: "auto" }); }, [step]);

  // Keyboard shortcuts (desktop): A–D to pick, ← back, ESC to leave
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") return navigate("/step-2");
      if (e.key === "ArrowLeft" && step > 0 && step < totalQ) {
        setDirection(-1); setStep((s) => s - 1); return;
      }
      if (step < totalQ) {
        const idx = e.key.toUpperCase().charCodeAt(0) - 65;
        const q = QUESTIONS[step];
        if (idx >= 0 && idx < q.options.length) {
          setAnswers((prev) => ({ ...prev, [q.id]: q.options[idx] }));
          setTimeout(() => goForward(step + 1), 240);
        }
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [step]);

  const goForward = (newStep) => {
    setDirection(1);
    setStep(newStep);
    window.history.pushState({ applyStep: newStep }, "");
  };

  const select = (opt) => {
    setAnswers((prev) => ({ ...prev, [currentQ.id]: opt }));
    setTimeout(() => goForward(step + 1), 240);
  };

  const goBack = () => {
    if (step === 0) { navigate("/step-2"); return; }
    // Trigger browser back so history stays in sync with the visible step.
    window.history.back();
  };

  const handleSubmit = async () => {
    const errs = {};
    if (!contact.firstName.trim()) errs.firstName = "Required";
    if (!contact.email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contact.email.trim())) errs.email = "Valid email required";
    if (Object.keys(errs).length) { setContactErrors(errs); return; }
    setSubmitting(true);

    const payload = {
      ...contact,
      answers: QUESTIONS.reduce((acc, q) => ({ ...acc, [q.id]: answers[q.id] || "" }), {}),
      submittedAt: new Date().toISOString(),
    };

    let result = { bucket: "review", score: 0 };
    try {
      const res = await fetch("/api/apply", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (res.ok) result = await res.json();
    } catch (err) {
      console.error("apply submit failed:", err);
    }
    try {
      sessionStorage.setItem("dominance_lead_first_name", contact.firstName.trim());
      sessionStorage.setItem("dominance_lead_email", contact.email.trim());
    } catch {}

    if (result?.bucket === "qualified") {
      try { sessionStorage.setItem("dominance_cal_link", result.calLink || ""); } catch {}
      navigate("/qualified");
    } else if (result?.bucket === "reject") {
      navigate("/declined");
    } else {
      navigate("/application-received");
    }
  };

  return (
    <main className="apply-page">
      <div className="apply-container">
        <header className="apply-head">
          <div className="apply-head-label">
            <img src="assets/dominance-d-white.png" alt="" className="apply-d" />
            <span>Revenue Growth Call Application</span>
          </div>
          {!isContact ? (
            <span className="apply-step-count">
              <b>{String(step + 1).padStart(2, "0")}</b>
              <span className="sep">/</span>
              <span className="of">{String(totalQ).padStart(2, "0")}</span>
            </span>
          ) : (
            <span className="apply-step-count"><b>Final</b></span>
          )}
          <button className="apply-leave" onClick={() => navigate("/step-2")} aria-label="Leave application">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M6 6 L18 18 M18 6 L6 18" /></svg>
          </button>
        </header>

        <div className="apply-rail" role="presentation">
          {QUESTIONS.map((q, i) => (
            <div key={q.id} className={`stepper-seg${(i < step || isContact) ? " done" : ""}${(i === step && !isContact) ? " active" : ""}`} />
          ))}
          <div className={`stepper-seg${isContact ? " active" : ""}`} />
        </div>

        <section className="apply-body">
          {!isContact ? (
            <div className={`step-pane ${direction > 0 ? "in-fwd" : "in-back"}`} key={`s-${step}`}>
              <div className="step-num">
                <span className="step-num-dot" />
                Question {String(step + 1).padStart(2, "0")}
                <span className="step-num-of">of 0{totalQ}</span>
              </div>
              <h2 className="step-q">{currentQ.label}</h2>
              {currentQ.intro && (
                <div className="q-intro">
                  <p className="q-intro-lead">{currentQ.intro.lead}</p>
                  <p className="q-intro-body">{currentQ.intro.body}</p>
                  <div className="q-intro-stat"><span className="q-intro-stat-dot" />{currentQ.intro.stat}</div>
                </div>
              )}
              <div className="step-options">
                {currentQ.options.map((opt, oi) => (
                  <button key={opt} className={`step-option${answers[currentQ.id] === opt ? " selected" : ""}`}
                    onClick={() => select(opt)} style={{ animationDelay: `${oi * 50}ms` }}>
                    <span className="step-option-key">{String.fromCharCode(65 + oi)}</span>
                    <span className="step-option-text">{opt}</span>
                    <span className="step-option-arrow">
                      <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14 M13 5l7 7-7 7" /></svg>
                    </span>
                  </button>
                ))}
              </div>
            </div>
          ) : (
            <div className={`step-pane ${direction > 0 ? "in-fwd" : "in-back"}`} key="contact">
              <div className="step-num">
                <span className="step-num-dot" />
                Final Step
                <span className="step-num-of">— Your details</span>
              </div>
              <h2 className="step-q">Where should we send your answer?</h2>
              <div className="modal-contact-form">
                <div className="modal-input-group">
                  <label className="modal-input-label">First name <span className="req">*</span></label>
                  <input className={`modal-input${contactErrors.firstName ? " modal-input-err" : ""}`}
                    type="text" placeholder="Alex" value={contact.firstName} autoComplete="given-name"
                    onChange={(e) => { setContact((p) => ({ ...p, firstName: e.target.value })); if (contactErrors.firstName) setContactErrors((p) => ({ ...p, firstName: null })); }} />
                  {contactErrors.firstName && <span className="modal-input-error">{contactErrors.firstName}</span>}
                </div>
                <div className="modal-input-group">
                  <label className="modal-input-label">Work email <span className="req">*</span></label>
                  <input className={`modal-input${contactErrors.email ? " modal-input-err" : ""}`}
                    type="email" placeholder="alex@company.com" value={contact.email} autoComplete="email"
                    onChange={(e) => { setContact((p) => ({ ...p, email: e.target.value })); if (contactErrors.email) setContactErrors((p) => ({ ...p, email: null })); }} />
                  {contactErrors.email && <span className="modal-input-error">{contactErrors.email}</span>}
                </div>
                <div className="modal-input-group">
                  <label className="modal-input-label">Company name</label>
                  <input className="modal-input" type="text" placeholder="Acme Inc." value={contact.company}
                    autoComplete="organization" onChange={(e) => setContact((p) => ({ ...p, company: e.target.value }))} />
                </div>
                <div className="modal-input-group">
                  <label className="modal-input-label">Company website or LinkedIn</label>
                  <input className="modal-input" type="text" placeholder="https://..." value={contact.website}
                    autoComplete="url" onChange={(e) => setContact((p) => ({ ...p, website: e.target.value }))} />
                </div>
              </div>
            </div>
          )}
        </section>

        <footer className="apply-foot">
          <button className="btn-ghost apply-back" onClick={goBack}
            style={{ visibility: step === 0 ? "hidden" : "visible" }}>
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5 M11 19l-7-7 7-7" /></svg>
            Back
          </button>
          {isContact && (
            <button className="btn apply-submit" onClick={handleSubmit} disabled={submitting}>
              <span className="glint" /><span>{submitting ? "Sending…" : "Submit application"}</span><span className="arrow">→</span>
            </button>
          )}
        </footer>
      </div>
    </main>
  );
}

window.ApplyPage = ApplyPage;
