import React from "react";
import { useEffect, useRef } from "react";
import gsap from "gsap";
import ScrollTrigger from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);
import { HighlightOptions } from "../types";

// Cambia la firma a:
export const useHighlight = (highlightOptions: HighlightOptions = {}) => {
  const elementRef = useRef<HTMLSpanElement | null>(null);
  const { textColor, highlightColor, start, end } = highlightOptions;

  useEffect(() => {
    const element = elementRef.current;
    if (!element) return;

    const defaultTextColor = "#FFFFFF";
    const defaultHighlightColor = "#6D00C7";
    const defaultStart = "bottom 98%";
    const defaultEnd = "bottom 65%";

    const finalTextColor = textColor || defaultTextColor;
    const finalHighlightColor = highlightColor || defaultHighlightColor;
    const finalStart = start || defaultStart;
    const finalEnd = end || defaultEnd;

    if (!element.classList.contains("react-scroll-text-highlight")) {
      element.classList.add("react-scroll-text-highlight");
    }

    const text = element.textContent || "";
    element.setAttribute("highlight-text", text);

    element.style.setProperty("--text-color", finalTextColor);
    element.style.setProperty("--highlight-color", finalHighlightColor);

    gsap.to(element, {
      keyframes: [
        {
          "--animate-padding-X": "0.3em",
          "padding-left": "0.3em",
          "padding-right": "0.3em",
          "--animate-width": "20%",
          duration: 0.3,
        },
        {
          "--animate-width": "100%",
          duration: 0.7,
        },
      ],
      scrollTrigger: {
        trigger: element,
        start: finalStart,
        end: finalEnd,
        scrub: true,
      },
    });

    return () => {
      ScrollTrigger.getById(element.id)?.kill();
      gsap.killTweensOf(element);
      element.classList.remove("custom-highlight");
      element.removeAttribute("highlight-text");
      element.style.removeProperty("--text-color");
      element.style.removeProperty("--highlight-color");
    };
  }, [textColor, highlightColor]);

  return elementRef;
};
