"use client";

import gsap from "gsap";
import { useGSAP } from "@gsap/react";
import { SplitText } from "gsap/all";

// Register SplitText only in the browser
if (typeof window !== "undefined") {
  gsap.registerPlugin(SplitText);
}

interface StaggerTitleOptions {
  duration?: number;
  stagger?: number;
  distance?: number;
  ease?: string;
}

/**
 * useStaggerTitleLeft
 *
 * Simple, modern left-to-right word stagger for titles.
 * - Splits the target selector into words
 * - Animates each word from left (x < 0) with a fade-in
 */
const useStaggerTitleLeft = (
  titleClassName: string,
  options?: StaggerTitleOptions
) => {
  useGSAP(() => {
    const titleElement = document.querySelector(titleClassName);

    if (!titleElement) {
      console.warn(
        `useStaggerTitleLeft: Element not found for selector ${titleClassName}`
      );
      return;
    }

    const {
      duration = 0.8,
      stagger = 0.08,
      distance = 40,
      ease = "power2.out",
    } = options || {};

    const split = SplitText.create(titleClassName, {
      type: "words",
    });

    gsap.fromTo(
      split.words,
      { x: -distance, opacity: 0 },
      {
        x: 0,
        opacity: 1,
        duration,
        stagger,
        ease,
        overwrite: "auto",
      }
    );

    return () => {
      split.revert();
    };
  }, [titleClassName, options]);
};

export default useStaggerTitleLeft;

