"use client";

import { useEffect, useRef } from "react";

interface CountryData {
  name: string;
  count: number;
  // In a real implementation, we would have coordinates
  x?: number;
  y?: number;
}

interface ObservatoryMapProps {
  countries: CountryData[];
  onCountrySelect: (country: string) => void;
  selectedCountry: string | null;
}

export function ObservatoryMap({ 
  countries, 
  onCountrySelect,
  selectedCountry 
}: ObservatoryMapProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  
  // Draw the map and country markers
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    
    // Set canvas dimensions
    const updateCanvasDimensions = () => {
      const parent = canvas.parentElement;
      if (parent) {
        canvas.width = parent.clientWidth;
        canvas.height = parent.clientHeight;
      }
    };
    
    updateCanvasDimensions();
    window.addEventListener('resize', updateCanvasDimensions);
    
    // Clear canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // Draw world map background (simplified)
    ctx.fillStyle = '#e0e0e0';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // Draw grid lines for better visualization
    ctx.strokeStyle = '#ffffff';
    ctx.lineWidth = 0.5;
    
    // Horizontal grid lines
    for (let y = 0; y < canvas.height; y += 30) {
      ctx.beginPath();
      ctx.moveTo(0, y);
      ctx.lineTo(canvas.width, y);
      ctx.stroke();
    }
    
    // Vertical grid lines
    for (let x = 0; x < canvas.width; x += 30) {
      ctx.beginPath();
      ctx.moveTo(x, 0);
      ctx.lineTo(x, canvas.height);
      ctx.stroke();
    }
    
    // Draw country markers (in random positions)
    countries.forEach((country, index) => {
      // Generate random positions (in a real app, we would use actual coordinates)
      const x = (index * 50 + 100) % (canvas.width - 50);
      const y = 50 + Math.floor(index / 5) * 50;
      
      // Draw marker
      ctx.beginPath();
      ctx.arc(x, y, country.count > 5 ? 10 : (country.count > 2 ? 7 : 5), 0, Math.PI * 2);
      
      // Highlight selected country
      if (selectedCountry === country.name) {
        ctx.fillStyle = '#3b82f6';
      } else {
        ctx.fillStyle = '#ef4444';
      }
      
      ctx.fill();
      
      // Draw country name
      ctx.fillStyle = '#000000';
      ctx.font = '12px Arial';
      ctx.fillText(country.name, x + 12, y + 4);
      
      // Store coordinates for click detection
      country.x = x;
      country.y = y;
    });
    
    // Handle click events
    const handleClick = (e: MouseEvent) => {
      const rect = canvas.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      
      // Check if a country marker was clicked
      for (const country of countries) {
        if (country.x && country.y) {
          const distance = Math.sqrt(
            Math.pow(x - country.x, 2) + Math.pow(y - country.y, 2)
          );
          
          if (distance <= 10) {
            onCountrySelect(country.name);
            break;
          }
        }
      }
    };
    
    canvas.addEventListener('click', handleClick);
    
    // Cleanup
    return () => {
      window.removeEventListener('resize', updateCanvasDimensions);
      canvas.removeEventListener('click', handleClick);
    };
  }, [countries, selectedCountry, onCountrySelect]);
  
  return (
    <div className="w-full h-full bg-gray-100 rounded-lg relative">
      <canvas 
        ref={canvasRef} 
        className="w-full h-full rounded-lg"
      />
      {countries.length === 0 && (
        <div className="absolute inset-0 flex items-center justify-center">
          <p className="text-gray-500">No countries detected in the news</p>
        </div>
      )}
    </div>
  );
} 