"use client";

import React from "react";
import gsap from "gsap";
import ScrollTrigger from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);
import { useHighlight } from "./hooks/useHighlight";
import { TextHighlightProps } from "./types";

const styles = {
  highlight: `
    .react-scroll-text-highlight {
      position: relative;
      display: inline-block;
      box-sizing: border-box;
      --animate-width: 0%;
      --animate-padding-X: 0em;
    }

    .react-scroll-text-highlight::before {
      position: absolute;
      inset: 0;
      overflow: hidden;
      transform-origin: left;
      width: var(--animate-width);
      padding-left: var(--animate-padding-X);
      padding-right: var(--animate-padding-X);
      box-sizing: inherit;
      content: "";
      background-color: var(--highlight-color);
      border-radius: 100em;
      margin: -0.2em 0;
    }

    .react-scroll-text-highlight::after {
      content: attr(highlight-text);
      position: absolute;
      inset: 0;
      color: var(--text-color);
      padding: 0.2em 0.3em;
      margin-top: -0.2em;
      margin-bottom: -0.2em;
      overflow: hidden;
      pointer-events: none;
      clip-path: inset(0 calc(100% - var(--animate-width)) -0.1em 0 round 100em);
      border-radius: 100em;
    }
  `,
};

const TextHighlight: React.FC<TextHighlightProps> = ({
  children,
  textColor,
  highlightColor,
  start,
  end,
}) => {
  const highLightRef = useHighlight({
    textColor,
    highlightColor,
    start,
    end,
  });

  return (
    <>
      <style>{styles.highlight}</style>
      <span ref={highLightRef}>{children}</span>
    </>
  );
};

export default TextHighlight;
