"use client";

import { cn } from "@/lib/utils";
import { type HTMLAttributes, useEffect, useState } from "react";

interface SonOfAGlitchProps extends HTMLAttributes<HTMLHeadingElement> {
  text: string;
  textClassName?: string;
  glitchClassName?: string;
  showGlitch?: boolean;
}

export const SonOfAGlitch = ({
  text,
  className,
  textClassName,
  glitchClassName,
  showGlitch = true,
}: SonOfAGlitchProps) => {
  const [isGlitching, setIsGlitching] = useState(showGlitch);

  useEffect(() => {
    setIsGlitching(showGlitch);
  }, [showGlitch]);

  return (
    <h1 className={cn("relative font-mono", className)}>
      <span
        className={cn(
          "absolute top-0 left-0 w-full h-full bg-transparent",
          isGlitching &&
            "before:content-[attr(data-text)] before:absolute before:top-0 before:w-full before:h-full before:bg-transparent before:left-[-2px] before:text-red-500 before:overflow-hidden before:animate-glitch-1",
          isGlitching &&
            "after:content-[attr(data-text)] after:absolute after:top-0 after:w-full after:h-full after:bg-transparent after:left-[2px] after:text-blue-500 after:overflow-hidden after:animate-glitch-2",
          glitchClassName,
        )}
        data-text={text}
      ></span>
      <span className={cn(textClassName)}>{text}</span>
    </h1>
  );
};
