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

interface Bubble {
  id: number;
  x: number;
  y: number;
  size: number;
  created: number;
}

export const InteractiveBubbles = () => {
  const [bubbles, setBubbles] = useState<Bubble[]>([]);
  const [nextId, setNextId] = useState(0);

  const createBubble = useCallback((x: number, y: number) => {
    const newBubble: Bubble = {
      id: nextId,
      x,
      y,
      size: Math.random() * 8 + 6, // 6-14px (smaller)
      created: Date.now(),
    };
    
    setBubbles(prev => [...prev, newBubble]);
    setNextId(prev => prev + 1);

    // Remove bubble after animation (faster)
    setTimeout(() => {
      setBubbles(prev => prev.filter(bubble => bubble.id !== newBubble.id));
    }, 1500);
  }, [nextId]);

  const handleMouseMove = useCallback((e: MouseEvent) => {
    // Only create bubbles occasionally to avoid too many
    if (Math.random() < 0.02) { // 2% chance per mouse move
      createBubble(e.clientX, e.clientY);
    }
  }, [createBubble]);

  const handleClick = useCallback((e: MouseEvent) => {
    // Create multiple bubbles on click
    for (let i = 0; i < 5; i++) {
      setTimeout(() => {
        createBubble(
          e.clientX + (Math.random() - 0.5) * 100,
          e.clientY + (Math.random() - 0.5) * 100
        );
      }, i * 50);
    }
  }, [createBubble]);

  useEffect(() => {
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('click', handleClick);

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('click', handleClick);
    };
  }, [handleMouseMove, handleClick]);

  return (
    <div className="fixed inset-0 pointer-events-none z-10">
      {bubbles.map((bubble) => (
        <div
          key={bubble.id}
          className="soap-bubble bubble-small"
          style={{
            left: bubble.x,
            top: bubble.y,
            width: bubble.size,
            height: bubble.size,
          }}
        />
      ))}
    </div>
  );
};
