"use client";
import { useEffect, useRef } from "react";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";

import Title from "@/components/atoms/Title";

gsap.registerPlugin(ScrollTrigger);

const VideoShowcase = () => {
  const boxRef = useRef<HTMLDivElement>(null);
  const sectionRef = useRef<HTMLElement>(null);

  useEffect(() => {
    if (!sectionRef.current || !boxRef.current) return;

    // Wait for other ScrollTriggers (like pinned hero) to be set up first
    const timeoutId = setTimeout(() => {
      ScrollTrigger.refresh();

      const animation = gsap.fromTo(
        boxRef.current,
        { yPercent: 50, scale: 0.8 },
        {
          yPercent: 10,
          scale: 1,
          ease: "sine",
          scrollTrigger: {
            trigger: sectionRef.current,
            start: "10% bottom",
            end: "70% bottom",
            scrub: 1.5,
            // markers: true,
          },
        }
      );

      return () => {
        animation.scrollTrigger?.kill();
        animation.kill();
      };
    }, 500);

    return () => {
      clearTimeout(timeoutId);
    };
  }, []);

  return (
    <section
      ref={sectionRef}
      className="video-showcase-section py-8 md:py-12 lg:py-16 xl:py-20 2xl:py-24"
    >
      <div className="container mx-auto lg:px-6">
        <Title
          text="Video Showcase"
          className="text-center lg:text-left mb-10 md:mb-16"
        />
      </div>

      <div className="w-full min-h-[40dvh] md:min-h-[50dvh] scale-95 lg:scale-100 lg:min-h-dvh relative">
        <div
          ref={boxRef}
          className="w-full absolute flex items-center justify-center will-change-transform"
        >
          <video
            src="/videos/video-showcase/showcase.mp4"
            className="object-cover lg:h-[80dvh] aspect-video rounded-sm"
            autoPlay
            playsInline
            loop
            muted
            preload="auto"
          />
        </div>
      </div>
    </section>
  );
};

export default VideoShowcase;
