'use client';

import { cn } from '@/lib/utils';
import { type ReactNode, useEffect, useRef, useState } from 'react';

interface MagicCardProps {
  children: ReactNode;
  className?: string;
  gradientSize?: number;
  gradientColor?: string;
}

export const MagicCard = ({ children, className, gradientSize = 200, gradientColor = '#262626' }: MagicCardProps) => {
  const mouseX = useRef<number>(0);
  const mouseY = useRef<number>(0);
  const cardRef = useRef<HTMLDivElement>(null);
  const [isHovering, setIsHovering] = useState(false);

  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      if (cardRef.current) {
        const rect = cardRef.current.getBoundingClientRect();
        mouseX.current = e.clientX - rect.left;
        mouseY.current = e.clientY - rect.top;
        cardRef.current.style.setProperty('--mouse-x', `${mouseX.current}px`);
        cardRef.current.style.setProperty('--mouse-y', `${mouseY.current}px`);
      }
    };

    const currentCardRef = cardRef.current;
    if (currentCardRef) {
      currentCardRef.addEventListener('mousemove', handleMouseMove);
    }

    return () => {
      if (currentCardRef) {
        currentCardRef.removeEventListener('mousemove', handleMouseMove);
      }
    };
  }, []);

  return (
    <div
      ref={cardRef}
      onMouseEnter={() => setIsHovering(true)}
      onMouseLeave={() => setIsHovering(false)}
      className={cn(
        'relative w-full h-full p-px rounded-2xl transition-all duration-300 ease-in-out',
        'bg-neutral-900 hover:bg-neutral-800',
        className
      )}
      style={{
        background: isHovering
          ? `radial-gradient(var(--gradient-size, ${gradientSize}px) circle at var(--mouse-x) var(--mouse-y), var(--gradient-color, ${gradientColor}), transparent 100%)`
          : 'transparent',
      }}
    >
      <div className="relative w-full h-full bg-neutral-950/90 rounded-[15px] p-8">
        {children}
      </div>
    </div>
  );
};
