"use client";

import { useEffect, useState, useRef } from "react";

interface CursorDotBackgroundProps {
  dotSize?: number;
  dotSpacing?: number;
  fadeDistance?: number;
  opacity?: number;
  className?: string;
}

export function CursorDotBackground({
  dotSize = 1,
  dotSpacing = 20,
  fadeDistance = 100,
  opacity = 0.3,
  className = "",
}: CursorDotBackgroundProps) {
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const [isHovering, setIsHovering] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      if (containerRef.current) {
        const rect = containerRef.current.getBoundingClientRect();
        setMousePosition({
          x: e.clientX - rect.left,
          y: e.clientY - rect.top,
        });
      }
    };

    const handleMouseEnter = () => setIsHovering(true);
    const handleMouseLeave = () => setIsHovering(false);

    const container = containerRef.current;
    if (container) {
      container.addEventListener("mousemove", handleMouseMove);
      container.addEventListener("mouseenter", handleMouseEnter);
      container.addEventListener("mouseleave", handleMouseLeave);
    }

    return () => {
      if (container) {
        container.removeEventListener("mousemove", handleMouseMove);
        container.removeEventListener("mouseenter", handleMouseEnter);
        container.removeEventListener("mouseleave", handleMouseLeave);
      }
    };
  }, []);

  // Generate dots based on container size
  const generateDots = () => {
    if (!containerRef.current) return [];

    const rect = containerRef.current.getBoundingClientRect();
    const width = rect.width;
    const height = rect.height;
    
    const dots = [];
    const cols = Math.ceil(width / dotSpacing);
    const rows = Math.ceil(height / dotSpacing);

    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < cols; col++) {
        const x = col * dotSpacing;
        const y = row * dotSpacing;
        
        // Calculate distance from mouse position
        const distance = Math.sqrt(
          Math.pow(x - mousePosition.x, 2) + Math.pow(y - mousePosition.y, 2)
        );
        
        // Calculate opacity based on distance and hover state
        let dotOpacity = 0;
        if (isHovering && distance <= fadeDistance) {
          dotOpacity = opacity * (1 - distance / fadeDistance);
        }
        
        if (dotOpacity > 0) {
          dots.push({
            x,
            y,
            opacity: dotOpacity,
          });
        }
      }
    }

    return dots;
  };

  return (
    <div
      ref={containerRef}
      className={`absolute inset-0 pointer-events-none ${className}`}
      style={{
        backgroundImage: `radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px)`,
        backgroundSize: `${dotSpacing}px ${dotSpacing}px`,
      }}
    >
      {generateDots().map((dot, index) => (
        <div
          key={index}
          className="absolute rounded-full bg-white transition-opacity duration-150 ease-out"
          style={{
            left: dot.x,
            top: dot.y,
            width: dotSize,
            height: dotSize,
            opacity: dot.opacity,
            transform: "translate(-50%, -50%)",
          }}
        />
      ))}
    </div>
  );
}
