"use client";

import { useEffect } from "react";

export default function AnimationProvider() {
  useEffect(() => {
    const initAOS = () => {
      import("aos").then(({ default: AOS }) => {
        AOS.init({
          duration: 800,
          once: true,
          easing: "ease-in-out",
        });
      });
    };

    if ("requestIdleCallback" in window) {
      (window as Window).requestIdleCallback(() => initAOS(), { timeout: 2000 });
    } else {
      setTimeout(initAOS, 1000);
    }
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;

    let smoother: import("gsap/ScrollSmoother").ScrollSmoother | undefined;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let ctx: any;
    let removeResizeListener: (() => void) | undefined;

    const initGSAP = async () => {
      // ScrollSmoother requires both wrapper and content nodes to exist.
      // Pages without them (or a teardown mid-navigation) would otherwise log
      // "ScrollSmoother needs a valid content element."
      if (
        !document.querySelector("#smooth-wrapper") ||
        !document.querySelector("#smooth-content")
      ) {
        return;
      }

      const { default: gsap } = await import("gsap");
      const { ScrollTrigger } = await import("gsap/ScrollTrigger");
      const { default: ScrollSmoother } = await import("gsap/ScrollSmoother");

      gsap.registerPlugin(ScrollTrigger, ScrollSmoother);

      ctx = gsap.context(() => {
        ScrollSmoother.get()?.kill();
        smoother = ScrollSmoother.create({
          smooth: 1.2,
          effects: true,
          smoothTouch: false,
          normalizeScroll: false,
          ignoreMobileResize: true,
        });
      });

      const handleResize = () => ScrollTrigger.refresh();
      window.addEventListener("resize", handleResize);
      removeResizeListener = () => {
        window.removeEventListener("resize", handleResize);
        ScrollTrigger.getAll().forEach((st) => st.kill());
      };
    };

    if ("requestIdleCallback" in window) {
      (window as Window).requestIdleCallback(() => initGSAP(), { timeout: 3000 });
    } else {
      setTimeout(initGSAP, 1500);
    }

    return () => {
      if (ctx) ctx.revert();
      if (smoother) smoother.kill();
      removeResizeListener?.();
    };
  }, []);

  return null;
}
