import React from 'react';
import { Player, Card } from '../../types';

interface AssignmentProps {
  players: Player[];
  detectedCards: Card[];
  onAssignedCards: (cards: Card[]) => void;
}

const Assignment: React.FC<AssignmentProps> = ({ players, detectedCards, onAssignedCards }) => {
  // Calculate radial sectors based on player count
  const calculateRadialSectors = (playerCount: number) => {
    const sectors = [];
    const anglePerSector = (2 * Math.PI) / playerCount;
    
    for (let i = 0; i < playerCount; i++) {
      const startAngle = i * anglePerSector;
      const endAngle = (i + 1) * anglePerSector;
      
      sectors.push({
        id: i,
        startAngle,
        endAngle,
        player: players[i]
      });
    }
    
    return sectors;
  };

  // Assign cards to players based on radial sectors
  const assignCardsToPlayers = () => {
    if (players.length === 0 || detectedCards.length === 0) {
      onAssignedCards([]);
      return;
    }

    const sectors = calculateRadialSectors(players.length);
    const assignedCards = [...detectedCards];
    
    // Simple assignment: find nearest player for each card based on position
    const cardsWithAssignments = assignedCards.map(card => {
      // Convert card position to angle relative to center
      const centerX = 320; // Video width centered
      const centerY = 240; // Video height centered
      const dx = card.x - centerX;
      const dy = card.y - centerY;
      const angle = Math.atan2(dy, dx) + Math.PI; // Normalize to 0-2π
      
      // Find the sector that contains this angle
      let assignedPlayer = sectors[0].player; // Default to first player
      
      for (const sector of sectors) {
        if (angle >= sector.startAngle && angle < sector.endAngle) {
          assignedPlayer = sector.player;
          break;
        }
      }
      
      return {
        ...card,
        assignedTo: assignedPlayer.id
      };
    });
    
    onAssignedCards(cardsWithAssignments);
  };

  // Run assignment when cards or players change
  React.useEffect(() => {
    assignCardsToPlayers();
  }, [detectedCards, players]);

  // Helper function to calculate radial positions for visualization
  const calculatePlayerPosition = (index: number, totalPlayers: number) => {
    const angle = (index * 2 * Math.PI) / totalPlayers;
    const radius = 150; // Radius in pixels
    return {
      x: 320 + radius * Math.cos(angle),
      y: 240 + radius * Math.sin(angle)
    };
  };

  return null;
};

export default Assignment;