/* DOMINANCE — Page 2: VSL + qualification form (modal, one-at-a-time) */

const QUESTIONS = [
  {
    id: "q1",
    label: "What does your business sell?",
    options: ["B2B services or consulting","SaaS or software","Coaching or education","E-commerce or DTC","Other"],
  },
  {
    id: "q2",
    label: "What's your role?",
    options: ["Owner / CEO / Founder","VP / Director / Head of Sales","Manager","Employee or Other"],
  },
  {
    id: "q3",
    label: "What's your average deal size?",
    options: ["Under $5,000","$5,000–$15,000","$15,000–$50,000","$50,000+"],
  },
  {
    id: "q4",
    label: "How many new clients do you close per month?",
    options: ["0–2","3–5","6–10","10+"],
  },
  {
    id: "q5",
    label: "What's your biggest challenge right now?",
    options: ["Not enough qualified leads in the pipeline","Too much time spent on prospecting manually","Inconsistent month-to-month revenue","Just exploring options"],
  },
  {
    id: "q6",
    label: "When are you looking to start?",
    options: ["Immediately — if it makes sense","Within 30 days","3+ months out","Just researching"],
  },
  {
    id: "q7",
    label: "Are you ready to invest at this level to scale?",
    intro: {
      lead: "Performance-based, like it should be.",
      body: "\"I charge $500/month for the infrastructure — it all goes to domains, inboxes, and leads. Same way a builder charges for materials before laying the first brick. Beyond that, I only get paid when you get a qualified meeting on your calendar.\"",
      stat: "Upfront: only the $500 tech fee. Zero risk to test it.",
    },
    options: ["Yes — let's scale","Want to see ROI projections first","Not ready at this level right now"],
  },
];

function ApplicationModal({ open, onClose, onComplete }) {
  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);

  useEffect(() => {
    if (open) {
      setStep(0); setAnswers({});
      setContact({ firstName: "", email: "", company: "", website: "" });
      setContactErrors({}); setSubmitting(false); setDirection(1);
    }
  }, [open]);

  useEffect(() => {
    if (!open) return;

    // Modal only opens on desktop now (mobile uses the /apply route), so
    // overflow:hidden is enough — no iOS-grade hacks needed.
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    const onKey = (e) => {
      if (e.key === "Escape") return onClose();
      if (e.key === "ArrowLeft" && step > 0 && step < QUESTIONS.length) {
        setDirection(-1); setStep((s) => s - 1); return;
      }
      if (step < QUESTIONS.length) {
        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(() => { setDirection(1); setStep((s) => s + 1); }, 240);
        }
      }
    };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prevOverflow;
      window.removeEventListener("keydown", onKey);
    };
  }, [open, onClose, step]);

  if (!open) return null;

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

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

  const goBack = () => { if (step === 0) return; setDirection(-1); setStep((s) => s - 1); };

  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);

    // POST to our serverless function, which scores the lead and notifies Slack.
    // Answers are sent keyed by question id (q1..q7) so the API doesn't have to
    // parse human-readable labels.
    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) {
      // Network error — fall back to "review" so the prospect isn't stranded.
      // Their data is lost in this case; we accept that for resilience over UX.
      console.error("apply submit failed:", err);
    }

    // Stash identity for the qualified page (Cal.com embed pre-fills name/email).
    // Done here while we still have the contact in scope.
    try {
      sessionStorage.setItem("dominance_lead_first_name", contact.firstName.trim());
      sessionStorage.setItem("dominance_lead_email", contact.email.trim());
    } catch {}

    onComplete(result);
  };

  return (
    <div className="modal-root" role="dialog" aria-modal="true">
      <div className="modal-backdrop" onClick={onClose} />
      <div className="modal-shell">
        <div className="modal-vignette" aria-hidden="true" />
        <div className="modal-head">
          <div className="modal-head-left">
            <img src="assets/dominance-d-white.png" alt="" className="modal-d" />
            <span className="modal-head-label">Revenue Growth Call Application</span>
          </div>
          <div className="modal-head-right">
            {!isContact && (
              <span className="modal-step-count">
                <b>{String(step + 1).padStart(2, "0")}</b>
                <span className="sep">/</span>
                <span className="of">{String(totalQ).padStart(2, "0")}</span>
              </span>
            )}
            <button className="modal-close" onClick={onClose} aria-label="Close">
              <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>
          </div>
        </div>

        <div className="stepper-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>

        <div className="modal-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>
          )}
        </div>

        <div className="modal-foot">
          <button className="btn-ghost modal-back" onClick={goBack} disabled={step === 0}
            style={{ opacity: step === 0 ? 0.35 : 1, pointerEvents: step === 0 ? "none" : "auto" }}>
            <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>
          <span className="modal-foot-status">
            {isContact ? <>Fill in your details to <b>submit</b></> : <>Select an option <span className="kbd">A–{String.fromCharCode(64 + currentQ.options.length)}</span> to continue</>}
          </span>
          {isContact ? (
            <button className="btn" onClick={handleSubmit} disabled={submitting}>
              <span className="glint" /><span>{submitting ? "Sending…" : "Submit application"}</span><span className="arrow">→</span>
            </button>
          ) : <span style={{ width: 1 }} />}
        </div>
      </div>
    </div>
  );
}

function VslPage({ tweaks, navigate }) {
  const [modalOpen, setModalOpen] = useState(false);
  return (
    <>
      <TopNav status="Step 2 of 2 — Watch & Apply" />
      <main className="page">
        <div className="container">
          <section className="vsl-head fade-in">
            <span className="eyebrow"><span className="tick" />Step 02 / 02 — The Process</span>
            <h1 className="title" style={{ maxWidth: "20ch" }}>Here's exactly how we book you qualified sales calls.</h1>
            <p className="lede">10 minutes. Understand the full process before we talk.</p>
          </section>

          <section className="vsl-grid fade-in-2 reveal">
            <div>
              <VideoFrame runtime={tweaks.videoRuntime} live="VSL" caption="Full walkthrough" />
              <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 16 }}>
                <span className="btn-pill">Chapters</span>
                <span className="btn-pill">01 — The model</span>
                <span className="btn-pill">02 — Infrastructure</span>
                <span className="btn-pill">03 — Booking engine</span>
                <span className="btn-pill">04 — Pricing</span>
              </div>
            </div>
            <aside className="vsl-side">
              <div className="side-card">
                <h4>What you'll learn</h4>
                <div className="steps">
                  <div className="step done"><div className="n">1</div><div className="body"><b>Why cold email wins in 2026</b><span>And how it became the #1 B2B acquisition channel.</span></div></div>
                  <div className="step active"><div className="n">2</div><div className="body"><b>Our sending infrastructure</b><span>Domains, deliverability, and scaling without burning.</span></div></div>
                  <div className="step"><div className="n">3</div><div className="body"><b>Reply-to-booked-call system</b><span>The sequence logic that turns cold replies into calls.</span></div></div>
                  <div className="step"><div className="n">4</div><div className="body"><b>Pay-on-show pricing</b><span>You pay only for calls that actually show. No tricks.</span></div></div>
                </div>
              </div>
              <div className="side-card">
                <h4>The model</h4>
                <p style={{ margin: 0, fontSize: 14, lineHeight: 1.55, color: "var(--text-1)" }}>
                  We build end-to-end cold email infrastructure, run your outbound at scale, and only invoice when a qualified prospect attends a scheduled call. No setup fees. No retainers.
                </p>
                <div style={{ display: "flex", gap: 12, marginTop: 16, flexWrap: "wrap" }}>
                  <span className="btn-pill">Pay per show</span>
                  <span className="btn-pill">No retainer</span>
                  <span className="btn-pill">Month-to-month</span>
                </div>
              </div>
            </aside>
          </section>

          <section className="apply-cta fade-in-3 reveal" id="apply">
            <div className="apply-cta-inner">
              <div className="apply-cta-text">
                <span className="eyebrow"><span className="tick" />Think You're a Fit?</span>
                <h2 className="title" style={{ marginTop: 14 }}>Apply for a Revenue Growth Call.</h2>
                <div className="apply-cta-meta" style={{ marginTop: 16 }}>
                  <span><b>7</b> questions</span><span>·</span><span><b>~2 min</b> to complete</span><span>·</span><span><b>Instant</b> or <b>24h</b> reply</span>
                </div>
              </div>
              <div className="apply-cta-action">
                <button className="btn magnetic" onClick={() => {
                  // Mobile gets a dedicated /apply page (no modal — iOS Safari
                  // can't be made to behave inside a fixed overlay). Desktop
                  // keeps the modal so the VSL stays visible behind it.
                  if (window.matchMedia("(max-width: 640px)").matches) {
                    navigate("/apply");
                  } else {
                    setModalOpen(true);
                  }
                }}>
                  <span className="glint" /><span>Apply Now and See If You Qualify</span><span className="arrow">→</span>
                </button>
                <span className="apply-cta-note">Reviewed personally by Nik.</span>
              </div>
            </div>
          </section>
        </div>
      </main>
      <Footer />
      <ApplicationModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        onComplete={(result) => {
          setModalOpen(false);
          // QUALIFIED → /qualified (Cal.com embed).
          // REVIEW    → /application-received (Nik triages from Slack within 24h).
          // REJECT    → /declined (closed, no follow-up promised).
          // Network-error fallback defaults result.bucket to "review" — these
          // visitors land on /application-received, which is the safe default
          // (we'd rather give a stranger 24h of attention than wrongly decline).
          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");
          }
        }}
      />
    </>
  );
}

window.VslPage = VslPage;
// Shared with page-apply.jsx (mobile flow uses the same questions).
window.APPLY_QUESTIONS = QUESTIONS;
