import { ActionFormData } from '@minecraft/server-ui';
/**
 * UI handler for time tracking and leaderboards
 */
export class TimeTrackerUI {
    timeTracker;
    constructor(timeTracker) {
        this.timeTracker = timeTracker;
    }
    /**
     * Show main time tracker menu
     */
    async showMainMenu(player) {
        const session = this.timeTracker.getActiveSession(player);
        let bodyText = "§6=== Time Tracker Menu ===\n\n";
        if (session && session.isActive) {
            const elapsed = Date.now() - session.startTime;
            bodyText += `§a⏱ Active Run in Progress\n`;
            bodyText += `§7Time: §f${this.formatElapsedTime(elapsed)}\n`;
            bodyText += `§7Current Area: §f${session.currentAreaId}\n`;
            bodyText += `§7Segments: §f${session.segmentTimes.length}\n\n`;
        }
        else {
            bodyText += `§7No active run\n\n`;
        }
        const form = new ActionFormData()
            .title("My Statistics")
            .body(bodyText)
            .button("§9View Leaderboard\n§8Click Here")
            .button("§9My Stats\n§8Click Here")
            .button("§9Current Run Info\n§8Click Here");
        if (session && session.isActive) {
            form.button("§9Cancel Run\n§8Click Here");
        }
        form.button("§l§cExit Menu§r\n§8Click Here");
        try {
            const response = await form.show(player);
            if (response.canceled)
                return;
            const hasActiveRun = session && session.isActive;
            const cancelButtonIndex = hasActiveRun ? 3 : -1;
            switch (response.selection) {
                case 0: // View Leaderboard
                    await this.showLeaderboard(player);
                    break;
                case 1: // My Stats
                    await this.showPlayerStats(player);
                    break;
                case 2: // Current Run Info
                    if (hasActiveRun) {
                        await this.showCurrentRunInfo(player, session);
                    }
                    else {
                        player.sendMessage("§cNo active run!");
                    }
                    break;
                case 3: // Cancel Run (if active)
                    if (hasActiveRun) {
                        this.timeTracker.cancelPlayerRun(player);
                    }
                    break;
            }
        }
        catch (error) {
            player.sendMessage("§cError showing menu!");
        }
    }
    /**
     * Show leaderboard with top times
     */
    async showLeaderboard(player, page = 0) {
        const leaderboard = this.timeTracker.getLeaderboard();
        const pageSize = 10;
        const totalPages = Math.ceil(leaderboard.length / pageSize);
        const startIndex = page * pageSize;
        const endIndex = Math.min(startIndex + pageSize, leaderboard.length);
        if (leaderboard.length === 0) {
            const form = new ActionFormData()
                .title("Leaderboard")
                .body("§7No completed runs yet!\n\n§eComplete the course to set the first record!")
                .button("§l§cExit Menu§r\n§8Click Here");
            try {
                await form.show(player);
            }
            catch (error) {
                // Error showing form
            }
            return;
        }
        let bodyText = `§6§l=== LEADERBOARD ===§r\n`;
        bodyText += `§7Page ${page + 1} of ${totalPages}\n\n`;
        // Display leaderboard entries for current page
        for (let i = startIndex; i < endIndex; i++) {
            const entry = leaderboard[i];
            const timeFormatted = this.timeTracker.formatTimeCompact(entry.totalTime);
            const isCurrentPlayer = entry.playerId === player.id;
            // Medal emojis for top 3
            let prefix = `§7${entry.rank}.`;
            if (entry.rank === 1)
                prefix = "§6🥇";
            else if (entry.rank === 2)
                prefix = "§f🥈";
            else if (entry.rank === 3)
                prefix = "§c🥉";
            const highlight = isCurrentPlayer ? "§a→ " : "";
            bodyText += `${highlight}${prefix} §f${entry.playerName}§r - §e${timeFormatted}\n`;
        }
        const form = new ActionFormData()
            .title("Leaderboard")
            .body(bodyText);
        // Add pagination buttons
        if (page > 0) {
            form.button("§9← Previous Page\n§8Click Here");
        }
        if (page < totalPages - 1) {
            form.button("§9Next Page →\n§8Click Here");
        }
        form.button("§9View My Stats\n§8Click Here");
        form.button("§l§cExit Menu§r\n§8Click Here");
        try {
            const response = await form.show(player);
            if (response.canceled)
                return;
            let buttonIndex = 0;
            // Handle Previous Page button
            if (page > 0) {
                if (response.selection === buttonIndex) {
                    await this.showLeaderboard(player, page - 1);
                    return;
                }
                buttonIndex++;
            }
            // Handle Next Page button
            if (page < totalPages - 1) {
                if (response.selection === buttonIndex) {
                    await this.showLeaderboard(player, page + 1);
                    return;
                }
                buttonIndex++;
            }
            // Handle View My Stats button
            if (response.selection === buttonIndex) {
                await this.showPlayerStats(player);
                return;
            }
            buttonIndex++;
            // Handle Back button
            if (response.selection === buttonIndex) {
                await this.showMainMenu(player);
            }
        }
        catch (error) {
            player.sendMessage("§cError showing leaderboard!");
        }
    }
    /**
     * Show player's personal statistics
     */
    async showPlayerStats(player) {
        const runs = this.timeTracker.getPlayerRuns(player.id);
        const leaderboard = this.timeTracker.getLeaderboard();
        const playerRank = leaderboard.findIndex(entry => entry.playerId === player.id);
        let bodyText = `§6=== ${player.name}'s Stats ===§r\n\n`;
        if (runs.length === 0) {
            bodyText += "§7No completed runs yet!\n\n";
            bodyText += "§eEnter a starting area to begin your first run!";
        }
        else {
            const bestRun = runs.reduce((best, run) => run.totalDuration < best.totalDuration ? run : best);
            bodyText += `§bTotal Runs: §f${runs.length}\n`;
            if (playerRank >= 0) {
                bodyText += `§bLeaderboard Rank: §f#${playerRank + 1}\n`;
            }
            else {
                bodyText += `§bLeaderboard Rank: §7Not ranked\n`;
            }
            bodyText += `§bBest Time: §f${this.timeTracker.formatTimeCompact(bestRun.totalDuration)}\n`;
            // Calculate average time
            const totalTime = runs.reduce((sum, run) => sum + run.totalDuration, 0);
            const avgTime = totalTime / runs.length;
            bodyText += `§bAverage Time: §f${this.timeTracker.formatTimeCompact(avgTime)}\n\n`;
            bodyText += `§e§lRecent Runs:\n`;
            const recentRuns = runs.slice(0, 5);
            for (let i = 0; i < recentRuns.length; i++) {
                const run = recentRuns[i];
                const timeFormatted = this.timeTracker.formatTimeCompact(run.totalDuration);
                const date = new Date(run.completedAt).toLocaleDateString();
                const isBest = run.runId === bestRun.runId ? " §a★" : "";
                bodyText += `§7${i + 1}. ${timeFormatted} - ${date}${isBest}\n`;
            }
        }
        const form = new ActionFormData()
            .title("My Statistics")
            .body(bodyText);
        if (runs.length > 0) {
            form.button("§9View All Runs\n§8Click Here");
        }
        form.button("§9View Leaderboard\n§8Click Here");
        form.button("§l§cExit Menu§r\n§8Click Here");
        try {
            const response = await form.show(player);
            if (response.canceled)
                return;
            let buttonIndex = 0;
            if (runs.length > 0) {
                if (response.selection === buttonIndex) {
                    await this.showAllPlayerRuns(player);
                    return;
                }
                buttonIndex++;
            }
            if (response.selection === buttonIndex) {
                await this.showLeaderboard(player);
                return;
            }
            buttonIndex++;
            // Exit Menu button - just return (closes menu)
        }
        catch (error) {
            player.sendMessage("§cError showing stats!");
        }
    }
    /**
     * Show all runs for a player
     */
    async showAllPlayerRuns(player, page = 0) {
        const runs = this.timeTracker.getPlayerRuns(player.id);
        const pageSize = 8;
        const totalPages = Math.ceil(runs.length / pageSize);
        const startIndex = page * pageSize;
        const endIndex = Math.min(startIndex + pageSize, runs.length);
        let bodyText = `§6=== All Your Runs ===§r\n`;
        bodyText += `§7Page ${page + 1} of ${totalPages}\n`;
        bodyText += `§7Total: ${runs.length} runs\n\n`;
        for (let i = startIndex; i < endIndex; i++) {
            const run = runs[i];
            const timeFormatted = this.timeTracker.formatTimeCompact(run.totalDuration);
            const date = new Date(run.completedAt).toLocaleString();
            bodyText += `§7${i + 1}. §f${timeFormatted}\n   §8${date}\n   §7Segments: ${run.segmentTimes.length}\n\n`;
        }
        const form = new ActionFormData()
            .title("All Runs")
            .body(bodyText);
        if (page > 0) {
            form.button("§9← Previous Page\n§8Click Here");
        }
        if (page < totalPages - 1) {
            form.button("§9Next Page →\n§8Click Here");
        }
        form.button("§l§cExit Menu§r\n§8Click Here");
        try {
            const response = await form.show(player);
            if (response.canceled)
                return;
            let buttonIndex = 0;
            if (page > 0) {
                if (response.selection === buttonIndex) {
                    await this.showAllPlayerRuns(player, page - 1);
                    return;
                }
                buttonIndex++;
            }
            if (page < totalPages - 1) {
                if (response.selection === buttonIndex) {
                    await this.showAllPlayerRuns(player, page + 1);
                    return;
                }
                buttonIndex++;
            }
            if (response.selection === buttonIndex) {
                await this.showPlayerStats(player);
            }
        }
        catch (error) {
            player.sendMessage("§cError showing runs!");
        }
    }
    /**
     * Show current active run information
     */
    async showCurrentRunInfo(player, session) {
        const elapsed = Date.now() - session.startTime;
        let bodyText = `§a§l⏱ ACTIVE RUN§r\n\n`;
        bodyText += `§bElapsed Time: §f${this.formatElapsedTime(elapsed)}\n`;
        bodyText += `§bSegments Completed: §f${session.segmentTimes.length}\n\n`;
        if (session.segmentTimes.length > 0) {
            bodyText += `§e§lSegment Times:\n`;
            for (let i = 0; i < session.segmentTimes.length; i++) {
                const segment = session.segmentTimes[i];
                const segmentTime = this.timeTracker.formatTimeCompact(segment.duration);
                bodyText += `§7${i + 1}. ${segment.fromAreaName} → ${segment.toAreaName}\n`;
                bodyText += `   §f${segmentTime}\n`;
            }
        }
        else {
            bodyText += `§7No segments completed yet.\n§7Keep going to reach the next checkpoint!`;
        }
        const form = new ActionFormData()
            .title("Current Run")
            .body(bodyText)
            .button("§9Refresh\n§8Click Here")
            .button("§9Cancel Run\n§8Click Here")
            .button("§l§cExit Menu§r\n§8Click Here");
        try {
            const response = await form.show(player);
            if (response.canceled)
                return;
            switch (response.selection) {
                case 0: // Refresh
                    const updatedSession = this.timeTracker.getActiveSession(player);
                    if (updatedSession) {
                        await this.showCurrentRunInfo(player, updatedSession);
                    }
                    else {
                        player.sendMessage("§cRun is no longer active!");
                    }
                    break;
                case 1: // Cancel Run
                    this.timeTracker.cancelPlayerRun(player);
                    break;
                case 2: // Back
                    await this.showMainMenu(player);
                    break;
            }
        }
        catch (error) {
            player.sendMessage("§cError showing run info!");
        }
    }
    /**
     * Format elapsed time for display
     */
    formatElapsedTime(milliseconds) {
        const totalSeconds = Math.floor(milliseconds / 1000);
        const minutes = Math.floor(totalSeconds / 60);
        const seconds = totalSeconds % 60;
        return `${minutes}:${seconds.toString().padStart(2, '0')}`;
    }
}
