// Tobeads — VideoCarousel ("CHOOSE YOUR BUILD")
// A Nintendo-Switch-style rotating product/video showcase. Large center
// cartridge with side cards peeking, left/right controls, pixel pagination.
// Video is a PLACEHOLDER (poster + play button) — drop real <video> sources
// into the `video` field when assets exist; the play button already calls
// onPlay so wiring real playback later is a one-liner.

const { useState: useStateTV, useEffect: useEffectTV, useRef: useRefTV } = React;

// Each card: a "build reel". `accent` drives the cartridge screen color.
const REELS = [
  { id: 'r1', tag: '30-MIN BUILD',     title: '30-Minute Build',     sub: 'Pixel heart, start to finish.',  accent: 'var(--ylw)', seed: 'starter-48', len: '0:34' },
  { id: 'r2', tag: 'PHOTO → MAP',      title: 'Photo to Bead Map',   sub: 'Upload a pic, get a pattern.',    accent: 'var(--cyn)', seed: 'custom-kit', len: '0:48' },
  { id: 'r3', tag: 'PRESET DEMO',      title: 'Preset Kit Demo',     sub: 'Ready-made world, unboxed.',     accent: 'var(--pnk)', seed: 'creator-96', len: '0:41' },
  { id: 'r4', tag: 'CREATOR MODE',     title: 'Creator Mode',        sub: 'Design your own bead level.',     accent: 'var(--v2)',  seed: 'premium-120', len: '1:02' },
  { id: 'r5', tag: 'NEW ARRIVAL',      title: 'New Arrival',         sub: 'Fresh drop from the studio.',     accent: 'var(--cyn)', seed: 'ultimate-221', len: '0:29' },
];

function VideoCarousel({ light = true }) {
  const [idx, setIdx] = useStateTV(0);
  const n = REELS.length;
  const A = () => window.AudioManager;

  function go(dir) {
    setIdx(i => (i + dir + n) % n);
    A() && A().playHover();
  }
  function jump(i) {
    if (i === idx) return;
    setIdx(i);
    A() && A().playHover();
  }
  function play(reel) {
    A() && A().playSelect();
    // Placeholder: no real video yet. Hook real playback here.
    // e.g. open a modal <video src={reel.video} autoPlay/> when assets exist.
  }

  // keyboard when in view
  const ref = useRefTV(null);
  useEffectTV(() => {
    let active = false;
    const io = new IntersectionObserver(([e]) => { active = e.isIntersecting; }, { threshold: 0.45 });
    if (ref.current) io.observe(ref.current);
    function onKey(e) {
      if (!active) return;
      if (e.key === 'ArrowRight') { e.preventDefault(); go(1); }
      else if (e.key === 'ArrowLeft') { e.preventDefault(); go(-1); }
    }
    window.addEventListener('keydown', onKey);
    return () => { window.removeEventListener('keydown', onKey); io.disconnect(); };
  }, []);

  const left = (idx - 1 + n) % n;
  const right = (idx + 1) % n;
  const center = REELS[idx];

  return (
    <section ref={ref} className={`tvtv ${light ? 'sec-light sec-light-grid' : ''}`} style={{ padding: '84px 24px 72px', position: 'relative' }}>
      <div className="wrap" style={{ position: 'relative' }}>
        {/* header */}
        <div style={{ textAlign: 'center', marginBottom: 14 }}>
          <div className="aw-eyebrow" style={{ justifyContent: 'center', color: light ? 'var(--ink2)' : 'var(--gray)' }}>
            <span className="blk" style={{ background: 'var(--pnk)', boxShadow: '0 0 8px var(--pnk)' }}/>TOBEADS TV
          </div>
          <h2 className="px" style={{ fontSize: 'clamp(18px, 3.4vw, 32px)', marginTop: 16, color: light ? 'var(--ink)' : 'var(--wh)' }}>CHOOSE YOUR BUILD</h2>
          <p className="aw-disp" style={{ fontSize: 16, color: light ? 'var(--ink2)' : 'var(--gray)', marginTop: 12 }}>
            Watch a bead kit turn from pixels into a real build.
          </p>
        </div>

        {/* stage */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, justifyContent: 'center', marginTop: 24 }}>
          <button className="car-ctrl aw-hide-mob" onClick={() => go(-1)} aria-label="Previous"><window.Icon.ArrowL size={20}/></button>

          <div className="carousel-stage" style={{ flex: 1, maxWidth: 860 }}>
            {/* left peek */}
            <ReelCard reel={REELS[left]} variant="side" onClick={() => go(-1)} className="aw-hide-mob"/>
            {/* center */}
            <ReelCard reel={center} variant="center" onPlay={() => play(center)}/>
            {/* right peek */}
            <ReelCard reel={REELS[right]} variant="side" onClick={() => go(1)} className="aw-hide-mob"/>
          </div>

          <button className="car-ctrl aw-hide-mob" onClick={() => go(1)} aria-label="Next"><window.Icon.Arrow size={20}/></button>
        </div>

        {/* mobile controls */}
        <div className="aw-only-mob" style={{ display: 'flex', justifyContent: 'center', gap: 16, marginTop: 18 }}>
          <button className="car-ctrl" onClick={() => go(-1)} aria-label="Previous"><window.Icon.ArrowL size={18}/></button>
          <button className="car-ctrl" onClick={() => go(1)} aria-label="Next"><window.Icon.Arrow size={18}/></button>
        </div>

        {/* pagination */}
        <div className="car-dots">
          {REELS.map((r, i) => (
            <button key={r.id} className={`car-dot ${i === idx ? 'on' : ''}`} onClick={() => jump(i)} aria-label={`Go to ${r.title}`}/>
          ))}
        </div>
        <div className="px" style={{ textAlign: 'center', marginTop: 16, fontSize: 8, color: light ? 'var(--ink2)' : 'var(--gray2)' }}>
          ◀ ▶ SWITCH CARTRIDGE · {String(idx + 1).padStart(2,'0')} / {String(n).padStart(2,'0')}
        </div>
      </div>
    </section>
  );
}
window.VideoCarousel = VideoCarousel;

function ReelCard({ reel, variant, onPlay, onClick, className = '' }) {
  const isCenter = variant === 'center';
  return (
    <div
      className={`cart-card ${variant} cart-scan ${className}`}
      onClick={isCenter ? undefined : onClick}
      style={{ '--acc': reel.accent }}
    >
      {/* cartridge "screen": pixel art poster on a dark screen with accent glow */}
      <div className="cart-screen" style={{ background: '#05050F', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(70% 70% at 50% 42%, ${reel.accent}28, transparent 72%)` }}/>
        <div style={{ width: isCenter ? '42%' : '62%', position: 'relative', opacity: 0.95 }}>
          <window.PixelArt seed={reel.seed} size={isCenter ? 12 : 10}/>
        </div>
      </div>

      <span className="cart-tag" style={{ borderColor: reel.accent, color: reel.accent }}>{reel.tag}</span>

      {isCenter && (
        <>
          <button className="play-btn" onClick={(e) => { e.stopPropagation(); onPlay && onPlay(); }} aria-label={`Play ${reel.title}`}>
            <svg width="20" height="22" viewBox="0 0 20 22" shapeRendering="crispEdges">
              <polygon points="2,1 2,21 19,11" fill="currentColor"/>
            </svg>
          </button>
          <div className="cart-foot">
            <div>
              <div className="px" style={{ fontSize: 11, color: 'var(--wh)' }}>{reel.title}</div>
              <div className="aw-disp" style={{ fontSize: 13, color: 'var(--gray)', marginTop: 6 }}>{reel.sub}</div>
            </div>
            <span className="px hh-badge" style={{ fontSize: 8, color: reel.accent, border: `2px solid ${reel.accent}`, padding: '4px 6px' }}>{reel.len}</span>
          </div>
        </>
      )}
    </div>
  );
}
