/* Codaroo · shared React components (all pages)
   Loaded via <script type="text/babel" src="components.jsx">
   Requires React, Lucide already on window. */

/* ─── Lucide icon helper ─────────────────────────────────── */
function Icon({ n, size = 24, sw = 2.5, style }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (window.lucide && ref.current) {
      ref.current.innerHTML = '';
      const el = document.createElement('i');
      el.setAttribute('data-lucide', n);
      ref.current.appendChild(el);
      window.lucide.createIcons({ attrs: { width: size, height: size, 'stroke-width': sw }, el: ref.current });
    }
  }, [n, size, sw]);
  return <span ref={ref} style={{ display: 'inline-flex', ...style }} />;
}

/* ─── Button ─────────────────────────────────────────────── */
function Button({ children, variant = 'primary', size = 'md', block = false,
  iconLeft = null, iconRight = null, as = 'button', className = '', ...rest }) {
  const Tag = as;
  const cls = ['cd-btn', `cd-btn--${variant}`, `cd-btn--${size}`,
    block ? 'cd-btn--block' : '', className].filter(Boolean).join(' ');
  return (
    <Tag className={cls} {...rest}>
      {iconLeft  && <span className="cd-btn__icon">{iconLeft}</span>}
      {children  && <span>{children}</span>}
      {iconRight && <span className="cd-btn__icon">{iconRight}</span>}
    </Tag>
  );
}

/* ─── Badge ──────────────────────────────────────────────── */
function Badge({ children, tone = 'grape', solid = false, size = 'md',
  dot = false, icon = null, className = '', ...rest }) {
  const cls = ['cd-badge', `cd-badge--${tone}`,
    solid ? 'cd-badge--solid' : '',
    size === 'lg' ? 'cd-badge--lg' : '', className].filter(Boolean).join(' ');
  return (
    <span className={cls} {...rest}>
      {dot && <span className="cd-badge__dot" />}
      {icon}{children}
    </span>
  );
}

/* ─── Stat ───────────────────────────────────────────────── */
function Stat({ value, label, tone = 'grape', plain = false, className = '', ...rest }) {
  const cls = ['cd-stat', `cd-stat--${tone}`, plain ? 'cd-stat--plain' : '', className].filter(Boolean).join(' ');
  return (
    <div className={cls} {...rest}>
      <span className="cd-stat__value">{value}</span>
      <span className="cd-stat__label">{label}</span>
    </div>
  );
}

/* ─── Avatar ─────────────────────────────────────────────── */
function _initials(name = '') {
  return name.trim().split(/\s+/).slice(0, 2).map(p => p[0]?.toUpperCase() || '').join('');
}
function Avatar({ src, name = '', tone = 'grape', size = 'md', status = false, className = '', ...rest }) {
  const cls = ['cd-avatar', `cd-avatar--${size}`, `cd-avatar--${tone}`, className].filter(Boolean).join(' ');
  return (
    <span className={cls} {...rest}>
      {src ? <img src={src} alt={name} /> : <span>{_initials(name) || '🦘'}</span>}
      {status && <span className="cd-avatar__status" />}
    </span>
  );
}

/* ─── ProgramCard ────────────────────────────────────────── */
const TONE_MAP = { Sprint: 'sky', Quest: 'coral', Odyssey: 'grape', 'Free Challenge': 'mint' };
function ProgramCard({ name, length, price, per = '/ program', description, emoji = '🦘',
  features = [], featured = false, badgeText, tone, ctaText = 'Pick this program',
  onSelect, className = '', ...rest }) {
  const accent = tone || TONE_MAP[name] || 'grape';
  const cls = ['cd-pcard', `cd-pcard--${accent}`, featured ? 'cd-pcard--featured' : '', className].filter(Boolean).join(' ');
  const btnVariant = accent === 'grape' ? 'primary' : accent;
  return (
    <div className={cls} {...rest}>
      {(featured || badgeText) && (
        <div className="cd-pcard__ribbon">
          <Badge tone={accent} solid size="lg">{badgeText || 'Most popular'}</Badge>
        </div>
      )}
      <div className="cd-pcard__head">
        <span className="cd-pcard__dot">{emoji}</span>
        <div>
          <h3 className="cd-pcard__name">{name}</h3>
          <span className="cd-pcard__len">{length}</span>
        </div>
      </div>
      {description && <p className="cd-pcard__desc">{description}</p>}
      <div className="cd-pcard__price">
        <span className="cd-pcard__amount">{price}</span>
        <span className="cd-pcard__per">{per}</span>
      </div>
      <ul className="cd-pcard__list">
        {features.map((f, i) => (
          <li key={i}>
            <span className="cd-pcard__tick">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 13l4 4L19 7"/>
              </svg>
            </span>
            {f}
          </li>
        ))}
      </ul>
      <div className="cd-pcard__foot">
        <Button variant={btnVariant} block size="md" onClick={onSelect}>{ctaText}</Button>
      </div>
    </div>
  );
}

/* ─── Input ──────────────────────────────────────────────── */
let _inputId = 0;
function Input({ label, hint, error, icon = null, id, className = '', ...rest }) {
  const fieldId = id || React.useMemo(() => `cd-input-${++_inputId}`, []);
  return (
    <div className="cd-field">
      {label && <label className="cd-field__label" htmlFor={fieldId}>{label}</label>}
      <div className="cd-input-wrap">
        {icon && <span className="cd-input-wrap__icon">{icon}</span>}
        <input id={fieldId}
          className={['cd-input', icon ? 'cd-input--has-icon' : '', error ? 'cd-input--error' : '', className].filter(Boolean).join(' ')}
          aria-invalid={!!error} {...rest} />
      </div>
      {error  ? <span className="cd-field__error">{error}</span>
              : hint ? <span className="cd-field__hint">{hint}</span> : null}
    </div>
  );
}

/* ─── Checkbox ───────────────────────────────────────────── */
function Checkbox({ label, round = false, className = '', ...rest }) {
  return (
    <label className={['cd-check', round ? 'cd-check--round' : '', className].filter(Boolean).join(' ')}>
      <input type="checkbox" {...rest} />
      <span className="cd-check__box" aria-hidden="true">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round">
          <path d="M5 13l4 4L19 7"/>
        </svg>
      </span>
      {label && <span className="cd-check__label">{label}</span>}
    </label>
  );
}

/* ─── IconButton ─────────────────────────────────────────── */
function IconButton({ children, variant = 'secondary', size = 'md', round = false, label, className = '', ...rest }) {
  const cls = ['cd-iconbtn', `cd-iconbtn--${variant}`, `cd-iconbtn--${size}`,
    round ? 'cd-iconbtn--round' : '', className].filter(Boolean).join(' ');
  return (
    <button className={cls} aria-label={label} title={label} {...rest}>{children}</button>
  );
}

/* ─── ProgressBar ────────────────────────────────────────── */
function ProgressBar({ value = 0, max = 100, tone = 'grape', size = 'md', showValue = false, valueText, className = '' }) {
  const pct = Math.min(100, (value / max) * 100);
  const cls = ['cd-pbar', `cd-pbar--${tone}`, size === 'lg' ? 'cd-pbar--lg' : '', className].filter(Boolean).join(' ');
  return (
    <div className={cls}>
      {showValue && <div className="cd-pbar__label"><span>{valueText || `${Math.round(pct)}%`}</span></div>}
      <div className="cd-pbar__track">
        <div className="cd-pbar__fill" style={{ width: `${pct}%` }} />
      </div>
    </div>
  );
}

/* ─── Brand ──────────────────────────────────────────────── */
function Brand({ home = true }) {
  return (
    <a className="lp-brand" href={home ? '#top' : 'index.html'}>
      <img className="lp-brand__mark" src="assets/logo-mark.svg" alt="" />
      <span className="lp-brand__word">Coda<span className="roo">roo</span></span>
    </a>
  );
}

/* ─── Nav ────────────────────────────────────────────────── */
function Nav({ onStart, onLogin, home = true, active }) {
  return (
    <nav className="lp-nav">
      <div className="lp-wrap lp-nav__inner">
        <Brand home={home} />
        <div className="lp-nav__links">
          <a href="pricing.html"      className={active === 'programs' ? 'active' : ''}>Programs</a>
          <a href="safety.html"       className={active === 'safety'   ? 'active' : ''}>Safety</a>
          <a href="how-it-works.html" className={active === 'how'      ? 'active' : ''}>How it works</a>
          <a href="contact.html"      className={active === 'contact'  ? 'active' : ''}>Contact</a>
        </div>
        <div className="lp-nav__cta">
          <Button variant="ghost"   size="sm" onClick={onLogin}>Log in</Button>
          <Button variant="primary" size="sm" onClick={onStart}>Start free week</Button>
        </div>
      </div>
    </nav>
  );
}

/* ─── Hero ───────────────────────────────────────────────── */
function Hero({ onStart }) {
  return (
    <header className="lp-hero lp-section" id="top">
      <div className="lp-wrap lp-hero__grid">
        <div>
          <Badge tone="grape" solid size="lg">🦘 Grades 3–9 · No AI chat, ever</Badge>
          <h1>Learn to code.<br/>The <span className="hl">safe</span>, <span className="hl hl-coral">fun</span> way.</h1>
          <p className="lp-hero__sub">A self-guided coding adventure for kids. Real projects, smart challenges, and lessons that teach kids to use AI <i>safely</i> — never by chatting with one.</p>
          <div className="lp-hero__cta">
            <Button variant="primary" size="lg" onClick={onStart} iconRight={<span>→</span>}>Start your free week</Button>
            <Button variant="secondary" size="lg" as="a" href="pricing.html">See the programs</Button>
          </div>
          <div className="lp-hero__trust">
            <Icon n="shield-check" size={18} />
            Human-written lessons · Cancel anytime · Ad-free
          </div>
          <div className="lp-hero__stats">
            <Stat value="10k+" label="Kids coding"       tone="coral" />
            <Stat value="4.9★" label="Parent rating"    tone="sunny" />
            <Stat value="98%"  label="Finish their quest" tone="mint" />
          </div>
        </div>
        <div className="lp-stage">
          <div className="lp-blob cd-anim-float" />
          <img className="lp-mascot cd-anim-float" src="assets/logo-mark.svg" alt="Codaroo mascot" />
          <div className="lp-chip lp-chip--code cd-anim-float"><span className="g">def</span>&nbsp;<span className="y">hop</span>():</div>
          <div className="lp-chip lp-chip--star  cd-anim-wobble">⭐️ Level 4!</div>
          <div className="lp-chip lp-chip--badge cd-anim-wobble">🏆 Trophy unlocked</div>
        </div>
      </div>
    </header>
  );
}

/* ─── SafetyBand ─────────────────────────────────────────── */
function SafeCard({ icon, bg, title, children }) {
  return (
    <div className="lp-safe-card">
      <span className="lp-safe-card__icon" style={{ background: bg }}>
        <Icon n={icon} size={28} />
      </span>
      <h3>{title}</h3>
      <p>{children}</p>
    </div>
  );
}
function SafetyBand() {
  return (
    <section className="lp-safety lp-section" id="safety">
      <div className="lp-wrap lp-center">
        <span className="lp-eyebrow">The Codaroo promise</span>
        <h2 className="lp-title">Zero AI chat. Every lesson written by humans.</h2>
        <p className="lp-lead">Kids learn <i>about</i> AI — how to prompt it safely and where it goes wrong — without ever talking to one. Most of the course is hands-on coding that needs no AI at all.</p>
        <div className="lp-safety__grid" style={{ textAlign: 'left' }}>
          <SafeCard icon="message-square-off" bg="var(--coral-500)" title="No chatbot. Period.">
            There's no open-ended AI to chat with. Every lesson is written and reviewed by real humans.
          </SafeCard>
          <SafeCard icon="shield-check" bg="var(--sky-500)" title="Safe AI, taught right">
            Kids learn what makes a prompt safe, what AI is good and bad at, and smart digital-citizen habits.
          </SafeCard>
          <SafeCard icon="puzzle" bg="var(--mint-500)" title="Real coding, unplugged">
            Loops, logic, and debugging through small challenges kids solve themselves — no AI required.
          </SafeCard>
        </div>
      </div>
    </section>
  );
}

/* ─── HowItWorks ─────────────────────────────────────────── */
function Step({ num, emoji, title, children }) {
  return (
    <div className="lp-step">
      <span className="lp-step__num">{num}</span>
      <div className="lp-step__emoji">{emoji}</div>
      <h3>{title}</h3>
      <p>{children}</p>
    </div>
  );
}
function HowItWorks() {
  return (
    <section className="lp-section" id="how">
      <div className="lp-wrap lp-center">
        <span className="lp-eyebrow">How it works</span>
        <h2 className="lp-title">Four hops to your first trophy</h2>
        <p className="lp-lead">Self-guided means your kid drives. You just cheer them on.</p>
        <div className="lp-steps" style={{ textAlign: 'left' }}>
          <Step num="1" emoji="🧭" title="Pick a program">Choose 4, 8, or 12 weeks — Sprint, Quest, or Odyssey.</Step>
          <Step num="2" emoji="📦" title="Get your kit">A Codaroo t-shirt + wall poster ship to your door.</Step>
          <Step num="3" emoji="💻" title="Code a little daily">Bite-size lessons and challenges. Just a computer + internet.</Step>
          <Step num="4" emoji="🏆" title="Earn your trophy">Finish the quest to unlock a certificate and a real trophy.</Step>
        </div>
      </div>
    </section>
  );
}

/* ─── Programs ───────────────────────────────────────────── */
function Programs({ onSelect }) {
  const sel = (name) => () => onSelect && onSelect(name);
  return (
    <section className="lp-programs lp-section" id="programs">
      <div className="lp-wrap lp-center">
        <span className="lp-eyebrow">Pick your adventure</span>
        <h2 className="lp-title">One price. Everything included.</h2>
        <p className="lp-lead">Every program ships the t-shirt + poster, and ends with a certificate and trophy. Pick the length that fits your kid.</p>
        <div className="lp-prog-grid" style={{ textAlign: 'left' }}>
          <ProgramCard name="Free Challenge" length="No commitment" price="Free" per="" emoji="🧩" tone="mint"
            description="Not ready to commit? Try one real challenge — no AI, no card."
            features={['1 sample coding challenge','Create a free account','See how Codaroo works']}
            ctaText="Create free account" onSelect={sel('Free Challenge')} />
          <ProgramCard name="Sprint" length="4 weeks" price="$199" emoji="⚡"
            description="A taste of coding — fundamentals + first projects."
            features={['12 guided lessons','Unplugged code challenges','T-shirt + wall poster','Certificate + trophy']}
            onSelect={sel('Sprint')} />
          <ProgramCard name="Quest" length="8 weeks" price="$349" emoji="🧭" featured
            description="The core journey — logic, real projects &amp; safe AI prompting."
            features={['Everything in Sprint','Safe AI-prompting lessons','Bigger build projects','Mid-quest check-in']}
            onSelect={sel('Quest')} />
          <ProgramCard name="Odyssey" length="12 weeks" price="$449" emoji="🚀"
            description="The full adventure — bigger builds and a capstone."
            features={['Everything in Quest','Capstone project','Showcase gallery spot','Bonus trophy badge']}
            onSelect={sel('Odyssey')} />
        </div>
        <div className="lp-prog-note">
          <Icon n="gift" size={18} /> Free first week on every program · no card needed to start
        </div>
      </div>
    </section>
  );
}

/* ─── Rewards ────────────────────────────────────────────── */
function Reward({ emoji, when, tone, title, children }) {
  return (
    <div className="lp-reward">
      <div className="lp-reward__art">{emoji}</div>
      <div className="lp-reward__when"><Badge tone={tone} size="md">{when}</Badge></div>
      <h3>{title}</h3>
      <p>{children}</p>
    </div>
  );
}
function Rewards() {
  return (
    <section className="lp-section" id="rewards">
      <div className="lp-wrap lp-center">
        <span className="lp-eyebrow">Goodies &amp; glory</span>
        <h2 className="lp-title">Real stuff shows up at your door</h2>
        <p className="lp-lead">Codaroo isn't just a screen. Kids get tangible rewards to start strong and finish proud.</p>
        <div className="lp-rewards__grid">
          <Reward emoji="👕" when="On signup" tone="sky"   title="Codaroo T-shirt">Wear your crew colors from day one.</Reward>
          <Reward emoji="🖼️" when="On signup" tone="sky"  title="Codaroo Poster">A big wall poster packed with code tips and mascots.</Reward>
          <Reward emoji="🎓" when="On finish" tone="coral" title="Certificate">An official Codaroo coder certificate.</Reward>
          <Reward emoji="🏆" when="On finish" tone="coral" title="Trophy">A real trophy for the shelf. Earned, not given.</Reward>
        </div>
      </div>
    </section>
  );
}

/* ─── Proof ──────────────────────────────────────────────── */
function Proof() {
  return (
    <section className="lp-proof lp-section">
      <div className="lp-wrap lp-proof__grid">
        <div className="lp-quote">
          <div className="lp-quote__mark">"</div>
          <p>My daughter built a game in week three — and I never once worried about who she was talking to. That peace of mind is everything.</p>
          <div className="lp-quote__by">
            <Avatar name="Maya R" tone="coral" size="lg" />
            <div>
              <b>Maya R.</b>
              <span>Parent of a 5th grader · Quest</span>
            </div>
          </div>
        </div>
        <div>
          <span className="lp-eyebrow">Parents trust Codaroo</span>
          <h2 className="lp-title" style={{ fontSize: 'clamp(26px,3vw,38px)' }}>Loved by kids, approved by grown-ups.</h2>
          <div className="lp-proof__stats">
            <Stat value="4.9★" label="Avg parent rating" tone="sunny" />
            <Stat value="0"    label="AI chatbots"       tone="coral" />
            <Stat value="10k+" label="Young coders"      tone="grape" />
            <Stat value="98%"  label="Finish their quest" tone="mint" />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── FinalCTA ───────────────────────────────────────────── */
function FinalCTA({ onStart }) {
  return (
    <section className="lp-final lp-section">
      <div className="lp-wrap lp-final__inner">
        <h2>Ready to hop in? 🦘</h2>
        <p>Start your free week today. No AI chat, no ads, no pressure.</p>
        <Button variant="sunny" size="lg" onClick={onStart} iconRight={<span>→</span>}>Start your free week</Button>
      </div>
    </section>
  );
}

/* ─── Footer ─────────────────────────────────────────────── */
function Footer({ home = true }) {
  const L = (hash, page) => home ? hash : page;
  return (
    <footer className="lp-footer">
      <div className="lp-wrap">
        <div className="lp-footer__grid">
          <div className="lp-footer__brand">
            <Brand home={home} />
            <p>The safe, fun way for grades 3–9 to learn real code — and how to work alongside AI, responsibly.</p>
            <span className="lp-woman"><Icon n="sparkles" size={15} /> Proudly woman-owned</span>
          </div>
          <div>
            <h4>Programs</h4>
            <a href={L('#programs','index.html#programs')}>Sprint · 4 weeks</a>
            <a href={L('#programs','index.html#programs')}>Quest · 8 weeks</a>
            <a href={L('#programs','index.html#programs')}>Odyssey · 12 weeks</a>
            <a href={L('#rewards', 'index.html#rewards')}>Rewards</a>
          </div>
          <div>
            <h4>Parents</h4>
            <a href="safety.html">Our safety promise</a>
            <a href="how-it-works.html">How it works</a>
            <a href="pricing.html">Pricing &amp; FAQ</a>
            <a href="contact.html">Contact us</a>
          </div>
          <div>
            <h4>Codaroo</h4>
            <a href="safety.html">About safety</a>
            <a href="pricing.html">Pricing</a>
            <a href="contact.html">Contact</a>
            <a href="contact.html">Help</a>
          </div>
        </div>
        <div className="lp-footer__bottom">
          <span>© 2026 Codaroo, Inc. · Made with 💜 for curious kids.</span>
          <a href="contact.html" style={{ color: 'inherit', fontWeight: 700 }}>hello@codaroo.com</a>
        </div>
      </div>
    </footer>
  );
}

/* ─── AuthModal ──────────────────────────────────────────── */
function AuthModal({ open, mode, setMode, origin, onClose, onSuccess }) {
  const [revealed, setRevealed] = React.useState(false);

  React.useEffect(() => {
    if (!open) { setRevealed(false); return; }
    const id = requestAnimationFrame(() => requestAnimationFrame(() => setRevealed(true)));
    return () => cancelAnimationFrame(id);
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') handleClose(); };
    document.body.style.overflow = 'hidden';
    window.addEventListener('keydown', onKey);
    return () => { document.body.style.overflow = ''; window.removeEventListener('keydown', onKey); };
  }, [open]);

  if (!open) return null;

  const ox = ((origin && origin.x) ?? window.innerWidth / 2) + 'px';
  const oy = ((origin && origin.y) ?? window.innerHeight / 2) + 'px';
  const clip = revealed ? `circle(165% at ${ox} ${oy})` : `circle(0px at ${ox} ${oy})`;

  const handleClose = () => { setRevealed(false); setTimeout(onClose, 460); };
  const submit = (e) => { e.preventDefault(); onSuccess(mode); };
  const isSignup = mode === 'signup';

  return (
    <div className="lp-auth" style={{ clipPath: clip, WebkitClipPath: clip }}>
      <div className="lp-auth__bg" />
      <img className="lp-auth__float lp-auth__float--1 cd-anim-float" src="assets/logo-mark.svg" alt="" />
      <img className="lp-auth__float lp-auth__float--2 cd-anim-wobble" src="assets/logo-mark.svg" alt="" />
      <img className="lp-auth__float lp-auth__float--3 cd-anim-float"  src="assets/logo-mark.svg" alt="" />

      <div className="lp-auth__card cd-anim-pop">
        <IconButton label="Close" className="lp-auth__close" onClick={handleClose}>
          <Icon n="x" size={20} />
        </IconButton>
        <div className="lp-auth__brand">
          <img src="assets/logo-mark.svg" alt="" />
          <b>Coda<span className="roo">roo</span></b>
        </div>
        <div className="lp-auth__title">{isSignup ? 'Start your free week 🦘' : 'Welcome back!'}</div>
        <p className="lp-auth__sub">{isSignup ? 'No card needed. Cancel anytime.' : 'Log in to keep your streak going.'}</p>

        <div className="lp-auth__tabs" role="tablist">
          <button className={`lp-auth__tab ${isSignup ? 'active' : ''}`}  onClick={() => setMode('signup')}>Sign up</button>
          <button className={`lp-auth__tab ${!isSignup ? 'active' : ''}`} onClick={() => setMode('login')}>Log in</button>
        </div>

        <form className="lp-auth__form" onSubmit={submit}>
          {isSignup && <Input label="Kid's first name" placeholder="e.g. Ada"    icon={<Icon n="user" size={20} />} required />}
          <Input label="Parent email"  type="email"    placeholder="you@email.com" icon={<Icon n="mail" size={20} />} required />
          <Input label="Password"      type="password" placeholder="••••••••"      icon={<Icon n="lock" size={20} />} required />
          {isSignup && <Checkbox label="I'm a parent or guardian" defaultChecked />}
          <Button type="submit" variant="primary" size="lg" block iconRight={<span>→</span>}>
            {isSignup ? 'Start my free week' : 'Log in'}
          </Button>
        </form>

        <div className="lp-auth__trust"><Icon n="shield-check" size={16} /> No AI chat · Human-written lessons</div>
        <p className="lp-auth__alt">
          {isSignup ? 'Already have an account?' : 'New to Codaroo?'}{' '}
          <button onClick={() => setMode(isSignup ? 'login' : 'signup')}>{isSignup ? 'Log in' : 'Start free'}</button>
        </p>
      </div>
    </div>
  );
}

/* ─── Subpage shell ──────────────────────────────────────── */
function SitePage({ active, children }) {
  const [auth, setAuth] = React.useState({ open: false, mode: 'signup', origin: null });
  const openAuth = (mode) => (e) => {
    const origin = e && e.clientX ? { x: e.clientX, y: e.clientY } : null;
    setAuth({ open: true, mode, origin });
  };
  const start = openAuth('signup');
  const login = openAuth('login');

  React.useEffect(() => {
    window.__cdStart = () => setAuth({ open: true, mode: 'signup', origin: null });
    window.__cdLogin = () => setAuth({ open: true, mode: 'login', origin: null });
  }, []);

  const closeAuth = () => setAuth(a => ({ ...a, open: false }));
  const setMode   = (mode) => setAuth(a => ({ ...a, mode }));
  const success   = (mode) => {
    window.cdBurst && window.cdBurst(120);
    window.cdToast && window.cdToast(mode === 'signup'
      ? 'Account created — taking you in… <b>🦘</b>'
      : 'Welcome back — taking you in… <b>🦘</b>');
    setTimeout(() => { window.location.href = 'dashboard/index.html'; }, 950);
  };

  return (
    <div className="lp">
      <Nav onStart={start} onLogin={login} home={false} active={active} />
      {children}
      <FinalCTA onStart={start} />
      <Footer home={false} />
      <AuthModal open={auth.open} mode={auth.mode} origin={auth.origin}
        setMode={setMode} onClose={closeAuth} onSuccess={success} />
    </div>
  );
}

function PageHead({ crumb = 'Parents', title, sub }) {
  return (
    <header className="lp-pagehead">
      <div className="lp-wrap">
        <div className="crumb"><a href="index.html">Home</a> › {crumb}</div>
        <h1>{title}</h1>
        {sub && <p>{sub}</p>}
      </div>
    </header>
  );
}

/* ─── Page: Safety ───────────────────────────────────────── */
function SafetyPage() {
  return (
    <SitePage active="safety">
      <PageHead title="Our safety promise"
        sub="Codaroo is built so kids learn real coding — and how to work with AI — without ever chatting with one." />
      <SafetyBand />
      <section className="lp-section">
        <div className="lp-wrap">
          <div className="lp-split">
            <div className="lp-list-card lp-dont">
              <h3>What your child will never do</h3>
              <ul>
                <li>Chat or message with an AI chatbot</li>
                <li>See open-ended, unreviewed AI output</li>
                <li>Share personal info with a machine</li>
                <li>Run into ads, links out, or social feeds</li>
              </ul>
            </div>
            <div className="lp-list-card lp-do">
              <h3>What they'll learn instead</h3>
              <ul>
                <li>Real coding — loops, logic, and debugging</li>
                <li>How to write a safe, clear AI prompt</li>
                <li>What AI is good at — and where it's wrong</li>
                <li>Smart, kind digital-citizen habits</li>
              </ul>
            </div>
          </div>
        </div>
      </section>
      <section className="lp-section" style={{ paddingTop: 0 }}>
        <div className="lp-wrap lp-center">
          <span className="cd-eyebrow">Built for grown-ups' peace of mind</span>
          <div className="lp-feature-grid">
            <div className="lp-feature"><div className="lp-feature__emoji">✍️</div><h3>Human-written</h3><p>Every lesson is authored and reviewed by real educators.</p></div>
            <div className="lp-feature"><div className="lp-feature__emoji">🚫</div><h3>No chatbot</h3><p>There is no open-ended AI for kids to talk to. Full stop.</p></div>
            <div className="lp-feature"><div className="lp-feature__emoji">📵</div><h3>Ad-free</h3><p>No ads, no tracking-for-profit, no social pressure.</p></div>
            <div className="lp-feature"><div className="lp-feature__emoji">🔐</div><h3>Privacy-first</h3><p>We never ask kids for personal details to do a lesson.</p></div>
          </div>
        </div>
      </section>
    </SitePage>
  );
}

/* ─── Page: How it works ─────────────────────────────────── */
function HowItWorksPage() {
  return (
    <SitePage active="how">
      <PageHead title="How it works"
        sub="Self-guided means your kid drives the adventure. You just cheer them on." />
      <HowItWorks />
      <section className="lp-section" style={{ paddingTop: 0 }}>
        <div className="lp-wrap lp-center">
          <span className="cd-eyebrow">A day in the life</span>
          <h2 className="lp-title">What a typical session looks like</h2>
          <p className="lp-lead" style={{ margin: '0 auto' }}>Short, self-paced, and satisfying — about 20–30 minutes.</p>
          <div className="lp-feature-grid">
            <div className="lp-feature"><div className="lp-feature__emoji">▶️</div><h3>Watch a mini-lesson</h3><p>A bite-size, human-made lesson introduces one idea.</p></div>
            <div className="lp-feature"><div className="lp-feature__emoji">🧩</div><h3>Try a challenge</h3><p>Solve a small puzzle to practice it — most need zero AI.</p></div>
            <div className="lp-feature"><div className="lp-feature__emoji">🖍️</div><h3>Color your calendar</h3><p>Fill in a bubble on the wall poster. Watch progress grow.</p></div>
            <div className="lp-feature"><div className="lp-feature__emoji">🏅</div><h3>Earn a badge</h3><p>Finish the week to unlock badges on the way to the trophy.</p></div>
          </div>
          <div style={{ marginTop: 34 }}>
            <Badge tone="mint" solid size="lg">💻 All you need: a computer + internet</Badge>
          </div>
        </div>
      </section>
    </SitePage>
  );
}

/* ─── Page: Pricing ──────────────────────────────────────── */
const FAQS = [
  ['Does my child ever talk to an AI?', 'No. There is no chatbot in Codaroo. Kids learn how to prompt AI safely through human-written lessons — they never chat with one.'],
  ['What ages is Codaroo for?', 'Grades 3–9, roughly ages 8–15. Lessons adapt in tone and challenge so younger and older kids both feel at home.'],
  ['What do we need to get started?', 'Just a computer and an internet connection. No installs, no special hardware, no extra apps.'],
  ['What comes in the kit?', 'On signup we ship a Codaroo t-shirt and a wall poster (your program calendar). Finish the program and we send a certificate and a real trophy.'],
  ['Can I cancel?', 'Yes — the first week is free, and you can cancel anytime. No long-term contract.'],
  ['Do I need to sit with my child?', 'It\'s fully self-guided, so kids can work independently. We still recommend a grown-up nearby, especially for younger learners.'],
  ['Which program should we pick?', 'Sprint (4 weeks) is a taster, Quest (8 weeks) is the core journey with safe-AI lessons, and Odyssey (12 weeks) adds a capstone build. You can start small and upgrade.'],
];
function PricingPage() {
  return (
    <SitePage active="programs">
      <PageHead title="Pricing &amp; FAQ"
        sub="One simple price per program. Everything's included — the kit, the certificate, and the trophy." />
      <Programs onSelect={() => window.__cdStart && window.__cdStart()} />
      <section className="lp-section" style={{ paddingTop: 0 }}>
        <div className="lp-wrap lp-center">
          <span className="cd-eyebrow">Good questions</span>
          <h2 className="lp-title">Frequently asked</h2>
          <div className="lp-faq" style={{ textAlign: 'left' }}>
            {FAQS.map(([q, a], i) => (
              <details className="faq" key={i} open={i === 0}>
                <summary>{q}<span className="chev" /></summary>
                <div className="faq__body"><p>{a}</p></div>
              </details>
            ))}
          </div>
        </div>
      </section>
    </SitePage>
  );
}

/* ─── Page: Contact ──────────────────────────────────────── */
function ContactCard({ icon, bg, title, children }) {
  return (
    <div className="lp-contact-card">
      <span className="ic" style={{ background: bg }}><Icon n={icon} size={22} /></span>
      <div><h4>{title}</h4><p>{children}</p></div>
    </div>
  );
}
function ContactPage() {
  const submit = (e) => {
    e.preventDefault();
    window.cdBurst && window.cdBurst(70);
    window.cdToast && window.cdToast('Thanks! We\'ll reply within 1 business day. <b>🦘</b>');
    e.target.reset();
  };
  return (
    <SitePage active="contact">
      <PageHead title="Contact us"
        sub="Questions about programs, safety, or your order? We're happy to help." />
      <section className="lp-section">
        <div className="lp-wrap lp-contact">
          <form className="lp-contact__form" onSubmit={submit}>
            <h3>Send us a note</h3>
            <Input label="Your name" placeholder="e.g. Jordan"    icon={<Icon n="user" size={20} />} required />
            <Input label="Email" type="email" placeholder="you@email.com" icon={<Icon n="mail" size={20} />} required />
            <Input label="Subject" placeholder="What's this about?" />
            <div className="lp-field">
              <label htmlFor="msg">Message</label>
              <textarea id="msg" className="lp-textarea" placeholder="Tell us how we can help…" required />
            </div>
            <Button type="submit" variant="primary" size="lg" iconRight={<span>→</span>}>Send message</Button>
          </form>
          <aside className="lp-contact__aside">
            <ContactCard icon="mail" bg="var(--grape-500)" title="Email us">
              <a href="mailto:hello@codaroo.com">hello@codaroo.com</a><br />We reply within 1 business day.
            </ContactCard>
            <ContactCard icon="clock" bg="var(--sky-500)" title="Support hours">
              Mon–Fri, 9am–5pm PT. Weekend notes answered Monday.
            </ContactCard>
            <ContactCard icon="shield-check" bg="var(--mint-600)" title="Safety questions">
              Read <a href="safety.html">our safety promise</a> — or ask us anything.
            </ContactCard>
            <ContactCard icon="sparkles" bg="var(--coral-500)" title="Proudly woman-owned">
              A small team building a safe place for kids to code.
            </ContactCard>
          </aside>
        </div>
      </section>
    </SitePage>
  );
}

/* ─── Expose everything ──────────────────────────────────── */
Object.assign(window, {
  Icon, Button, Badge, Stat, Avatar, ProgramCard, Input, Checkbox, IconButton, ProgressBar,
  Brand, Nav, Hero, SafetyBand, HowItWorks, Programs, Rewards, Proof, FinalCTA, Footer,
  AuthModal, SitePage, PageHead,
  SafetyPage, HowItWorksPage, PricingPage, ContactPage,
});
