/* global React, ReactDOM */
const { useState, useEffect, useRef } = React;

// ============ TWEAK DEFAULTS ============
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentPalette": ["#E85D2C", "#0B0B0B", "#F5F1EA"],
  "showStickyBar": true,
  "showExitIntent": true,
  "headline": "Stop coding yourself into a stiff, foggy, 38-year-old body.",
  "subhead": "You already know the desk is doing a number on you. It's 20 minutes a day, just a yoga mat, two weeks — and if it clicks, the next two are on us. Built around the way engineers actually live. You've got nothing to lose here.",
  "presalePrice": 49,
  "regularPrice": 99,
  "launchWeeks": 2,
  "waitlistCount": 2,
  "leadMagnetTitle": "Get the free Cognitive Reset PDF",
  "leadMagnetSubtitle": "The whole system + desk stretches + sleep & biohacking — written simply, for engineers.",
  "ctaCopy": "Send me the free PDF"
}/*EDITMODE-END*/;

// ============ ENDPOINTS (replace once connected) ============
const CONFIG = {
  // POST { email, source, notifyOnLaunch, presaleInterest } → Airtable webhook or similar
  emailEndpoint: "/api/subscribe",
  // Page that handles Stripe checkout (separate file in this project)
  checkoutPage: "/checkout",
};

// ============ COUNTDOWN ============
function useCountdown(targetMs) {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);
  const diff = Math.max(0, targetMs - now);
  return {
    d: Math.floor(diff / 86400000),
    h: Math.floor((diff % 86400000) / 3600000),
    m: Math.floor((diff % 3600000) / 60000),
    s: Math.floor((diff % 60000) / 1000),
  };
}
const LAUNCH_TARGET = new Date("2026-07-01T12:00:00").getTime();

// ============ LOCALSTORAGE HELPERS ============
const LS_KEY = "rb4_lead";
function readLead() {
  try { return JSON.parse(localStorage.getItem(LS_KEY) || "null"); } catch { return null; }
}
function saveLead(data) {
  try { localStorage.setItem(LS_KEY, JSON.stringify(data)); } catch {}
}

// ============ LOGO ============
function Logo() {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
        <rect x="1" y="1" width="26" height="26" rx="6" stroke="currentColor" strokeWidth="1.5"/>
        <path d="M8 14 L13 14 M8 8 L20 8 M8 20 L20 20" stroke="currentColor" strokeWidth="1.8" strokeLinecap="square"/>
        <circle cx="20" cy="14" r="3" stroke="currentColor" strokeWidth="1.8"/>
      </svg>
      <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 13, letterSpacing: "0.06em", fontWeight: 600 }}>
        REBUILD<span style={{ color: "var(--accent)" }}>4</span>
      </span>
    </div>
  );
}

// ============ ANNOUNCEMENT BAR ============
function AnnouncementBar({ presalePrice, regularPrice }) {
  const c = useCountdown(LAUNCH_TARGET);
  return (
    <div className="announcement">
      <span className="pulse-dot"></span>
      <span>Free PDF available now · Presale closes at launch in</span>
      <code className="ann-time">{String(c.d).padStart(2,"0")}d : {String(c.h).padStart(2,"0")}h : {String(c.m).padStart(2,"0")}m : {String(c.s).padStart(2,"0")}s</code>
      <span className="ann-sep">·</span>
      <span>Founding <strong>${presalePrice}</strong> → ${regularPrice} after launch</span>
    </div>
  );
}

// ============ NAV ============
function Nav({ onCTA }) {
  return (
    <nav className="nav">
      <Logo />
      <div className="nav-links">
        <a href="#inside">What's inside</a>
        <a href="#how">How it works</a>
        <a href="#reviews">Reviews</a>
        <a href="#faq">FAQ</a>
      </div>
      <button className="nav-cta" onClick={onCTA}>Get free PDF →</button>
    </nav>
  );
}

// ============ EMAIL CAPTURE FORM ============
function EmailCapture({ ctaCopy, presalePrice, regularPrice }) {
  const existing = readLead();
  const [done, setDone] = useState(!!existing?.stage && existing.stage !== "");
  const [email, setEmail] = useState(existing?.email || "");
  const [notify, setNotify] = useState(existing?.notifyOnLaunch ?? true);
  const [presale, setPresale] = useState(existing?.presaleInterest ?? false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  async function submit(e) {
    e.preventDefault();
    setError("");
    if (!/^\S+@\S+\.\S+$/.test(email)) {
      setError("Add a valid email.");
      return;
    }
    setSubmitting(true);
    const payload = {
      email,
      name: "",
      notifyOnLaunch: notify,
      presaleInterest: presale,
      stage: presale ? "presale" : "subscribed",
      source: "hero",
    };
    // POST to the secure serverless function (api/subscribe.js) — the Airtable
    // token NEVER lives in client code. Disable the button while in-flight to
    // prevent double-submits (handled via `submitting`).
    let ok = false;
    try {
      const res = await fetch(CONFIG.emailEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: payload.email, name: payload.name, notifyOnLaunch: payload.notifyOnLaunch, presaleInterest: payload.presaleInterest, stage: payload.stage, source: payload.source }),
      });
      ok = res.ok;
    } catch {
      ok = false;
    }
    setSubmitting(false);
    if (!ok) {
      setError("Something went wrong on our end — please try again in a moment.");
      return;
    }
    saveLead({ ...payload, ts: Date.now() });
    if (window.fbq) window.fbq('track', 'Lead');
    if (presale) {
      window.location.href = `${CONFIG.checkoutPage}?email=${encodeURIComponent(email)}`;
    } else {
      setDone(true);
    }
  }

  if (done) {
    return (
      <div className="capture captured">
        <div className="capture-success">
          <span className="capture-tick">✓</span>
          <div>
            <div className="capture-success-t">PDF on its way to <strong>{email}</strong></div>
            <div className="capture-success-s">
              Check your inbox in ~30 seconds. (Not there? Try Promotions / Spam.) Changed your mind? <button className="link-btn" onClick={() => setDone(false)}>Lock in ${presalePrice} now →</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <form className="capture" onSubmit={submit}>
      <div className="capture-row">
        <input
          type="email"
          placeholder="you@company.com"
          value={email}
          onChange={e => setEmail(e.target.value)}
          disabled={submitting}
          autoComplete="email"
          required
        />
        <button type="submit" className="btn-primary btn-lg" disabled={submitting}>
          {submitting ? "Sending…" : (presale ? `Get PDF + lock in $${presalePrice} →` : ctaCopy)}
          {!submitting && (
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
              <path d="M3 9 L15 9 M10 4 L15 9 L10 14" stroke="currentColor" strokeWidth="2" strokeLinecap="square"/>
            </svg>
          )}
        </button>
      </div>
      {error && <div className="capture-error">{error}</div>}
      <div className="opt-block">
        <label className={`opt ${notify ? "on" : ""}`}>
          <input type="checkbox" checked={notify} onChange={e => setNotify(e.target.checked)} />
          <div>
            <div className="opt-t">Yes, notify me when the full video program launches</div>
          </div>
        </label>
        <label className={`opt opt-presale ${presale ? "on" : ""}`}>
          <input type="checkbox" checked={presale} onChange={e => setPresale(e.target.checked)} />
          <div>
            <div className="opt-t">
              I want to lock in the founding price of <span className="opt-price">${presalePrice}</span> now — add me to the waitlist <span className="opt-strike">${regularPrice} after launch</span>
            </div>
          </div>
        </label>
      </div>
      <div className="capture-trust">
        <span className="check-mini">✓</span> No spam &nbsp;
        <span className="check-mini">✓</span> Unsubscribe anytime &nbsp;
        <span className="check-mini">✓</span> 30-day refund on founding &nbsp;
        <span className="check-mini">✓</span> Auto-refund if we don't ship in 30d
      </div>
      <div className="capture-direct-buy">
        Already have the PDF? <a href={CONFIG.checkoutPage}>Skip to checkout →</a>
      </div>
    </form>
  );
}

// ============ HERO ============
function Hero({ headline, subhead, leadMagnetTitle, leadMagnetSubtitle, ctaCopy, presalePrice, regularPrice, waitlistCount }) {
  const [playing, setPlaying] = useState(false);

  return (
    <section className="hero">
      <div className="hero-inner">
        <div className="hero-left">
          <div className="hero-eyebrow">
            <span className="eyebrow-dot"></span>
            <span>FREE PDF GUIDE · FOUNDING PRESALE OPEN</span>
          </div>
          <h1 className="hero-h1">
            Stop coding yourself into a <span className="ink-highlight">stiff, foggy</span>, 38-year-old body.
          </h1>
          <p className="hero-sub">{subhead}</p>

          <div className="capture-card">
            <div className="capture-card-head">
              <div className="capture-card-title">{leadMagnetTitle}</div>
              <div className="capture-card-sub">{leadMagnetSubtitle}</div>
            </div>
            <EmailCapture ctaCopy={ctaCopy} presalePrice={presalePrice} regularPrice={regularPrice} />
          </div>

          <div className="hero-built-by">
            <div className="bb-row sub">
              <span className="bb-label">EARLY</span>
              <span className="bb-dot"></span>
              <span>{waitlistCount} engineers already on the founding list — be one of the first.</span>
            </div>
          </div>
        </div>

        <div className="hero-right">
          <div className={`hero-video ${playing ? "playing" : ""}`}>
            <video
              className="video-el"
              src="videos/boris.mp4"
              autoPlay
              muted
              loop
              playsInline
              preload="metadata"
            />
            <div className="video-overlay-grad" />
            <div className="video-meta">
              <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.1em" }}>BORIS · GYMNASTICS COACH</span>
              <h3 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 24, lineHeight: 1.05, margin: "6px 0 0", fontWeight: 400 }}>
                We know what we're talking about — get support from the best.
              </h3>
            </div>
            <div className="video-corner-tag">
              <span className="expert-dot"></span> PROVEN EXPERTISE
            </div>
          </div>
          <div className="hero-stats">
            <div className="stat">
              <div className="stat-num">20<span className="stat-unit">min</span></div>
              <div className="stat-lbl">per session</div>
            </div>
            <div className="stat-div" />
            <div className="stat">
              <div className="stat-num">2–4<span className="stat-unit">wk</span></div>
              <div className="stat-lbl">you pick the pace</div>
            </div>
            <div className="stat-div" />
            <div className="stat">
              <div className="stat-num">1<span className="stat-unit">mat</span></div>
              <div className="stat-lbl">no other equipment</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============ WHAT'S IN THE PDF ============
function PDFContents({ onScrollToCapture }) {
  const items = [
    {
      tag: "01",
      title: "The Cognitive Reset System",
      body: "The full mental-clarity protocol mapped out: when to move, what to do, why 20 minutes works when 60 doesn't.",
    },
    {
      tag: "02",
      title: "5-Minute Desk Stretches",
      body: "Lower-back focused, plus neck and hips. Do them between standups. No mat needed for these — just stand up.",
    },
    {
      tag: "03",
      title: "Biohacking & Sleep Improvement",
      body: "The 4 sleep levers that move the needle for builders. Plus the supplement-protocol cheat sheet (zero fluff).",
    },
  ];
  return (
    <section className="pdf-contents">
      <div className="container">
        <div className="comparison-head">
          <h2 className="section-h2">Three sections. Written for engineers — no fluff, no spiritual stuff.</h2>
        </div>
        <div className="pdf-grid">
          {items.map((it, i) => (
            <div key={i} className="pdf-card">
              <div className="pdf-tag">{it.tag}</div>
              <h3>{it.title}</h3>
              <p>{it.body}</p>
              <div className="pdf-card-rule" />
            </div>
          ))}
        </div>
        <div className="pdf-cta-row">
          <button className="btn-primary" onClick={onScrollToCapture}>
            Send me the PDF →
          </button>
          <span className="pdf-cta-sub">~6,000 words · email only · unsubscribe in one click</span>
        </div>
      </div>
    </section>
  );
}

// ============ PROBLEM / AUDIT ============
function ProblemSection() {
  const [checked, setChecked] = useState({});
  const items = [
    "Hips feel locked after a long sprint",
    "3 PM brain fog — coffee stopped working",
    "Lower back complains when you stand up",
    "You used to be active; now you're not",
    "Started a gym plan — bailed within weeks",
    "Sleep is okay but not deep",
  ];
  const score = Object.values(checked).filter(Boolean).length;
  return (
    <section className="problem">
      <div className="container">
        <div className="problem-head">
          <h2 className="section-h2">Take the 10-second desk-body audit.</h2>
          <p className="section-lede">Tick what sounds like your week. If 3+ ring true — the PDF is built for you.</p>
        </div>
        <div className="audit-grid">
          {items.map((it, i) => (
            <button key={i} className={`audit-item ${checked[i] ? "on" : ""}`} onClick={() => setChecked({ ...checked, [i]: !checked[i] })}>
              <span className="audit-checkbox">
                {checked[i] && <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 7 L6 11 L12 3" stroke="currentColor" strokeWidth="2.4" strokeLinecap="square"/></svg>}
              </span>
              <span>{it}</span>
            </button>
          ))}
        </div>
        <div className={`audit-result ${score >= 1 ? "show" : ""}`}>
          {score >= 1 && score <= 2 && <p><strong>{score} of 6.</strong> Mild desk body. The free PDF alone will move the needle.</p>}
          {score >= 3 && score <= 4 && <p><strong>{score} of 6.</strong> Classic desk body — exactly who we wrote this for.</p>}
          {score >= 5 && <p><strong>{score} of 6.</strong> You're the engineer this whole thing is built for. The PDF is a fast start.</p>}
        </div>
      </div>
    </section>
  );
}

// ============ COMPARISON ============
function Comparison() {
  return (
    <section className="comparison" id="how">
      <div className="container">
        <div className="comparison-head">
          <h2 className="section-h2">Undo 8 hours at a desk in 20 minutes. <span className="ink-highlight">Not a gym schedule.</span></h2>
          <p className="section-lede">You debug your code all day. We built a 20-minute protocol to debug your posture, clear the fog, and get you back to peak output — no commute, no equipment, no hour you don't have.</p>
        </div>
        <div className="comp-grid">
          <div className="comp-col bad">
            <div className="comp-tag">A TYPICAL GYM PLAN</div>
            <ul>
              <li><span className="x">✕</span> 1–2 hours, plus the commute</li>
              <li><span className="x">✕</span> Equipment you don't own or use</li>
              <li><span className="x">✕</span> Splits that ignore mobility</li>
              <li><span className="x">✕</span> Soreness that kills coding focus</li>
              <li><span className="x">✕</span> No plan for the weeks you fall off</li>
            </ul>
          </div>
          <div className="comp-col good">
            <div className="comp-tag accent">REBUILD4 PROTOCOL</div>
            <ul>
              <li><span className="check">✓</span> 20 minutes per session</li>
              <li><span className="check">✓</span> Just a yoga mat — at home or office</li>
              <li><span className="check">✓</span> Mobility + strength + stretching together</li>
              <li><span className="check">✓</span> Designed to energize, not drain</li>
              <li><span className="check">✓</span> 2 or 4-week pace — you choose & can extend</li>
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============ TIMELINE ============
function Timeline() {
  const weeks = [
    { n: "WEEK 01", t: "The Unstick", body: "Hips loosen first. Lower back stops complaining within days. You'll feel a difference at your desk in the first week.", marker: "Mobility opens up" },
    { n: "WEEK 02", t: "Decide your pace", body: "Some stop here and keep the routine — that's the 2-week option. Others continue, going deeper into strength and progressions.", marker: "Choose: stop or continue" },
    { n: "WEEK 03", t: "The Energy Shift", body: "If you continue: 3 PM brain fog fades. Afternoon focus stays sharp. Sleep tends to deepen without changing anything else.", marker: "Sharper afternoons" },
    { n: "WEEK 04", t: "Owning the Routine", body: "Strength + mobility + stretching are now a 20-minute habit that fits inside your workday. You can keep it forever.", marker: "Habit, not a program" },
  ];
  return (
    <section className="timeline">
      <div className="container">
        <div className="comparison-head">
          <h2 className="section-h2">What the first 4 weeks look like.</h2>
          <p className="section-lede">If 2 weeks is all you can commit to right now — that's fine. You can extend at any point if you feel the results.</p>
        </div>
        <div className="tl-grid">
          {weeks.map((w, i) => (
            <div key={i} className="tl-card">
              <div className="tl-num">{String(i+1).padStart(2,"0")}</div>
              <div className="tl-week">{w.n}</div>
              <h3 className="tl-title">{w.t}</h3>
              <p className="tl-body">{w.body}</p>
              <div className="tl-marker"><span className="marker-dot"></span> {w.marker}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============ REAL REVIEWS ============
function Reviews() {
  const items = [
    {
      quote: "I use it whenever I feel the cognitive overload coming. The brain fog clears, I feel better, and I get back to work. Simple as that.",
      name: "Antoni",
      role: "AI & Cognitive Science Student",
      avatar: "A",
      tone: "warm"
    },
    {
      quote: "I feel happy the moment I'm done. I feel active, I feel my body — without it being too big of a thing. My legs are stronger, I'm running better, and it's only 20 minutes. 100% continuing.",
      name: "Jesse",
      role: "Founder",
      avatar: "J",
      tone: "cool"
    },
  ];
  return (
    <section className="testimonials" id="reviews">
      <div className="container">
        <div className="comparison-head">
          <h2 className="section-h2">From the first two builders who've used it.</h2>
          <p className="section-lede">We're early. These are two real reviews from the early users — no marketing copy, just what they actually said.</p>
        </div>
        <div className="tm-grid two-up">
          {items.map((t, i) => (
            <figure key={i} className="tm-card">
              <div className="tm-stars">
                {[0,1,2,3,4].map(j => (
                  <svg key={j} width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 0L10 5.5L16 6L11.5 10L13 16L8 13L3 16L4.5 10L0 6L6 5.5Z"/></svg>
                ))}
              </div>
              <blockquote>"{t.quote}"</blockquote>
              <figcaption>
                <div className={`tm-avatar ${t.tone}`}>{t.avatar}</div>
                <div>
                  <div className="tm-name">{t.name}</div>
                  <div className="tm-role">{t.role}</div>
                </div>
              </figcaption>
            </figure>
          ))}
        </div>
        <div className="tm-honest">
          <span className="honest-tag">WHY ONLY TWO?</span>
          <p>Because we're early — and we'd rather show you two real voices than five fake ones. The free PDF is the same system they used. Try it. If you finish it and it changes something, you'll be the next one quoted here.</p>
        </div>
      </div>
    </section>
  );
}

// ============ INSIDE / MODULES ============
function Inside({ onScrollToCapture }) {
  const items = [
    { tag: "01", title: "Core Mobility Routines", body: "20-minute follow-along sessions that hit hips, spine and shoulders — the joints a coding day shuts down first." },
    { tag: "02", title: "5-Min Desk Stretches", body: "Standalone micro-routines for between standups. Lower-back-first, plus neck and wrists. Do them in your chair if you have to." },
    { tag: "03", title: "Biohacking + Sleep", body: "The sleep and energy levers that actually move the needle for builders. No 17-step morning routines — just the few that work." },
    { tag: "04", title: "2 or 4-Week Pace", body: "Pick 2 weeks if you want a low-commitment trial. Pick 4 if you want deeper change. Extend any time you feel the results." },
    { tag: "05", title: "Beginner → Advanced Progressions", body: "Every movement has 3 levels. The Day-1 assessment routes you to the right one — you start exactly where you are." },
    { tag: "06", title: "Habit + Restart System", body: "Built around real life: travel weeks, deadline weeks, sick days. Missed two days? There's a one-minute reboot for that." },
  ];
  return (
    <section className="inside" id="inside">
      <div className="container">
        <div className="comparison-head">
          <h2 className="section-h2">Six modules. Built for an engineer's calendar.</h2>
          <p className="section-lede">This is what you get access to when the full video program launches. The free PDF is the written companion — it'll give you most of the system before the videos even ship.</p>
        </div>
        <div className="inside-grid">
          {items.map((it, i) => (
            <div key={i} className="in-card">
              <div className="in-head">
                <span className="in-tag">{it.tag}</span>
              </div>
              <h3>{it.title}</h3>
              <p>{it.body}</p>
            </div>
          ))}
        </div>
        <div className="inside-cta">
          <button className="btn-primary" onClick={onScrollToCapture}>Get free PDF + presale option →</button>
        </div>
      </div>
    </section>
  );
}

// ============ COACHES ============
function Coaches() {
  const c = [
    { name: "Boris", role: "Gymnastics Coach", years: "15", bio: "Multiple-time national champion. Believes every body — even one shaped by 8-hour standups — can move like an athlete.", color: "warm", video: "videos/boris.mp4" },
    { name: "Teo", role: "Calisthenics Coach", years: "8", bio: "Combines flexibility and functional strength. Spent years engineering a no-equipment progression system.", color: "cool", video: "videos/teo.mp4" },
    { name: "Leon", role: "Wellness & Nutrition", years: "5+", bio: "Certified across gym, calisthenics, and yoga. Designs the recovery and sustainability layer of REBUILD4.", color: "neutral", video: "videos/leon.mp4" },
  ];
  return (
    <section className="coaches">
      <div className="container">
        <div className="comparison-head">
          <h2 className="section-h2">Three coaches. <span className="ink-highlight">One obsession.</span></h2>
        </div>
        <div className="coach-grid">
          {c.map((coach, i) => (
            <div key={i} className="coach-card">
              <div className={`coach-portrait ${coach.color} ${coach.video ? "has-video" : ""}`}>
                {coach.video ? (
                  <video
                    className="coach-video"
                    src={coach.video}
                    autoPlay
                    muted
                    loop
                    playsInline
                    preload="metadata"
                  />
                ) : (
                  <div className="portrait-frame">
                    <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, letterSpacing: "0.15em", opacity: 0.6 }}>COACH PORTRAIT</span>
                    <div className="portrait-initial">{coach.name[0]}</div>
                  </div>
                )}
                <div className="coach-portrait-grad" />
                <div className="coach-portrait-name">
                  <div className="cpn-name">{coach.name}</div>
                  <div className="cpn-role">{coach.role}</div>
                </div>
              </div>
              <div className="coach-meta">
                <div className="coach-name-row">
                  <h3>{coach.name}</h3>
                  <span className="coach-years">{coach.years} yrs</span>
                </div>
                <div className="coach-role">{coach.role}</div>
                <p>{coach.bio}</p>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============ PRESALE / GUARANTEE ============
function Presale({ presalePrice, regularPrice, onScrollToCapture, launchWeeks }) {
  return (
    <section className="guarantee" id="presale">
      <div className="container">
        <div className="guarantee-card">
          <div className="g-badge">
            <svg width="48" height="48" viewBox="0 0 48 48" fill="none">
              <path d="M24 4 L40 12 V24 C40 34 33 41 24 44 C15 41 8 34 8 24 V12 Z" stroke="currentColor" strokeWidth="2" strokeLinejoin="round"/>
              <path d="M16 24 L22 30 L33 18" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
            <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 10, letterSpacing: "0.15em" }}>FOUNDING PRESALE · 30-DAY REFUND</span>
          </div>
          <h2 className="g-h2">Pay <span className="ink-highlight">${presalePrice} today</span>, get access the day it launches.</h2>
          <p className="g-lede">After launch the price becomes ${regularPrice}. Everyone who pre-orders gets the founding price, locked in. Honest pre-order — not a waitlist, not a guess.</p>

          <div className="g-grid">
            <div className="g-step">
              <div className="g-step-n">01</div>
              <div className="g-step-t">Get the free PDF today</div>
              <div className="g-step-b">No risk, no card. Decide if the system feels right for you.</div>
            </div>
            <div className="g-arrow">→</div>
            <div className="g-step">
              <div className="g-step-n">02</div>
              <div className="g-step-t">Lock in ${presalePrice}</div>
              <div className="g-step-b">Charged today via Stripe. We use that to fund the final video production.</div>
            </div>
            <div className="g-arrow">→</div>
            <div className="g-step">
              <div className="g-step-n">03</div>
              <div className="g-step-t">Access on launch (~{launchWeeks} weeks)</div>
              <div className="g-step-b">Email goes out the moment it's live. 30-day refund from launch — no forms, no calls.</div>
            </div>
          </div>

          <div className="presale-prices">
            <div className="pp-now">
              <div className="pp-lbl">FOUNDING (NOW)</div>
              <div className="pp-amt">${presalePrice}</div>
              <div className="pp-sub">Pre-order · refundable for 30 days from launch</div>
            </div>
            <div className="pp-vs">vs</div>
            <div className="pp-later">
              <div className="pp-lbl">REGULAR (AFTER LAUNCH)</div>
              <div className="pp-amt strike">${regularPrice}</div>
              <div className="pp-sub">Public price the day the program ships.</div>
            </div>
          </div>

          <button className="btn-primary btn-xl" onClick={onScrollToCapture}>
            Get free PDF · lock in ${presalePrice} option →
          </button>
          <div className="g-fineprint">No payment required to receive the free PDF. The ${presalePrice} option is shown after you give us your email — totally optional.</div>
          <a href={CONFIG.checkoutPage} className="direct-checkout-link">Already have the PDF? Go straight to checkout →</a>
        </div>
      </div>
    </section>
  );
}

// ============ FAQ ============
function FAQ() {
  const [open, setOpen] = useState(0);
  const items = [
    { q: "What's the free PDF, exactly?", a: "A ~6,000-word guide covering the full system (mobility + strength + stretching), the 5-minute desk stretches for lower-back relief, and the sleep / biohacking levers we use. Written simply, for software engineers — no spiritual stuff, no fluff." },
    { q: "Wait — so is this a finished program or not?", a: "The system is real and being used by early members. The full video program is being filmed and launches in roughly 2 weeks. The PDF is the written companion — usable on its own from day one. The presale ($49) is for the video program when it ships." },
    { q: "Is the $49 a subscription?", a: "No — it's a one-time pre-order for the launch version of the video program. You get access for the duration of the program (the 2 or 4-week structure, including extensions). We don't offer lifetime access — we'd rather be honest about that than over-promise. 30-day refund from launch day if it's not for you." },
    { q: "How does the 2 vs 4-week thing work?", a: "You pick the pace when you start. Two weeks = lower commitment, a clean trial. Four weeks = deeper changes. If you finish 2 weeks and feel the results, you can extend into the 4-week structure — you're not locked in either direction." },
    { q: "How many days per week?", a: "Three, four or five — whatever fits your calendar. There's no fixed 'X sessions to complete' number; the system adapts to how many days a week you can give it." },
    { q: "Do I actually need a yoga mat?", a: "Yes. A yoga mat is the only thing you need — for floor work, mobility, and stretching. No pull-up bar, no dumbbells, no equipment beyond that." },
    { q: "Who's behind this?", a: "Three coaches: Boris (gymnastics, 15 yrs), Teo (calisthenics, 8 yrs), Leon (wellness & nutrition). We're a small team and intentionally transparent — that's why this page tells you exactly where we are (early), not where we wish we were." },
    { q: "What if the program never launches?", a: "If we don't ship in 30 days from your purchase, you get a full automatic refund — no email needed. Pre-orders are how we validate demand and fund the final production; we're not going to take your money and disappear." },
  ];
  return (
    <section className="faq" id="faq">
      <div className="container container-narrow">
        <div className="comparison-head">
          <h2 className="section-h2">Questions before you give us your email.</h2>
        </div>
        <div className="faq-list">
          {items.map((it, i) => (
            <div key={i} className={`faq-item ${open === i ? "open" : ""}`}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{it.q}</span>
                <span className="faq-icon">{open === i ? "−" : "+"}</span>
              </button>
              {open === i && <div className="faq-a">{it.a}</div>}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============ FINAL CTA ============
function FinalCTA({ presalePrice, regularPrice, ctaCopy, leadMagnetTitle, leadMagnetSubtitle }) {
  return (
    <section className="final-cta" id="claim">
      <div className="container">
        <div className="closer">
          <h2 className="closer-h2">Two minutes of effort today. <span className="ink-highlight">Undo months of desk damage in two weeks.</span></h2>
          <p className="closer-sub">Get the free PDF. Decide if the system fits. If it does, lock in ${presalePrice} — or just wait for the launch email. Both options are fine.</p>
          <div className="closer-capture">
            <div className="capture-card-head">
              <div className="capture-card-title">{leadMagnetTitle}</div>
              <div className="capture-card-sub">{leadMagnetSubtitle}</div>
            </div>
            <EmailCapture ctaCopy={ctaCopy} presalePrice={presalePrice} regularPrice={regularPrice} />
          </div>
        </div>
      </div>
    </section>
  );
}

// ============ FOOTER ============
function Footer() {
  return (
    <footer className="footer">
      <div className="container footer-inner">
        <Logo />
        <div className="footer-links">
          <a href="#faq">FAQ</a>
          <a href="mailto:contact.rebuild4@gmail.com">Contact</a>
          <a href="/refund-policy">Refund policy</a>
          <a href="/privacy-policy">Privacy</a>
        </div>
        <div className="footer-fine">© 2026 REBUILD4 · Pre-orders are a real commitment to ship — full refund if we don't launch within 30 days.</div>
      </div>
    </footer>
  );
}

// ============ STICKY BAR ============
function StickyBar({ presalePrice, regularPrice, show, onCTA }) {
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 700);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  if (!show || !visible) return null;
  return (
    <div className="sticky-bar">
      <div className="sticky-inner">
        <div className="sticky-left">
          <div className="sticky-eyebrow">FOUNDING ACCESS · OPEN NOW</div>
          <div className="sticky-price">
            <span className="sticky-now">Free PDF</span>
            <span className="sticky-sub-inline">+ optional ${presalePrice} presale <span className="sticky-was">${regularPrice} after launch</span></span>
          </div>
        </div>
        <button className="btn-primary btn-lg sticky-cta" onClick={onCTA}>Get free PDF →</button>
      </div>
    </div>
  );
}

// ============ EXIT INTENT ============
function ExitIntent({ enabled, presalePrice }) {
  const [open, setOpen] = useState(false);
  const [done, setDone] = useState(false);
  const [email, setEmail] = useState("");
  const fired = useRef(false);
  useEffect(() => {
    if (!enabled) return;
    const onLeave = (e) => {
      if (e.clientY < 5 && !fired.current && !readLead()?.email) {
        fired.current = true;
        setOpen(true);
      }
    };
    document.addEventListener("mouseleave", onLeave);
    return () => document.removeEventListener("mouseleave", onLeave);
  }, [enabled]);

  async function submit(e) {
    e.preventDefault();
    if (!/^\S+@\S+\.\S+$/.test(email)) return;
    let ok = false;
    try {
      const res = await fetch(CONFIG.emailEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, name: "", source: "exit-intent", stage: "lead" }),
      });
      ok = res.ok;
    } catch { ok = false; }
    if (!ok) return;
    saveLead({ email, ts: Date.now(), source: "exit-intent", stage: "lead" });
    setDone(true);
  }

  if (!open) return null;
  return (
    <div className="exit-overlay" onClick={() => setOpen(false)}>
      <div className="exit-modal" onClick={e => e.stopPropagation()}>
        <button className="exit-close" onClick={() => setOpen(false)}>×</button>
        {!done ? (
          <>
            <div className="exit-eyebrow">BEFORE YOU GO</div>
            <h3>Grab the free PDF on the way out.</h3>
            <p>The whole system + desk stretches + sleep/biohacking, written for engineers. No spam — just the PDF.</p>
            <form onSubmit={submit}>
              <input type="email" placeholder="you@company.com" value={email} onChange={e => setEmail(e.target.value)} required />
              <button type="submit">Send me the PDF</button>
            </form>
            <div className="exit-or">— OR —</div>
            <button className="exit-secondary" onClick={() => setOpen(false)}>
              Maybe later — close this →
            </button>
          </>
        ) : (
          <>
            <div className="exit-check">✓</div>
            <h3>Sent. Check your inbox in 30 seconds.</h3>
            <p>From: hello@rebuild4.com · Subject: "Your REBUILD4 PDF"</p>
          </>
        )}
      </div>
    </div>
  );
}

// ============ TWEAKS UI ============
function TweaksUI({ tweaks, setTweak }) {
  const { TweaksPanel, TweakSection, TweakToggle, TweakText, TweakNumber, TweakColor, TweakSlider } = window;
  if (!TweaksPanel) return null;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Layout">
        <TweakToggle label="Sticky CTA bar" value={tweaks.showStickyBar} onChange={v => setTweak("showStickyBar", v)} />
        <TweakToggle label="Exit-intent modal" value={tweaks.showExitIntent} onChange={v => setTweak("showExitIntent", v)} />
      </TweakSection>
      <TweakSection label="Copy">
        <TweakText label="Headline" value={tweaks.headline} onChange={v => setTweak("headline", v)} />
        <TweakText label="Subhead" value={tweaks.subhead} onChange={v => setTweak("subhead", v)} />
        <TweakText label="Lead-magnet title" value={tweaks.leadMagnetTitle} onChange={v => setTweak("leadMagnetTitle", v)} />
        <TweakText label="Lead-magnet sub" value={tweaks.leadMagnetSubtitle} onChange={v => setTweak("leadMagnetSubtitle", v)} />
        <TweakText label="CTA copy" value={tweaks.ctaCopy} onChange={v => setTweak("ctaCopy", v)} />
      </TweakSection>
      <TweakSection label="Pricing">
        <TweakNumber label="Presale price" value={tweaks.presalePrice} onChange={v => setTweak("presalePrice", v)} min={9} max={297} step={1} />
        <TweakNumber label="Regular price" value={tweaks.regularPrice} onChange={v => setTweak("regularPrice", v)} min={19} max={497} step={1} />
        <TweakNumber label="Launch in (weeks)" value={tweaks.launchWeeks} onChange={v => setTweak("launchWeeks", v)} min={1} max={12} step={1} />
        <TweakSlider label="Waitlist count" value={tweaks.waitlistCount} min={0} max={500} step={1} onChange={v => setTweak("waitlistCount", v)} />
      </TweakSection>
      <TweakSection label="Palette">
        <TweakColor label="Color palette" value={tweaks.accentPalette} options={[
          ["#E85D2C", "#0B0B0B", "#F5F1EA"],
          ["#3B82F6", "#0B0F1A", "#F4F6FB"],
          ["#22C55E", "#0A0F0B", "#F2F6F2"],
          ["#7C3AED", "#0E0A1B", "#F4F1FA"],
          ["#0B0B0B", "#E85D2C", "#F5F1EA"],
        ]} onChange={v => setTweak("accentPalette", v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

// ============ APP ============
function App() {
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    const [accent, ink, paper] = tweaks.accentPalette;
    document.documentElement.style.setProperty("--accent", accent);
    document.documentElement.style.setProperty("--ink", ink);
    document.documentElement.style.setProperty("--paper", paper);
  }, [tweaks.accentPalette]);

  const scrollToCapture = () => {
    const el = document.querySelector(".capture-card") || document.querySelector(".closer-capture");
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 80;
      window.scrollTo({ top: y, behavior: "smooth" });
      const input = el.querySelector('input[type="email"]');
      if (input) setTimeout(() => input.focus(), 600);
    }
  };

  return (
    <>
      <AnnouncementBar presalePrice={tweaks.presalePrice} regularPrice={tweaks.regularPrice} />
      <Nav onCTA={scrollToCapture} />
      <Hero
        headline={tweaks.headline}
        subhead={tweaks.subhead}
        leadMagnetTitle={tweaks.leadMagnetTitle}
        leadMagnetSubtitle={tweaks.leadMagnetSubtitle}
        ctaCopy={tweaks.ctaCopy}
        presalePrice={tweaks.presalePrice}
        regularPrice={tweaks.regularPrice}
        waitlistCount={tweaks.waitlistCount}
      />
      <PDFContents onScrollToCapture={scrollToCapture} />
      <ProblemSection />
      <Comparison />
      <Timeline />
      <Reviews />
      <Inside onScrollToCapture={scrollToCapture} />
      <Coaches />
      <Presale
        presalePrice={tweaks.presalePrice}
        regularPrice={tweaks.regularPrice}
        onScrollToCapture={scrollToCapture}
        launchWeeks={tweaks.launchWeeks}
      />
      <FAQ />
      <FinalCTA
        presalePrice={tweaks.presalePrice}
        regularPrice={tweaks.regularPrice}
        ctaCopy={tweaks.ctaCopy}
        leadMagnetTitle={tweaks.leadMagnetTitle}
        leadMagnetSubtitle={tweaks.leadMagnetSubtitle}
      />
      <Footer />
      <StickyBar
        presalePrice={tweaks.presalePrice}
        regularPrice={tweaks.regularPrice}
        show={tweaks.showStickyBar}
        onCTA={scrollToCapture}
      />
      <ExitIntent enabled={tweaks.showExitIntent} presalePrice={tweaks.presalePrice} />
      <TweaksUI tweaks={tweaks} setTweak={setTweak} />
    </>
  );
}

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