import { create } from 'zustand';

export type QueuePhase = 'idle' | 'searching' | 'found' | 'server_loading' | 'ready';

export interface QueuePlayer {
  id: string;
  username: string;
  avatar?: string;
  connected?: boolean;
}

export interface QueueMatch {
  id: string;
  map: string;
  game_mode: string;
  team1: { name: string; players: QueuePlayer[] };
  team2: { name: string; players: QueuePlayer[] };
  connect_string?: string;
  server_progress?: number;
  server_status?: string;
  join_deadline?: string;
}

interface QueueState {
  phase: QueuePhase;
  gameMode: string;
  selectedMaps: string[];
  searchStartedAt: number | null;
  playersFound: number;
  totalPlayers: number;
  match: QueueMatch | null;

  setPhase: (phase: QueuePhase) => void;
  setGameMode: (mode: string) => void;
  toggleMap: (mapId: string) => void;
  setSelectedMaps: (maps: string[]) => void;
  startSearch: () => void;
  cancelSearch: () => void;
  setPlayersFound: (count: number) => void;
  setMatch: (match: QueueMatch) => void;
  reset: () => void;
}

export const useQueueStore = create<QueueState>((set) => ({
  phase: 'idle',
  gameMode: 'competitive',
  selectedMaps: ['de_dust2', 'de_mirage', 'de_inferno'],
  searchStartedAt: null,
  playersFound: 0,
  totalPlayers: 10,
  match: null,

  setPhase: (phase) => set({ phase }),
  setGameMode: (gameMode) => set({ gameMode }),

  toggleMap: (mapId) =>
    set((state) => {
      const maps = state.selectedMaps.includes(mapId)
        ? state.selectedMaps.filter((m) => m !== mapId)
        : [...state.selectedMaps, mapId];
      if (maps.length === 0) return state;
      return { selectedMaps: maps };
    }),

  setSelectedMaps: (selectedMaps) => set({ selectedMaps }),
  startSearch: () => set({ phase: 'searching', searchStartedAt: Date.now(), playersFound: 1 }),
  cancelSearch: () => set({ phase: 'idle', searchStartedAt: null, playersFound: 0, match: null }),
  setPlayersFound: (playersFound) => set({ playersFound }),
  setMatch: (match) => set({ match }),

  reset: () =>
    set({
      phase: 'idle',
      searchStartedAt: null,
      playersFound: 0,
      match: null,
    }),
}));
