/* 6ix Mela — reel band. Desktop: 3 vertical players; exactly one is "focused"
   (enlarged + outlined). Clicking a video focuses it and turns its sound on;
   the previously focused one shrinks and mutes. The sound pill on the focused
   video toggles that video's audio off/on (it stays focused/enlarged).
   Below 1000px only the center video renders (full-width on mobile). */
const REELS = {
  left:   { src: 'assets/reel/left.mp4' },
  center: { src: 'assets/hype-reel.mp4' },
  right:  { src: 'assets/reel/right.mp4' },
};

function VideoBand() {
  const secRef = React.useRef(null);
  const vids = React.useRef({});
  const [active, setActive] = React.useState('center'); // focused / enlarged video
  const [soundOn, setSoundOn] = React.useState(true);    // is the focused video's audio on
  const [isDesktop, setIsDesktop] = React.useState(false);
  const activeRef = React.useRef('center');
  const soundRef = React.useRef(true);
  React.useEffect(() => { activeRef.current = active; }, [active]);
  React.useEffect(() => { soundRef.current = soundOn; }, [soundOn]);

  const setRef = (side) => (el) => { if (el) { vids.current[side] = el; } else { delete vids.current[side]; } };

  // render side videos only on desktop
  React.useEffect(() => {
    const mq = window.matchMedia('(min-width: 1000px)');
    const on = () => setIsDesktop(mq.matches);
    on();
    if (mq.addEventListener) mq.addEventListener('change', on); else mq.addListener(on);
    return () => { if (mq.removeEventListener) mq.removeEventListener('change', on); else mq.removeListener(on); };
  }, []);

  // only the focused video plays sound, and only when soundOn; keep them all playing
  React.useEffect(() => {
    Object.keys(vids.current).forEach((side) => {
      const v = vids.current[side];
      if (!v) return;
      v.muted = !(side === active && soundOn);
      const p = v.play(); if (p && p.catch) p.catch(() => {});
    });
  }, [active, soundOn, isDesktop]);

  // browsers block sound-on autoplay; start the focused video's audio on first interaction
  React.useEffect(() => {
    const kick = () => {
      const v = vids.current[activeRef.current];
      if (v && soundRef.current) { v.muted = false; const p = v.play(); if (p && p.catch) p.catch(() => {}); }
      done();
    };
    const done = () => ['pointerdown','touchstart','keydown'].forEach((e) => window.removeEventListener(e, kick));
    ['pointerdown','touchstart','keydown'].forEach((e) => window.addEventListener(e, kick));
    return done;
  }, []);

  // play in view, pause out of view
  React.useEffect(() => {
    const sec = secRef.current;
    if (!sec) return;
    const io = new IntersectionObserver(([en]) => {
      Object.values(vids.current).forEach((v) => {
        if (!v) return;
        if (en.isIntersecting) { const p = v.play(); if (p && p.catch) p.catch(() => {}); }
        else v.pause();
      });
    }, { threshold: 0.25 });
    io.observe(sec);
    return () => io.disconnect();
  }, [isDesktop]);

  const focusVideo = (side) => { setActive(side); setSoundOn(true); };
  const onPill = (side, e) => {
    e.stopPropagation();
    if (side === active) setSoundOn((s) => !s);   // toggle audio on the focused video
    else focusVideo(side);                         // focusing a side video turns its sound on
  };

  const player = (side) => {
    const isFocus = active === side;
    const audioOn = isFocus && soundOn;
    return (
      <div className={'reel-item' + (isFocus ? ' focus' : '')} key={side}
        onClick={() => focusVideo(side)} role="button" tabIndex={0}
        onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); focusVideo(side); } }}
        aria-label={isFocus ? 'Focused video' : 'Play this video with sound'}>
        <video ref={setRef(side)} className="reel-video" loop playsInline preload="metadata" muted>
          <source src={REELS[side].src} type="video/mp4" />
        </video>
        <button type="button" className={'v-sound reel-sound' + (audioOn ? ' active' : '')}
          onClick={(e) => onPill(side, e)}
          aria-label={audioOn ? 'Turn sound off' : 'Turn sound on'}>
          <Icon name={audioOn ? 'mic' : 'music'} size={18} />
          <span>{audioOn ? 'Sound on' : 'Sound off'}</span>
        </button>
      </div>
    );
  };

  return (
    <section className="videoband reel3" id="film" ref={secRef}>
      <div className="reel-row">
        {isDesktop && player('left')}
        {player('center')}
        {isDesktop && player('right')}
      </div>
    </section>);
}
window.VideoBand = VideoBand;
