import { ref } from 'vue'
import type {
    ActiveRoomState,
    ActiveRoomSelectionInput,
} from './state'
import { readActiveRoomSnapshot, saveActiveRoom } from './storage'

const activeRoom = ref<ActiveRoomState | null>(readActiveRoomSnapshot())

function normalizeRoom(input: ActiveRoomSelectionInput): ActiveRoomState {
    return {
        roomId: input.roomId,
        roomName: input.roomName ?? '',
        gameType: input.gameType ?? 'chengdu',
        ownerId: input.ownerId ?? '',
        maxPlayers: input.maxPlayers ?? 4,
        playerCount: input.playerCount ?? input.players?.length ?? 0,
        status: input.status ?? 'waiting',
        createdAt: input.createdAt ?? '',
        updatedAt: input.updatedAt ?? '',
        players: input.players ?? [],
        myHand: [],
        game: {
            state: {
                wall: [],
                scores: {},
                dealerIndex: -1,
                currentTurn: -1,
                phase: 'waiting',
            },
        },
    }
}

// 设置当前房间
export function setActiveRoom(input: ActiveRoomSelectionInput) {
    const next = normalizeRoom(input)
    activeRoom.value = next
    saveActiveRoom(next)
}

// 使用房间状态
export function useActiveRoomState() {
    return activeRoom
}