// ============================================
// Game Data Persistence Layer
// ============================================

import type { KuldvillakGame, GameMetadata } from '$lib/types/kuldvillak';
import { storage, STORAGE_KEYS } from '$lib/services';
import { toastStore } from './toast.svelte';

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

/**
 * Get all saved Kuldvillak games metadata (lightweight list)
 */
export function getKuldvillakGamesList(): GameMetadata[] {
    try {
        const games = storage.get<KuldvillakGame[]>(STORAGE_KEYS.GAMES_LIST);
        if (!games) return [];

        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);
        toastStore.error('Failed to load games list');
        return [];
    }
}

/**
 * Get all saved Kuldvillak games (full data)
 */
export function getAllKuldvillakGames(): KuldvillakGame[] {
    try {
        return storage.get<KuldvillakGame[]>(STORAGE_KEYS.GAMES_LIST) ?? [];
    } catch (e) {
        console.error('Failed to load games:', e);
        toastStore.error('Failed to load games');
        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 {
    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);
        }

        storage.set(STORAGE_KEYS.GAMES_LIST, games);
        return true;
    } catch (e) {
        console.error('Failed to save game:', e);
        toastStore.error('Failed to save game');
        return false;
    }
}

/**
 * Delete a Kuldvillak game by ID
 */
export function deleteKuldvillakGame(gameId: string): boolean {
    try {
        const games = getAllKuldvillakGames();
        const filtered = games.filter((g) => g.id !== gameId);
        storage.set(STORAGE_KEYS.GAMES_LIST, filtered);
        return true;
    } catch (e) {
        console.error('Failed to delete game:', e);
        toastStore.error('Failed to delete game');
        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: 'intro',
        currentRoundIndex: 0
    };

    // 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 (gameId) {
        storage.set('kuldvillak-active-game', gameId);
    } else {
        storage.remove('kuldvillak-active-game');
    }
}

/**
 * Get the ID of the last active game
 */
export function getActiveKuldvillakGameId(): string | null {
    return storage.get<string>('kuldvillak-active-game');
}

/**
 * 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);
        toastStore.error('Failed to import game: Invalid file format');
        return null;
    }
}

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

/**
 * Get approximate storage usage
 * Note: This function still accesses localStorage directly for stats
 */
export function getStorageStats(): { used: number; available: number } {
    if (typeof localStorage === 'undefined') {
        return { used: 0, available: 0 };
    }

    let used = 0;
    for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key) {
            used += (localStorage.getItem(key)?.length ?? 0) * 2; // UTF-16 = 2 bytes per char
        }
    }

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

    return { used, available };
}
