function useCountdown(target) {
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, target - now);
  const days = Math.floor(diff / 86400000);
  const hours = Math.floor(diff / 3600000) % 24;
  const mins = Math.floor(diff / 60000) % 60;
  const secs = Math.floor(diff / 1000) % 60;
  return { days, hours, mins, secs };
}

function Digits({ value, pad = 2 }) {
  const str = String(value).padStart(pad, '0');
  return <>{str.split('').map((c, i) => <span key={i} className="countdown-digit">{c}</span>)}</>;
}

// Rotating word stack — outgoing word rolls UP while incoming word rolls
// UP from bottom. Both render simultaneously during the swap.
function RotatingWord({ words, interval = 2600 }) {
  const [i, setI] = React.useState(0);
  const [prev, setPrev] = React.useState(null); // { word, key } currently exiting
  const [key, setKey] = React.useState(0);
  const wordsKey = words.join('|');
  React.useEffect(() => {
    const id = setInterval(() => {
      setI(v => {
        const next = (v + 1) % words.length;
        setPrev({ word: words[v], key: 'out-' + Date.now() });
        setKey(k => k + 1);
        return next;
      });
    }, interval);
    return () => clearInterval(id);
  }, [wordsKey, interval]);

  // Clear the exiting word after its animation finishes (matches roll-out duration)
  React.useEffect(() => {
    if (!prev) return;
    const t = setTimeout(() => setPrev(null), 900);
    return () => clearTimeout(t);
  }, [prev]);

  // Measure the widest word so the container doesn't jump horizontally.
  const measureRef = React.useRef(null);
  const [width, setWidth] = React.useState(null);
  React.useLayoutEffect(() => {
    function measure() {
      if (!measureRef.current) return;
      const spans = measureRef.current.querySelectorAll('span');
      let max = 0;
      spans.forEach(s => { max = Math.max(max, s.getBoundingClientRect().width); });
      if (max > 0) setWidth(max);
    }
    measure();
    if (document.fonts && document.fonts.ready) {
      document.fonts.ready.then(measure);
    }
    const ro = new ResizeObserver(measure);
    if (measureRef.current) ro.observe(measureRef.current);
    window.addEventListener('resize', measure);
    return () => { ro.disconnect(); window.removeEventListener('resize', measure); };
  }, [words]);

  const word = words[i];
  return (
    <span className="rotating-word" style={{ width: width ? width + 'px' : 'auto', minWidth: '6ch' }}>
      {/* invisible measure row */}
      <span ref={measureRef} aria-hidden="true" style={{position:'absolute', visibility:'hidden', pointerEvents:'none', whiteSpace:'nowrap', top:0, left:0}}>
        {words.map((w, k) => <span key={k} style={{display:'block'}}>{w}</span>)}
      </span>
      {prev && (
        <span className="rotating-word__letters rotating-word__letters--out" key={prev.key} aria-hidden="true">
          {prev.word.split('').map((ch, k) => (
            <span
              key={k}
              className="rotating-word__letter rotating-word__letter--out"
              style={{ animationDelay: `${k * 35}ms` }}
            >{ch}</span>
          ))}
        </span>
      )}
      <span className="rotating-word__letters" key={key} aria-label={word}>
        {word.split('').map((ch, k) => (
          <span
            key={k}
            className="rotating-word__letter"
            style={{ animationDelay: `${k * 45}ms` }}
          >{ch}</span>
        ))}
      </span>
    </span>
  );
}

function Hero({ layout, intensity, theme }) {
  // July 24, 2026
  const target = new Date('2026-07-24T09:00:00-04:00').getTime();
  const { days, hours, mins, secs } = useCountdown(target);

  const rotatingWords = React.useMemo(() => (
    ['intelligence', 'productivity', 'proactivity', 'assistance', 'creativity', 'presence']
  ), []);

  const layouts = {
    orb: (
      <>
        <div className="hero-canvas">
          <window.Orb intensity={intensity === 'heavy' ? 1.2 : intensity === 'subtle' ? 0.4 : 0.9} theme={theme} />
        </div>
        <div className="container hero-content">
          <div className="hero-eyebrow reveal in">
            <span className="pulse"></span>
            <span>VEIRON / CORTEX · V.04 · RUNNING ON PROPRIETARY GPU GRID</span>
          </div>
          <h1 className="hero-title reveal in">
            A new <em>layer</em> of<br/>
            <RotatingWord words={rotatingWords} />
          </h1>
          <div className="hero-bottom">
            <p className="hero-sub reveal in">
              Veiron is an ambient AI for the self — a companion that learns
              your rhythms through wearable signals and guides your life
              with clarity, privacy, and presence.
            </p>
            <div className="hero-actions reveal in">
              <a className="btn-primary" href="#cta">
                Reserve your CoPilot
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
              </a>
              <a className="btn-ghost" href="#products">
                <span style={{width:8,height:8,borderRadius:999,background:'var(--accent-cyan)'}}></span>
                Watch the reveal
              </a>
            </div>
          </div>
        </div>
      </>
    ),
    editorial: (
      <>
        <div className="container hero-content" style={{gridTemplateRows:'auto 1fr auto', position:'relative'}}>
          <div className="hero-eyebrow reveal in">
            <span className="pulse"></span>
            <span>PRESS RELEASE · MIAMI · 07/24/2026</span>
          </div>
          <h1 className="hero-title reveal in" style={{fontSize:'clamp(80px,15vw,260px)', lineHeight:0.88, maxWidth:'100%'}}>
            <em>Every</em><br/>
            body speaks.<br/>
            <span style={{color:'var(--fg-dim)'}}>We </span><span className="grad">listen.</span>
          </h1>
          <div className="hero-bottom">
            <p className="hero-sub reveal in">
              One signal at a time. Veiron reads your biosignals, learns your
              patterns, and returns your life to you — intelligently.
            </p>
            <div className="hero-actions reveal in">
              <a className="btn-primary" href="#cta">Reserve CoPilot →</a>
            </div>
          </div>
        </div>
        <div className="hero-canvas" style={{opacity:0.5, filter:'blur(30px)'}}>
          <window.Orb intensity={0.7} theme={theme} />
        </div>
      </>
    ),
    split: (
      <>
        <div className="container" style={{position:'relative', zIndex:2, display:'grid', gridTemplateColumns:'1.1fr 1fr', gap:40, alignItems:'center', minHeight:'calc(100vh - 200px)'}}>
          <div>
            <div className="hero-eyebrow reveal in"><span className="pulse"></span><span>V.04 · PROPRIETARY CORTEX</span></div>
            <h1 className="hero-title reveal in" style={{fontSize:'clamp(56px, 8vw, 140px)', marginTop:32}}>
              Intelligence<br/>that <em>knows</em><br/>you back.
            </h1>
            <p className="hero-sub reveal in" style={{marginTop:32}}>
              LifeCoPilot learns from wearable signals and ambient context.
              Forge lets you build on top of it. Both run entirely on
              Veiron's own GPU grid — private by architecture.
            </p>
            <div className="hero-actions reveal in" style={{marginTop:32}}>
              <a className="btn-primary" href="#cta">Get access</a>
              <a className="btn-ghost" href="#products">Explore the ecosystem</a>
            </div>
          </div>
          <div style={{position:'relative', aspectRatio:'1/1', maxWidth:560}}>
            <window.Orb intensity={intensity === 'heavy' ? 1.3 : 1} theme={theme} />
          </div>
        </div>
      </>
    )
  };

  return (
    <section className="hero" id="hero">
      {layouts[layout] || layouts.orb}
      {/* Countdown overlay */}
      {layout === 'orb' && (
        <div style={{ position:'absolute', top: 140, right: 24, zIndex: 3, display:'flex', flexDirection:'column', alignItems:'flex-end', gap:12 }} className="reveal in">
          <div style={{fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.2em', color:'var(--fg-mute)', textTransform:'uppercase'}}>
            Miami reveal · 07.24.26
          </div>
          <div className="countdown" style={{width: 320}}>
            <div className="countdown-cell">
              <div className="countdown-num"><Digits value={days} /></div>
              <div className="countdown-label">Days</div>
            </div>
            <div className="countdown-cell">
              <div className="countdown-num"><Digits value={hours} /></div>
              <div className="countdown-label">Hrs</div>
            </div>
            <div className="countdown-cell">
              <div className="countdown-num"><Digits value={mins} /></div>
              <div className="countdown-label">Min</div>
            </div>
            <div className="countdown-cell">
              <div className="countdown-num"><Digits value={secs} /></div>
              <div className="countdown-label">Sec</div>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}
window.Hero = Hero;
