// Interactive intake/quiz flow — 7 steps with real state, transitions, and validation

const { useState: useS, useEffect: useE } = React;

function IntakePage({ onBack, onComplete, doctor }) {
  const [step, setStep] = useS(0);
  const [data, setData] = useS({
    primaryConcern: null,
    age: "",
    symptoms: [],
    energy: 5,
    sleep: null,
    height: { ft: "", in: "" },
    weight: "",
    medical: [],
    email: "",
    firstName: "",
    state: "",
  });

  const update = (patch) => setData((d) => ({ ...d, ...patch }));

  const steps = [
    { key: "concern", label: "Goal" },
    { key: "age", label: "About you" },
    { key: "symptoms", label: "Symptoms" },
    { key: "energy", label: "Energy" },
    { key: "vitals", label: "Vitals" },
    { key: "medical", label: "Medical" },
    { key: "results", label: "Results" },
  ];

  const next = () => setStep((s) => Math.min(s + 1, steps.length - 1));
  const prev = () => step === 0 ? onBack?.() : setStep((s) => s - 1);

  const canProceed = () => {
    switch (step) {
      case 0: return !!data.primaryConcern;
      case 1: return data.age && parseInt(data.age) >= 18 && data.firstName.trim().length > 0;
      case 2: return data.symptoms.length > 0;
      case 3: return data.sleep !== null;
      case 4: return data.height.ft && data.weight;
      case 5: return data.email.includes("@") && data.state;
      default: return true;
    }
  };

  return (
    <div style={{ minHeight: "100vh", background: "var(--ink-900)", display: "flex", flexDirection: "column" }}>
      {/* Top bar */}
      <div style={{ borderBottom: "1px solid var(--line)", padding: "20px 32px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <Logo />
        <button onClick={onBack} style={{ background: "transparent", border: "none", color: "var(--cream-400)", fontSize: 14 }}>
          Save & exit
        </button>
      </div>

      {/* Progress */}
      <div style={{ padding: "24px 32px", borderBottom: "1px solid var(--line)" }}>
        <div className="container-narrow" style={{ padding: 0 }}>
          <div style={{ display: "flex", gap: 6, marginBottom: 12 }}>
            {steps.map((s, i) => (
              <div key={s.key} style={{
                flex: 1, height: 3, borderRadius: 2,
                background: i <= step ? "var(--gold-500)" : "var(--line-strong)",
                transition: "background 300ms",
              }}></div>
            ))}
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--cream-400)" }}>
            <span>Step {step + 1} of {steps.length}</span>
            <span>{Math.round(((step + 1) / steps.length) * 100)}% complete</span>
          </div>
        </div>
      </div>

      {/* Content */}
      <div style={{ flex: 1, display: "flex", alignItems: "center", padding: "48px 32px" }}>
        <div className="container-narrow" style={{ padding: 0, width: "100%" }}>
          <div key={step} className="fade-in">
            {step === 0 && <StepConcern data={data} update={update} />}
            {step === 1 && <StepAbout data={data} update={update} />}
            {step === 2 && <StepSymptoms data={data} update={update} />}
            {step === 3 && <StepEnergy data={data} update={update} />}
            {step === 4 && <StepVitals data={data} update={update} />}
            {step === 5 && <StepContact data={data} update={update} />}
            {step === 6 && <StepResults data={data} doctor={doctor} onComplete={onComplete} />}
          </div>
        </div>
      </div>

      {/* Footer */}
      {step < 6 && (
        <div style={{ padding: 32, borderTop: "1px solid var(--line)" }}>
          <div className="container-narrow" style={{ padding: 0, display: "flex", justifyContent: "space-between" }}>
            <button onClick={prev} className="btn btn-ghost">
              <span style={{ transform: "rotate(180deg)", display: "inline-flex" }}><ArrowRight /></span> Back
            </button>
            <button
              onClick={next}
              disabled={!canProceed()}
              className="btn btn-primary"
              style={{ opacity: canProceed() ? 1 : 0.4, pointerEvents: canProceed() ? "auto" : "none" }}
            >
              Continue <ArrowRight />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Step 0: Primary concern ──
function StepConcern({ data, update }) {
  const concerns = [
    { id: "energy", title: "Low energy & drive", body: "Tired, foggy, motivation is gone." },
    { id: "performance", title: "Sexual performance", body: "ED, libido, or both." },
    { id: "weight", title: "Weight & body comp", body: "Stubborn fat, can't gain muscle." },
    { id: "hair", title: "Hair loss", body: "Thinning, receding, looking for help." },
    { id: "general", title: "General optimization", body: "Feel okay, want to feel great." },
    { id: "unsure", title: "Honestly, I'm not sure", body: "Something's off — let's figure it out." },
  ];
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 12 }}>Question 1</div>
      <h2 className="display" style={{ fontSize: "clamp(36px, 4.5vw, 56px)", margin: 0, marginBottom: 12 }}>
        What brings you to <span className="serif-italic" style={{ color: "var(--gold-500)" }}>GTX</span>?
      </h2>
      <p style={{ color: "var(--cream-300)", fontSize: 16, marginBottom: 40 }}>
        Pick whichever fits best. We'll dig into the details next.
      </p>
      <div style={{ display: "grid", gridTemplateColumns: useIsMobile() ? "1fr" : "repeat(2, 1fr)", gap: 12 }}>
        {concerns.map((c) => (
          <button
            key={c.id}
            onClick={() => update({ primaryConcern: c.id })}
            style={{
              background: data.primaryConcern === c.id ? "var(--ink-700)" : "var(--ink-800)",
              border: `1px solid ${data.primaryConcern === c.id ? "var(--gold-500)" : "var(--line-strong)"}`,
              borderRadius: 10, padding: 24, textAlign: "left", color: "var(--cream-50)",
              transition: "all 150ms", cursor: "pointer",
              display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16,
            }}
          >
            <div>
              <div className="display" style={{ fontSize: 22, marginBottom: 6 }}>{c.title}</div>
              <div style={{ fontSize: 13, color: "var(--cream-400)" }}>{c.body}</div>
            </div>
            <div style={{
              width: 22, height: 22, borderRadius: "50%",
              border: `1.5px solid ${data.primaryConcern === c.id ? "var(--gold-500)" : "var(--line-strong)"}`,
              display: "flex", alignItems: "center", justifyContent: "center",
              background: data.primaryConcern === c.id ? "var(--gold-500)" : "transparent",
              color: "var(--ink-900)", flexShrink: 0,
            }}>
              {data.primaryConcern === c.id && <Check size={12} />}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// ── Step 1: About ──
function StepAbout({ data, update }) {
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 12 }}>Question 2</div>
      <h2 className="display" style={{ fontSize: "clamp(36px, 4.5vw, 56px)", margin: 0, marginBottom: 40 }}>
        Let's start with <span className="serif-italic" style={{ color: "var(--gold-500)" }}>the basics</span>.
      </h2>
      <div style={{ display: "grid", gridTemplateColumns: useIsMobile() ? "1fr" : "2fr 1fr", gap: 20, maxWidth: 600 }}>
        <div>
          <label className="label-sm" style={{ display: "block", marginBottom: 10 }}>First name</label>
          <input className="input" placeholder="Marcus" value={data.firstName} onChange={(e) => update({ firstName: e.target.value })} />
        </div>
        <div>
          <label className="label-sm" style={{ display: "block", marginBottom: 10 }}>Age</label>
          <input className="input" type="number" placeholder="42" value={data.age} onChange={(e) => update({ age: e.target.value })} />
        </div>
      </div>
      <p style={{ marginTop: 32, fontSize: 13, color: "var(--cream-400)", display: "flex", alignItems: "center", gap: 8, maxWidth: 600 }}>
        <span style={{ color: "var(--gold-500)" }}><Check /></span>
        We treat men 21 and older. Your information is encrypted and HIPAA-compliant.
      </p>
    </div>
  );
}

// ── Step 2: Symptoms ──
function StepSymptoms({ data, update }) {
  const all = [
    "Persistent fatigue", "Low libido", "Erectile dysfunction", "Brain fog",
    "Weight gain", "Loss of muscle", "Poor sleep", "Mood / irritability",
    "Joint aches", "Reduced motivation", "Slow recovery", "Hair thinning",
  ];
  const toggle = (s) => {
    const has = data.symptoms.includes(s);
    update({ symptoms: has ? data.symptoms.filter((x) => x !== s) : [...data.symptoms, s] });
  };
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 12 }}>Question 3</div>
      <h2 className="display" style={{ fontSize: "clamp(36px, 4.5vw, 56px)", margin: 0, marginBottom: 12 }}>
        Which of these have you <span className="serif-italic" style={{ color: "var(--gold-500)" }}>noticed</span>?
      </h2>
      <p style={{ color: "var(--cream-300)", fontSize: 16, marginBottom: 40 }}>Select all that apply. Be honest — this is between you and your doctor.</p>
      <div style={{ display: "grid", gridTemplateColumns: useIsMobile() ? "1fr 1fr" : "repeat(3, 1fr)", gap: 10 }}>
        {all.map((s) => {
          const on = data.symptoms.includes(s);
          return (
            <button
              key={s}
              onClick={() => toggle(s)}
              style={{
                background: on ? "rgba(13,110,201,0.10)" : "var(--ink-800)",
                border: `1px solid ${on ? "var(--gold-500)" : "var(--line-strong)"}`,
                color: "var(--cream-50)",
                borderRadius: 8, padding: "16px 18px", textAlign: "left",
                fontSize: 14, fontFamily: "var(--font-sans)",
                display: "flex", alignItems: "center", gap: 10,
                transition: "all 150ms",
              }}
            >
              <span style={{
                width: 18, height: 18, borderRadius: 4,
                border: `1.5px solid ${on ? "var(--gold-500)" : "var(--line-strong)"}`,
                background: on ? "var(--gold-500)" : "transparent",
                display: "flex", alignItems: "center", justifyContent: "center",
                color: "var(--ink-900)", flexShrink: 0,
              }}>
                {on && <Check size={11} />}
              </span>
              {s}
            </button>
          );
        })}
      </div>
      <div style={{ marginTop: 24, fontSize: 13, color: "var(--cream-400)" }}>
        {data.symptoms.length === 0 ? "Select at least one to continue." : `${data.symptoms.length} selected`}
      </div>
    </div>
  );
}

// ── Step 3: Energy + sleep ──
function StepEnergy({ data, update }) {
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 12 }}>Question 4</div>
      <h2 className="display" style={{ fontSize: "clamp(36px, 4.5vw, 56px)", margin: 0, marginBottom: 40 }}>
        How's your <span className="serif-italic" style={{ color: "var(--gold-500)" }}>baseline</span>?
      </h2>

      <div style={{ marginBottom: 56 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 16 }}>
          <label className="label-sm">Energy level on a typical day</label>
          <span className="display tab-num" style={{ fontSize: 32, color: "var(--gold-500)" }}>{data.energy}<span style={{ fontSize: 16, color: "var(--cream-400)" }}>/10</span></span>
        </div>
        <input
          type="range" min={1} max={10} value={data.energy}
          onChange={(e) => update({ energy: parseInt(e.target.value) })}
          style={{ width: "100%", accentColor: "var(--gold-500)" }}
        />
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--cream-500)", marginTop: 8 }}>
          <span>Drained</span><span>Average</span><span>Peak performance</span>
        </div>
      </div>

      <div>
        <label className="label-sm" style={{ display: "block", marginBottom: 16 }}>How would you rate your sleep?</label>
        <div style={{ display: "grid", gridTemplateColumns: useIsMobile() ? "1fr 1fr" : "repeat(4, 1fr)", gap: 10 }}>
          {[
            { id: "great", t: "Great", b: "7+ hrs, wake refreshed" },
            { id: "okay", t: "Okay", b: "Some nights are off" },
            { id: "poor", t: "Poor", b: "Wake tired most days" },
            { id: "broken", t: "Broken", b: "Trouble falling/staying asleep" },
          ].map((s) => {
            const on = data.sleep === s.id;
            return (
              <button
                key={s.id}
                onClick={() => update({ sleep: s.id })}
                style={{
                  background: on ? "var(--ink-700)" : "var(--ink-800)",
                  border: `1px solid ${on ? "var(--gold-500)" : "var(--line-strong)"}`,
                  color: "var(--cream-50)",
                  borderRadius: 8, padding: 18, textAlign: "left",
                }}
              >
                <div className="display" style={{ fontSize: 20, marginBottom: 4 }}>{s.t}</div>
                <div style={{ fontSize: 12, color: "var(--cream-400)" }}>{s.b}</div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── Step 4: Vitals ──
function StepVitals({ data, update }) {
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 12 }}>Question 5</div>
      <h2 className="display" style={{ fontSize: "clamp(36px, 4.5vw, 56px)", margin: 0, marginBottom: 12 }}>
        Quick <span className="serif-italic" style={{ color: "var(--gold-500)" }}>vitals</span>.
      </h2>
      <p style={{ color: "var(--cream-300)", marginBottom: 40 }}>Used for dose calculation and BMI. Approximate is fine.</p>
      <div style={{ display: "grid", gridTemplateColumns: useIsMobile() ? "1fr" : "1fr 1fr", gap: 20, maxWidth: 600 }}>
        <div>
          <label className="label-sm" style={{ display: "block", marginBottom: 10 }}>Height</label>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            <div style={{ position: "relative" }}>
              <input className="input" type="number" placeholder="5" value={data.height.ft} onChange={(e) => update({ height: { ...data.height, ft: e.target.value } })} />
              <span style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", color: "var(--cream-400)", fontSize: 13 }}>ft</span>
            </div>
            <div style={{ position: "relative" }}>
              <input className="input" type="number" placeholder="11" value={data.height.in} onChange={(e) => update({ height: { ...data.height, in: e.target.value } })} />
              <span style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", color: "var(--cream-400)", fontSize: 13 }}>in</span>
            </div>
          </div>
        </div>
        <div>
          <label className="label-sm" style={{ display: "block", marginBottom: 10 }}>Weight</label>
          <div style={{ position: "relative" }}>
            <input className="input" type="number" placeholder="190" value={data.weight} onChange={(e) => update({ weight: e.target.value })} />
            <span style={{ position: "absolute", right: 14, top: "50%", transform: "translateY(-50%)", color: "var(--cream-400)", fontSize: 13 }}>lbs</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Step 5: Contact ──
function StepContact({ data, update }) {
  const states = ["TX", "CA", "FL", "NY", "CO", "AZ", "WA", "GA", "NC", "VA", "OH", "IL", "PA", "TN", "MA", "OR", "MI", "MN", "WI", "MO"];
  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 12 }}>Almost done</div>
      <h2 className="display" style={{ fontSize: "clamp(36px, 4.5vw, 56px)", margin: 0, marginBottom: 12 }}>
        Where should we <span className="serif-italic" style={{ color: "var(--gold-500)" }}>send your results</span>?
      </h2>
      <p style={{ color: "var(--cream-300)", marginBottom: 40 }}>We'll prepare a personalized plan and email it to you in the next 60 seconds.</p>

      <div style={{ display: "grid", gridTemplateColumns: useIsMobile() ? "1fr" : "2fr 1fr", gap: 16, maxWidth: 600 }}>
        <div>
          <label className="label-sm" style={{ display: "block", marginBottom: 10 }}>Email</label>
          <input className="input" type="email" placeholder="you@email.com" value={data.email} onChange={(e) => update({ email: e.target.value })} />
        </div>
        <div>
          <label className="label-sm" style={{ display: "block", marginBottom: 10 }}>State</label>
          <select className="input" value={data.state} onChange={(e) => update({ state: e.target.value })} style={{ appearance: "none" }}>
            <option value="">Select...</option>
            {states.map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
      </div>

      <div style={{ marginTop: 32, padding: 20, border: "1px solid var(--line-strong)", borderRadius: 8, background: "var(--ink-800)", maxWidth: 600 }}>
        <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
          <span style={{ color: "var(--gold-500)", flexShrink: 0, marginTop: 2 }}><Check /></span>
          <div style={{ fontSize: 13, color: "var(--cream-300)", lineHeight: 1.6 }}>
            By continuing you agree to our <a href="#" style={{ color: "var(--gold-500)", textDecoration: "underline" }}>Terms of Service</a> and consent to telehealth treatment. We will never share your information. HIPAA-compliant infrastructure.
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Step 6: Results / handoff ──
function StepResults({ data, doctor, onComplete }) {
  const [analyzing, setAnalyzing] = useS(true);
  useE(() => {
    const t = setTimeout(() => setAnalyzing(false), 2400);
    return () => clearTimeout(t);
  }, []);

  const recommendation = (() => {
    const c = data.primaryConcern;
    if (c === "energy" || c === "general" || c === "unsure") return SERVICES.find((s) => s.id === "trt");
    if (c === "performance") return SERVICES.find((s) => s.id === "ed");
    if (c === "weight") return SERVICES.find((s) => s.id === "weight");
    if (c === "hair") return SERVICES.find((s) => s.id === "hair");
    return SERVICES[0];
  })();

  if (analyzing) {
    return (
      <div style={{ textAlign: "center", padding: "60px 0" }}>
        <div style={{ width: 48, height: 48, margin: "0 auto 32px", borderRadius: "50%", border: "2px solid var(--line-strong)", borderTopColor: "var(--gold-500)", animation: "spin 800ms linear infinite" }}></div>
        <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
        <h2 className="display" style={{ fontSize: 36, margin: 0, marginBottom: 12 }}>Analyzing your responses</h2>
        <p style={{ color: "var(--cream-300)", margin: 0 }}>{doctor.name} is reviewing your intake...</p>
      </div>
    );
  }

  return (
    <div>
      <div className="eyebrow" style={{ marginBottom: 12, color: "var(--success)" }}>✓ Your personalized plan is ready</div>
      <h2 className="display" style={{ fontSize: "clamp(36px, 4.5vw, 56px)", margin: 0, marginBottom: 12 }}>
        {data.firstName ? `${data.firstName}, you're` : "You're"} a candidate for{" "}
        <span className="serif-italic" style={{ color: "var(--gold-500)" }}>{recommendation.name}</span>.
      </h2>
      <p style={{ color: "var(--cream-300)", fontSize: 16, marginBottom: 40, maxWidth: 640, lineHeight: 1.6 }}>
        Based on your symptoms and profile, our system has prepared a recommended starting protocol. Final decisions are made by {doctor.name} after your consultation and bloodwork.
      </p>

      <div style={{ display: "grid", gridTemplateColumns: useIsMobile() ? "1fr" : "1.4fr 1fr", gap: 24, marginBottom: 48 }}>
        <div style={{ padding: 32, background: "var(--ink-800)", borderRadius: 12, border: "1px solid var(--gold-700)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 24 }}>
            <span style={{ color: "var(--gold-500)" }}><ServiceIcon id={recommendation.id} size={28} /></span>
            <div>
              <div className="label-sm" style={{ color: "var(--gold-500)" }}>Recommended</div>
              <div className="display" style={{ fontSize: 24 }}>{recommendation.name}</div>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 24 }}>
            <Stat label="Match strength" value="High" tone="success" />
            <Stat label="Estimated cost" value={`$${recommendation.price}/mo`} />
            <Stat label="Time to first dose" value="≈ 7 days" />
            <Stat label="Lab visits/year" value="4" />
          </div>
          <p style={{ fontSize: 14, color: "var(--cream-300)", lineHeight: 1.6, margin: 0 }}>
            {recommendation.blurb} Your protocol will be customized based on your bloodwork and consultation.
          </p>
        </div>
        <div style={{ padding: 32, background: "var(--ink-800)", borderRadius: 12, border: "1px solid var(--line-strong)" }}>
          <div className="label-sm" style={{ marginBottom: 16 }}>What happens next</div>
          <ol style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 16 }}>
            {[
              "Get your labs through any provider (we recommend Function Health)",
              "Book a 30-min video visit with " + doctor.name.split(" ").slice(-1)[0],
              "Receive treatment within 7 days",
            ].map((s, i) => (
              <li key={i} style={{ display: "flex", gap: 12, fontSize: 14, color: "var(--cream-200)", lineHeight: 1.5 }}>
                <span style={{ width: 24, height: 24, borderRadius: "50%", background: "var(--gold-500)", color: "var(--ink-900)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 600, flexShrink: 0 }}>{i + 1}</span>
                {s}
              </li>
            ))}
          </ol>
        </div>
      </div>

      <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
        <button onClick={onComplete} className="btn btn-primary btn-lg">
          Activate my plan & schedule consult <ArrowRight />
        </button>
        <button className="btn btn-ghost btn-lg">Save plan, continue later</button>
      </div>
    </div>
  );
}

function Stat({ label, value, tone }) {
  return (
    <div>
      <div style={{ fontSize: 11, color: "var(--cream-400)", textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 6 }}>{label}</div>
      <div className="display" style={{ fontSize: 22, color: tone === "success" ? "var(--success)" : "var(--cream-50)" }}>{value}</div>
    </div>
  );
}

Object.assign(window, { IntakePage });
