const { useState, useEffect, useRef, useMemo } = React;

const TWEAKS = /*EDITMODE-BEGIN*/{
  "primaryAccent": "violet",
  "showParticles": true,
  "scrollIntensity": "cinematic",
  "heroHeadline": "Your marketing team, hired.\n30x cheaper. 200% faster.",
  "accentColor": "violet",
  "mobileHeroLayout": "stacked",
  "mobileNav": "hamburger",
  "showStickyCta": true,
  "snapSections": false
}/*EDITMODE-END*/;

// ---------- TWEAK SETUP ----------
function useTweaks(defaults) {
  const [t, setT] = useState(defaults);
  const setTweak = (k, v) => {
    const next = typeof k === 'object' ? { ...t, ...k } : { ...t, [k]: v };
    setT(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, '*');
  };
  return [t, setTweak];
}

// ---------- VIEWPORT HOOK ----------
function useIsMobile(breakpoint = 768) {
  const [is, setIs] = useState(typeof window !== 'undefined' ? window.innerWidth <= breakpoint : false);
  useEffect(() => {
    const onR = () => setIs(window.innerWidth <= breakpoint);
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, [breakpoint]);
  return is;
}

// ---------- NAV (responsive · hamburger on mobile · collapses on scroll-down) ----------
function Nav() {
  const [open, setOpen] = useState(false);
  const [collapsed, setCollapsed] = useState(false);
  const isMobile = useIsMobile(720);
  const close = () => setOpen(false);

  useEffect(() => {
    if (isMobile) { setCollapsed(false); return; }
    let lastY = window.scrollY;
    setCollapsed(lastY > 2);
    function onScroll() {
      const y = window.scrollY;
      if (y <= 2) setCollapsed(false);
      else if (y > lastY) setCollapsed(true);
      else if (y < lastY) setCollapsed(false);
      lastY = y;
    }
    function onWheel(e) {
      if (e.deltaY > 0) setCollapsed(true);
      else if (e.deltaY < 0) setCollapsed(false);
    }
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('wheel', onWheel, { passive: true });
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('wheel', onWheel);
    };
  }, [isMobile]);

  return (
    <>
      <nav className={`nav ${collapsed && !open && !isMobile ? 'nav-collapsed' : ''}`}>
        <a className="brand" href="#" onClick={close}><img src="assets/logo.png" alt="logo" className="brand-logo" /></a>
        <div className="nav-links">
          <a href="#operators">Operators</a>
          <a href="pricing.html">Pricing</a>
          <a href="#faq">FAQ</a>
        </div>
        <div className="nav-actions">
          <a href="https://app.tryvexa.ai" className="btn btn-ghost btn-signin">Sign in</a>
          <a href="pricing.html" className="btn btn-primary btn-buy">Buy now</a>
          <button
            type="button"
            className={`hamburger ${open ? 'open' : ''}`}
            aria-label="Menu"
            aria-expanded={open}
            onClick={() => setOpen(o => !o)}
          >
            <span></span>
            <span></span>
            <span></span>
          </button>
        </div>
      </nav>
      <div className={`mobile-menu ${open ? 'open' : ''}`} role="dialog" aria-hidden={!open}>
        <div className="mobile-menu-inner">
          <a href="#operators" onClick={close}>Operators<span className="arrow">→</span></a>
          <a href="#how" onClick={close}>How it works<span className="arrow">→</span></a>
          <a href="pricing.html" onClick={close}>Pricing<span className="arrow">→</span></a>
          <a href="#faq" onClick={close}>FAQ<span className="arrow">→</span></a>
          <div className="mobile-menu-actions">
            <a href="https://app.tryvexa.ai" className="btn btn-ghost" onClick={close}>Sign in</a>
            <a href="pricing.html" className="btn btn-primary" onClick={close}>Buy now <span className="mono">→</span></a>
          </div>
          <p className="mobile-menu-foot">Two operators. One flat price.</p>
        </div>
      </div>
    </>
  );
}

// ---------- STICKY MOBILE CTA ----------
function StickyCta({ tweaks, plan = 'annual' }) {
  const planMo = Math.round(PRICE_BASE * (PLANS[plan]?.mult ?? 0.60));
  const [show, setShow] = useState(false);
  useEffect(() => {
    function onS() {
      // Show after scrolling past first viewport, hide near final-cta + footer
      const final = document.querySelector('.final-cta');
      const footer = document.querySelector('footer');
      const y = window.scrollY;
      const past = y > window.innerHeight * 0.6;
      let nearEnd = false;
      if (final) {
        const r = final.getBoundingClientRect();
        if (r.top < window.innerHeight * 0.9) nearEnd = true;
      }
      if (footer) {
        const r = footer.getBoundingClientRect();
        if (r.top < window.innerHeight) nearEnd = true;
      }
      setShow(past && !nearEnd);
    }
    onS();
    window.addEventListener('scroll', onS, { passive: true });
    return () => window.removeEventListener('scroll', onS);
  }, []);
  if (!tweaks?.showStickyCta) return null;
  return (
    <div className={`sticky-cta ${show ? 'show' : ''}`} aria-hidden={!show}>
      <div className="sticky-cta-inner">
        <div className="sticky-cta-meta">
          <div className="sticky-cta-pill mono"><span className="dot"></span> Two operators</div>
          <div className="sticky-cta-price">From <strong>${planMo}/mo</strong></div>
        </div>
        <a href="pricing.html" className="btn btn-primary btn-sticky">Buy now <span className="mono">→</span></a>
      </div>
    </div>
  );
}

// ---------- AVATAR CARD ----------
function AvatarCard({ src, name, role, accent }) {
  return (
    <div className="avatar-card" style={{ '--accent-glow': accent }}>
      <div className="avatar-img">
        <img src={src} alt={name} />
      </div>
      <div className="avatar-name">{name}</div>
      <div className="avatar-role">{role}</div>
    </div>
  );
}

// ---------- HERO + CINEMATIC AVATAR REVEAL ----------
// Scroll progress 0→1 across cinema container. Three acts:
//   0.00–0.35  hero (text large, avatars below)
//   0.35–0.55  transition (hero fades, avatars zoom & split)
//   0.55–1.00  showcase (Nara selected → Cato selected based on sub-progress)
// ---------- Single source of truth for the two avatars ----------
// Two floating <img> elements live at the App level. They follow refs:
// hero slot (in CinematicHero) when at top of page, stage slot (in StageSection)
// when the stage is in view. As user scrolls, position interpolates between them.
const AGENTS = {
  nara: {
    img: 'assets/nara.png',
    name: 'NARA',
    role: 'Email Marketer',
    accent: 'rgba(120,160,255,0.55)',
    accentText: '#cfd8ff',
    headline: 'Ships email revenue while you sleep.',
    description: 'Nara studies past sends, segments, and competitor moves, then drafts campaigns and lifecycle flows in your brand voice. Trained on $25M+ in DTC email revenue.',
    bullets: [
      'Drafts lifecycle flows in your brand voice',
      'Weekly campaigns shipped while you sleep',
      'Trained on $25M+ in real DTC revenue',
    ],
  },
  cato: {
    img: 'assets/cato.png',
    name: 'CATO',
    role: 'CMO',
    accent: 'rgba(200,140,255,0.55)',
    accentText: '#e8d4ff',
    headline: 'Runs ads like a ten-year CMO.',
    description: 'Cato scans competitors, generates creative, uploads to ads manager, kills fatigue, and scales winners. Funnel analysis, media buying, creative strategy - one operator.',
    bullets: [
      'Generates creative + uploads to ads manager',
      'Kills fatigued ads, scales winners daily',
      'Backed by $100M+ in profitable ad spend',
    ],
  },
};

function FloatingAvatar({ src, name, role, accentClass, heroRef, stageRef, morphRef, stageSectionRef, morphed, hidden }) {
  const [style, setStyle] = useState(null);
  // Apply the smooth CSS transition only while a morph is in flight, NOT during
  // scroll. This kills the lag that makes the avatar look like it overshoots.
  const [isMorphing, setIsMorphing] = useState(false);

  useEffect(() => {
    setIsMorphing(true);
    const t = setTimeout(() => setIsMorphing(false), 750);
    return () => clearTimeout(t);
  }, [morphed]);

  useEffect(() => {
    function update() {
      if (!heroRef.current || !stageRef.current || !stageSectionRef.current) return;
      const sectionRect = stageSectionRef.current.getBoundingClientRect();
      const heroRect = heroRef.current.getBoundingClientRect();
      const stageRect = stageRef.current.getBoundingClientRect();
      const morphRect = morphRef.current ? morphRef.current.getBoundingClientRect() : stageRect;

      // Avatar tracks the stage slot whenever the section is even partially in
      // the viewport. Otherwise it sits at the hero slot. No interpolation,
      // no overshoot. the avatar is locked to the slot's exact position.
      const sectionAtAll = sectionRect.top < window.innerHeight && sectionRect.bottom > 0;
      const target = sectionAtAll ? stageRect : heroRect;

      const position = morphed
        ? morphRect
        : {
            top: target.top,
            left: target.left,
            width: target.width,
            height: target.height,
          };

      const visible = !hidden && (sectionRect.bottom > 0);

      // Always-on smooth transition: short for scroll tracking (no teleport),
      // longer when explicitly morphing (button click expands the frame).
      const dur = isMorphing ? 600 : 320;
      const ease = 'cubic-bezier(0.4, 0, 0.2, 1)';
      const positionTransition =
        `top ${dur}ms ${ease}, left ${dur}ms ${ease}, width ${dur}ms ${ease}, height ${dur}ms ${ease}, `;

      setStyle({
        position: 'fixed',
        top: `${position.top}px`,
        left: `${position.left}px`,
        width: `${position.width}px`,
        height: `${position.height}px`,
        opacity: visible ? 1 : 0,
        visibility: visible ? 'visible' : 'hidden',
        transition: positionTransition + 'opacity 240ms ease',
        pointerEvents: 'none',
        zIndex: 5,
      });
    }
    update();
    window.addEventListener('scroll', update, { passive: true });
    window.addEventListener('resize', update);
    return () => {
      window.removeEventListener('scroll', update);
      window.removeEventListener('resize', update);
    };
  }, [heroRef, stageRef, morphRef, stageSectionRef, morphed, hidden, isMorphing]);

  // While the frame is animating (open/close), tick every frame so the avatar
  // tracks the morph slot's growing/shrinking position.
  useEffect(() => {
    let raf;
    const start = performance.now();
    function tick(now) {
      window.dispatchEvent(new Event('scroll'));
      if (now - start < 800) raf = requestAnimationFrame(tick);
    }
    raf = requestAnimationFrame(tick);
    return () => raf && cancelAnimationFrame(raf);
  }, [morphed]);

  if (!style) return null;
  return (
    <div className={`floating-avatar ${accentClass} ${morphed ? 'morphed' : ''}`} style={style}>
      <img src={src} alt={name} className="floating-avatar-img" />
      <div className="floating-avatar-name mono">{name}</div>
      <div className="floating-avatar-role mono">{role}</div>
    </div>
  );
}

function StageSection({ sectionRef, playing, setPlaying }) {
  const naraVideoRef = useRef(null);
  const catoVideoRef = useRef(null);

  // Drive the actual <video> elements based on `playing`
  useEffect(() => {
    [['nara', naraVideoRef], ['cato', catoVideoRef]].forEach(([key, ref]) => {
      const v = ref.current;
      if (!v) return;
      if (playing === key) {
        v.muted = true;
        const tryPlay = () => {
          const p = v.play();
          if (p && typeof p.catch === 'function') {
            p.catch(err => console.warn(`video ${key} play rejected:`, err));
          }
        };
        if (v.readyState >= 3) tryPlay();
        else {
          v.addEventListener('canplay', tryPlay, { once: true });
          try { v.load(); } catch (_) {}
        }
      } else {
        try { v.pause(); v.currentTime = 0; } catch (_) {}
      }
    });
  }, [playing]);

  const renderFrame = (key, agent, videoRef) => {
    const isPlaying = playing === key;
    const isInactive = playing && playing !== key;
    return (
      <div className={`stage-frame-wrap ${isPlaying ? 'is-playing-wrap' : ''} ${isInactive ? 'is-inactive-wrap' : ''}`}>
        <div className={`stage-frame stage-frame-${key} ${isPlaying ? 'is-playing' : ''}`}>
          <video
            ref={videoRef}
            src={`assets/${key}.mp4`}
            muted
            playsInline
            autoPlay={isPlaying}
            preload="auto"
            className="stage-video"
            controls={isPlaying}
            onEnded={() => setPlaying(p => (p === key ? null : p))}
            onError={e => console.warn(`video ${key} error`, e?.target?.error)}
          />
          <div className="op-video-corners" aria-hidden="true">
            <span></span><span></span><span></span><span></span>
          </div>
          {/* description panel - slides in when playing */}
          <div className={`stage-info ${isPlaying ? 'on' : ''}`}>
            <div className="stage-info-name mono" style={{ color: agent.accentText }}>
              {agent.name} · {agent.role}
            </div>
            <h3 className="stage-info-headline">{agent.headline}</h3>
            <p className="stage-info-copy">{agent.description}</p>
          </div>
          {/* The actual avatar for this frame, planted inside the box.
              CSS handles entry, morph-on-click, and exit. */}
          <img className="stage-avatar" src={agent.img} alt={agent.name} />
        </div>
        <button
          className={`stage-cta ${isPlaying ? 'is-active' : ''}`}
          onClick={() => setPlaying(isPlaying ? null : key)}
          style={{ '--accent-glow': agent.accent }}
        >
          {isPlaying ? 'Close video' : 'See workflow'} <span className="mono">▸</span>
        </button>
      </div>
    );
  };

  return (
    <section ref={sectionRef} className="stage-section" id="operators">
      <div className="stage-sticky">
        <div className={`stage-frames ${playing ? 'has-playing' : ''}`}>
          {renderFrame('nara', AGENTS.nara, naraVideoRef)}
          {renderFrame('cato', AGENTS.cato, catoVideoRef)}
        </div>
      </div>
    </section>
  );
}

// ---------- Cinematic hero/showcase --------------------------------------
// 5 acts: hero → Nara showcase → Nara video → Cato showcase → Cato video
function WorkflowModal({ agentKey, onClose }) {
  const agent = AGENTS[agentKey];
  const videoRef = useRef(null);
  // Three staged phases: 'opening' → 'info' (description visible) → 'video' (video playing)
  const [phase, setPhase] = useState('opening');

  useEffect(() => {
    // Stage the entrance: avatar + info appear first, then video starts after ~900ms
    const t1 = setTimeout(() => setPhase('info'), 50);
    const t2 = setTimeout(() => setPhase('video'), 900);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);

  // Start video only after the info phase has had a moment to be read
  useEffect(() => {
    if (phase !== 'video') return;
    const v = videoRef.current;
    if (!v) return;
    v.muted = true;
    const tryPlay = () => {
      const p = v.play();
      if (p && typeof p.catch === 'function') p.catch(err => console.warn('modal video rejected:', err));
    };
    if (v.readyState >= 3) tryPlay();
    else v.addEventListener('canplay', tryPlay, { once: true });
  }, [phase]);

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

  return (
    <div className="workflow-modal-backdrop" onClick={onClose}>
      <div
        className={`workflow-modal phase-${phase}`}
        onClick={e => e.stopPropagation()}
        style={{ '--accent-glow': agent.accent }}
      >
        <button className="workflow-modal-close" onClick={onClose} aria-label="Close">×</button>

        {/* Top header: morphed avatar + info side-by-side */}
        <div className="workflow-modal-header">
          <div className="workflow-modal-avatar-wrap">
            <img className="workflow-modal-avatar" src={agent.img} alt={agent.name} />
          </div>
          <div className="workflow-modal-info">
            <div className="workflow-modal-name mono" style={{ color: agent.accentText }}>
              <span className="dot"></span> {agent.name} · {agent.role}
            </div>
            <h2 className="workflow-modal-headline">{agent.headline}</h2>
            <p className="workflow-modal-copy">{agent.description}</p>
            {agent.bullets && (
              <ul className="workflow-modal-bullets">
                {agent.bullets.map((b, i) => (
                  <li key={i} style={{ '--bullet-delay': `${360 + i * 90}ms` }}>
                    <span className="check" style={{ color: agent.accentText }}>✓</span> {b}
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>

        {/* Video: appears after the info phase */}
        <div className="workflow-modal-video-wrap">
          <video
            ref={videoRef}
            src={`assets/${agentKey}.mp4`}
            muted
            playsInline
            preload="auto"
            controls
            className="workflow-modal-video"
            onError={e => console.warn('modal video error', e?.target?.error)}
          />
        </div>
      </div>
    </div>
  );
}

function CinematicHero({ onShowWorkflow }) {
  const containerRef = useRef(null);
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    function onScroll() {
      if (!containerRef.current) return;
      const rect = containerRef.current.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      if (total <= 0) { setProgress(0); return; }
      const scrolled = -rect.top;
      const p = Math.max(0, Math.min(1, scrolled / total));
      setProgress(p);
    }
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const ease = t => t < 0 ? 0 : t > 1 ? 1 : (t < 0.5 ? 4*t*t*t : 1 - Math.pow(-2*t + 2, 3) / 2);

  // Hero only. Nara/Cato live in their own AgentSection components below.
  const heroOp = 1;
  const heroY = -progress * 40;
  const heroAvatarsOp = 1;
  const heroAvatarsScale = 1;

  return (
    <div className="cinema" id="operators" ref={containerRef}>
      <div className="cinema-stick">
        {/* Particles */}
        {TWEAKS.showParticles && (
          <div className="particles">
            {Array.from({ length: 18 }).map((_, i) => (
              <span
                key={i}
                className={`particle ${['', 'v', 'p'][i % 3]}`}
                style={{
                  left: `${(i * 53) % 100}%`,
                  top: `${(i * 37) % 100}%`,
                  animationDelay: `${(i % 7) * 0.4}s`,
                  animationDuration: `${6 + (i % 5)}s`,
                  opacity: heroAvatarsOp * 0.6
                }}
              />
            ))}
          </div>
        )}

        {/* ACT 1 · Hero */}
        <div className="scene" style={{ opacity: heroOp, pointerEvents: heroOp > 0.5 ? 'auto' : 'none' }}>
          <div className="hero-content" style={{ transform: `translateY(${heroY}px)` }}>
            <div className="hero-badge"><span className="gradient-text">AI for Marketing</span></div>
            <h1 className="hero-title" style={{ whiteSpace: 'pre-line' }}>
              <span className="gradient-text">{TWEAKS.heroHeadline}</span>
            </h1>
            <p className="hero-lede" style={{ whiteSpace: 'pre-line' }}>
              {"Email marketer and CMO working on autopilot.\nResearches, writes, ships and learns while you focus on your business."}
            </p>
            <div className="hero-actions hero-actions-centered">
              <a href="pricing.html" className="btn btn-primary btn-xl">Buy now <span className="mono">→</span></a>
            </div>
            <div className="hero-bullets">
              <span><span className="check">✓</span> 14-day money-back</span>
              <span><span className="check">✓</span> Works in any language</span>
              <span><span className="check">✓</span> 24/7 AI optimization</span>
            </div>
            <div className="hero-avatars hero-avatars-xl">
              <div className="avatar-card">
                <button
                  type="button"
                  className="avatar-img avatar-img-button"
                  onClick={() => onShowWorkflow && onShowWorkflow('nara')}
                  aria-label="See Nara workflow"
                >
                  <img src="assets/nara.png" alt="NARA" />
                </button>
                <div className="avatar-name">NARA</div>
                <div className="avatar-role">Email Marketer</div>
                <button
                  type="button"
                  className="hero-avatar-cta"
                  style={{ '--accent-glow': 'rgba(120,160,255,0.55)' }}
                  onClick={() => onShowWorkflow && onShowWorkflow('nara')}
                >
                  See workflow <span className="mono">▸</span>
                </button>
              </div>
              <div className="avatar-card">
                <button
                  type="button"
                  className="avatar-img avatar-img-button"
                  onClick={() => onShowWorkflow && onShowWorkflow('cato')}
                  aria-label="See Cato workflow"
                >
                  <img src="assets/cato.png" alt="CATO" />
                </button>
                <div className="avatar-name">CATO</div>
                <div className="avatar-role">CMO</div>
                <button
                  type="button"
                  className="hero-avatar-cta"
                  style={{ '--accent-glow': 'rgba(200,140,255,0.55)' }}
                  onClick={() => onShowWorkflow && onShowWorkflow('cato')}
                >
                  See workflow <span className="mono">▸</span>
                </button>
              </div>
            </div>
          </div>
        </div>

      </div>

      {/* Scene progress dots */}
      <div className={`scene-dots ${progress > 0.05 && progress < 0.95 ? 'visible' : ''}`}>
        <div className={`dot ${progress < 0.4 ? 'active' : ''}`}></div>
        <div className={`dot ${progress >= 0.4 && progress < 0.7 ? 'active' : ''}`}></div>
        <div className={`dot ${progress >= 0.7 ? 'active' : ''}`}></div>
      </div>
    </div>
  );
}

// ---------- REVEAL HOOK ----------
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const obs = new IntersectionObserver(
      entries => entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); }),
      { threshold: 0.15 }
    );
    els.forEach(el => obs.observe(el));
    return () => obs.disconnect();
  }, []);
}

// ---------- IN ACTION (product demo) ----------
function InAction() {
  const cards = [
    {
      key: 'nara',
      tone: 'nara',
      avatar: 'assets/nara.png',
      quote: "Nara, check last month's best campaign and create an iteration for tomorrow",
      desc: "Nara pulls last month's top performer, mines the winning hooks, and ships a calibrated email draft scheduled for tomorrow.",
      finalMessage: 'Drafted 3 subject lines + body. Scheduled for tomorrow, 9:30am.',
      result: 'nara',
    },
    {
      key: 'cato',
      tone: 'cato',
      avatar: 'assets/cato.png',
      quote: "Cato, analyze the angles I've tested and create 3 ad sets for top 3 angles",
      desc: 'Cato sweeps every angle you have run, ranks them by ROAS and CPA, then builds 3 fresh ad sets ready to launch.',
      finalMessage: 'Built 9 ads across 3 ad sets. Ready to push live.',
      result: 'cato',
    },
  ];
  const naraSubjects = [
    '🔥 Restocked: the heat-wave drop',
    '⚡ Back in stock — won\'t last',
    'You asked, we restocked.',
  ];
  const catoAngles = [
    { label: 'Pain-relief', roas: '4.2x', cpa: '$11' },
    { label: 'Time-saver',  roas: '3.8x', cpa: '$13' },
    { label: 'Status proof', roas: '3.1x', cpa: '$15' },
  ];
  return (
    <section className="wrap inaction-section" style={{ padding: '40px 24px 80px' }}>
      <div className="inaction-grid">
        {cards.map((c, i) => (
          <div key={c.key} className={`inaction-card inaction-${c.tone} reveal delay-${i + 2}`}>
            <div className="inaction-glow" aria-hidden="true"></div>
            <div className="inaction-top">
              <div className="inaction-quote">{c.quote}</div>
              <p className="inaction-desc">{c.desc}</p>
            </div>
            <div className="inaction-stage">
              <div className="inaction-phone">
                <div className="inaction-phone-notch"></div>
                <div className="inaction-phone-screen">
                  <div className="inaction-chat">
                    <div className={`inaction-bubble inaction-bubble-${c.tone} inaction-bubble-final`}>
                      {c.finalMessage}
                    </div>

                    {c.result === 'nara' && (
                      <div className="inaction-result inaction-result-nara">
                        <div className="inaction-result-label mono">SUBJECT LINES</div>
                        {naraSubjects.map((s, j) => (
                          <div key={j} className="inaction-chip" style={{ animationDelay: `${0.9 + j * 0.18}s` }}>
                            <span className="inaction-chip-dot"></span>{s}
                          </div>
                        ))}
                        <div className="inaction-email-card" style={{ animationDelay: '1.6s' }}>
                          <div className="inaction-email-row">
                            <span className="inaction-email-icon">📅</span>
                            <span className="inaction-email-time">Tomorrow · 9:30am</span>
                            <span className="inaction-email-status mono">SCHEDULED</span>
                          </div>
                          <div className="inaction-email-bar">
                            <span className="inaction-email-bar-fill"></span>
                          </div>
                        </div>
                      </div>
                    )}

                    {c.result === 'cato' && (
                      <div className="inaction-result inaction-result-cato">
                        <div className="inaction-result-label mono">TOP 3 ANGLES</div>
                        {catoAngles.map((a, j) => (
                          <div key={j} className="inaction-angle" style={{ animationDelay: `${0.9 + j * 0.18}s` }}>
                            <span className="inaction-angle-rank mono">0{j + 1}</span>
                            <span className="inaction-angle-label">{a.label}</span>
                            <span className="inaction-angle-stat mono">{a.roas}</span>
                            <span className="inaction-angle-stat inaction-angle-stat-cpa mono">{a.cpa}</span>
                          </div>
                        ))}
                        <div className="inaction-ads-grid" style={{ animationDelay: '1.6s' }}>
                          {Array.from({ length: 9 }).map((_, j) => (
                            <div key={j} className="inaction-ad-tile" style={{ animationDelay: `${1.7 + j * 0.05}s` }}></div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
              <img className={`inaction-avatar inaction-avatar-${c.tone}`} src={c.avatar} alt="" />
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ---------- HOW IT WORKS ----------
function HowItWorks() {
  const steps = [
    ['01', 'Connect', 'Plug in store, ad accounts, brand voice, and competitor list.'],
    ['02', 'Train', 'Nara & Cato ingest past sends, winners, flops, customer groups, ad creatives.'],
    ['03', 'Launch', 'Campaigns, flows, ads, and segments ship from one mission board.'],
    ['04', 'Scale', 'You get notifications when they find winners. Nara & Cato will get sharper every week.'],
  ];
  return (
    <section id="how" className="wrap how-vexa-section" style={{ padding: '40px 24px 80px' }}>
      <div className="section-head" style={{ justifyContent: 'center', textAlign: 'center' }}>
        <div className="left reveal delay-1" style={{ marginLeft: 'auto', marginRight: 'auto' }}>
          <h2><span className="gradient-text">From data to revenue in four moves.</span></h2>
        </div>
      </div>
      <div className="how-vexa-list">
        {steps.map(([n, t, d], i) => (
          <div key={n} className={`how-vexa-step reveal delay-${i + 1}`}>
            <div className="how-vexa-num">{n}</div>
            <div className="how-vexa-body">
              <h3 className="how-vexa-title">{t}</h3>
              <p className="how-vexa-copy">{d}</p>
            </div>
            <div className="how-vexa-visual">
              <div className="how-vexa-placeholder">
                <span className="step-video-label mono">VIDEO</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ---------- HOW IT HELPS TO SCALE ----------
function HowItScales() {
  const leftFeatures = [
    'Analyzes everything with AI - knows what to optimize and how',
    'Trained on millions of marketing assets from top eCommerce brands',
    'Auto-uploads ads + media buys, then moves into scaling mode',
    'Kills fatigued creative the moment performance dips',
  ];
  const rightFeatures = [
    'Doubles down on winners. Ships campaigns, flows, ads, funnels',
    'Trained on $100M+ in real ad spend across DTC and SaaS',
    'Surfaces funnel improvements and creates the fixes for you',
    'Non-stop competitor analysis across email and paid stages',
  ];
  const stats = [
    ['10M+', 'creative assets analyzed'],
    ['$100M+', 'ad spend trained on'],
    ['24/7', 'always optimizing'],
  ];
  return (
    <section className="wrap scale-section" style={{ padding: '40px 24px 120px' }}>
      <div className="section-head" style={{ justifyContent: 'center', textAlign: 'center' }}>
        <div className="left reveal delay-1" style={{ marginLeft: 'auto', marginRight: 'auto' }}>
          <h2><span className="gradient-text">How it helps you scale</span></h2>
          <p>Trained on data from top eCommerce brands and millions in real ad spend.</p>
        </div>
      </div>

      <div className="scale-grid">
        <div className="scale-col scale-col-left">
          {leftFeatures.map((f, i) => (
            <div key={i} className={`scale-card reveal delay-${i + 1}`}>
              <span className="scale-check">✓</span>
              <span>{f}</span>
            </div>
          ))}
        </div>

        <div className="scale-center reveal delay-2">
          <div className="scale-device">
            <div className="scale-device-screen">
              <div className="scale-device-pill scale-pill-1 mono">winners ↑ 38%</div>
              <div className="scale-device-pill scale-pill-2 mono">CAC ↓ 24%</div>
              <div className="scale-device-pill scale-pill-3 mono">CTR ↑ 51%</div>
              <div className="scale-device-pill scale-pill-4 mono">fatigue killed</div>
              <div className="scale-device-glow"></div>
            </div>
          </div>
        </div>

        <div className="scale-col scale-col-right">
          {rightFeatures.map((f, i) => (
            <div key={i} className={`scale-card reveal delay-${i + 1}`}>
              <span className="scale-check">✓</span>
              <span>{f}</span>
            </div>
          ))}
        </div>
      </div>

      <p className="scale-stats-tagline reveal delay-3">This isn't just an AI wrapper. It's content intelligence.</p>

      {/* 99+ languages: cinematic flag marquee */}
      <div className="scale-languages reveal delay-3">
        <div className="scale-languages-label mono">
          <span className="scale-languages-dot"></span> 99+ languages supported
        </div>
        <div className="scale-flags-marquee">
          <div className="scale-flags-track">
            {(() => {
              const flags = ['🇺🇸','🇬🇧','🇫🇷','🇩🇪','🇪🇸','🇮🇹','🇯🇵','🇰🇷','🇨🇳','🇮🇳','🇧🇷','🇲🇽','🇨🇦','🇦🇺','🇳🇱','🇸🇪','🇳🇴','🇩🇰','🇫🇮','🇵🇱','🇹🇷','🇱🇹','🇦🇪','🇸🇦','🇿🇦','🇦🇷','🇨🇱','🇪🇬','🇮🇩','🇹🇭','🇻🇳','🇵🇭','🇲🇾','🇸🇬','🇨🇭','🇦🇹','🇧🇪','🇮🇪','🇵🇹','🇬🇷','🇨🇿','🇭🇺','🇷🇴','🇺🇦','🇮🇱','🇳🇿','🇨🇴','🇵🇪','🇵🇰','🇧🇩'];
              const looped = [...flags, ...flags];
              return looped.map((f, i) => (
                <span key={i} className="scale-flag">{f}</span>
              ));
            })()}
          </div>
        </div>
      </div>

      <div className="scale-stats reveal delay-3">
        {stats.map(([n, l]) => (
          <div key={n} className="scale-stat">
            <div className="scale-stat-num gradient-text">{n}</div>
            <div className="scale-stat-lbl">{l}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ---------- WHY THIS WORKS ----------
function WhyThisWorks() {
  const [mode, setMode] = useState('with');
  const isWith = mode === 'with';
  const fails = [
    "They test 1–2 ideas and quit when they don't work",
    'They optimize on the wrong metrics',
    'They scale too slow or react too late',
    "They make content that doesn't stop the scroll",
  ];
  const wins = [
    '$100M+ in proven, winning campaigns',
    '10M+ high-performing creatives analyzed',
    'Every platform algorithm update since 2019',
    'Works in any language and currency, built for global teams',
    'Real data, not guesswork, built for consistent conversions',
  ];
  const items = isWith ? wins : fails;
  const title = isWith
    ? "Vexa wins because it's trained on what works:"
    : 'Most teams fail at growth because:';
  return (
    <section className="wrap why-works-section" style={{ padding: '40px 24px 120px' }}>
      <div className="section-head" style={{ justifyContent: 'center', textAlign: 'center' }}>
        <div className="left reveal delay-1" style={{ marginLeft: 'auto', marginRight: 'auto' }}>
          <h2><span className="gradient-text">Why this works<br />and manual work doesn't</span></h2>
        </div>
      </div>

      <div className="why-works-single reveal delay-2">
        <div className={`why-card ${isWith ? 'why-card-win' : 'why-card-fail'}`}>
          <div className={`why-toggle ${isWith ? 'is-with' : 'is-without'}`} role="tablist">
            <button
              type="button"
              role="tab"
              aria-selected={!isWith}
              className={`why-toggle-btn ${!isWith ? 'active' : ''}`}
              onClick={() => setMode('without')}
            >
              Without Vexa
            </button>
            <button
              type="button"
              role="tab"
              aria-selected={isWith}
              className={`why-toggle-btn ${isWith ? 'active' : ''}`}
              onClick={() => setMode('with')}
            >
              With Vexa
            </button>
            <span className="why-toggle-thumb" aria-hidden="true"></span>
          </div>

          <div key={mode} className="why-card-inner">
            <div className={`why-avatar ${isWith ? 'why-avatar-glow' : 'why-avatar-dim'}`}>
              <div className={`why-avatar-bg ${isWith ? 'why-avatar-bg-win' : 'why-avatar-bg-fail'}`}></div>
              <img src="assets/cato.png" alt="" />
            </div>
            <h3 className="why-card-title">{title}</h3>
            <ul className="why-list">
              {items.map((t, i) => (
                <li key={i}>
                  <span className={isWith ? 'why-check' : 'why-x'}>{isWith ? '✓' : '✕'}</span>
                  <span>{t}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- INTEGRATIONS ----------
function Integrations() {
  const apps = [
    { name: 'Slack',  src: 'assets/stack/Slack_icon_2019.svg.png',           tx: -340, ty: -70, delay: '0s'   },
    { name: 'Asana',  src: 'assets/stack/Asana-Symbol.png',                  tx: -180, ty:  130, delay: '0.6s' },
    { name: 'Monday', src: 'assets/stack/monday-icon-icon-sm.png',           tx:    0, ty: -150, delay: '1.2s' },
    { name: 'Notion', src: 'assets/stack/Notion-logo.svg.png',               tx:  200, ty:  120, delay: '1.8s' },
    { name: 'Drive',  src: 'assets/stack/Google_Drive_icon_(2020).svg.png',  tx:  340, ty: -60, delay: '2.4s' },
  ];
  const tiles = Array.from({ length: 56 });
  return (
    <section className="wrap integrations-section" style={{ padding: '40px 24px 120px' }}>
      <div className="section-head" style={{ justifyContent: 'center', textAlign: 'center' }}>
        <div className="left reveal delay-1" style={{ marginLeft: 'auto', marginRight: 'auto' }}>
          <h2><span className="gradient-text">Fully integrated with your stack</span></h2>
          <p>It posts to every platform: results, low-hanging fruits, revenue leaks, future winners.</p>
        </div>
      </div>

      <div className="integrations-stage reveal delay-2">
        <div className="integrations-floor">
          <div className="integrations-tiles">
            {tiles.map((_, i) => (
              <div key={i} className="integration-tile" style={{ animationDelay: `${(i % 8) * 0.18}s` }}></div>
            ))}
          </div>
        </div>
        <div className="integrations-glow"></div>
        <div className="integrations-orbs">
          {apps.map((a) => (
            <div
              key={a.name}
              className="integration-orb"
              style={{ '--tx': `${a.tx}px`, '--ty': `${a.ty}px`, animationDelay: a.delay }}
            >
              <div className="integration-orb-logo">
                <img src={a.src} alt={a.name} />
              </div>
              <div className="integration-orb-label">{a.name}</div>
            </div>
          ))}
          <div className="integration-center">
            <img src="assets/logo.png" alt="Vexa" />
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- HOW VEXA WORKS ----------
function HowVexaWorks() {
  const steps = [
    ['01', 'Input your branding', "Vexa's AI will learn your brand in seconds."],
    ['02', 'Input past-data', 'Vexa will analyze all your winner email flows, campaigns and performing angles on Meta.'],
    ['03', 'Activate & Scale', "Nara will run email marketing like Duolingo - creates and publishes monthly campaigns and flows with one-click. Cato will take care of Facebook ad strategy - from creative to copy to optimization. You get notifications when they find winners."],
  ];
  return (
    <section className="wrap how-vexa-section" style={{ padding: '40px 24px 120px' }}>
      <div className="section-head" style={{ justifyContent: 'center', textAlign: 'center' }}>
        <div className="left reveal delay-1" style={{ marginLeft: 'auto', marginRight: 'auto' }}>
          <h2><span className="gradient-text">How Vexa works</span></h2>
        </div>
      </div>
      <div className="how-vexa-list">
        {steps.map(([n, t, d], i) => (
          <div key={n} className={`how-vexa-step reveal delay-${i + 1}`}>
            <div className="how-vexa-num">{n}</div>
            <div className="how-vexa-body">
              <h3 className="how-vexa-title">{t}</h3>
              <p className="how-vexa-copy">{d}</p>
            </div>
            <div className="how-vexa-visual">
              <div className="how-vexa-placeholder">
                <span className="step-video-label mono">VIDEO</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ---------- PRICING ----------
const PLANS = {
  monthly:   { mult: 1,    label: 'Monthly',   note: 'Billed monthly',          save: null      },
  quarterly: { mult: 0.80, label: 'Quarterly', note: 'Billed every 3 months',  save: '20% OFF' },
  annual:    { mult: 0.60, label: 'Annual',    note: 'Billed yearly',           save: '40% OFF' }
};
const PRICE_BASE = 200;

function Pricing({ plan, setPlan }) {
  const plans = PLANS;
  const base = PRICE_BASE;
  const mo = Math.round(base * plans[plan].mult);
  const singleBase = 129;
  const singleMo = Math.round(singleBase * plans[plan].mult);
  const [singleAgent, setSingleAgent] = useState('nara');
  const singleAgentLabel = singleAgent === 'nara' ? 'Nara' : 'Cato';
  const singleAgentRole = singleAgent === 'nara' ? 'Email marketer' : 'CMO';
  return (
    <section id="pricing" className="wrap" style={{ padding: '120px 24px' }}>
      <div className="section-head" style={{ justifyContent: 'center', textAlign: 'center' }}>
        <div className="left reveal delay-1" style={{ marginLeft: 'auto', marginRight: 'auto' }}>
          <h2><span className="gradient-text">Pays for itself in one campaign.</span></h2>
          <p>Get 40% OFF on annual plan</p>
        </div>
      </div>

      {/* Premium pill switch */}
      <div className="plan-switch plan-switch-3 reveal delay-2" data-plan={plan}>
        <div className="plan-switch-thumb" aria-hidden="true"></div>
        {Object.entries(plans).map(([key, p]) => (
          <button
            key={key}
            type="button"
            className={`plan-switch-opt ${plan === key ? 'active' : ''}`}
            onClick={() => setPlan(key)}
          >
            <span className="plan-switch-label">{p.label}</span>
            {p.save && <span className="plan-switch-save">{p.save}</span>}
          </button>
        ))}
      </div>

      <div className="pricing-grid pricing-grid-3">
        {/* Single operator · pick Nara or Cato */}
        <div className="price-card price-card-single reveal delay-1">
          <div className="name">Single operator</div>
          <div className="single-toggle">
            <button
              type="button"
              className={`single-toggle-opt ${singleAgent === 'nara' ? 'active' : ''}`}
              onClick={() => setSingleAgent('nara')}
            >
              Nara
            </button>
            <button
              type="button"
              className={`single-toggle-opt ${singleAgent === 'cato' ? 'active' : ''}`}
              onClick={() => setSingleAgent('cato')}
            >
              Cato
            </button>
          </div>
          <div className="price" key={`single-price-${plan}-${singleAgent}`}>
            ${singleMo}<small> /mo</small>
          </div>
          <p className="plan-note" key={`single-note-${plan}-${singleAgent}`}>
            {plans[plan].note}
            {plan !== 'monthly' && <> · was <span className="plan-strike">${singleBase}/mo</span></>}
          </p>
          <ul>
            <li>{singleAgentLabel} · {singleAgentRole}</li>
            <li>Unlimited {singleAgent === 'nara' ? 'campaigns + flows' : 'ads + creative'}</li>
            <li>Brand-voice training</li>
            <li>{singleAgent === 'nara' ? 'Competitor scanning · email' : 'Competitor scanning · ads'}</li>
            <li>Founder support</li>
            <li>Add the other operator anytime</li>
          </ul>
          <a href="#" className="btn btn-ghost" style={{ width: '100%', justifyContent: 'center' }}>Start with {singleAgentLabel}</a>
        </div>

        {/* Both operators · featured */}
        <div className="price-card featured price-card-subscription reveal delay-2">
          <span className="ribbon ribbon-lifetime">Most popular</span>
          <div className="name">Both operators</div>
          <div className="price" key={`price-${plan}`}>${mo}<small> /mo</small></div>
          <p className="plan-note" key={`note-${plan}`}>
            {plans[plan].note}
            {plan !== 'monthly' && <> · was <span className="plan-strike">${base}/mo</span></>}
          </p>
          <ul>
            <li>Both operators · Nara + Cato</li>
            <li>Unlimited campaigns, flows, ad creative</li>
            <li>Brand-voice training</li>
            <li>Competitor scanning · email + ads</li>
            <li>Cross-channel funnel analysis</li>
            <li>Founder priority support</li>
          </ul>
          <a href="#" className="btn btn-primary" style={{ width: '100%', justifyContent: 'center' }}>Start subscription <span className="mono">→</span></a>
        </div>

        {/* Custom · Enterprise */}
        <div className="price-card reveal delay-3">
          <div className="name">Custom · Enterprise</div>
          <div className="price price-custom">Custom</div>
          <p className="plan-note">Two dedicated professionals embedded with your team.</p>
          <ul>
            <li>Dedicated CMO operator</li>
            <li>Dedicated marketing operator</li>
            <li>Custom training on your data</li>
            <li>Direct Slack channel with founders</li>
            <li>Custom integrations & reporting</li>
            <li>Bring-your-own SLAs & security review</li>
          </ul>
          <a href="#" className="btn btn-ghost" style={{ width: '100%', justifyContent: 'center' }}>Talk to founders</a>
        </div>
      </div>
    </section>
  );
}

// ---------- TESTIMONIALS ----------
function Testimonials() {
  const items = [
    ['Nara shipped 14 campaigns in our first week. Two became evergreen flows that still print revenue.', 'Sasha L.', 'Founder · Lumen Skin'],
    ['Cato cut our CAC by 38% in 30 days by killing fatigued creative we had been ignoring.', 'Diego R.', 'Head of Growth · Tinker'],
    ['Honestly the cleanest growth tooling I have used. It feels like hiring two senior operators for the price of an intern.', 'Priya M.', 'CEO · Forge & Co.']
  ];
  const more = [
    ['Replaced our $8k/mo agency in week two. The Slack updates from Cato are sharper than anything we got from humans.', 'Marcus T.', 'Founder · Halcyon Goods'],
    ['Nara learns the brand voice scarily well. Our open rates jumped from 22% to 41% inside a month.', 'Eleni K.', 'CMO · Polaris Labs'],
    ['I was skeptical. Then Cato found three creative angles we had completely missed and one of them is now our top spender.', 'Jordan P.', 'Growth lead · Northwind'],
    ['Honestly the onboarding is what sold me. They ingested our docs and shipped a real campaign in under an hour.', 'Aisha B.', 'Founder · Coastline Co.'],
    ['We run lean. Vexa is the only reason we can compete on paid + lifecycle without a 10-person growth team.', 'Tomas V.', 'CEO · Drift & Bloom'],
    ['Cato found our hero creative was tanking on iOS and shifted spend before we even noticed. Saved us ~$4k that week.', 'Riya S.', 'Head of Paid · Stockyard'],
    ['It is unreal that Nara can write a 6-email post-purchase flow that actually sounds like us. Approving everything is the only manual step.', 'Wes O.', 'Founder · Atlas Provisions'],
    ['Stopped scheduling weekly creative meetings. Cato just ships, kills, and reports. The hours back are insane.', 'Léa F.', 'CMO · Maison Verte'],
    ['Best $/hour I have spent on this business. Nara alone has paid for the year three times over in winback revenue.', 'Hassan A.', 'Owner · Junction Tea'],
    ['The thing nobody talks about: it is fast. Brief in, draft out, in the time it takes to refill coffee.', 'Quinn M.', 'Operator · Field Notes'],
  ];
  const [showAll, setShowAll] = useState(false);
  const visible = showAll ? [...items, ...more] : items;
  return (
    <section className="wrap" style={{ padding: '40px 24px 120px' }}>
      <div className="section-head" style={{ justifyContent: 'center', textAlign: 'center' }}>
        <div className="left reveal delay-1" style={{ marginLeft: 'auto', marginRight: 'auto' }}>
          <h2><span className="gradient-text">Founders shipping with Vexa.</span></h2>
        </div>
      </div>
      <div className="testimonial-grid">
        {visible.map(([q, n, t], i) => (
          <div key={i} className={`testimonial ${i < 3 ? `reveal delay-${i + 1}` : 'tm-extra'}`}>
            <blockquote>{q}</blockquote>
            <div className="who">
              <div className="av"></div>
              <div>
                <div className="name">{n}</div>
                <div className="title">{t}</div>
              </div>
            </div>
          </div>
        ))}
      </div>
      <div className="testimonial-cta-wrap">
        <button
          className="testimonial-more"
          onClick={() => setShowAll(s => !s)}
          aria-expanded={showAll}
        >
          {showAll ? (
            <>See less <span className="mono">↑</span></>
          ) : (
            <><span className="tm-count">8,438+</span> founders love Vexa. See more <span className="mono">↓</span></>
          )}
        </button>
      </div>
    </section>
  );
}

// ---------- FAQ ----------
function FAQ() {
  const [open, setOpen] = useState(0);
  const items = [
    ['Is this one app or two products?', 'Two operators sold separately or as a bundle. Nara handles email lifecycle revenue. Cato handles paid growth and CMO-level judgment. Run one or both.'],
    ['How fast can we go live?', 'Connect data, describe brand voice, approve the first missions. Most teams are shipping campaigns inside the first hour.'],
    ['Will Vexa replace my team?', 'No. It replaces the rote work: research, drafts, pulling reports, monitoring fatigue. Your team focuses on judgment, not tabs.'],
    ['What about brand safety?', 'Every output is reviewable. Nara and Cato never push to live without your approval until you explicitly enable autopilot mode.'],
    ['How does pricing scale?', 'Flat $200 for both operators. No spend percentages, no surprise overages. Quarterly saves 20%, annual saves 40%.'],
    ['What integrations do you support?', 'Klaviyo, Mailchimp, Customer.io, Postmark for email. Meta, Google, TikTok, Reddit, LinkedIn for paid. Shopify, Stripe, Segment, and Mixpanel on the data side. New ones ship monthly.'],
    ['Where does the training come from?', 'Years of senior-operator experience and millions in real ad spend across DTC, SaaS, and marketplaces. Then re-grounded on your brand voice and historical data on day one.'],
    ['Who owns the outputs and the data?', 'You do. Outputs are yours. Your data is never used to train models that other customers see. Full export and deletion any time.'],
    ['Is there a free trial?', 'Seven-day money-back guarantee on the monthly plan. If Vexa is not pulling weight, refund and walk.'],
    ['Can I run only Nara, or only Cato?', 'Yes. Single-operator pricing is $129/mo each. Most teams start with one and add the second within the first month.'],
    ['What hours does Vexa work?', '24/7. Cato monitors fatigue and budgets continuously. Nara drafts overnight so you wake up to a queue ready for review.'],
    ['Do I need a marketing team to use it?', 'No. Founders run Vexa solo all the time. Bring brand opinions, approve the work. The operator handles the rest.'],
    ['How do approvals work?', 'A clean inbox of campaigns, ad sets, and creative. One-click approve, request changes, or send back with notes. Set autopilot per channel when you trust it.'],
    ['Can it match my brand voice?', 'Yes. Drop in your style guide, past sends, top-performing creative, and Slack tone. Nara and Cato calibrate before they ship anything.'],
    ['What is the refund policy?', 'Seven days, no questions, full refund on monthly. Annual prorates within the first 30 days.'],
    ['Do you offer enterprise or custom plans?', 'Yes. Custom is for teams with multiple brands, white-glove onboarding, and SOC 2 / SSO needs. Talk to us.'],
  ];
  return (
    <section id="faq" className="wrap faq-section" style={{ padding: '40px 24px 120px' }}>
      <div className="section-head" style={{ justifyContent: 'center', textAlign: 'center' }}>
        <div className="left reveal delay-1" style={{ marginLeft: 'auto', marginRight: 'auto' }}>
          <h2><span className="gradient-text">F.A.Q.</span></h2>
        </div>
      </div>
      <div className="faq-list reveal delay-2">
        {items.map(([q, a], i) => (
          <div key={i} className={`faq-item ${open === i ? 'open' : ''}`} onClick={() => setOpen(open === i ? -1 : i)}>
            <div className="faq-q"><span>{q}</span><span className="icon">+</span></div>
            <div className="faq-a">{a}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ---------- FINAL CTA ----------
function FinalCTA() {
  return (
    <section className="final-cta wrap">
      <h2 className="reveal" style={{ fontSize: 'clamp(48px, 7vw, 96px)' }}><span className="gradient-text">Ready to ship the growth with AI?</span></h2>
      <p className="reveal delay-1" style={{ color: 'var(--soft)', fontSize: 19, maxWidth: 580, margin: '24px auto 36px', lineHeight: 1.5 }}>
        Live in under an hour
      </p>
      <div className="reveal delay-2" style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
        <a href="pricing.html" className="btn btn-primary">Buy now <span className="mono">→</span></a>
        <a href="#" className="btn btn-ghost">Talk to founders</a>
      </div>
    </section>
  );
}

// ---------- FOOTER ----------
function Footer() {
  return (
    <footer>
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <div className="brand"><img src="assets/logo.png" alt="logo" className="brand-logo" /></div>
            <p style={{ color: 'var(--muted)', fontSize: 14, lineHeight: 1.5, margin: '14px 0 0', maxWidth: 280 }}>
              Two operators trained like a senior growth team. Email revenue and paid growth, on autopilot.
            </p>
          </div>
          <div>
            <h4>Operators</h4>
            <ul>
              <li><a href="#">Nara · Email</a></li>
              <li><a href="#">Cato · CMO</a></li>
            </ul>
          </div>
          <div>
            <h4>Company</h4>
            <ul>
              <li><a href="#">About</a></li>
              <li><a href="#">Manifesto</a></li>
              <li><a href="#">Careers</a></li>
            </ul>
          </div>
          <div>
            <h4>Resources</h4>
            <ul>
              <li><a href="#">Docs</a></li>
              <li><a href="#">Changelog</a></li>
              <li><a href="#">Status</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 VEXA · TRYVEXA.AI</span>
          <span>BUILT IN SF & LISBON</span>
        </div>
      </div>
    </footer>
  );
}

// ---------- TWEAKS PANEL ----------
function VexaTweaks({ tweaks: tProp, setTweak: setTProp }) {
  // Allow standalone use too
  const [tLocal, setTLocal] = useTweaks(TWEAKS);
  const t = tProp ?? tLocal;
  const setTweak = setTProp ?? setTLocal;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Theme">
        <TweakRadio
          label="Accent"
          value={t.accentColor || 'violet'}
          options={[
            { value: 'violet', label: 'Violet' },
            { value: 'cyan',   label: 'Cyan' },
            { value: 'pink',   label: 'Pink' },
            { value: 'amber',  label: 'Amber' }
          ]}
          onChange={v => setTweak('accentColor', v)}
        />
      </TweakSection>
      <TweakSection title="Hero">
        <TweakText label="Headline" value={t.heroHeadline} onChange={v => setTweak('heroHeadline', v)} />
        <TweakRadio
          label="Mobile hero"
          value={t.mobileHeroLayout || 'stacked'}
          options={[
            { value: 'stacked', label: 'Stacked' },
            { value: 'side',    label: 'Side-by-side' },
            { value: 'morph',   label: 'Morphing' }
          ]}
          onChange={v => setTweak('mobileHeroLayout', v)}
        />
      </TweakSection>
      <TweakSection title="Mobile">
        <TweakRadio
          label="Sticky CTA"
          value={t.showStickyCta ? 'on' : 'off'}
          options={[{ value: 'on', label: 'On' }, { value: 'off', label: 'Off' }]}
          onChange={v => setTweak('showStickyCta', v === 'on')}
        />
        <TweakRadio
          label="Scroll snap"
          value={t.snapSections ? 'on' : 'off'}
          options={[{ value: 'on', label: 'On' }, { value: 'off', label: 'Off' }]}
          onChange={v => setTweak('snapSections', v === 'on')}
        />
      </TweakSection>
      <TweakSection title="Motion">
        <TweakRadio
          label="Particles"
          value={t.showParticles ? 'on' : 'off'}
          options={[{ value: 'on', label: 'On' }, { value: 'off', label: 'Off' }]}
          onChange={v => setTweak('showParticles', v === 'on')}
        />
        <TweakRadio
          label="Scroll intensity"
          value={t.scrollIntensity}
          options={[{ value: 'subtle', label: 'Subtle' }, { value: 'cinematic', label: 'Cinematic' }]}
          onChange={v => setTweak('scrollIntensity', v)}
        />
      </TweakSection>
    </TweaksPanel>
  );
}

// ---------- MAIN APP ----------
function App() {
  useReveal();
  const [tweaks, setTweak] = useTweaks(TWEAKS);
  const [plan, setPlan] = useState('annual');
  const [workflowModal, setWorkflowModal] = useState(null);

  useEffect(() => {
    document.documentElement.setAttribute('data-accent', tweaks.accentColor || 'violet');
    document.documentElement.setAttribute('data-snap', tweaks.snapSections ? 'on' : 'off');
    document.documentElement.setAttribute('data-mobile-hero', tweaks.mobileHeroLayout || 'stacked');
  }, [tweaks.accentColor, tweaks.snapSections, tweaks.mobileHeroLayout]);

  return (
    <>
      <div className="bg-aurora"></div>
      <div className="bg-grid"></div>

      <Nav />

      <main>
        <CinematicHero onShowWorkflow={setWorkflowModal} />
        <InAction />
        <HowItWorks />
        <HowItScales />
        <Integrations />
        <WhyThisWorks />
        <Testimonials />
        <FAQ />
        <FinalCTA />
      </main>

      <Footer />
      <StickyCta tweaks={tweaks} plan={plan} />
      <VexaTweaks tweaks={tweaks} setTweak={setTweak} />
      {workflowModal && (
        <WorkflowModal
          agentKey={workflowModal}
          onClose={() => setWorkflowModal(null)}
        />
      )}
    </>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App />);
