"use client";
import React, { useState, useEffect, useRef } from "react";
import { cn } from "../shared/utils";

// Self-contained animated span component to replace motion.span
const AnimatedSpan = ({ 
  children, 
  initial, 
  animate, 
  transition, 
  className,
  ...props 
}: {
  children: React.ReactNode;
  initial?: any;
  animate?: any;
  transition?: any;
  className?: string;
  [key: string]: any;
}) => {
  const spanRef = useRef<HTMLSpanElement>(null);

  useEffect(() => {
    if (spanRef.current && animate) {
      const element = spanRef.current;

      // Apply initial styles
      if (initial) {
        Object.assign(element.style, initial);
      }

      // Apply animated styles after delay
      setTimeout(() => {
        if (animate) {
          Object.assign(element.style, animate);
        }
      }, transition?.delay || 0);
    }
  }, [animate, initial, transition]);

  return (
    <span 
      ref={spanRef} 
      className={cn("transition-all duration-500 ease-out", className)}
      {...props}
    >
      {children}
    </span>
  );
};

export function ColourfulText({ text }: { text: string }) {
  const colors = [
    "rgb(131, 179, 32)",
    "rgb(47, 195, 106)",
    "rgb(42, 169, 210)",
    "rgb(4, 112, 202)",
    "rgb(107, 10, 255)",
    "rgb(183, 0, 218)",
    "rgb(218, 0, 171)",
    "rgb(230, 64, 92)",
    "rgb(232, 98, 63)",
    "rgb(249, 129, 47)",
  ];

  const [currentColors, setCurrentColors] = useState(colors);
  const [count, setCount] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      const shuffled = [...colors].sort(() => Math.random() - 0.5);
      setCurrentColors(shuffled);
      setCount((prev) => prev + 1);
    }, 5000);

    return () => clearInterval(interval);
  }, []);

  return (
    <>
      {text.split("").map((char, index) => (
        <AnimatedSpan
          key={`${char}-${count}-${index}`}
          initial={{
            y: 0,
            color: currentColors[index % currentColors.length],
            scale: 1,
            filter: "blur(0px)",
            opacity: 1,
          }}
          animate={{
            color: currentColors[index % currentColors.length],
            y: -3,
            scale: 1.01,
            filter: "blur(5px)",
            opacity: 0.8,
          }}
          transition={{
            duration: 0.5,
            delay: index * 0.05,
          }}
          className="inline-block whitespace-pre font-sans tracking-tight"
          style={{
            transform: `translateY(0px) scale(1)`,
            transition: `all 0.5s ease-out ${index * 0.05}s`,
          }}
        >
          {char}
        </AnimatedSpan>
      ))}
    </>
  );
}
