import { useEffect, useState, useCallback } from 'react';

interface Position {
  x: number;
  y: number;
}

const CustomCursor = () => {
  const [position, setPosition] = useState<Position>({ x: 0, y: 0 });
  const [isHovering, setIsHovering] = useState(false);
  const [isVisible, setIsVisible] = useState(false);
  const [cursorText, setCursorText] = useState('');

  const handleMouseMove = useCallback((e: MouseEvent) => {
    setPosition({ x: e.clientX, y: e.clientY });
    if (!isVisible) setIsVisible(true);
  }, [isVisible]);

  const handleMouseEnter = useCallback(() => {
    setIsVisible(true);
  }, []);

  const handleMouseLeave = useCallback(() => {
    setIsVisible(false);
  }, []);

  useEffect(() => {
    window.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseenter', handleMouseEnter);
    document.addEventListener('mouseleave', handleMouseLeave);

    // Check for hoverable elements
    const checkHoverElements = () => {
      const hoverElements = document.querySelectorAll('[data-cursor="view"]');
      
      hoverElements.forEach((el) => {
        el.addEventListener('mouseenter', () => {
          setIsHovering(true);
          setCursorText('VIEW');
        });
        el.addEventListener('mouseleave', () => {
          setIsHovering(false);
          setCursorText('');
        });
      });

      const linkElements = document.querySelectorAll('a, button, [data-cursor="pointer"]');
      linkElements.forEach((el) => {
        if (!el.hasAttribute('data-cursor')) {
          el.addEventListener('mouseenter', () => {
            setIsHovering(true);
            setCursorText('');
          });
          el.addEventListener('mouseleave', () => {
            setIsHovering(false);
          });
        }
      });
    };

    // Initial check
    checkHoverElements();

    // MutationObserver to handle dynamically added elements
    const observer = new MutationObserver(checkHoverElements);
    observer.observe(document.body, { childList: true, subtree: true });

    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseenter', handleMouseEnter);
      document.removeEventListener('mouseleave', handleMouseLeave);
      observer.disconnect();
    };
  }, [handleMouseMove, handleMouseEnter, handleMouseLeave]);

  if (!isVisible) return null;

  return (
    <>
      {/* Main cursor dot */}
      <div
        className="fixed pointer-events-none z-[9999] mix-blend-difference"
        style={{
          left: position.x,
          top: position.y,
          transform: 'translate(-50%, -50%)',
        }}
      >
        <div
          className={`rounded-full bg-primary-foreground transition-all duration-300 ease-out ${
            isHovering ? 'w-20 h-20 opacity-100' : 'w-3 h-3 opacity-100'
          }`}
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          {cursorText && (
            <span className="text-primary text-xs font-medium tracking-wider">
              {cursorText}
            </span>
          )}
        </div>
      </div>

      {/* Cursor trail */}
      <div
        className="fixed pointer-events-none z-[9998] mix-blend-difference"
        style={{
          left: position.x,
          top: position.y,
          transform: 'translate(-50%, -50%)',
          transition: 'left 0.15s ease-out, top 0.15s ease-out',
        }}
      >
        <div
          className={`rounded-full border border-primary-foreground transition-all duration-500 ease-out ${
            isHovering ? 'w-24 h-24 opacity-50' : 'w-8 h-8 opacity-30'
          }`}
        />
      </div>
    </>
  );
};

export default CustomCursor;
