const { useEffect, useRef } = React;

function Timeline({ activeIdx, setActiveIdx }) {
  const itemRefs = useRef([]);
  const photoBgRefs = useRef({});  // keyed by experience id
  const total = window.EXPERIENCES.length;

  // Keep ProgressRail in sync as cards scroll into view
  useEffect(() => {
    const observers = itemRefs.current.map((el, i) => {
      if (!el) return null;
      const obs = new IntersectionObserver(
        ([entry]) => { if (entry.isIntersecting) setActiveIdx(i); },
        { threshold: 0.4 }
      );
      obs.observe(el);
      return obs;
    });
    return () => observers.forEach(obs => obs && obs.disconnect());
  }, [setActiveIdx]);

  // Dolly-zoom each photo background card as it travels through the viewport
  useEffect(() => {
    function onScroll() {
      window.EXPERIENCES.forEach((e, i) => {
        if (!e.photo) return;
        const img = photoBgRefs.current[e.id];
        const card = itemRefs.current[i];
        if (!img || !card) return;
        const rect = card.getBoundingClientRect();
        const totalTravel = rect.height + window.innerHeight;
        const scrolled = window.innerHeight - rect.top;
        const progress = Math.max(0, Math.min(1, scrolled / totalTravel));
        img.style.transform = `scale(${1 + progress * 0.25})`;
      });
    }
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [total]);

  return (
    <section id="timeline">
      {window.EXPERIENCES.map((e, i) => {
        const V = window.VISUAL_MAP[e.visual];
        const hasPhoto = !!e.photo;
        const flipClass = '';
        const photoClass = hasPhoto ? ' tl-item--photo-bg' : '';

        return (
          <div key={e.id} ref={el => itemRefs.current[i] = el} className={`tl-item${flipClass}${photoClass}`}>

            {/* Photo background — any entry with a photo: field gets this */}
            {hasPhoto && (
              <div className="tl-photo-bg">
                <img ref={el => photoBgRefs.current[e.id] = el} src={e.photo} alt="" aria-hidden="true" />
                <div className="tl-photo-overlay" />
              </div>
            )}

            <div className="tl-left">
              {e.logos && e.logos.length > 0 && (
                <div className="tl-logos">
                  {e.logos.map((l, k) => (
                    <div key={k} className="tl-logo-chip" title={l.label}>
                      <img src={l.src} alt={l.alt} />
                    </div>
                  ))}
                </div>
              )}
              <div className="tl-eyebrow">
                <span className="dot" />
                <span className="tl-year">{e.year}</span>
                <span className="tl-counter">
                  {String(i + 1).padStart(2, '0')} / {String(total).padStart(2, '0')} · {e.tag}
                </span>
              </div>
              <h2 className="tl-role">{e.role}</h2>
              <div className="tl-company">{e.company} — {e.location}</div>
              <div className="label" style={{ marginBottom: 18, color: 'var(--accent)' }}>
                ▸ {e.contract}
              </div>
              <p className="tl-desc">{e.description}</p>
              <ul className="tl-highlights">
                {e.highlights.map((h, j) => <li key={j}>{h}</li>)}
              </ul>
            </div>
            <div className="tl-right">
              {hasPhoto && V
                ? <div className="tl-visual-bubble"><V active={true} /></div>
                : V ? <V active={true} /> : null
              }
            </div>
          </div>
        );
      })}
    </section>
  );
}

window.Timeline = Timeline;
