import { describe, it, expect, vi, beforeEach } from 'vitest';
import { Player, GameConfig, DEFAULT_GAME_CONFIG } from '../../types';

describe('Presenter Feature Logic', () => {
  const createPlayer = (overrides: Partial<Player> = {}): Player => ({
    id: 'player-1',
    name: 'Test Player',
    score: 0,
    previousScore: 0,
    streak: 0,
    lastAnswerCorrect: null,
    selectedShape: null,
    pointsBreakdown: null,
    isBot: false,
    avatarSeed: 0.5,
    color: '#ff0000',
    ...overrides,
  });

  describe('auto-assignment of presenter', () => {
    const shouldAutoAssignPresenter = (
      players: Player[],
      newPlayerId: string,
      hostParticipates: boolean,
      currentPresenterId: string | null
    ): string | null => {
      if (hostParticipates) return null;
      if (currentPresenterId) return null;
      
      const realPlayers = players.filter(p => p.id !== 'host');
      const isFirstRealPlayer = realPlayers.length === 1 && realPlayers[0].id === newPlayerId;
      
      return isFirstRealPlayer ? newPlayerId : null;
    };

    it('assigns first joiner as presenter when host does not participate', () => {
      const players = [createPlayer({ id: 'player-1', name: 'Alice' })];
      
      const result = shouldAutoAssignPresenter(players, 'player-1', false, null);
      
      expect(result).toBe('player-1');
    });

    it('does not assign presenter when host participates', () => {
      const players = [
        createPlayer({ id: 'host', name: 'Host' }),
        createPlayer({ id: 'player-1', name: 'Alice' }),
      ];
      
      const result = shouldAutoAssignPresenter(players, 'player-1', true, null);
      
      expect(result).toBeNull();
    });

    it('does not reassign presenter when one already exists', () => {
      const players = [
        createPlayer({ id: 'player-1', name: 'Alice' }),
        createPlayer({ id: 'player-2', name: 'Bob' }),
      ];
      
      const result = shouldAutoAssignPresenter(players, 'player-2', false, 'player-1');
      
      expect(result).toBeNull();
    });

    it('does not assign second joiner as presenter', () => {
      const players = [
        createPlayer({ id: 'player-1', name: 'Alice' }),
        createPlayer({ id: 'player-2', name: 'Bob' }),
      ];
      
      const result = shouldAutoAssignPresenter(players, 'player-2', false, null);
      
      expect(result).toBeNull();
    });

    it('ignores host player when counting real players', () => {
      const players = [
        createPlayer({ id: 'host', name: 'Host' }),
        createPlayer({ id: 'player-1', name: 'Alice' }),
      ];
      
      const result = shouldAutoAssignPresenter(players, 'player-1', false, null);
      
      expect(result).toBe('player-1');
    });
  });

  describe('ADVANCE message validation', () => {
    type AdvanceAction = 'START' | 'NEXT' | 'SCOREBOARD';
    
    const validateAdvanceMessage = (
      senderPeerId: string,
      presenterId: string | null,
      action: AdvanceAction,
      currentGameState: string
    ): { valid: boolean; reason?: string } => {
      if (senderPeerId !== presenterId) {
        return { valid: false, reason: 'Sender is not the presenter' };
      }
      
      const validTransitions: Record<string, AdvanceAction[]> = {
        'LOBBY': ['START'],
        'REVEAL': ['NEXT', 'SCOREBOARD'],
        'SCOREBOARD': ['NEXT'],
      };
      
      const allowedActions = validTransitions[currentGameState] || [];
      if (!allowedActions.includes(action)) {
        return { valid: false, reason: `Invalid action ${action} for state ${currentGameState}` };
      }
      
      return { valid: true };
    };

    it('accepts ADVANCE from presenter', () => {
      const result = validateAdvanceMessage('player-1', 'player-1', 'START', 'LOBBY');
      
      expect(result.valid).toBe(true);
    });

    it('rejects ADVANCE from non-presenter', () => {
      const result = validateAdvanceMessage('player-2', 'player-1', 'START', 'LOBBY');
      
      expect(result.valid).toBe(false);
      expect(result.reason).toBe('Sender is not the presenter');
    });

    it('rejects ADVANCE when no presenter is set', () => {
      const result = validateAdvanceMessage('player-1', null, 'START', 'LOBBY');
      
      expect(result.valid).toBe(false);
      expect(result.reason).toBe('Sender is not the presenter');
    });

    it('accepts START action only in LOBBY state', () => {
      expect(validateAdvanceMessage('p1', 'p1', 'START', 'LOBBY').valid).toBe(true);
      expect(validateAdvanceMessage('p1', 'p1', 'START', 'QUESTION').valid).toBe(false);
      expect(validateAdvanceMessage('p1', 'p1', 'START', 'REVEAL').valid).toBe(false);
    });

    it('accepts SCOREBOARD action only in REVEAL state', () => {
      expect(validateAdvanceMessage('p1', 'p1', 'SCOREBOARD', 'REVEAL').valid).toBe(true);
      expect(validateAdvanceMessage('p1', 'p1', 'SCOREBOARD', 'LOBBY').valid).toBe(false);
      expect(validateAdvanceMessage('p1', 'p1', 'SCOREBOARD', 'SCOREBOARD').valid).toBe(false);
    });

    it('accepts NEXT action in REVEAL and SCOREBOARD states', () => {
      expect(validateAdvanceMessage('p1', 'p1', 'NEXT', 'REVEAL').valid).toBe(true);
      expect(validateAdvanceMessage('p1', 'p1', 'NEXT', 'SCOREBOARD').valid).toBe(true);
      expect(validateAdvanceMessage('p1', 'p1', 'NEXT', 'LOBBY').valid).toBe(false);
    });

    it('rejects all actions in QUESTION state (no advancing mid-question)', () => {
      expect(validateAdvanceMessage('p1', 'p1', 'START', 'QUESTION').valid).toBe(false);
      expect(validateAdvanceMessage('p1', 'p1', 'NEXT', 'QUESTION').valid).toBe(false);
      expect(validateAdvanceMessage('p1', 'p1', 'SCOREBOARD', 'QUESTION').valid).toBe(false);
    });
  });

  describe('presenter reconnection handling', () => {
    const handlePresenterReconnection = (
      reconnectedPlayerId: string,
      previousPlayerId: string | null,
      currentPresenterId: string | null
    ): string | null => {
      if (!previousPlayerId) return currentPresenterId;
      if (previousPlayerId === currentPresenterId) {
        return reconnectedPlayerId;
      }
      return currentPresenterId;
    };

    it('updates presenter ID when presenter reconnects with new peer ID', () => {
      const result = handlePresenterReconnection('new-peer-id', 'old-peer-id', 'old-peer-id');
      
      expect(result).toBe('new-peer-id');
    });

    it('keeps presenter ID unchanged when non-presenter reconnects', () => {
      const result = handlePresenterReconnection('new-peer-id', 'old-peer-id', 'presenter-id');
      
      expect(result).toBe('presenter-id');
    });

    it('keeps presenter ID unchanged when no previous ID provided', () => {
      const result = handlePresenterReconnection('new-peer-id', null, 'presenter-id');
      
      expect(result).toBe('presenter-id');
    });

    it('handles null current presenter', () => {
      const result = handlePresenterReconnection('new-peer-id', 'old-peer-id', null);
      
      expect(result).toBeNull();
    });
  });

  describe('setPresenterPlayer validation', () => {
    const canSetPresenter = (
      role: 'HOST' | 'CLIENT',
      hostParticipates: boolean,
      targetPlayerId: string | null,
      players: Player[]
    ): { allowed: boolean; reason?: string } => {
      if (role !== 'HOST') {
        return { allowed: false, reason: 'Only host can set presenter' };
      }
      
      if (hostParticipates) {
        return { allowed: false, reason: 'Cannot set presenter when host participates' };
      }
      
      if (targetPlayerId === null) {
        return { allowed: true };
      }
      
      const playerExists = players.some(p => p.id === targetPlayerId && p.id !== 'host');
      if (!playerExists) {
        return { allowed: false, reason: 'Target player not found' };
      }
      
      return { allowed: true };
    };

    it('allows host to set presenter when not participating', () => {
      const players = [createPlayer({ id: 'player-1' })];
      const result = canSetPresenter('HOST', false, 'player-1', players);
      
      expect(result.allowed).toBe(true);
    });

    it('disallows client from setting presenter', () => {
      const players = [createPlayer({ id: 'player-1' })];
      const result = canSetPresenter('CLIENT', false, 'player-1', players);
      
      expect(result.allowed).toBe(false);
      expect(result.reason).toBe('Only host can set presenter');
    });

    it('disallows setting presenter when host participates', () => {
      const players = [createPlayer({ id: 'player-1' })];
      const result = canSetPresenter('HOST', true, 'player-1', players);
      
      expect(result.allowed).toBe(false);
      expect(result.reason).toBe('Cannot set presenter when host participates');
    });

    it('allows setting presenter to null (removing presenter)', () => {
      const players = [createPlayer({ id: 'player-1' })];
      const result = canSetPresenter('HOST', false, null, players);
      
      expect(result.allowed).toBe(true);
    });

    it('disallows setting non-existent player as presenter', () => {
      const players = [createPlayer({ id: 'player-1' })];
      const result = canSetPresenter('HOST', false, 'player-999', players);
      
      expect(result.allowed).toBe(false);
      expect(result.reason).toBe('Target player not found');
    });

    it('disallows setting host as presenter', () => {
      const players = [
        createPlayer({ id: 'host', name: 'Host' }),
        createPlayer({ id: 'player-1' }),
      ];
      const result = canSetPresenter('HOST', false, 'host', players);
      
      expect(result.allowed).toBe(false);
      expect(result.reason).toBe('Target player not found');
    });
  });

  describe('sendAdvance client behavior', () => {
    const canSendAdvance = (
      role: 'HOST' | 'CLIENT',
      isConnectedToHost: boolean
    ): boolean => {
      return role === 'CLIENT' && isConnectedToHost;
    };

    it('allows client to send advance when connected', () => {
      expect(canSendAdvance('CLIENT', true)).toBe(true);
    });

    it('disallows client from sending advance when disconnected', () => {
      expect(canSendAdvance('CLIENT', false)).toBe(false);
    });

    it('disallows host from sending advance (host controls directly)', () => {
      expect(canSendAdvance('HOST', true)).toBe(false);
    });
  });

  describe('PRESENTER_CHANGED message handling', () => {
    type PresenterChangedHandler = (
      currentPlayerId: string | null,
      newPresenterId: string | null
    ) => { isPresenter: boolean; shouldShowNotification: boolean };

    const handlePresenterChanged: PresenterChangedHandler = (currentPlayerId, newPresenterId) => {
      const isPresenter = currentPlayerId !== null && currentPlayerId === newPresenterId;
      const shouldShowNotification = isPresenter;
      
      return { isPresenter, shouldShowNotification };
    };

    it('detects when current player becomes presenter', () => {
      const result = handlePresenterChanged('player-1', 'player-1');
      
      expect(result.isPresenter).toBe(true);
      expect(result.shouldShowNotification).toBe(true);
    });

    it('detects when current player is not presenter', () => {
      const result = handlePresenterChanged('player-1', 'player-2');
      
      expect(result.isPresenter).toBe(false);
      expect(result.shouldShowNotification).toBe(false);
    });

    it('handles null current player ID', () => {
      const result = handlePresenterChanged(null, 'player-1');
      
      expect(result.isPresenter).toBe(false);
    });

    it('handles null presenter ID', () => {
      const result = handlePresenterChanged('player-1', null);
      
      expect(result.isPresenter).toBe(false);
    });

    it('handles both null', () => {
      const result = handlePresenterChanged(null, null);
      
      expect(result.isPresenter).toBe(false);
    });
  });

  describe('WELCOME message presenter payload', () => {
    const buildWelcomePayload = (
      playerId: string,
      presenterId: string | null,
      isReconnect: boolean,
      reconnectedPlayerWasPresenter: boolean
    ): { playerId: string; presenterId: string | null } => {
      let finalPresenterId = presenterId;
      
      if (isReconnect && reconnectedPlayerWasPresenter) {
        finalPresenterId = playerId;
      }
      
      return {
        playerId,
        presenterId: finalPresenterId,
      };
    };

    it('includes presenter ID in welcome payload', () => {
      const result = buildWelcomePayload('player-1', 'player-2', false, false);
      
      expect(result.presenterId).toBe('player-2');
    });

    it('updates presenter ID when presenter reconnects', () => {
      const result = buildWelcomePayload('new-peer-id', 'old-peer-id', true, true);
      
      expect(result.presenterId).toBe('new-peer-id');
    });

    it('keeps presenter ID when non-presenter reconnects', () => {
      const result = buildWelcomePayload('player-1', 'player-2', true, false);
      
      expect(result.presenterId).toBe('player-2');
    });

    it('handles null presenter', () => {
      const result = buildWelcomePayload('player-1', null, false, false);
      
      expect(result.presenterId).toBeNull();
    });
  });

  describe('edge cases', () => {
    it('handles rapid presenter changes', () => {
      let presenterId: string | null = null;
      const changes: string[] = [];
      
      const setPresenterId = (id: string | null) => {
        presenterId = id;
        changes.push(id ?? 'null');
      };
      
      setPresenterId('player-1');
      setPresenterId('player-2');
      setPresenterId('player-3');
      setPresenterId('player-1');
      
      expect(presenterId).toBe('player-1');
      expect(changes).toEqual(['player-1', 'player-2', 'player-3', 'player-1']);
    });

    it('handles player leaving who was presenter', () => {
      const handlePlayerLeave = (
        leavingPlayerId: string,
        currentPresenterId: string | null,
        remainingPlayers: Player[]
      ): string | null => {
        if (leavingPlayerId !== currentPresenterId) {
          return currentPresenterId;
        }
        
        const realPlayers = remainingPlayers.filter(p => p.id !== 'host');
        return realPlayers.length > 0 ? realPlayers[0].id : null;
      };

      const players = [
        createPlayer({ id: 'player-2', name: 'Bob' }),
        createPlayer({ id: 'player-3', name: 'Charlie' }),
      ];
      
      const result = handlePlayerLeave('player-1', 'player-1', players);
      
      expect(result).toBe('player-2');
    });

    it('handles presenter leaving when no other players', () => {
      const handlePlayerLeave = (
        leavingPlayerId: string,
        currentPresenterId: string | null,
        remainingPlayers: Player[]
      ): string | null => {
        if (leavingPlayerId !== currentPresenterId) {
          return currentPresenterId;
        }
        
        const realPlayers = remainingPlayers.filter(p => p.id !== 'host');
        return realPlayers.length > 0 ? realPlayers[0].id : null;
      };

      const result = handlePlayerLeave('player-1', 'player-1', []);
      
      expect(result).toBeNull();
    });

    it('handles game ending with presenter', () => {
      const handleGameEnd = (presenterId: string | null): string | null => {
        return null;
      };
      
      expect(handleGameEnd('player-1')).toBeNull();
      expect(handleGameEnd(null)).toBeNull();
    });

    it('handles host joining their own game when not participating', () => {
      const shouldAssignHostAsPresenter = (
        joiningPlayerId: string,
        hostParticipates: boolean
      ): boolean => {
        if (joiningPlayerId === 'host') return false;
        return !hostParticipates;
      };
      
      expect(shouldAssignHostAsPresenter('host', false)).toBe(false);
      expect(shouldAssignHostAsPresenter('player-1', false)).toBe(true);
      expect(shouldAssignHostAsPresenter('player-1', true)).toBe(false);
    });
  });
});
