/* BioReveal — Quiz step components, brand-matched (white paper, ink type, dusty rose accent) */

const StepIntro = ({ onNext }) => {
  const { FaceScanDemo, HowAIWorks, OurServices, SampleReveal, SocialProof, FAQ, StartCTA } = window.BR_LANDING;
  return (
    <>
      <section className="br-hero">
        <div className="container br-hero-inner">
          <div className="br-hero-copy">
            <div className="eyebrow" style={{ marginBottom: 20, display: "block" }}>★ BIOREVEAL · 90-SECOND ANALYSIS</div>
            <h1 className="br-hero-h1">Decode<br/><span className="accent">your stack.</span></h1>
            <p className="br-hero-p">A 90-second AI read of your goals, signals, and lifestyle. We map you against 47,000+ outcomes to surface the peptides most likely to move your mind, body, and life.</p>
            <button className="btn btn-dark btn-lg" onClick={onNext} style={{ marginTop: 8 }}>Begin analysis →</button>
            <ul className="br-hero-meta">
              <li><span>★</span> 90-second scan</li>
              <li><span>★</span> No bloodwork</li>
              <li><span>★</span> MD-reviewed</li>
            </ul>
          </div>
          <div className="br-hero-vials">
            {["BPC-157", "NAD+", "Ipamorelin", "GHK-Cu"].map(p => (
              <div key={p} className="br-hero-vial"><ProductShot product={p} chip={false}/></div>
            ))}
          </div>
        </div>
      </section>

      {/* Live face-scan demo */}
      <section className="br-section br-facescan-section">
        <div className="container">
          <FaceScanDemo/>
        </div>
      </section>

      <HowAIWorks/>
      <OurServices/>
      <SampleReveal/>
      <SocialProof/>
      <FAQ/>
      <StartCTA onNext={onNext}/>
    </>
  );
};

const GOALS = [
  { id: "muscle",    icon: "◆", label: "Build muscle",       sub: "Train harder. Recover faster." },
  { id: "weight",    icon: "▼", label: "Lose weight",        sub: "Quiet cravings. Move the scale." },
  { id: "skin",      icon: "✿", label: "Fix your skin",      sub: "Calm redness. Smooth texture." },
  { id: "hair",      icon: "❋", label: "Grow your hair",     sub: "Wake sleeping follicles." },
  { id: "energy",    icon: "✦", label: "More energy",        sub: "Stop needing the second coffee." },
  { id: "sleep",     icon: "☾", label: "Sleep deeper",       sub: "Wake up actually rested." },
  { id: "brain",     icon: "▲", label: "Think smarter",      sub: "Sharper focus. Calmer mood." },
  { id: "longevity", icon: "∞", label: "Age slower",         sub: "Look 30 at 40." },
  { id: "libido",    icon: "♥", label: "More drive",         sub: "Reignite the spark." },
];

// Goals takes both: structured chip selection (max 3) + free-text "tell us
// in your own words" — the textarea becomes the highest-leverage signal
// Claude sees (verbatim patient language). Stored as { ids: [...], note: "..." }.
const StepGoals = ({ value, onChange }) => {
  const v = Array.isArray(value) ? { ids: value, note: "" } : (value || { ids: [], note: "" });
  const ids = v.ids || [];
  const note = v.note || "";
  const toggle = (id) => {
    const next = ids.includes(id) ? ids.filter(x => x !== id) : [...ids, id].slice(-3);
    onChange({ ids: next, note });
  };
  const setNote = (t) => onChange({ ids, note: t });
  return (
    <>
      <div className="br-eyebrow">01 / 04 · Pick up to 3</div>
      <h2 className="br-question">What do you want different in 90 days?</h2>
      <p className="br-sub">No wrong answers — just your honest list.</p>
      <div className="br-grid">
        {GOALS.map(g => (
          <button key={g.id} className={"br-tile " + (ids.includes(g.id) ? "selected" : "")} onClick={() => toggle(g.id)}>
            <div className="br-tile-icon">{g.icon}</div>
            <div className="br-tile-label">{g.label}</div>
            <div className="br-tile-sub">{g.sub}</div>
          </button>
        ))}
      </div>
      <div style={{ marginTop: 24 }}>
        <div className="br-eyebrow" style={{ marginBottom: 8 }}>In your own words (optional, but powerful)</div>
        <textarea
          value={note}
          onChange={(e) => setNote(e.target.value)}
          placeholder="e.g. I'm tired by 2pm every day, my skin keeps breaking out, and I can't sleep through the night."
          rows={3}
          style={{
            width: "100%", boxSizing: "border-box", padding: "14px 16px",
            background: "var(--paper-2)", border: "1.5px solid var(--paper-3)",
            borderRadius: "var(--r-md)", fontSize: 14, fontFamily: "inherit",
            color: "var(--ink)", lineHeight: 1.5, resize: "vertical", outline: "none",
          }}
        />
        <div style={{ marginTop: 6, fontSize: 11, color: "var(--muted)", fontFamily: "var(--font-mono)", letterSpacing: "0.05em" }}>
          ⓘ The AI uses every word. Be specific.
        </div>
      </div>
    </>
  );
};

// Step 2 of the funnel — capture lead info BEFORE the camera-permission ask
// so even bail-outs convert to leads. Required: name + email. Optional: phone
// (for SMS check-ins). Validation is light — we don't want to gate on it.
const StepContact = ({ value = {}, onChange }) => {
  const v = { name: "", email: "", phone: "", ...value };
  const set = (k, val) => onChange({ ...v, [k]: val });
  const emailOk = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.email || "");
  const nameOk = (v.name || "").trim().length >= 2;
  return (
    <>
      <div className="br-eyebrow">02 / 04 · Where to send your read</div>
      <h2 className="br-question">Who are we writing this for?</h2>
      <p className="br-sub">We email your analysis the moment it's ready and text check-ins as your protocol unfolds. Nothing else.</p>

      <div style={{ marginBottom: 16 }}>
        <div className="br-eyebrow" style={{ marginBottom: 8 }}>First name</div>
        <input type="text" value={v.name} onChange={(e) => set("name", e.target.value)}
          placeholder="Alex"
          autoComplete="given-name"
          style={{ width: "100%", boxSizing: "border-box", padding: "14px 16px", background: "var(--paper-2)", border: "1.5px solid " + (nameOk || !v.name ? "var(--paper-3)" : "#e2c8c8"), borderRadius: "var(--r-md)", fontSize: 15, fontFamily: "inherit", color: "var(--ink)", outline: "none" }}/>
      </div>

      <div style={{ marginBottom: 16 }}>
        <div className="br-eyebrow" style={{ marginBottom: 8 }}>Email <span style={{ opacity: 0.5 }}>· required</span></div>
        <input type="email" value={v.email} onChange={(e) => set("email", e.target.value.trim())}
          placeholder="you@where.com"
          autoComplete="email"
          style={{ width: "100%", boxSizing: "border-box", padding: "14px 16px", background: "var(--paper-2)", border: "1.5px solid " + (emailOk || !v.email ? "var(--paper-3)" : "#e2c8c8"), borderRadius: "var(--r-md)", fontSize: 15, fontFamily: "inherit", color: "var(--ink)", outline: "none" }}/>
      </div>

      <div style={{ marginBottom: 12 }}>
        <div className="br-eyebrow" style={{ marginBottom: 8 }}>Phone <span style={{ opacity: 0.5 }}>· optional, for check-ins</span></div>
        <input type="tel" value={v.phone} onChange={(e) => set("phone", e.target.value)}
          placeholder="(555) 123-4567"
          autoComplete="tel"
          style={{ width: "100%", boxSizing: "border-box", padding: "14px 16px", background: "var(--paper-2)", border: "1.5px solid var(--paper-3)", borderRadius: "var(--r-md)", fontSize: 15, fontFamily: "inherit", color: "var(--ink)", outline: "none" }}/>
      </div>

      <div style={{ display: "flex", gap: 10, alignItems: "flex-start", marginTop: 16, fontSize: 12, color: "var(--muted)", lineHeight: 1.5 }}>
        <span style={{ flexShrink: 0, width: 16, height: 16, borderRadius: 4, background: "var(--lime)", color: "var(--ink)", display: "grid", placeItems: "center", fontSize: 10, fontWeight: 800 }}>✓</span>
        <span>BioReveal is a fit-finder, not medical advice. A licensed clinician reviews every protocol before fulfillment. No spam — unsubscribe anytime.</span>
      </div>
    </>
  );
};

// NEW: compact safety screen — age, sex, pregnant, cancer flag, meds, allergies
// Replaces StepFeel + StepTraining + StepVices + StepBasics + StepMedical for
// the v2 funnel. Full clinical intake moves to the post-protocol consult form.
const StepSafety = ({ value = {}, onChange }) => {
  const v = {
    age: 32, sex: null, pregnant: false, cancer_history: false,
    current_meds: "", allergies: "",
    ...value,
  };
  const set = (k, val) => onChange({ ...v, [k]: val });
  return (
    <>
      <div className="br-eyebrow">04 / 04 · Safety screen · 30 seconds</div>
      <h2 className="br-question">A few safety basics.</h2>
      <p className="br-sub">Required for clinician review. Honest answers protect you.</p>

      <div style={{ marginBottom: 20 }}>
        <div className="br-eyebrow" style={{ marginBottom: 10 }}>Sex assigned at birth</div>
        <div style={{ display: "flex", gap: 10 }}>
          {["female", "male", "intersex"].map(s => (
            <button key={s} className={"br-option " + (v.sex === s ? "selected" : "")} style={{ flex: 1, justifyContent: "center", textTransform: "capitalize" }} onClick={() => set("sex", s)}>
              {s}
            </button>
          ))}
        </div>
      </div>

      <div className="br-slider-row" style={{ marginBottom: 24 }}>
        <label><span>Age</span><span className="val">{v.age}</span></label>
        <input type="range" min="18" max="75" value={v.age}
          style={{ "--p": ((v.age - 18) / 57 * 100) + "%" }}
          onChange={(e) => set("age", Number(e.target.value))} />
        <div className="br-slider-low-high"><span>18</span><span>75</span></div>
      </div>

      <div style={{ marginBottom: 18 }}>
        <div className="br-eyebrow" style={{ marginBottom: 10 }}>Pregnant, breastfeeding, or trying to conceive?</div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className={"br-option " + (v.pregnant === false ? "selected" : "")} style={{ flex: 1, justifyContent: "center" }} onClick={() => set("pregnant", false)}>No</button>
          <button className={"br-option " + (v.pregnant === true ? "selected" : "")} style={{ flex: 1, justifyContent: "center" }} onClick={() => set("pregnant", true)}>Yes</button>
        </div>
      </div>

      <div style={{ marginBottom: 18 }}>
        <div className="br-eyebrow" style={{ marginBottom: 10 }}>Personal or 1st-degree-family cancer history?</div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className={"br-option " + (v.cancer_history === false ? "selected" : "")} style={{ flex: 1, justifyContent: "center" }} onClick={() => set("cancer_history", false)}>No</button>
          <button className={"br-option " + (v.cancer_history === true ? "selected" : "")} style={{ flex: 1, justifyContent: "center" }} onClick={() => set("cancer_history", true)}>Yes</button>
        </div>
      </div>

      <div style={{ marginBottom: 16 }}>
        <div className="br-eyebrow" style={{ marginBottom: 8 }}>Current meds & supplements (optional)</div>
        <input type="text" value={v.current_meds} onChange={(e) => set("current_meds", e.target.value)}
          placeholder="e.g. metformin, levothyroxine, creatine"
          style={{ width: "100%", boxSizing: "border-box", padding: "12px 14px", background: "var(--paper-2)", border: "1.5px solid var(--paper-3)", borderRadius: "var(--r-md)", fontSize: 14, fontFamily: "inherit", color: "var(--ink)" }}/>
      </div>

      <div style={{ marginBottom: 16 }}>
        <div className="br-eyebrow" style={{ marginBottom: 8 }}>Drug or food allergies (optional)</div>
        <input type="text" value={v.allergies} onChange={(e) => set("allergies", e.target.value)}
          placeholder="e.g. sulfa, penicillin, shellfish"
          style={{ width: "100%", boxSizing: "border-box", padding: "12px 14px", background: "var(--paper-2)", border: "1.5px solid var(--paper-3)", borderRadius: "var(--r-md)", fontSize: 14, fontFamily: "inherit", color: "var(--ink)" }}/>
      </div>

      <div style={{ marginTop: 14, fontSize: 11, color: "var(--muted)", lineHeight: 1.5, fontFamily: "var(--font-mono)", letterSpacing: "0.05em" }}>
        🔒 <strong>HIPAA-ALIGNED</strong> · Only the reviewing clinician sees the full record. Full intake on your consult.
      </div>
    </>
  );
};

const StepSelfie = ({ value, onChange }) => {
  const [scanning, setScanning] = React.useState(false);
  const [done, setDone] = React.useState(!!value);
  const start = () => {
    setScanning(true);
    setTimeout(() => { setScanning(false); setDone(true); onChange({ captured: true }); }, 2400);
  };
  return (
    <>
      <div className="br-eyebrow">03 / 08 · Optional · Not stored</div>
      <h2 className="br-question">Snap a selfie.</h2>
      <p className="br-sub">A soft-light read of skin, eye area, and vitality cues. We use it as a fun visual signal — not a diagnostic. Skip if you'd rather not.</p>
      <div className="br-selfie-frame">
        <div className="br-corner tl"/><div className="br-corner tr"/>
        <div className="br-corner bl"/><div className="br-corner br"/>
        <div className="br-face-guide"><div className="br-face-guide-shape"/></div>
        {scanning && <div className="br-scan-line"/>}
        <div className="br-selfie-stat" style={{ top: 16, left: 44 }}>RGB · 24-BIT</div>
        <div className="br-selfie-stat" style={{ top: 16, right: 44 }}>● REC</div>
        <div className="br-selfie-stat" style={{ bottom: 16, left: 44 }}>{done ? "✓ ANALYZED" : scanning ? "SCANNING…" : "ALIGN FACE"}</div>
      </div>
      <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
        <button className={"br-option " + (done ? "selected" : "")} style={{ flex: 1, justifyContent: "center" }} onClick={start} disabled={scanning}>
          {done ? "✓ Captured" : scanning ? "Scanning…" : "Capture"}
        </button>
        <button className="br-option" style={{ flex: 1, justifyContent: "center" }} onClick={() => { setDone(true); onChange({ skipped: true }); }}>
          Skip
        </button>
      </div>
    </>
  );
};

const FEEL = [
  { id: "energy",   label: "Energy day-to-day",     low: "Drained",   high: "Wired" },
  { id: "sleep",    label: "Sleep quality",          low: "Wrecked",   high: "Restorative" },
  { id: "recovery", label: "Post-workout recovery",  low: "Days",      high: "Hours" },
  { id: "mood",     label: "Mood & focus",           low: "Foggy",     high: "Locked-in" },
  { id: "drive",    label: "Drive / libido",         low: "Flat",      high: "Roaring" },
];

const StepFeel = ({ value = {}, onChange }) => {
  const get = (id) => value[id] ?? 5;
  return (
    <>
      <div className="br-eyebrow">04 / 08 · Be honest</div>
      <h2 className="br-question">How do you feel right now?</h2>
      <p className="br-sub">1 = ground floor. 10 = peak. We calibrate from here.</p>
      <div className="br-slider-group">
        {FEEL.map(f => {
          const v = get(f.id);
          return (
            <div key={f.id} className="br-slider-row">
              <label><span>{f.label}</span><span className="val">{v}/10</span></label>
              <input type="range" min="1" max="10" value={v}
                style={{ "--p": ((v - 1) / 9 * 100) + "%" }}
                onChange={(e) => onChange({ ...value, [f.id]: Number(e.target.value) })} />
              <div className="br-slider-low-high"><span>{f.low}</span><span>{f.high}</span></div>
            </div>
          );
        })}
      </div>
    </>
  );
};

const TRAIN = [
  { id: "elite",   mark: "◆", label: "Elite",         sub: "5+ days, programmed" },
  { id: "regular", mark: "▲", label: "Regular",       sub: "3–4 days a week" },
  { id: "casual",  mark: "●", label: "Casual",        sub: "1–2 days, mixed" },
  { id: "none",    mark: "○", label: "Just walking",  sub: "Building back up" },
];

const StepTraining = ({ value, onChange }) => (
  <>
    <div className="br-eyebrow">05 / 08 · Movement profile</div>
    <h2 className="br-question">How are you training?</h2>
    <p className="br-sub">Stack intensity scales to your load.</p>
    <div className="br-options">
      {TRAIN.map(o => (
        <button key={o.id} className={"br-option " + (value === o.id ? "selected" : "")} onClick={() => onChange(o.id)}>
          <span className="br-option-mark">{o.mark}</span>
          <div>
            <div className="br-option-label">{o.label}</div>
            <div className="br-option-sub">{o.sub}</div>
          </div>
        </button>
      ))}
    </div>
  </>
);

const VICES = [
  { id: "drink",     icon: "◇", label: "Alcohol",         sub: "More than I'd like" },
  { id: "screen",    icon: "▢", label: "Late screens",    sub: "Scrolling past midnight" },
  { id: "stress",    icon: "≈", label: "Chronic stress",  sub: "Always wired" },
  { id: "sugar",     icon: "✕", label: "Sugar / refined", sub: "Cravings rule" },
  { id: "smoke",     icon: "~", label: "Nicotine",        sub: "Vape, smoke, pouch" },
  { id: "sedentary", icon: "—", label: "Mostly sitting",  sub: "Desk-bound days" },
];

const StepVices = ({ value = [], onChange }) => {
  const toggle = (id) => onChange(value.includes(id) ? value.filter(v => v !== id) : [...value, id]);
  return (
    <>
      <div className="br-eyebrow">06 / 08 · No judgment</div>
      <h2 className="br-question">What's blocking your peak?</h2>
      <p className="br-sub">Pick everything that applies. We adjust the protocol around it.</p>
      <div className="br-grid">
        {VICES.map(v => (
          <button key={v.id} className={"br-tile " + (value.includes(v.id) ? "selected" : "")} onClick={() => toggle(v.id)}>
            <div className="br-tile-icon">{v.icon}</div>
            <div className="br-tile-label">{v.label}</div>
            <div className="br-tile-sub">{v.sub}</div>
          </button>
        ))}
      </div>
    </>
  );
};

const StepBasics = ({ value = {}, onChange }) => {
  const sex = value.sex;
  const age = value.age ?? 32;
  return (
    <>
      <div className="br-eyebrow">07 / 08 · Calibration data</div>
      <h2 className="br-question">A few basics.</h2>
      <p className="br-sub">Sex and age shape baseline hormone curves.</p>
      <div style={{ marginBottom: 16 }}>
        <div className="br-eyebrow" style={{ marginBottom: 10 }}>Sex assigned at birth</div>
        <div style={{ display: "flex", gap: 10 }}>
          {["female", "male", "intersex"].map(s => (
            <button key={s} className={"br-option " + (sex === s ? "selected" : "")} style={{ flex: 1, justifyContent: "center", textTransform: "capitalize" }} onClick={() => onChange({ ...value, sex: s })}>
              {s}
            </button>
          ))}
        </div>
      </div>
      <div className="br-slider-row" style={{ marginTop: 24 }}>
        <label><span>Age</span><span className="val">{age}</span></label>
        <input type="range" min="18" max="75" value={age}
          style={{ "--p": ((age - 18) / 57 * 100) + "%" }}
          onChange={(e) => onChange({ ...value, age: Number(e.target.value) })} />
        <div className="br-slider-low-high"><span>18</span><span>75</span></div>
      </div>
    </>
  );
};

const StepEmail = ({ value = "", onChange }) => (
  <>
    <div className="br-eyebrow">08 / 08 · Where to send your blueprint</div>
    <h2 className="br-question">Reveal the protocol.</h2>
    <p className="br-sub">We'll email a copy of your stack + 12-week timeline. No spam, ever.</p>
    <input
      type="email"
      placeholder="you@where.com"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      style={{
        width: "100%", boxSizing: "border-box", padding: "18px 20px",
        background: "var(--paper-2)", border: "1.5px solid var(--paper-3)",
        borderRadius: "var(--r-md)", fontSize: 16, fontFamily: "inherit", color: "var(--ink)",
        marginTop: 8,
      }}
    />
    <div style={{ display: "flex", gap: 12, alignItems: "flex-start", marginTop: 16, fontSize: 13, color: "var(--muted)", lineHeight: 1.5 }}>
      <span style={{ flexShrink: 0, width: 18, height: 18, borderRadius: 4, background: "var(--lime)", color: "var(--ink)", display: "grid", placeItems: "center", fontSize: 11, fontWeight: 800 }}>✓</span>
      <span>I understand BioReveal is a fit-finder, not medical advice. A licensed clinician reviews every order before fulfillment.</span>
    </div>
  </>
);

// StepSelfie is the legacy fake-scan; StepVitals (in bioreveal-vitals.jsx) is the real rPPG one.
window.BR_STEPS = window.BR_STEPS || {};
Object.assign(window.BR_STEPS, { StepIntro, StepGoals, StepContact, StepSelfie, StepFeel, StepTraining, StepVices, StepBasics, StepSafety, StepEmail });
