/* page-timeline.jsx — interactive AI Timeline */
const { useState: useStateTL, useMemo: useMemoTL, useEffect: useEffectTL, useRef: useRefTL } = React;
const { ERAS, EVENTS } = window.RADAR_TL;

const TL_CATS = [
  { key: 'all', label: 'Everything' },
  { key: 'research', label: 'Research' },
  { key: 'model', label: 'Models' },
  { key: 'product', label: 'Products' },
  { key: 'funding', label: 'Funding' },
];
const TL_COLORS = { research: '#7c3aed', model: '#2563eb', product: '#db2777', funding: '#10b981' };

function TimelinePage() {
  useRevealAll();
  const [cat, setCat] = useStateTL('all');
  const bodyRef = useRefTL(null);
  const fillRef = useRefTL(null);
  const yearRef = useRefTL(null);
  const yearValRef = useRefTL(null);

  const eras = useMemoTL(() => ERAS.map((e) => ({
    ...e,
    events: EVENTS.filter((ev) => ev.era === e.id && (cat === 'all' || ev.cat === cat)),
  })).filter((e) => e.events.length > 0), [cat]);

  /* scroll-driven spine fill + floating year (rAF, no CSS transition dependence) */
  useEffectTL(() => {
    let raf = null;
    const update = () => {
      raf = null;
      const body = bodyRef.current, fill = fillRef.current, yearEl = yearRef.current;
      if (!body || !fill) return;
      const r = body.getBoundingClientRect();
      const vh = window.innerHeight;
      const progress = Math.max(0, Math.min(1, (vh * 0.55 - r.top) / r.height));
      fill.style.height = (progress * 100) + '%';

      // year: event dot closest to viewport center
      if (yearEl && yearValRef.current) {
        const dots = body.querySelectorAll('[data-year]');
        let best = null, bestDist = Infinity;
        dots.forEach((d) => {
          const dr = d.getBoundingClientRect();
          const dist = Math.abs(dr.top + dr.height / 2 - vh * 0.5);
          if (dist < bestDist) { bestDist = dist; best = d; }
        });
        const inRange = r.top < vh * 0.6 && r.bottom > vh * 0.3;
        yearEl.style.opacity = inRange ? '1' : '0';
        if (best) yearValRef.current.textContent = best.getAttribute('data-year');
      }
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    const iv = setInterval(onScroll, 300);
    update();
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      clearInterval(iv);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [cat]);

  return (
    <>
      <Nav active="timeline" />
      <PageHero eyebrow="AI timeline" title={<>Nine years that <span className="grad-text">changed everything.</span></>}
        sub="From one Google paper to models that do real work — every launch, breakthrough and mega-round that built the AI era. Scroll through it.">
        <div className="pills" style={{ marginTop: 26, marginBottom: 0 }}>
          {TL_CATS.map((c) => (
            <button key={c.key} className={'pill' + (cat === c.key ? ' on' : '')} onClick={() => setCat(c.key)}>{c.label}</button>
          ))}
        </div>
      </PageHero>

      <div className="tl-year" ref={yearRef}>
        <span className="lbl">Year</span>
        <span ref={yearValRef}>2017</span>
      </div>

      <main className="tl-wrap">
        <div className="tl-body" ref={bodyRef}>
          <div className="tl-spine"><div className="tl-spine-fill" ref={fillRef}></div></div>
          <div className="tl-spine-head"></div>

          {eras.map((era) => (
            <React.Fragment key={era.id}>
              <div className="tl-era reveal">
                <div className="range">{era.range}</div>
                <h2>{era.name}</h2>
                <p className="blurb">{era.blurb}</p>
              </div>
              {era.events.map((ev) => (
                <div key={ev.title} className={'tl-item' + (ev.milestone ? ' milestone' : '')} data-year={ev.year}>
                  <div className="tl-dot" style={{ '--dc': TL_COLORS[ev.cat] }}></div>
                  <article className="tl-card reveal">
                    <div className="tl-meta">
                      <span className="tl-date">{ev.date}</span>
                      <span className={'tl-cat tlc-' + ev.cat}>{ev.cat}</span>
                    </div>
                    <h3>{ev.title}</h3>
                    <p>{ev.desc}</p>
                  </article>
                </div>
              ))}
            </React.Fragment>
          ))}

          <div className="tl-end reveal">
            <div className="pulse"></div>
            <div className="t">The radar is live.</div>
            <div className="s">Whatever happens next in AI, you'll see it here first.</div>
            <div className="hero-ctas" style={{ marginTop: 22 }}>
              <a className="btn primary" href="news.html">See what happened today</a>
            </div>
          </div>
        </div>
      </main>
      <Footer />
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<TimelinePage />);
