import { gsap } from "@/lib/gsap";

export class SpecsAnimation {
  private readonly mm: gsap.MatchMedia;

  constructor() {
    this.mm = gsap.matchMedia();
    this.setInitialState();
    this.init();
  }

  private setInitialState(): void {
    gsap.set("#specs-car", { x: "100vw" });
  }

  private init(): void {
    this.initMobile();
    this.initDesktop();
  }

  private initMobile(): void {
    this.mm.add("(max-width: 767px)", () => {
      const tl = gsap.timeline({
        scrollTrigger: {
          trigger: "#specs",
          start: "top 70%",
        },
        defaults: { ease: "easeInOut" },
      });

      tl.to("#specs-car", { x: 0, duration: 1.25 }).from(
        ["#specs-car-wheel-left", "#specs-car-wheel-right"],
        {
          rotation: 360,
          duration: 1.25,
          transformOrigin: "center",
        },
        "<",
      );
    });
  }

  private initDesktop(): void {
    this.mm.add("(min-width: 768px)", () => {
      this.setDesktopInitialState();

      const tl = gsap.timeline({
        scrollTrigger: {
          trigger: "#specs",
          start: "-15% top",
        },
        defaults: { ease: "expo.inOut" },
      });

      tl.to("#car-front", {
        scale: 1,
        x: 0,
        y: 0,
        duration: 2,
        rotate: 0.01,
      })
        .to("#car-front-plate", { autoAlpha: 0, duration: 2 }, "<")
        .to(
          "#specs-car",
          {
            x: 0,
            duration: 2.25,
            ease: "easeInOut",
          },
          "-=1.5",
        )
        .from(
          ["#specs-car-wheel-left", "#specs-car-wheel-right"],
          {
            rotation: 1440,
            duration: 2.35,
            transformOrigin: "center",
            ease: "easeInOut",
          },
          "<",
        )
        .to("#specs-content", { autoAlpha: 1 }, "-=.5");
    });
  }

  private setDesktopInitialState(): void {
    gsap.set("#car-front", {
      scale: 22,
      x: "100%",
      y: "-220%",
      rotate: 1,
    });

    gsap.set("#specs-content", { autoAlpha: 0 });
  }

  public destroy(): void {
    this.mm.revert();
  }
}
