/* Multi-step partner application — BioReveal-style.
 * 5 steps: archetype → business → motivation → contact → confirm.
 * No real backend; submission stays client-side and shows a confirmation
 * with a Calendly stub for discovery call booking.
 */

const ARCHETYPES = [
  { slug: "hair-salons", label: "Hair Salon", icon: "✂" },
  { slug: "yoga-studios", label: "Yoga / Pilates", icon: "❀" },
  { slug: "chiropractors", label: "Chiropractor", icon: "✦" },
  { slug: "gyms", label: "Gym / PT Studio", icon: "✷" },
  { slug: "boutique-fitness", label: "Boutique Fitness Chain (HQ)", icon: "✪" },
  { slug: "med-spa", label: "Med Spa / IV Bar (wholesale tier)", icon: "★" },
  { slug: "other", label: "Other wellness venue", icon: "✿" },
];

const SIZE_BUCKETS = [
  "1-50 active members/clients",
  "51-200",
  "201-500",
  "501-1,500",
  "1,501-5,000",
  "5,000+",
];

const MOTIVATIONS = [
  "Add a recurring revenue stream",
  "Improve member retention",
  "Members are already asking",
  "Differentiate from competitors",
  "Layer on existing supplement/retail line",
  "All of the above",
];

const ApplyPage = () => {
  const Header = window.Header;
  const Footer = window.Footer;

  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    archetype: "",
    businessName: "",
    yearsInBusiness: "",
    size: "",
    state: "",
    city: "",
    decisionMaker: "",
    role: "",
    motivations: [],
    timeline: "",
    name: "",
    email: "",
    phone: "",
    note: "",
  });
  const [errors, setErrors] = React.useState({});

  const update = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const toggleMotivation = (m) => {
    setData((d) => ({
      ...d,
      motivations: d.motivations.includes(m)
        ? d.motivations.filter((x) => x !== m)
        : [...d.motivations, m],
    }));
  };

  function validate() {
    const e = {};
    if (step === 0 && !data.archetype) e.archetype = "Pick your archetype";
    if (step === 1) {
      if (!data.businessName.trim()) e.businessName = "Required";
      if (!data.size) e.size = "Required";
      if (!data.state.trim()) e.state = "Required";
    }
    if (step === 2) {
      if (data.motivations.length === 0) e.motivations = "Pick at least one";
      if (!data.timeline) e.timeline = "Required";
    }
    if (step === 3) {
      if (!data.name.trim()) e.name = "Required";
      if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email)) e.email = "Valid email required";
      if (!data.phone.trim() || data.phone.replace(/\D/g, "").length < 10) e.phone = "10-digit phone";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function next() {
    if (validate()) {
      setStep((s) => s + 1);
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  }
  function back() {
    setStep((s) => Math.max(0, s - 1));
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function submit() {
    if (!validate()) return;
    // Stub — future: POST to backend
    try {
      sessionStorage.setItem("partner_application", JSON.stringify({ ...data, ts: Date.now() }));
    } catch (e) {}
    setStep(4);
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  const stepLabels = ["Archetype", "Business", "Goals", "Contact", "Booked"];

  return (
    <div className="br-page partner-apply-page">
      <Header active="partners" />

      <section className="apply-section">
        <div className="container" style={{ maxWidth: 760 }}>
          {/* Progress */}
          {step < 4 && (
            <>
              <div className="apply-eyebrow">★ CERTIFIED PARTNER APPLICATION</div>
              <h1 className="apply-h1">Tell us about your venue.</h1>
              <p className="apply-sub">
                Five quick steps. We use this to qualify your archetype, set your per-patient fee, and prep your discovery call. No commitment — only confirmed Certified Partners proceed past the discovery call.
              </p>
              <div className="apply-progress">
                {stepLabels.slice(0, 4).map((label, i) => (
                  <div
                    key={label}
                    className={"apply-progress-step" + (i === step ? " active" : "") + (i < step ? " done" : "")}
                  >
                    <div className="apply-progress-dot">{i < step ? "✓" : i + 1}</div>
                    <div className="apply-progress-label">{label}</div>
                  </div>
                ))}
              </div>
            </>
          )}

          {/* STEP 0: Archetype */}
          {step === 0 && (
            <div className="apply-step">
              <div className="apply-step-label">Step 1 of 4</div>
              <h2 className="apply-step-title">What kind of venue do you run?</h2>
              <div className="apply-archetype-grid">
                {ARCHETYPES.map((a) => (
                  <button
                    key={a.slug}
                    onClick={() => update("archetype", a.slug)}
                    className={"apply-archetype-tile" + (data.archetype === a.slug ? " selected" : "")}
                  >
                    <div className="apply-archetype-icon">{a.icon}</div>
                    <div className="apply-archetype-label">{a.label}</div>
                  </button>
                ))}
              </div>
              {errors.archetype && <div className="apply-err">{errors.archetype}</div>}
              <div className="apply-actions">
                <span />
                <button className="btn btn-primary" onClick={next}>Continue →</button>
              </div>
            </div>
          )}

          {/* STEP 1: Business */}
          {step === 1 && (
            <div className="apply-step">
              <div className="apply-step-label">Step 2 of 4</div>
              <h2 className="apply-step-title">Your business.</h2>
              <div className="apply-grid">
                <div className="apply-field">
                  <label>Business name</label>
                  <input value={data.businessName} onChange={(e) => update("businessName", e.target.value)} placeholder="Aurora Yoga Studio" />
                  {errors.businessName && <div className="apply-err">{errors.businessName}</div>}
                </div>
                <div className="apply-field">
                  <label>Years in business</label>
                  <input value={data.yearsInBusiness} onChange={(e) => update("yearsInBusiness", e.target.value)} placeholder="6" />
                </div>
                <div className="apply-field">
                  <label>Size</label>
                  <div className="apply-pills">
                    {SIZE_BUCKETS.map((s) => (
                      <button
                        key={s}
                        onClick={() => update("size", s)}
                        className={"apply-pill" + (data.size === s ? " active" : "")}
                      >{s}</button>
                    ))}
                  </div>
                  {errors.size && <div className="apply-err">{errors.size}</div>}
                </div>
                <div className="apply-field">
                  <label>State</label>
                  <input value={data.state} onChange={(e) => update("state", e.target.value)} placeholder="TX" />
                  {errors.state && <div className="apply-err">{errors.state}</div>}
                </div>
                <div className="apply-field">
                  <label>City / Metro</label>
                  <input value={data.city} onChange={(e) => update("city", e.target.value)} placeholder="Austin" />
                </div>
                <div className="apply-field">
                  <label>Decision maker name</label>
                  <input value={data.decisionMaker} onChange={(e) => update("decisionMaker", e.target.value)} placeholder="(or leave blank if it's you)" />
                </div>
                <div className="apply-field">
                  <label>Your role</label>
                  <input value={data.role} onChange={(e) => update("role", e.target.value)} placeholder="Owner / GM / VP Partnerships" />
                </div>
              </div>
              <div className="apply-actions">
                <button className="btn btn-ghost" onClick={back}>← Back</button>
                <button className="btn btn-primary" onClick={next}>Continue →</button>
              </div>
            </div>
          )}

          {/* STEP 2: Motivation */}
          {step === 2 && (
            <div className="apply-step">
              <div className="apply-step-label">Step 3 of 4</div>
              <h2 className="apply-step-title">Why are you exploring this?</h2>
              <div className="apply-field">
                <label>Pick all that apply</label>
                <div className="apply-pills apply-pills-multi">
                  {MOTIVATIONS.map((m) => (
                    <button
                      key={m}
                      onClick={() => toggleMotivation(m)}
                      className={"apply-pill" + (data.motivations.includes(m) ? " active" : "")}
                    >{m}</button>
                  ))}
                </div>
                {errors.motivations && <div className="apply-err">{errors.motivations}</div>}
              </div>
              <div className="apply-field">
                <label>How soon would you want to be live?</label>
                <div className="apply-pills">
                  {["This month", "30-60 days", "60-90 days", "Just exploring"].map((t) => (
                    <button
                      key={t}
                      onClick={() => update("timeline", t)}
                      className={"apply-pill" + (data.timeline === t ? " active" : "")}
                    >{t}</button>
                  ))}
                </div>
                {errors.timeline && <div className="apply-err">{errors.timeline}</div>}
              </div>
              <div className="apply-actions">
                <button className="btn btn-ghost" onClick={back}>← Back</button>
                <button className="btn btn-primary" onClick={next}>Continue →</button>
              </div>
            </div>
          )}

          {/* STEP 3: Contact */}
          {step === 3 && (
            <div className="apply-step">
              <div className="apply-step-label">Step 4 of 4</div>
              <h2 className="apply-step-title">How do we reach you?</h2>
              <div className="apply-grid">
                <div className="apply-field apply-field-full">
                  <label>Your name</label>
                  <input value={data.name} onChange={(e) => update("name", e.target.value)} placeholder="Your name" />
                  {errors.name && <div className="apply-err">{errors.name}</div>}
                </div>
                <div className="apply-field">
                  <label>Email</label>
                  <input type="email" value={data.email} onChange={(e) => update("email", e.target.value)} placeholder="you@business.com" />
                  {errors.email && <div className="apply-err">{errors.email}</div>}
                </div>
                <div className="apply-field">
                  <label>Phone (mobile)</label>
                  <input value={data.phone} onChange={(e) => update("phone", e.target.value)} placeholder="555-555-5555" />
                  {errors.phone && <div className="apply-err">{errors.phone}</div>}
                </div>
                <div className="apply-field apply-field-full">
                  <label>Anything else we should know? (optional)</label>
                  <textarea
                    value={data.note}
                    onChange={(e) => update("note", e.target.value)}
                    rows={4}
                    placeholder="Specific peptides you're curious about, members already asking, etc."
                  />
                </div>
              </div>
              <div className="apply-actions">
                <button className="btn btn-ghost" onClick={back}>← Back</button>
                <button className="btn btn-primary" onClick={submit}>Submit application →</button>
              </div>
            </div>
          )}

          {/* STEP 4: Confirmation */}
          {step === 4 && (
            <div className="apply-step apply-done">
              <div className="apply-done-star">★</div>
              <h1 className="apply-h1">Application received.</h1>
              <p className="apply-sub">
                Thanks {data.name.split(" ")[0]}. We'll review your application and reach out to {data.email} within 1 business day to schedule your 15-minute discovery call.
              </p>

              <div className="apply-summary">
                <div className="apply-summary-eyebrow">★ YOUR APPLICATION</div>
                <div className="apply-summary-row"><span>Archetype</span><strong>{ARCHETYPES.find(a => a.slug === data.archetype)?.label}</strong></div>
                <div className="apply-summary-row"><span>Business</span><strong>{data.businessName}</strong></div>
                <div className="apply-summary-row"><span>Size</span><strong>{data.size}</strong></div>
                <div className="apply-summary-row"><span>Geo</span><strong>{data.city ? data.city + ", " : ""}{data.state}</strong></div>
                <div className="apply-summary-row"><span>Timeline</span><strong>{data.timeline}</strong></div>
              </div>

              <div className="apply-cal-box">
                <div className="apply-cal-eyebrow">★ NEXT STEP — BOOK YOUR DISCOVERY CALL</div>
                <div className="apply-cal-body">
                  Skip the back-and-forth. Pick a 15-minute slot now and we'll send the calendar invite.
                </div>
                <a href="https://cal.com/cynthia/partners-discovery" target="_blank" rel="noopener" className="btn btn-primary apply-cal-btn">
                  Book my discovery call →
                </a>
              </div>

              <div className="apply-meta-block">
                <div className="apply-meta-title">In the meantime — read these:</div>
                <ul className="apply-meta-list">
                  <li><a href={`/partners/${data.archetype === 'med-spa' || data.archetype === 'other' ? 'hair-salons' : data.archetype}.html`}>Your archetype's deep-dive page</a></li>
                  <li><a href="/partners.html#calculator">Run your numbers in the earnings calculator</a></li>
                  <li><a href="/peptides/">The peptide library — what each one does</a></li>
                </ul>
              </div>
            </div>
          )}
        </div>
      </section>

      <Footer />
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<ApplyPage />);
