// ============================================
// Buzzer System Type Definitions
// ============================================

import type { GamePhase } from './kuldvillak';

/** Connected player in a buzzer session */
export interface BuzzerPlayer {
    id: string;
    name: string;
    score: number;
    connected: boolean;
    lockedOut: boolean; // True if player buzzed too early
}

/** Current state of the buzzer */
export type BuzzerState =
    | 'disabled'  // Question not active, can't buzz
    | 'locked'    // Player buzzed too early, locked out
    | 'ready'     // Timer active, can buzz
    | 'buzzed';   // Someone has buzzed

/** Buzzer session state */
export interface BuzzerSessionState {
    roomCode: string;
    players: BuzzerPlayer[];
    buzzerState: BuzzerState;
    currentAnswerer: string | null; // Player ID who buzzed first
    buzzQueue: string[]; // First-come-first-served order
    gamePhase: GamePhase;
    timerActive: boolean;

    // Question data (synced from main game)
    currentQuestion: {
        text: string;
        answer: string;
        points: number;
        isDailyDouble: boolean;
    } | null;
    showAnswer: boolean;

    // Final round
    finalCategory: string | null;
    finalWagers: Record<string, number>;
    finalAnswers: Record<string, string>;

    // Result feedback
    lastResult: {
        playerId: string;
        correct: boolean;
        points: number;
    } | null;
}

// ============================================
// WebSocket Event Types
// ============================================

/** Events sent from client to server */
export type ClientEvent =
    | { type: 'join'; roomCode: string; playerName: string }
    | { type: 'buzz'; timestamp: number }
    | { type: 'submit-wager'; wager: number }
    | { type: 'submit-answer'; answer: string }
    | { type: 'disconnect' };

/** Events sent from server to client */
export type ServerEvent =
    | { type: 'joined'; playerId: string; player: BuzzerPlayer; players: BuzzerPlayer[] }
    | { type: 'game-state'; state: Partial<BuzzerSessionState> }
    | { type: 'player-joined'; player: BuzzerPlayer }
    | { type: 'player-left'; playerId: string }
    | { type: 'buzzer-pressed'; playerId: string; playerName: string }
    | { type: 'buzzer-state-change'; state: BuzzerState; currentAnswerer: string | null }
    | { type: 'answer-result'; playerId: string; correct: boolean; points: number }
    | { type: 'phase-change'; phase: GamePhase }
    | { type: 'question-update'; question: BuzzerSessionState['currentQuestion']; showAnswer: boolean }
    | { type: 'timer-update'; active: boolean }
    | { type: 'score-update'; playerId: string; score: number }
    | { type: 'final-category'; category: string }
    | { type: 'wager-accepted'; playerId: string }
    | { type: 'answer-accepted'; playerId: string }
    | { type: 'game-over'; rankings: { playerId: string; name: string; score: number; rank: number }[] }
    | { type: 'game-ended' }
    | { type: 'error'; message: string };

/** Events sent from moderator to buzzer server */
export type ModeratorEvent =
    | { type: 'create-room'; roomCode: string }
    | { type: 'start-game' }
    | { type: 'phase-change'; phase: GamePhase }
    | { type: 'question-selected'; question: BuzzerSessionState['currentQuestion'] }
    | { type: 'timer-start' }
    | { type: 'timer-stop' }
    | { type: 'mark-correct'; playerId: string; points: number }
    | { type: 'mark-wrong'; playerId: string; points: number }
    | { type: 'show-answer' }
    | { type: 'return-to-board' }
    | { type: 'final-category'; category: string }
    | { type: 'reveal-final-question'; question: string }
    | { type: 'final-timer-start' }
    | { type: 'game-over'; rankings: { playerId: string; name: string; score: number; rank: number }[] }
    | { type: 'end-game' }
    | { type: 'kick-player'; playerId: string };

// ============================================
// Room Code Generation
// ============================================

/** Generate a random 4-character room code */
export function generateRoomCode(): string {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; // Removed I and O to avoid confusion
    let code = '';
    for (let i = 0; i < 4; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return code;
}

/** Validate a room code format */
export function isValidRoomCode(code: string): boolean {
    return /^[A-Z]{4}$/.test(code.toUpperCase());
}
