// ============================================================
// Beyond the Falls - BOTTOM: Backstage · Values · Footer
// ============================================================
const { useEffect: useEffectB, useRef: useRefB, useState: useStateB } = React;

// ============================================================
// 7) BACKSTAGE - behind the falls (parallax + vertical reel)
// ============================================================
function Backstage() {
  const ref = useRefB(null);
  const bgRef = useRefB(null);
  const fgRef = useRefB(null);
  const reelRef = useRefB(null);
  const titleRef = useRefB(null);
  const [open, setOpen] = useStateB(false);
  const takes = window.BACKSTAGE_TAKES || [];
  const row = [...takes, ...takes];

  window.useMagicText(titleRef, ref, [255, 255, 255, 0.06], 260);

  useEffectB(() => {
    let mx = 0, my = 0, sp = 0;
    const onScroll = () => {
      if (!ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const vh = window.innerHeight;
      sp = (vh - r.top) / (vh + r.height);
      apply();
    };
    const onMove = (e) => {
      if (!ref.current) return;
      const r = ref.current.getBoundingClientRect();
      mx = (e.clientX - r.left) / r.width - 0.5;
      my = (e.clientY - r.top) / r.height - 0.5;
      apply();
    };
    const apply = () => {
      if (bgRef.current) bgRef.current.style.transform = `translate3d(${(sp-0.5)*-120 + mx*-30}px, ${(sp-0.5)*-30 + my*-20}px, 0)`;
      if (fgRef.current) fgRef.current.style.transform = `translate3d(${(sp-0.5)*220 + mx*40}px, ${(sp-0.5)*60 + my*26}px, 0) rotate(-3deg)`;
      if (reelRef.current) reelRef.current.style.transform = `translate3d(${(sp-0.5)*80 + mx*24}px, ${(sp-0.5)*-40 + my*14}px, 0)`;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    ref.current && ref.current.addEventListener('mousemove', onMove);
    onScroll();
    return () => { window.removeEventListener('scroll', onScroll); ref.current && ref.current.removeEventListener('mousemove', onMove); };
  }, []);

  return (
    <section ref={ref} className="bg-ink text-off relative overflow-hidden" style={{ minHeight: '88vh' }} data-screen-label="07 Backstage">
      <div className="absolute inset-0 grain"/>

      <div className="absolute top-8 inset-x-0 px-8 max-w-7xl mx-auto flex items-center justify-between text-[11px] font-mono tracking-[0.2em] uppercase text-white/55 z-10">
        <span className="inline-flex items-center gap-1.5"><window.BTFEye className="w-[10px] h-[10px] text-acid"/> Backstage</span>
        <span>Backstage reel</span>
      </div>

      <div ref={bgRef} className="absolute inset-0 flex items-center justify-center pointer-events-none will-change-transform">
        <div ref={titleRef} className="display-text text-white/[.06] text-center" style={{ fontSize: 'clamp(56px, 12vw, 220px)', lineHeight: .9, letterSpacing: '-0.04em' }}>
          BACKSTAGE
        </div>
      </div>

      <div ref={fgRef} className="absolute inset-x-0 top-[18%] flex justify-center pointer-events-none will-change-transform z-[15]">
        <div className="text-center">
          <div className="script-text text-acid" style={{ fontSize: 'clamp(36px, 6vw, 88px)', lineHeight: .9 }}>behind the falls</div>
        </div>
      </div>

      {/* One row of large vertical takes — hover pauses marquee for play */}
      <div ref={reelRef} className="absolute inset-x-0 top-[28%] bottom-[22%] z-20 flex items-center will-change-transform">
        <div className="bs-reel-mask relative w-full">
          <div className="marquee marquee-med gap-5 px-4">
            {row.map((t, i) => <TakeCard key={'a'+i} t={t} />)}
          </div>
        </div>
      </div>

      <div className="absolute bottom-8 inset-x-0 px-8 z-30">
        <div className="max-w-7xl mx-auto flex flex-col md:flex-row md:items-end md:justify-between gap-6">
          <div className="max-w-md text-white/70 text-[14px] leading-relaxed reveal">
            The cuts that never made the episode - <em className="text-acid not-italic">failed takes</em>, broken timing, and raw moments from set.
          </div>
          <div className="reveal reveal-delay-2">
            <window.Magnetic as="button" strength={0.4} data-magnet onClick={() => setOpen(true)}
              className="inline-flex items-center gap-2 rounded-full border border-acid/40 text-acid px-5 py-3 text-[13px] font-medium hover:bg-acid hover:text-ink transition pointer-events-auto">
              Watch the takes <window.Glyph.arrow className="w-4 h-4 -rotate-45"/>
            </window.Magnetic>
          </div>
        </div>
      </div>

      {open && (
        <window.Modal onClose={() => setOpen(false)} accent="#C6FF4A" bg="#1A0A0A" fg="#F4F3EE"
          tag="Backstage · Reel" title="Failed takes" script="the cuts we kept" file="BACKSTAGE / REEL">
          <div className="space-y-4 max-w-2xl text-[15px] leading-relaxed" style={{ color: '#F4F3EEcc' }}>
            <p>Behind every polished episode sits a pile of takes that almost worked - wrong line, wrong beat, right energy. This reel collects those vertical outtakes from the set.</p>
            <p>Custom player coming next. For now: the archive of placeholders - same frames, same labels, ready to swap for real footage.</p>
          </div>
          <div className="mt-6 flex flex-wrap gap-2">
            {['Vertical', 'Outtakes', 'Raw from set', 'Custom player soon'].map(t => (
              <window.Pill key={t} fg="#F4F3EE" accent="#C6FF4A">{t}</window.Pill>
            ))}
          </div>
          <div className="mt-8 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-3">
            {takes.map((t) => <TakeCard key={t.id} t={t} staticCard />)}
          </div>
        </window.Modal>
      )}
    </section>
  );
}

function TakeCard({ t, staticCard }) {
  const videoRef = useRefB(null);
  const [playing, setPlaying] = useStateB(false);
  const w = staticCard ? '100%' : 'min(28vw, 260px)';

  const toggle = (e) => {
    e.preventDefault();
    e.stopPropagation();
    const v = videoRef.current;
    if (!v || !t.src) return;
    document.querySelectorAll('video.bs-video').forEach((other) => {
      if (other !== v) { other.pause(); other.currentTime = 0; }
    });
    if (v.paused) {
      v.muted = true; // autoplay policy; loop preview stays in-card
      v.play().then(() => setPlaying(true)).catch(() => setPlaying(false));
    } else {
      v.pause();
      setPlaying(false);
    }
  };

  return (
    <div
      className={`bs-take shrink-0 relative overflow-hidden rounded-2xl border border-acid/25 pointer-events-auto ${staticCard ? '' : 'bs-take--float'} ${playing ? 'is-playing' : ''}`}
      style={{ width: w, aspectRatio: '9 / 16', background: t.tint || '#1A0A0A' }}
    >
      {t.src ? (
        <video
          ref={videoRef}
          className="bs-video absolute inset-0 w-full h-full object-cover"
          src={t.src}
          poster={t.poster}
          loop
          muted
          playsInline
          preload="metadata"
          controls={false}
          disablePictureInPicture
          controlsList="nofullscreen nodownload noplaybackrate noremoteplayback"
          onPlay={() => setPlaying(true)}
          onPause={() => setPlaying(false)}
        />
      ) : (
        <>
          <div className="absolute inset-0 plate-stripes-light opacity-40"/>
          <div className="absolute inset-0" style={{ background: `linear-gradient(180deg, rgba(198,255,74,.08) 0%, transparent 35%, rgba(0,0,0,.55) 100%)` }}/>
        </>
      )}
      <div className="absolute inset-0 pointer-events-none" style={{ background: playing ? 'transparent' : 'linear-gradient(180deg, rgba(0,0,0,.15) 0%, transparent 40%, rgba(0,0,0,.45) 100%)' }}/>
      <div className="absolute top-3 inset-x-3 flex items-center justify-between z-10 pointer-events-none">
        <span className="text-[9px] font-mono tracking-[0.18em] uppercase text-white/80">{t.label}</span>
        <span className="rounded-full border border-acid/40 px-2 py-0.5 text-[8px] font-mono tracking-[0.14em] uppercase text-acid bg-ink/40">{t.tag}</span>
      </div>
      <button
        type="button"
        onClick={toggle}
        aria-label={playing ? 'Pause take' : 'Play take'}
        className={`bs-play absolute z-20 w-12 h-12 rounded-full border border-acid/55 bg-ink/55 flex items-center justify-center text-acid backdrop-blur-sm
          ${playing ? 'opacity-0 hover:opacity-100' : 'opacity-100'}`}
      >
        {playing ? (
          <svg viewBox="0 0 24 24" className="w-4 h-4" fill="currentColor"><path d="M7 5h3v14H7zm7 0h3v14h-3z"/></svg>
        ) : (
          <svg viewBox="0 0 24 24" className="w-4 h-4 ml-0.5" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
        )}
      </button>
      <div className="absolute bottom-3 inset-x-3 z-10 text-[9px] font-mono tracking-[0.16em] uppercase text-white/50 pointer-events-none">
        loop · in frame
      </div>
    </div>
  );
}

// ============================================================
// 8) VALUES MARQUEE (replaces reviews)
// ============================================================
function Values() {
  const row = [...window.VALUES, ...window.VALUES];
  return (
    <section className="bg-off text-ink py-32 overflow-hidden" data-screen-label="08 Values">
      <div className="max-w-7xl mx-auto px-8 grid md:grid-cols-[1fr_1.4fr] gap-12 items-center">
        <div className="reveal">
          <div className="font-mono text-[11px] tracking-[0.2em] uppercase text-ink/60 flex items-center gap-1.5"><window.BTFEye className="w-[10px] h-[10px] text-noble"/> Meaning</div>
          <h2 className="mt-4 font-display font-bold tracking-tight" style={{ fontSize: 'clamp(56px, 9vw, 150px)', lineHeight: .9, letterSpacing: '-0.04em' }}>
            MEANING
          </h2>
          <div className="-mt-4 md:-mt-7 script-text text-leaf" style={{ fontSize: 'clamp(36px, 5vw, 80px)', transform:'rotate(-3deg)', display:'inline-block' }}>
            what it leaves behind
          </div>
          <p className="mt-6 max-w-sm text-[14px] text-ink/65 leading-relaxed">
            Balance is the only form of harmony that infringes on no one. These are the ideas the series leaves with a child - and the ones it quietly asks of the adults watching beside them.
          </p>
        </div>

        <div className="relative mask-x-fade space-y-4">
          <div className="marquee marquee-med gap-4">
            {row.map((r, i) => <ValueCard key={'a'+i} r={r}/>)}
          </div>
          <div className="marquee marquee-slow gap-4" style={{ animationDirection: 'reverse' }}>
            {row.map((r, i) => <ValueCard key={'b'+i} r={r}/>)}
          </div>
        </div>
      </div>
    </section>
  );
}

function ValueCard({ r }) {
  const kid = r.who === 'For children';
  return (
    <div className="shrink-0 w-[330px] rounded-2xl border border-ink/10 bg-white p-5 hover:-translate-y-1 hover:shadow-[0_24px_50px_-30px_rgba(6,32,22,.5)] transition">
      <div className="flex items-center gap-2 mb-3">
        <span className="w-7 h-7 rounded-full flex items-center justify-center" style={{ background: kid ? '#7CFFCB' : '#062016' }}>
          {kid ? <window.Glyph.spark className="w-3.5 h-3.5 text-noble"/> : <window.Glyph.drop className="w-3.5 h-3.5 text-biolum"/>}
        </span>
        <span className="text-[10px] font-mono tracking-[0.18em] uppercase text-ink/55">{r.who}</span>
      </div>
      <div className="text-[16px] leading-snug font-display font-medium" style={{ letterSpacing: '-0.01em' }}>{r.t}</div>
    </div>
  );
}

// ============================================================
// 9) FOOTER / CONTACTS
// ============================================================
function Footer() {
  const items = Array.from({ length: 6 }).map((_, i) => (
    <span key={i} className="inline-flex items-center pr-10 align-middle">
      <window.BTFLogo className="text-white w-auto" style={{ height: 'clamp(56px, 9vw, 150px)' }}/>
      <span className="script-text text-biolum mx-10" style={{ fontSize: 'clamp(40px,7vw,110px)', transform:'translateY(-.05em) rotate(-4deg)', display:'inline-block' }}>-</span>
    </span>
  ));
  return (
    <footer id="contact" className="text-white relative overflow-hidden" style={{ background: '#062016' }} data-screen-label="09 Footer">
      <div className="grain absolute inset-0"/>
      <div className="relative max-w-7xl mx-auto px-8 pt-16 grid md:grid-cols-[1.3fr_1fr] gap-10 items-start">
        <div>
          <div className="font-mono text-[11px] tracking-[0.2em] uppercase text-white/55 flex items-center gap-1.5"><window.BTFEye className="w-[10px] h-[10px] text-biolum"/> Contact</div>
          <div className="mt-4 font-display font-medium" style={{ fontSize: 'clamp(28px,3.4vw,44px)', letterSpacing:'-0.02em', lineHeight: 1.05 }}>
            Hear the inner voice. <span className="script-text text-biolum" style={{ fontSize:'1.4em', lineHeight:.5 }}>begin.</span>
          </div>
          <p className="mt-4 max-w-md text-[14px] text-white/65 leading-relaxed">
            For the full treatment, pitch deck, or partnership talks, reach the studio below.
          </p>
          <div className="mt-6 flex flex-wrap gap-2">
            {['hello@beyondthefalls.studio','Treatment','Pitch deck','Partnership'].map(l => (
              <window.Magnetic key={l} as="a" href="#" strength={0.3} data-magnet className="pill" style={{ background:'rgba(255,255,255,.06)', color:'#fff', border:'1px solid rgba(255,255,255,.16)' }}>
                <window.Glyph.dot className="w-1.5 h-1.5 text-biolum"/> {l}
              </window.Magnetic>
            ))}
          </div>
        </div>
        <div className="md:justify-self-end w-full md:max-w-xs grid grid-cols-2 gap-3">
          {[['Studio','Wizard Element'],['Platform','Narrative OS'],['Series','Fantasy AI'],['For','Young teens']].map(([k,v]) => (
            <div key={k} className="rounded-2xl p-4 border border-white/12 bg-white/[.04]">
              <div className="text-[10px] font-mono tracking-[0.18em] uppercase text-white/45">{k}</div>
              <div className="mt-1 font-display font-medium text-[15px]">{v}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="relative mt-16 mb-12">
        <div className="marquee marquee-slow whitespace-nowrap">{items}{items}</div>
      </div>

      <div className="relative max-w-7xl mx-auto px-8 pb-10">
        <div className="hairline-dark mb-8"/>
        <div className="flex flex-wrap items-center justify-between gap-6 text-[12px] text-white/55 font-mono tracking-[0.15em] uppercase">
          <div className="flex items-center gap-6">
            <span>© Beyond Studio · 26</span>
            <span>Balance · Not power</span>
          </div>
          <div className="flex items-center gap-2">
            {['Ig','Tt','Yt','Vm'].map(s => (
              <window.Magnetic key={s} as="a" href="#" strength={0.5} data-magnet className="w-9 h-9 rounded-full border border-white/15 flex items-center justify-center text-white/80 hover:bg-white/10 transition text-[10px] font-mono">
                {s}
              </window.Magnetic>
            ))}
          </div>
          <div className="flex items-center gap-6">
            <a href="#" className="hover:text-white">Imprint</a>
            <a href="#" className="hover:text-white">Privacy</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Backstage, Values, Footer });
