<script lang="ts">
    import { createEventDispatcher } from 'svelte';
    import { type Map, GameplayModifiers_GameOptions, Push_SongFinished, RealtimeScore } from 'moons-ta-client';
    import type { BeatSaverMap } from '$lib/services/beatsaver.js';
    import { type ScoreWithAccuracy, type PreviousResults, MapDifficulty } from '$lib/interfaces/match.interfaces';

    export let maps: PreviousResults[] = [];

    const dispatch = createEventDispatcher();

    const modifierNameMap: Record<number, string> = {
        [GameplayModifiers_GameOptions.None]: "",
        [GameplayModifiers_GameOptions.NoFail]: "No Fail",
        [GameplayModifiers_GameOptions.NoBombs]: "No Bombs",
        [GameplayModifiers_GameOptions.NoArrows]: "No Arrows",
        [GameplayModifiers_GameOptions.NoObstacles]: "No Walls",
        [GameplayModifiers_GameOptions.SlowSong]: "Slower Song",
        [GameplayModifiers_GameOptions.InstaFail]: "One Life",
        [GameplayModifiers_GameOptions.FailOnClash]: "Fail on Clash",
        [GameplayModifiers_GameOptions.BatteryEnergy]: "Four Lives",
        [GameplayModifiers_GameOptions.FastNotes]: "Fast Notes",
        [GameplayModifiers_GameOptions.FastSong]: "Faster Song",
        [GameplayModifiers_GameOptions.DisappearingArrows]: "Disappearing Arrows",
        [GameplayModifiers_GameOptions.GhostNotes]: "Ghost Notes",
        [GameplayModifiers_GameOptions.DemoNoFail]: "Demo No Fail",
        [GameplayModifiers_GameOptions.DemoNoObstacles]: "Demo No Obstacles",
        [GameplayModifiers_GameOptions.StrictAngles]: "Strict Angles",
        [GameplayModifiers_GameOptions.ProMode]: "Pro Mode",
        [GameplayModifiers_GameOptions.ZenMode]: "Zen Mode",
        [GameplayModifiers_GameOptions.SmallCubes]: "Small Notes",
        [GameplayModifiers_GameOptions.SuperFastSong]: "Super Fast Song"
    };

    function handleRemoveFromHistory(map: PreviousResults) {
        dispatch('removeFromHistory', { map });
    }

    function handleAddBackToQueue(map: PreviousResults) {
        dispatch('addBackToQueue', { map });
    }

    function handleCopyScores(map: PreviousResults) {
        const mapName = map.beatsaverData.name || 'Unknown Song';
        const artist = map.beatsaverData.metadata?.songAuthorName || 'Unknown Artist';
        const difficulty = getDifficultyName(map.taData.gameplayParameters?.beatmap?.difficulty || 0);
        
        let discordMessage = `**${mapName}** by ${artist}\n`;
        discordMessage += `**Difficulty:** ${difficulty}\n\n`;
        
        // Sort scores by total score (descending)
        const sortedScores = [...map.scores].sort((a, b) => b.score - a.score);
        
        sortedScores.forEach((score, index) => {
            const position = index + 1;
            const positionText = position === 1 ? '1st' : position === 2 ? '2nd' : position === 3 ? '3rd' : `${position}th`;
            const displayName = score.player?.name || score.player?.discordInfo?.username;
            
            discordMessage += `**${positionText} ${displayName}**\n`;
            discordMessage += `Score: ${score.score.toLocaleString()}\n`;
            discordMessage += `Accuracy: ${score.accuracy}%\n`;
            discordMessage += `Misses: ${score.misses} | Bad Cuts: ${score.badCuts}\n\n`;
        });
        
        navigator.clipboard.writeText(discordMessage).then(() => {
            console.log('Scores copied to clipboard');
        });
    }

    function handleShowDetails(map: PreviousResults) {
        dispatch('showMapDetails', { map });
    }

    function getActiveModifiersCompact(gameplayModifiers: number): string[] {
        const activeModifiers: string[] = [];
        const values = Object.values(GameplayModifiers_GameOptions)
            .filter((value): value is number => 
                typeof value === 'number' && 
                value !== GameplayModifiers_GameOptions.None &&
                value > 0
            )
            .sort((a, b) => a - b);
        
        for (const value of values) {
            if ((gameplayModifiers & value) === value) {
                const name = modifierNameMap[value];
                if (name && name.trim() !== "") {
                    activeModifiers.push(name);
                }
            }
        }
        
        return activeModifiers;
    }

    function getModifierArray(map: PreviousResults): string[] {
        if (map.taData.gameplayParameters?.gameplayModifiers?.options == 0) {
            return [];
        }
        return getActiveModifiersCompact(map.taData.gameplayParameters?.gameplayModifiers?.options || 0);
    }

    function getDifficultyName(difficulty: number): string {
        return MapDifficulty[difficulty] || 'Unknown';
    }

    function formatTime(date: Date): string {
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }

    function getCompletionTypeClass(type: string): string {
        switch (type) {
            case 'Completed':
                return 'completion-completed';
            case 'Still Awaiting Scores':
                return 'completion-awaiting';
            case 'Exited To Menu':
                return 'completion-exited';
            default:
                return 'completion-unknown';
        }
    }

    function getCompletionTypeIcon(type: string): string {
        switch (type) {
            case 'Completed':
                return 'check_circle';
            case 'Still Awaiting Scores':
                return 'schedule';
            case 'Exited To Menu':
                return 'exit_to_app';
            default:
                return 'help';
        }
    }
</script>

<div class="previously-played">
    <div class="history-header">
        <h3>Previously Played ({maps.length})</h3>
    </div>

    {#if maps.length === 0}
        <div class="empty-state">
            <span class="material-icons">history</span>
            <p>No maps played yet</p>
            <p class="empty-subtitle">Completed maps will appear here</p>
        </div>
    {:else}
        <div class="maps-list">
            {#each maps as map}
                <div class="map-card">
                    <div class="map-cover">
                        <img 
                            src={map.beatsaverData.versions[0]?.coverURL || '/default-song-cover.png'} 
                            alt="Map Cover" 
                        />
                    </div>
                    <div class="map-info">
                        <h4 class="map-title">{map.beatsaverData.name || 'Unknown Song'}</h4>
                        <p class="map-artist">{map.beatsaverData.metadata?.songAuthorName || 'Unknown Artist'}</p>
                        <div class="map-details">
                            <span class="difficulty-badge difficulty-{map.taData.gameplayParameters?.beatmap?.difficulty}">
                                {getDifficultyName(map.taData.gameplayParameters?.beatmap?.difficulty || 0)}
                            </span>
                            <span class="completion-tag {getCompletionTypeClass(map.completionType)}">
                                <span class="material-icons">{getCompletionTypeIcon(map.completionType)}</span>
                                {map.completionType}
                            </span>
                            {#if getModifierArray(map).length > 0}
                                <div class="modifiers">
                                    {#each getModifierArray(map) as modifier}
                                        <span class="modifier-tag">{modifier}</span>
                                    {/each}
                                </div>
                            {/if}
                        </div>
                        <div class="score-summary">
                            {#if map.scores.length > 0}
                                {@const topScore = map.scores.reduce((max, score) => score.score > max.score ? score : max)}
                                <span class="top-score">
                                    <span class="material-icons">emoji_events</span>
                                    {topScore.player?.name || topScore.player?.discordInfo?.username}: {topScore.accuracy.toString()}%
                                </span>
                            {/if}
                        </div>
                    </div>
                    <div class="map-actions">
                        <button 
                            class="action-button details-button" 
                            on:click={() => handleShowDetails(map)}
                            title="Show Details"
                        >
                            <span class="material-icons">info</span>
                        </button>
                        <button 
                            class="action-button copy-scores" 
                            on:click={() => handleCopyScores(map)}
                            title="Copy Scores to Clipboard"
                        >
                            <span class="material-icons">content_copy</span>
                        </button>
                        <button 
                            class="action-button add-back" 
                            on:click={() => handleAddBackToQueue(map)}
                            title="Add Back to Queue"
                        >
                            <span class="material-icons">add</span>
                        </button>
                        <button 
                            class="action-button remove-history" 
                            on:click={() => handleRemoveFromHistory(map)}
                            title="Remove from History"
                        >
                            <span class="material-icons">delete</span>
                        </button>
                    </div>
                </div>
            {/each}
        </div>
    {/if}
</div>

<style>
    .previously-played {
        background-color: var(--bg-secondary);
        border-radius: 0.75rem;
        padding: 1.5rem;
        height: fit-content;
    }

    .history-header {
        margin-bottom: 1.5rem;
    }

    .history-header h3 {
        font-size: 1.25rem;
        font-weight: 500;
        margin: 0;
        color: var(--text-primary);
    }

    .action-button {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.375rem;
        border-radius: 0.375rem;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        border: none;
        font-size: 0.875rem;
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
    }

    .action-button.details-button:hover {
        background-color: var(--accent-color);
        color: white;
        box-shadow: 0 0 10px var(--accent-glow);
    }

    .action-button.copy-scores:hover {
        background-color: var(--bg-primary);
        color: var(--accent-color);
    }

    .action-button.add-back:hover {
        background-color: var(--accent-color);
        color: white;
        box-shadow: 0 0 10px var(--accent-glow);
    }

    .action-button.remove-history:hover {
        background-color: var(--danger-color);
        color: white;
        box-shadow: 0 0 10px rgba(239, 68, 68, 0.3);
    }

    .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 3rem 1rem;
        color: var(--text-secondary);
        gap: 0.75rem;
        text-align: center;
    }

    .empty-state .material-icons {
        font-size: 3rem;
        opacity: 0.6;
        color: var(--text-secondary);
    }

    .empty-state p {
        margin: 0;
        font-size: 1rem;
    }

    .empty-subtitle {
        font-size: 0.875rem !important;
        opacity: 0.8;
    }

    .maps-list {
        display: flex;
        flex-direction: column;
        gap: 1rem;
        max-height: 60vh;
        overflow-y: auto;
    }

    .map-card {
        display: flex;
        align-items: center;
        gap: 1rem;
        padding: 1rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.5rem;
        transition: all 0.2s ease;
    }

    .map-card:hover {
        background-color: var(--bg-primary);
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }

    .map-cover {
        width: 3rem;
        height: 3rem;
        border-radius: 0.375rem;
        overflow: hidden;
        flex-shrink: 0;
    }

    .map-cover img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .map-info {
        flex: 1;
        min-width: 0;
    }

    .map-title {
        font-size: 1rem;
        font-weight: 500;
        margin: 0 0 0.25rem 0;
        color: var(--text-primary);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .map-artist {
        color: var(--text-secondary);
        font-size: 0.875rem;
        margin: 0 0 0.5rem 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .map-details {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        flex-wrap: wrap;
        margin-bottom: 0.5rem;
    }

    .difficulty-badge {
        padding: 0.125rem 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.75rem;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }

    .difficulty-0 { background-color: #10B981; color: white; } /* Easy - Green */
    .difficulty-1 { background-color: #3B82F6; color: white; } /* Normal - Blue */
    .difficulty-2 { background-color: #F59E0B; color: white; } /* Hard - Yellow */
    .difficulty-3 { background-color: #EF4444; color: white; } /* Expert - Red */
    .difficulty-4 { background-color: #8B5CF6; color: white; } /* Expert+ - Purple */

    .played-time {
        padding: 0.125rem 0.5rem;
        background-color: rgba(156, 163, 175, 0.1);
        color: var(--text-secondary);
        border-radius: 0.25rem;
        font-size: 0.75rem;
        font-weight: 500;
    }

    .completion-tag {
        display: flex;
        align-items: center;
        gap: 0.25rem;
        padding: 0.125rem 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.75rem;
        font-weight: 500;
    }

    .completion-completed {
        background-color: rgba(16, 185, 129, 0.1);
        color: #10B981;
        border: 1px solid rgba(16, 185, 129, 0.2);
    }

    .completion-awaiting {
        background-color: rgba(245, 158, 11, 0.1);
        color: #F59E0B;
        border: 1px solid rgba(245, 158, 11, 0.2);
    }

    .completion-exited {
        background-color: rgba(239, 68, 68, 0.1);
        color: #EF4444;
        border: 1px solid rgba(239, 68, 68, 0.2);
    }

    .completion-unknown {
        background-color: rgba(156, 163, 175, 0.1);
        color: var(--text-secondary);
        border: 1px solid rgba(156, 163, 175, 0.2);
    }

    .completion-tag .material-icons {
        font-size: 16px;
    }

    .modifiers {
        display: flex;
        gap: 0.25rem;
        flex-wrap: wrap;
    }

    .modifier-tag {
        padding: 0.125rem 0.375rem;
        background-color: rgba(79, 70, 229, 0.1);
        color: var(--accent-color);
        border-radius: 0.25rem;
        font-size: 0.625rem;
        font-weight: 500;
        border: 1px solid rgba(79, 70, 229, 0.2);
    }

    .score-summary {
        font-size: 0.75rem;
        color: var(--text-secondary);
    }

    .top-score {
        display: flex;
        align-items: center;
        gap: 0.25rem;
        background-color: rgba(251, 191, 36, 0.1);
        color: #F59E0B;
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        font-weight: 500;
    }

    .top-score .material-icons {
        font-size: 16px;
    }

    .map-actions {
        display: flex;
        gap: 0.5rem;
        flex-shrink: 0;
    }

    .material-icons {
        font-family: 'Material Icons';
        font-weight: normal;
        font-style: normal;
        font-size: 20px;
        line-height: 1;
        letter-spacing: normal;
        text-transform: none;
        display: inline-block;
        white-space: nowrap;
        word-wrap: normal;
        direction: ltr;
        -webkit-font-feature-settings: 'liga';
        -webkit-font-smoothing: antialiased;
    }

    /* Scrollbar Styling */
    .maps-list::-webkit-scrollbar {
        width: 0.375rem;
    }

    .maps-list::-webkit-scrollbar-track {
        background: var(--bg-primary);
        border-radius: 0.375rem;
    }

    .maps-list::-webkit-scrollbar-thumb {
        background: var(--bg-tertiary);
        border-radius: 0.375rem;
    }

    .maps-list::-webkit-scrollbar-thumb:hover {
        background: var(--text-secondary);
    }

    /* Responsive Design */
    @media (max-width: 768px) {
        .map-card {
            flex-direction: column;
            text-align: center;
            gap: 0.75rem;
        }

        .map-info {
            text-align: center;
        }

        .map-title,
        .map-artist {
            white-space: normal;
            overflow: visible;
            text-overflow: unset;
        }

        .map-details {
            justify-content: center;
        }

        .map-actions {
            flex-wrap: wrap;
            justify-content: center;
        }
    }
</style>