// ============================================
// LocalStorage Persistence for Game Data
// ============================================

import type { KuldvillakGame, GameMetadata } from '$lib/types/kuldvillak';

const STORAGE_PREFIX = 'ultimate_gaming';
const KULDVILLAK_GAMES_KEY = `${STORAGE_PREFIX}_kuldvillak_games`;
const KULDVILLAK_ACTIVE_KEY = `${STORAGE_PREFIX}_kuldvillak_active`;

// ============================================
// Kuldvillak Save/Load Functions
// ============================================

/**
 * Get all saved Kuldvillak games metadata (lightweight list)
 */
export function getKuldvillakGamesList(): GameMetadata[] {
    if (typeof localStorage === 'undefined') return [];

    try {
        const data = localStorage.getItem(KULDVILLAK_GAMES_KEY);
        if (!data) return [];

        const games: KuldvillakGame[] = JSON.parse(data);
        return games.map((game) => ({
            id: game.id,
            name: game.name,
            createdAt: game.createdAt,
            updatedAt: game.updatedAt,
            teamCount: game.teams.length,
            roundCount: game.rounds.length
        }));
    } catch (e) {
        console.error('Failed to load games list:', e);
        return [];
    }
}

/**
 * Get all saved Kuldvillak games (full data)
 */
export function getAllKuldvillakGames(): KuldvillakGame[] {
    if (typeof localStorage === 'undefined') return [];

    try {
        const data = localStorage.getItem(KULDVILLAK_GAMES_KEY);
        return data ? JSON.parse(data) : [];
    } catch (e) {
        console.error('Failed to load games:', e);
        return [];
    }
}

/**
 * Load a specific Kuldvillak game by ID
 */
export function loadKuldvillakGame(gameId: string): KuldvillakGame | null {
    const games = getAllKuldvillakGames();
    return games.find((g) => g.id === gameId) ?? null;
}

/**
 * Save a Kuldvillak game (creates new or updates existing)
 */
export function saveKuldvillakGame(game: KuldvillakGame): boolean {
    if (typeof localStorage === 'undefined') return false;

    try {
        const games = getAllKuldvillakGames();
        const existingIndex = games.findIndex((g) => g.id === game.id);

        // Update timestamp
        game.updatedAt = new Date().toISOString();

        if (existingIndex >= 0) {
            games[existingIndex] = game;
        } else {
            games.push(game);
        }

        localStorage.setItem(KULDVILLAK_GAMES_KEY, JSON.stringify(games));
        return true;
    } catch (e) {
        console.error('Failed to save game:', e);
        return false;
    }
}

/**
 * Delete a Kuldvillak game by ID
 */
export function deleteKuldvillakGame(gameId: string): boolean {
    if (typeof localStorage === 'undefined') return false;

    try {
        const games = getAllKuldvillakGames();
        const filtered = games.filter((g) => g.id !== gameId);
        localStorage.setItem(KULDVILLAK_GAMES_KEY, JSON.stringify(filtered));
        return true;
    } catch (e) {
        console.error('Failed to delete game:', e);
        return false;
    }
}

/**
 * Duplicate a Kuldvillak game
 */
export function duplicateKuldvillakGame(gameId: string): KuldvillakGame | null {
    const original = loadKuldvillakGame(gameId);
    if (!original) return null;

    const now = new Date().toISOString();
    const duplicate: KuldvillakGame = {
        ...JSON.parse(JSON.stringify(original)), // Deep clone
        id: crypto.randomUUID(),
        name: `${original.name} (Copy)`,
        createdAt: now,
        updatedAt: now
    };

    // Reset game state
    duplicate.state = {
        phase: 'lobby',
        currentRoundIndex: 0,
        currentQuestionId: null,
        currentCategoryId: null,
        activeTeamId: null,
        dailyDoubleWager: null,
        finalWagers: {},
        finalAnswers: {}
    };

    // Reset revealed questions and scores
    for (const round of duplicate.rounds) {
        for (const category of round.categories) {
            for (const question of category.questions) {
                question.isRevealed = false;
            }
        }
    }
    for (const team of duplicate.teams) {
        team.score = 0;
    }

    if (saveKuldvillakGame(duplicate)) {
        return duplicate;
    }
    return null;
}

// ============================================
// Active Game Session (for resuming)
// ============================================

/**
 * Save reference to currently active game
 */
export function setActiveKuldvillakGame(gameId: string | null): void {
    if (typeof localStorage === 'undefined') return;

    if (gameId) {
        localStorage.setItem(KULDVILLAK_ACTIVE_KEY, gameId);
    } else {
        localStorage.removeItem(KULDVILLAK_ACTIVE_KEY);
    }
}

/**
 * Get the ID of the last active game
 */
export function getActiveKuldvillakGameId(): string | null {
    if (typeof localStorage === 'undefined') return null;
    return localStorage.getItem(KULDVILLAK_ACTIVE_KEY);
}

/**
 * Load the last active game
 */
export function loadActiveKuldvillakGame(): KuldvillakGame | null {
    const activeId = getActiveKuldvillakGameId();
    if (!activeId) return null;
    return loadKuldvillakGame(activeId);
}

// ============================================
// Export/Import Functions
// ============================================

/**
 * Export a game to a JSON file (triggers download)
 */
export function exportKuldvillakGame(game: KuldvillakGame): void {
    const dataStr = JSON.stringify(game, null, 2);
    const blob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(blob);

    const link = document.createElement('a');
    link.href = url;
    link.download = `${game.name.replace(/[^a-z0-9]/gi, '_')}_kuldvillak.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}

/**
 * Import a game from a JSON file
 */
export async function importKuldvillakGame(file: File): Promise<KuldvillakGame | null> {
    try {
        const text = await file.text();
        const game: KuldvillakGame = JSON.parse(text);

        // Validate basic structure
        if (!game.id || !game.name || !game.rounds || !game.settings) {
            throw new Error('Invalid game file structure');
        }

        // Assign new ID to avoid conflicts
        game.id = crypto.randomUUID();
        game.createdAt = new Date().toISOString();
        game.updatedAt = new Date().toISOString();

        if (saveKuldvillakGame(game)) {
            return game;
        }
        return null;
    } catch (e) {
        console.error('Failed to import game:', e);
        return null;
    }
}

// ============================================
// Storage Stats
// ============================================

/**
 * Get approximate storage usage
 */
export function getStorageStats(): { used: number; available: number } {
    if (typeof localStorage === 'undefined') {
        return { used: 0, available: 0 };
    }

    let used = 0;
    for (const key in localStorage) {
        if (localStorage.hasOwnProperty(key)) {
            used += localStorage.getItem(key)?.length ?? 0;
        }
    }

    // localStorage typically has ~5MB limit
    const available = 5 * 1024 * 1024 - used;

    return { used, available };
}
