// variant-filmstrip.jsx — Horizontal filmstrip pinned to scroll

function useFrameWidth() {
  const get = () => {
    if (typeof window === 'undefined') return 480;
    const vw = window.innerWidth;
    return Math.round(Math.max(220, Math.min(480, vw * (vw < 640 ? 0.78 : 0.55))));
  };
  const [w, setW] = React.useState(get);
  React.useEffect(() => {
    const onR = () => setW(get());
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);
  return w;
}

function VariantFilmstrip({ items }) {
  const wrapRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0);
  const FRAME_W = useFrameWidth();
  const isNarrow = typeof window !== 'undefined' && window.innerWidth < 640;

  React.useEffect(() => {
    const onScroll = () => {
      const el = wrapRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight;
      const total = el.offsetHeight - vh;
      const scrolled = Math.min(Math.max(-rect.top, 0), total);
      setProgress(total > 0 ? scrolled / total : 0);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  const n = items.length;
  const float = progress * (n - 1);
  const idx = Math.max(0, Math.min(n - 1, Math.round(float)));
  const current = items[idx];

  // Filmstrip translate: each frame is FRAME_W wide; center the float-th frame
  const GAP = 14;
  const step = FRAME_W + GAP;
  const tx = -float * step;

  return (
    <section ref={wrapRef} style={{ height: `${n * 80}vh`, position: 'relative', background: 'var(--ink)' }}>
      <div style={{
        position: 'sticky', top: 0, height: '100vh',
        overflow: 'hidden', color: 'var(--cream)',
        background: 'radial-gradient(1200px 600px at 50% 60%, #3a2418 0%, var(--ink) 60%, #1c0f08 100%)',
      }}>
        {/* Year counter (ticking, top) */}
        <div style={{
          position: 'absolute', top: 'clamp(28px, 5vh, 64px)', left: 0, right: 0,
          display: 'flex', justifyContent: 'center', pointerEvents: 'none', zIndex: 4,
        }}>
          <TickingYear value={current.year} compact={isNarrow} />
        </div>

        {/* Filmstrip */}
        <div style={{
          position: 'absolute', top: '50%', left: '50%',
          transform: `translate(calc(-50% + ${tx}px), -50%)`,
          display: 'flex', gap: GAP, alignItems: 'center',
          willChange: 'transform',
        }}>
          {items.map((it, i) => (
            <FilmFrame key={i} item={it} active={i === idx} width={FRAME_W} />
          ))}
        </div>

        {/* Sprocket bars top/bottom of strip area */}
        <div style={{
          position: 'absolute', top: '50%', left: 0, right: 0,
          transform: 'translateY(-50%)', pointerEvents: 'none', zIndex: 1,
        }}>
          <SprocketBar offset="top" />
          <SprocketBar offset="bottom" />
        </div>

        {/* Caption bottom */}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 'clamp(28px, 6vh, 80px)',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
          color: 'var(--cream)', zIndex: 4, textAlign: 'center', padding: '0 24px',
        }}>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '.24em', textTransform: 'uppercase', color: 'rgba(255,251,235,.5)' }}>
            Frame {String(idx + 1).padStart(2,'0')} · {current.age} {czechYears(current.age)}
          </div>
          <div className="h-display" style={{ fontSize: 'clamp(24px, 3vw, 40px)' }}>{current.title}</div>
          <div style={{ color: 'rgba(255,251,235,.7)', maxWidth: '40ch' }}>{current.caption}</div>
        </div>

        {/* Scroll hint corner — hidden on narrow screens to avoid colliding with year counter */}
        {!isNarrow && (
          <div className="h-hand" style={{
            position: 'absolute', top: 'clamp(24px, 5vh, 60px)', right: 'clamp(24px, 5vw, 80px)',
            fontSize: 28, color: 'var(--orange)', zIndex: 4,
          }}>
            ↓ scroll = roll
          </div>
        )}
      </div>
    </section>
  );
}

function FilmFrame({ item, active, width }) {
  return (
    <div style={{
      width, flex: '0 0 auto',
      transform: active ? 'scale(1.04)' : 'scale(.92)',
      opacity: active ? 1 : .55,
      transition: 'transform .35s cubic-bezier(.22,1,.36,1), opacity .35s linear',
    }}>
      <div style={{
        background: '#0d0a08',
        padding: '34px 10px',
        borderRadius: 4,
        position: 'relative',
      }}>
        <div style={{ aspectRatio: '4/5', containerType: 'inline-size', position: 'relative' }}>
          {item.real ? (
            <div className="ph" data-real>
              <img src={item.real} alt={String(item.year)} />
            </div>
          ) : (
            <div className="ph" style={{ '--bg': item.bg, '--fg': item.fg }}>
              {item.placeholderText ? (
                <span className="ph-year" style={{
                  fontSize: 'clamp(22px, 7cqw, 64px)', lineHeight: 1.1,
                  padding: '0 8cqw', textAlign: 'center',
                  fontFamily: 'var(--hand)', fontWeight: 700,
                }}>{item.placeholderText}</span>
              ) : (
                <span className="ph-year">{item.year}</span>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function SprocketBar({ offset }) {
  const bars = Array.from({ length: 40 });
  const top = offset === 'top' ? 'calc(-50% - 8px)' : 'calc(50% - 8px)';
  // simpler: position relative to strip parent
  return (
    <div style={{
      position: 'absolute', left: '-20%', right: '-20%',
      [offset === 'top' ? 'top' : 'bottom']: 'calc(50% + 220px)',
      height: 18,
      display: 'flex', gap: 14, padding: '0 8px',
      transform: offset === 'top' ? 'translateY(-260px)' : 'translateY(260px)',
    }}>
      {bars.map((_, i) => (
        <div key={i} style={{
          width: 22, height: 14, borderRadius: 2,
          background: 'var(--cream)',
          opacity: .9,
        }} />
      ))}
    </div>
  );
}

function TickingYear({ value, compact }) {
  // Slot machine style: render the 4 digits, each in a clipping window with the digit shown.
  const digits = String(value).padStart(4, '0').split('');
  return (
    <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
      {digits.map((d, i) => <Digit key={i} digit={d} compact={compact} />)}
    </div>
  );
}

function Digit({ digit, compact }) {
  const H = compact ? 60 : 96;
  const W = compact ? 40 : 64;
  const fs = compact ? 52 : 84;
  const n = parseInt(digit, 10);
  return (
    <div style={{
      width: W, height: H, overflow: 'hidden', position: 'relative',
      background: 'rgba(255,251,235,.04)',
      borderRadius: 6,
      border: '1px solid rgba(255,251,235,.08)',
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0,
        transform: `translateY(${-n * H}px)`,
        transition: 'transform .5s cubic-bezier(.22,1,.36,1)',
      }}>
        {Array.from({ length: 10 }).map((_, i) => (
          <div key={i} className="h-display" style={{
            height: H, lineHeight: `${H}px`,
            textAlign: 'center',
            fontSize: fs, color: 'var(--yellow)',
            fontWeight: 800,
          }}>{i}</div>
        ))}
      </div>
    </div>
  );
}

window.VariantFilmstrip = VariantFilmstrip;
