// Prodz — Set Moments as 24h Stories. The Home rail shows only people you
// follow; tapping one opens this full-screen viewer and you move horizontally
// through their frames (and on into the next person). Tap right / left to
// advance, or swipe. Each frame links back to its bound production.

function StoryViewer({ start = 0 }) {
  const { L } = useL();
  const nav = useNav();
  const { Avatar } = window.ProdzDesignSystem_d0b87b;

  // flatten every followed person's frames into one horizontal reel
  const flat = [];
  STORIES.forEach((s, si) => s.frames.forEach((f, fi) => flat.push({ ...f, person: s.person, time: s.time, si, fi, count: s.frames.length })));
  const startFrame = Math.max(0, flat.findIndex((f) => f.si === start && f.fi === 0));

  const ref = useRefS(null);
  const [active, setActive] = useStateS(startFrame);

  useEffectS(() => { const el = ref.current; if (el) el.scrollLeft = startFrame * el.clientWidth; }, []);

  const onScroll = () => {
    const el = ref.current; if (!el) return;
    const i = Math.round(el.scrollLeft / el.clientWidth);
    if (i !== active) setActive(i);
  };
  const go = (dir) => {
    const el = ref.current; if (!el) return;
    const i = Math.min(flat.length - 1, Math.max(0, active + dir));
    el.scrollTo({ left: i * el.clientWidth, behavior: 'smooth' });
  };

  const cur = flat[active] || flat[0];
  const person = PEOPLE[cur.person];
  const prod = PRODUCTIONS.find((p) => p.id === cur.prod);

  return (
    <div style={{ position: 'relative', height: '100%', background: '#000', overflow: 'hidden' }}>
      {/* horizontal reel */}
      <div ref={ref} onScroll={onScroll} style={{ position: 'absolute', inset: 0, display: 'flex', overflowX: 'auto', overflowY: 'hidden', scrollSnapType: 'x mandatory', WebkitOverflowScrolling: 'touch', scrollbarWidth: 'none' }}>
        {flat.map((f, i) => (
          <div key={i} style={{ position: 'relative', width: '100%', height: '100%', flexShrink: 0, scrollSnapAlign: 'start' }}>
            <div style={{ position: 'absolute', inset: 0, background: `#111 url(${f.image}) center/cover` }} />
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(0,0,0,0.55) 0%, rgba(0,0,0,0) 22%, rgba(0,0,0,0) 60%, rgba(0,0,0,0.78) 100%)' }} />
          </div>
        ))}
      </div>

      {/* tap zones */}
      <button aria-label="Prev" onClick={() => go(-1)} style={{ position: 'absolute', left: 0, top: 64, bottom: 0, width: '32%', background: 'none', border: 'none', cursor: 'pointer', zIndex: 5 }} />
      <button aria-label="Next" onClick={() => go(1)} style={{ position: 'absolute', right: 0, top: 64, bottom: 0, width: '50%', background: 'none', border: 'none', cursor: 'pointer', zIndex: 5 }} />

      {/* progress segments for the active person */}
      <div style={{ position: 'absolute', top: 12, left: 12, right: 12, zIndex: 10, display: 'flex', gap: 4 }}>
        {Array.from({ length: cur.count }).map((_, k) => (
          <span key={k} style={{ flex: 1, height: 3, borderRadius: 2, background: 'rgba(255,255,255,0.3)', overflow: 'hidden' }}>
            <span style={{ display: 'block', height: '100%', borderRadius: 2, background: '#fff', width: k < cur.fi ? '100%' : k === cur.fi ? '100%' : '0%' }} />
          </span>
        ))}
      </div>

      {/* header: who + when + close */}
      <div style={{ position: 'absolute', top: 26, left: 12, right: 12, zIndex: 10, display: 'flex', alignItems: 'center', gap: 10 }}>
        <button onClick={() => nav.openProfile(cur.person)} style={{ display: 'flex', alignItems: 'center', gap: 10, background: 'none', border: 'none', cursor: 'pointer', padding: 0, flex: 1, textAlign: 'left' }}>
          <Avatar src={person.avatar} alt={person.name} size={36} ring="gold" />
          <span style={{ minWidth: 0 }}>
            <span style={{ display: 'block', fontSize: 13.5, fontWeight: 700, color: '#fff' }}>{person.name}</span>
            <span style={{ display: 'block', fontSize: 11, color: 'rgba(255,255,255,0.75)' }}>{tr(L, cur.time)}</span>
          </span>
        </button>
        <button onClick={nav.pop} aria-label="Close" style={{ width: 36, height: 36, borderRadius: '50%', border: 'none', cursor: 'pointer', background: 'rgba(255,255,255,0.14)', backdropFilter: 'blur(8px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Ic n="X" s={20} color="#fff" />
        </button>
      </div>

      {/* caption + production link */}
      <div style={{ position: 'absolute', left: 16, right: 16, bottom: 'calc(28px + env(safe-area-inset-bottom))', zIndex: 10 }}>
        {cur.caption && <div style={{ fontSize: 16, fontWeight: 600, color: '#fff', lineHeight: 1.35, marginBottom: 12, textShadow: '0 2px 12px rgba(0,0,0,0.6)' }}>{tr(L, cur.caption)}</div>}
        {prod && (
          <button onClick={() => nav.openProduction(prod.id)} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 13px', borderRadius: 'var(--radius-pill)', border: 'none', cursor: 'pointer', background: 'rgba(255,255,255,0.16)', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)', color: '#fff', fontSize: 12.5, fontWeight: 600 }}>
            <Ic n="Clapperboard" s={14} color="var(--prodz-teal)" />{prod.title}
            <Ic n="ChevronRight" s={14} color="rgba(255,255,255,0.7)" />
          </button>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { StoryViewer });
