"use client";

import { useRef, useEffect } from "react";
import gsap from "gsap";

const CELLS: {
  area:   string;
  src:    string;
  pos:    string;
  offset: number;
  kb:     { scale: number; xPercent: number; yPercent: number; duration: number };
}[] = [
  { area: "a", src: "/video-cuts/14502096_1920_1080_25fps.mp4",
    pos: "center 40%", offset: 0,
    kb: { scale: 1.08, xPercent: -3, yPercent: -2, duration: 18 } },

  { area: "b", src: "/video-cuts/4752336-hd_1066_1920_25fps.mp4",
    pos: "center center", offset: 2,
    kb: { scale: 1.06, xPercent:  3, yPercent:  2, duration: 14 } },

  { area: "c", src: "/video-cuts/5538180-uhd_2160_4096_25fps.mp4",
    pos: "center 30%", offset: 5,
    kb: { scale: 1.07, xPercent: -2, yPercent:  3, duration: 20 } },

  { area: "d", src: "/video-cuts/7964843-uhd_2160_3840_30fps-cut.mp4",
    pos: "center 55%", offset: 3,
    kb: { scale: 1.09, xPercent:  2, yPercent: -2, duration: 16 } },
];

export default function VideoSection() {
  const sectionRef = useRef<HTMLElement>(null);
  const cellRefs   = useRef<(HTMLDivElement   | null)[]>([]);
  const videoRefs  = useRef<(HTMLVideoElement | null)[]>([]);

  useEffect(() => {
    const section = sectionRef.current;
    const cells   = cellRefs.current.filter(Boolean)  as HTMLDivElement[];
    const videos  = videoRefs.current.filter(Boolean) as HTMLVideoElement[];
    if (!section) return;

    // ── Video: preloaded, seek on ready, play/pause on visibility ────────
    const playCleanups = videos.map((video, i) => {
      const onCanPlay = () => { video.currentTime = CELLS[i].offset; };
      video.addEventListener("canplay", onCanPlay, { once: true });
      const obs = new IntersectionObserver(
        ([e]) => {
          if (e.isIntersecting) video.play().catch(() => {});
          else                   video.pause();
        },
        { threshold: 0 }
      );
      obs.observe(video);
      return () => { obs.disconnect(); video.removeEventListener("canplay", onCanPlay); };
    });

    // ── Entry: staggered fade-in + ken-burns ─────────────────────────────
    gsap.set(cells, { opacity: 0 });
    const entryObs = new IntersectionObserver(([e]) => {
      if (!e.isIntersecting) return;
      videos.forEach((video, i) => {
        const { scale, xPercent, yPercent, duration } = CELLS[i].kb;
        gsap.fromTo(video,
          { scale: 1, xPercent: 0, yPercent: 0 },
          { scale, xPercent, yPercent, duration, ease: "sine.inOut", repeat: -1, yoyo: true }
        );
      });
      gsap.to(cells, { opacity: 1, duration: 1.2, stagger: 0.15, ease: "power2.out" });
      entryObs.disconnect();
    }, { threshold: 0.1 });
    entryObs.observe(section);

    return () => {
      playCleanups.forEach(fn => fn());
      entryObs.disconnect();
      gsap.killTweensOf(videos);
      gsap.killTweensOf(cells);
    };
  }, []);

  return (
    <section
      ref={sectionRef}
      className="video-grid"
    >
      {CELLS.map((cell, i) => (
        <div
          key={cell.area}
          ref={el => { cellRefs.current[i] = el; }}
          style={{ gridArea: cell.area, overflow: "hidden" }}
        >
          <video
            ref={el => { videoRefs.current[i] = el; }}
            muted
            loop
            playsInline
            preload="metadata"
            style={{
              display:        "block",
              width:          "100%",
              height:         "100%",
              objectFit:      "cover",
              objectPosition: cell.pos,
            }}
          >
            <source src={cell.src} type="video/mp4" />
          </video>
        </div>
      ))}
    </section>
  );
}
