// variant-polaroid.jsx — Polaroid stack with rotation & parallax neighbors

function usePolaroidSize() {
  const get = () => {
    if (typeof window === 'undefined') return { w: 420, h: 520, isNarrow: false };
    const vw = window.innerWidth;
    const vh = window.innerHeight;
    const isNarrow = vw < 640;
    // Width: scale with viewport, cap at 420. On mobile leave breathing room.
    const w = Math.round(Math.max(220, Math.min(420, vw * (isNarrow ? 0.72 : 0.6))));
    // Aspect ratio 420:520 ≈ 1:1.238. Cap height to keep room for caption on short screens.
    const h = Math.round(Math.min(w * 1.238, vh * (isNarrow ? 0.6 : 0.7)));
    return { w, h, isNarrow };
  };
  const [s, setS] = React.useState(get);
  React.useEffect(() => {
    const onR = () => setS(get());
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);
  return s;
}

function VariantPolaroid({ items }) {
  const wrapRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0); // 0..1 across the timeline section
  const { w: pw, h: ph, isNarrow } = usePolaroidSize();

  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); // continuous index
  const idx = Math.max(0, Math.min(n - 1, Math.round(float)));
  const current = items[idx];

  // Background tint subtly shifts with current photo
  const sectionStyle = {
    background: `linear-gradient(180deg, var(--cream) 0%, ${hexA(current.bg || '#FFF5D6', 0.5)} 50%, var(--cream) 100%)`
  };

  // On narrow screens, anchor polaroid above center and pin caption to the bottom.
  const stackOffsetY = isNarrow ? -ph * 0.32 : 0;

  return (
    <section ref={wrapRef} style={{ height: `${n * 80}vh`, position: 'relative', ...sectionStyle }}>
      <div style={{
        position: 'sticky', top: 0, height: '100vh',
        overflow: 'hidden',
      }}>
        {/* Background big year, faded */}
        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          pointerEvents: 'none',
        }}>
          <div className="h-display" style={{
            fontSize: 'clamp(160px, 38vw, 520px)',
            color: 'var(--ink)',
            opacity: .045,
            letterSpacing: '-.04em',
          }}>{current.year}</div>
        </div>

        {/* Polaroid stack */}
        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transform: `translateY(${stackOffsetY}px)`,
        }}>
          {items.map((it, i) => {
            const d = i - float; // distance from current
            const abs = Math.abs(d);
            if (abs > 2.6) return null;
            const rot = ((i * 53) % 17) - 8; // pseudo-random but stable
            const step = pw + (isNarrow ? 24 : 0);
            const tx = d * step + (i % 2 === 0 ? -6 : 6);
            const ty = Math.abs(d) * (isNarrow ? 14 : 24) + (i % 3 === 0 ? -10 : 10);
            const scale = 1 - Math.min(abs * 0.18, 0.5);
            const op = Math.max(0, 1 - abs * 0.5);
            const z = 100 - Math.round(abs * 10);
            return (
              <div key={i} style={{
                position: 'absolute',
                transform: `translate(${tx}px, ${ty}px) rotate(${rot + d * 4}deg) scale(${scale})`,
                opacity: op,
                zIndex: z,
                transition: 'transform .25s cubic-bezier(.22,1,.36,1), opacity .25s linear',
                filter: abs > 0.6 ? 'blur(2px)' : 'none',
              }}>
                <Polaroid item={it} active={abs < 0.5} w={pw} h={ph} />
              </div>
            );
          })}
        </div>

        {isNarrow ? (
          /* Mobile: stacked caption pinned to bottom, full-width, centered */
          <div style={{
            position: 'absolute', left: 0, right: 0, bottom: 'clamp(72px, 12vh, 120px)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
            padding: '0 20px', zIndex: 200, textAlign: 'center',
            pointerEvents: 'none',
          }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
              <span className="mono" style={{ fontSize: 11, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>
                {String(idx + 1).padStart(2, '0')} / {String(n).padStart(2, '0')}
              </span>
              <span className="h-hand" style={{ fontSize: 32, color: 'var(--coral-deep)', lineHeight: 1 }}>
                {current.age} {czechYears(current.age)}
              </span>
            </div>
            <div className="h-display" style={{ fontSize: 22, lineHeight: 1.1, marginTop: 4 }}>{current.title}</div>
            <div style={{ fontSize: 14, color: 'var(--ink-soft)', maxWidth: '36ch' }}>{current.caption}</div>
          </div>
        ) : (
          <>
            {/* Counter (desktop) */}
            <div style={{
              position: 'absolute', left: 'clamp(20px, 4vw, 60px)', bottom: 'clamp(24px, 4vh, 60px)',
              display: 'flex', flexDirection: 'column', gap: 4, zIndex: 200,
            }}>
              <span className="mono" style={{ fontSize: 12, letterSpacing: '.18em', textTransform: 'uppercase', color: 'var(--ink-soft)' }}>
                {String(idx + 1).padStart(2, '0')} / {String(n).padStart(2, '0')}
              </span>
              <span className="h-hand" style={{ fontSize: 'clamp(48px, 7vw, 88px)', color: 'var(--coral-deep)', lineHeight: 1 }}>
                {current.age} {czechYears(current.age)}
              </span>
            </div>

            <div style={{
              position: 'absolute', right: 'clamp(20px, 4vw, 60px)', bottom: 'clamp(24px, 4vh, 60px)',
              textAlign: 'right', maxWidth: '40ch', zIndex: 200,
            }}>
              <div className="h-display" style={{ fontSize: 'clamp(28px, 3.4vw, 52px)' }}>{current.title}</div>
              <div style={{ marginTop: 6, color: 'var(--ink-soft)' }}>{current.caption}</div>
            </div>
          </>
        )}
      </div>
    </section>
  );
}

function Polaroid({ item, active, w = 420, h = 520 }) {
  // Frame paddings scale gently with size so small mobile polaroids don't look chunky.
  const pad = Math.max(8, Math.round(w * 0.033));
  const bottomPad = Math.max(36, Math.round(w * 0.133));
  return (
    <div style={{
      width: w, height: h,
      background: '#fffdf6',
      padding: `${pad}px ${pad}px ${bottomPad}px`,
      boxShadow: active
        ? '0 30px 60px -20px rgba(42,24,16,.35), 0 8px 18px -8px rgba(42,24,16,.2)'
        : '0 12px 24px -10px rgba(42,24,16,.25)',
      borderRadius: 2,
    }}>
      <div style={{ width: '100%', height: '100%', position: 'relative', containerType: 'inline-size' }}>
        {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 style={{
        position: 'absolute', left: 0, right: 0, bottom: Math.round(bottomPad * 0.21),
        textAlign: 'center',
        fontFamily: 'var(--hand)', fontSize: Math.max(18, Math.round(w * 0.062)), color: 'var(--ink)',
        transform: 'rotate(-1.5deg)',
      }}>
        {item.year}
      </div>
    </div>
  );
}

function czechYears(n) {
  if (n === 1) return 'rok';
  if (n >= 2 && n <= 4) return 'roky';
  return 'let';
}

function hexA(hex, a) {
  const h = hex.replace('#','');
  const r = parseInt(h.substring(0,2),16), g = parseInt(h.substring(2,4),16), b = parseInt(h.substring(4,6),16);
  return `rgba(${r},${g},${b},${a})`;
}

window.VariantPolaroid = VariantPolaroid;
window.Polaroid = Polaroid;
window.hexA = hexA;
window.czechYears = czechYears;
