"use client";

import { useEffect, useRef, useSyncExternalStore } from "react";
import lottie, { AnimationItem } from "lottie-web";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";

const emptySubscribe = () => () => {};
function useIsClient() {
  return useSyncExternalStore(
    emptySubscribe,
    () => true,
    () => false
  );
}

export default function LottieBasketballScene() {
  const containerRef = useRef<HTMLDivElement>(null);
  const animRef = useRef<AnimationItem | null>(null);
  const mounted = useIsClient();

  useEffect(() => {
    if (!mounted || typeof window === "undefined" || !containerRef.current) return;

    gsap.registerPlugin(ScrollTrigger);

    const anim = lottie.loadAnimation({
      container: containerRef.current,
      renderer: "svg",
      loop: false,
      autoplay: false,
      path: "/models/basketball-scroll.json",
    });

    animRef.current = anim;

    const setupScrollScrubbing = () => {
      if (!anim.totalFrames) return;
      const totalFrames = anim.totalFrames;

      ScrollTrigger.create({
        trigger: document.body,
        start: "top top",
        end: "bottom bottom",
        scrub: 1,
        onUpdate: (self) => {
          const targetFrame = self.progress * (totalFrames - 1);
          anim.goToAndStop(targetFrame, true);
        },
      });
    };

    anim.addEventListener("DOMLoaded", setupScrollScrubbing);
    anim.addEventListener("data_ready", setupScrollScrubbing);

    return () => {
      anim.removeEventListener("DOMLoaded", setupScrollScrubbing);
      anim.removeEventListener("data_ready", setupScrollScrubbing);
      anim.destroy();
      ScrollTrigger.getAll().forEach((st) => st.kill());
    };
  }, [mounted]);

  if (!mounted) return null;

  return (
    <div
      id="lottie-fullpage-overlay"
      className="fixed inset-0 z-0 pointer-events-none w-full h-full opacity-35 filter blur-[0.5px] scale-95 md:scale-100 transition-opacity duration-700 transform-gpu will-change-transform flex items-center justify-center overflow-hidden"
    >
      <div
        ref={containerRef}
        className="w-full h-full max-w-[1400px] max-h-[100vh] flex items-center justify-center"
      />
    </div>
  );
}

// Optimized Ambient Lottie Card Media Component (0.45x Speed + Auto-Pause when 60% out of view)
export function LottieCardMedia({
  speed = 0.45,
  startFrame = 0,
  endFrame,
}: {
  speed?: number;
  startFrame?: number;
  endFrame?: number;
}) {
  const containerRef = useRef<HTMLDivElement>(null);
  const animRef = useRef<AnimationItem | null>(null);
  const mounted = useIsClient();

  useEffect(() => {
    if (!mounted || typeof window === "undefined" || !containerRef.current) return;

    const anim = lottie.loadAnimation({
      container: containerRef.current,
      renderer: "svg",
      loop: true,
      autoplay: true,
      path: "/models/basketball-scroll.json",
    });

    animRef.current = anim;

    anim.addEventListener("DOMLoaded", () => {
      anim.setSpeed(speed);
      if (startFrame >= 0 && endFrame && endFrame > startFrame) {
        anim.playSegments([startFrame, endFrame], true);
      } else if (startFrame > 0) {
        anim.goToAndPlay(startFrame, true);
      }

      if (containerRef.current) {
        const svg = containerRef.current.querySelector("svg");
        if (svg) {
          svg.style.mixBlendMode = "multiply";
          svg.style.background = "transparent";
        }
      }
    });

    // IntersectionObserver: Auto-pause when 60% or more out of view (<40% in view)
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (animRef.current) {
          if (entry.intersectionRatio >= 0.4) {
            animRef.current.play();
          } else {
            animRef.current.pause();
          }
        }
      },
      { threshold: [0, 0.4, 1.0] }
    );

    if (containerRef.current) {
      observer.observe(containerRef.current);
    }

    return () => {
      observer.disconnect();
      anim.destroy();
    };
  }, [mounted, speed, startFrame, endFrame]);

  if (!mounted) return null;

  return (
    <div
      ref={containerRef}
      className="w-full h-auto h-[380px] bg-transparent border-0 shadow-none flex items-center justify-center pointer-events-none overflow-visible scale-110 opacity-85 transition-opacity duration-700 transform-gpu will-change-transform"
      style={{ mixBlendMode: "multiply", background: "transparent" }}
    />
  );
}

// Reusable Ambient Sign Up Card Media Component (0.45x Speed + Auto-Pause when 60% out of view)
export function SignUpCardMedia({
  speed = 0.45,
  startFrame = 0,
  endFrame,
}: {
  speed?: number;
  startFrame?: number;
  endFrame?: number;
}) {
  const containerRef = useRef<HTMLDivElement>(null);
  const animRef = useRef<AnimationItem | null>(null);
  const mounted = useIsClient();

  useEffect(() => {
    if (!mounted || typeof window === "undefined" || !containerRef.current) return;

    const anim = lottie.loadAnimation({
      container: containerRef.current,
      renderer: "svg",
      loop: true,
      autoplay: true,
      path: "/models/signup-scroll.json",
    });

    animRef.current = anim;

    anim.addEventListener("DOMLoaded", () => {
      anim.setSpeed(speed);
      if (startFrame >= 0 && endFrame && endFrame > startFrame) {
        anim.playSegments([startFrame, endFrame], true);
      } else if (startFrame > 0) {
        anim.goToAndPlay(startFrame, true);
      }

      if (containerRef.current) {
        const svg = containerRef.current.querySelector("svg");
        if (svg) {
          svg.style.mixBlendMode = "multiply";
          svg.style.background = "transparent";
        }
      }
    });

    // IntersectionObserver: Auto-pause when 60% or more out of view (<40% in view)
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (animRef.current) {
          if (entry.intersectionRatio >= 0.4) {
            animRef.current.play();
          } else {
            animRef.current.pause();
          }
        }
      },
      { threshold: [0, 0.4, 1.0] }
    );

    if (containerRef.current) {
      observer.observe(containerRef.current);
    }

    return () => {
      observer.disconnect();
      anim.destroy();
    };
  }, [mounted, speed, startFrame, endFrame]);

  if (!mounted) return null;

  return (
    <div
      ref={containerRef}
      className="w-full h-auto h-[380px] bg-transparent border-0 shadow-none flex items-center justify-center pointer-events-none overflow-visible scale-110 opacity-85 transition-opacity duration-700 transform-gpu will-change-transform"
      style={{ mixBlendMode: "multiply", background: "transparent" }}
    />
  );
}
