<script lang="ts">
    import { createEventDispatcher } from 'svelte';
    import { type Map, GameplayModifiers_GameOptions, Push_SongFinished } 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 mapData: PreviousResults | null;
    export let isVisible: boolean = false;

    const dispatch = createEventDispatcher();

    // Copy options
    let includeMapInfo = true;
    let includeEndTime = false;
    let includeMisses = true;
    let includeBadCuts = true;
    let includeAccuracy = true;

    // Modifiers mapping
    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 closePopup() {
        dispatch('close');
    }

    function getActiveModifiers(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 getDifficultyName(difficulty: number): string {
        return MapDifficulty[difficulty] || 'Unknown';
    }

    function formatTime(seconds: number): string {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = Math.floor(seconds % 60);
        return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
    }

    function formatBPM(bpm: number): string {
        return Math.round(bpm).toString();
    }

    function getCompletionStatus(score: ScoreWithAccuracy, songDuration: number): string {
        const timeDifference = Math.abs(score.endTime - songDuration);
        if (timeDifference <= 2) {
            return 'Completed';
        } else {
            return `Exited early at: ${formatTime(score.endTime)}`;
        }
    }

    function isCompleted(score: ScoreWithAccuracy, songDuration: number): boolean {
        const timeDifference = Math.abs(score.endTime - songDuration);
        return timeDifference <= 2;
    }

    function copyScoresToClipboard() {
        const mapName = mapData!.beatsaverData.name || 'Unknown Song';
        const artist = mapData!.beatsaverData.metadata?.songAuthorName || 'Unknown Artist';
        const difficulty = getDifficultyName(mapData!.taData.gameplayParameters?.beatmap?.difficulty || 0);
        const songDuration = mapData!.beatsaverData.metadata?.duration || 0;
        
        let discordMessage = '';
        
        if (includeMapInfo) {
            discordMessage += `## **${mapName}** by ${artist}\n`;
            discordMessage += `**Difficulty:** ${difficulty}\n`;
            
            const modifiers = getActiveModifiers(mapData!.taData.gameplayParameters?.gameplayModifiers?.options || 0);
            if (modifiers.length > 0) {
                discordMessage += `**Modifiers:** ${modifiers.join(', ')}\n`;
            }
            
            discordMessage += '\n';
        }
        
        // Sort scores by total score (descending)
        const sortedScores = [...mapData!.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 || 'Unknown Player';
            
            discordMessage += `**${positionText} ${displayName}**\n`;
            discordMessage += `Score: ${score.score.toLocaleString()}`;
            
            if (includeAccuracy) {
                discordMessage += ` | Accuracy: ${score.accuracy}%\n`;
            }
            
            if (includeEndTime) {
                discordMessage += `-# `;
                const completionStatus = getCompletionStatus(score, songDuration);
                discordMessage += `Status: ${completionStatus}\n`;
            }

            if (includeMisses || includeBadCuts) {
                let errorLine = '';
                if (includeMisses) errorLine += `Misses: ${score.misses}`;
                if (includeMisses && includeBadCuts) errorLine += ' | ';
                if (includeBadCuts) errorLine += `Bad Cuts: ${score.badCuts}`;
                discordMessage += `${errorLine}\n`;
            }
            
            discordMessage += '\n';
        });
        
        navigator.clipboard.writeText(discordMessage).then(() => {
            console.log('Scores copied to clipboard');
        });
    }

    $: activeModifiers = getActiveModifiers(mapData?.taData.gameplayParameters?.gameplayModifiers?.options || 0);
    $: sortedScores = mapData?.scores ? [...mapData.scores].sort((a, b) => b.score - a.score) : [];
    $: songDuration = mapData?.beatsaverData.metadata?.duration || 0;
    $: isAwaitingScores = mapData?.completionType === 'Still Awaiting Scores';
</script>

{#if isVisible && mapData}
    <!-- svelte-ignore a11y-no-static-element-interactions -->
    <!-- svelte-ignore a11y-click-events-have-key-events -->
    <div class="popup-overlay" on:click={closePopup}>
        <div class="popup-content" on:click|stopPropagation>
            <!-- Header -->
            <div class="popup-header">
                <div class="header-content">
                    <div class="map-cover">
                        <img 
                            src={mapData.beatsaverData.versions[0]?.coverURL || '/default-song-cover.png'} 
                            alt="Map Cover" 
                        />
                    </div>
                    <div class="map-info">
                        <h2 class="map-title">{mapData.beatsaverData.name || 'Unknown Song'}</h2>
                        <p class="map-artist">{mapData.beatsaverData.metadata?.songAuthorName || 'Unknown Artist'}</p>
                        <p class="map-mapper">Mapped by {mapData.beatsaverData.metadata?.levelAuthorName || 'Unknown Mapper'}</p>
                    </div>
                </div>
                <button class="close-button" on:click={closePopup}>
                    <span class="material-icons">close</span>
                </button>
            </div>

            <!-- Awaiting Scores Indicator -->
            {#if isAwaitingScores}
                <div class="awaiting-scores">
                    <div class="loader"></div>
                    <span>Still awaiting scores...</span>
                </div>
            {/if}

            <!-- Map Details -->
            <div class="map-details-section">
                <h3>Map Details</h3>
                <div class="details-grid">
                    <div class="detail-item">
                        <span class="material-icons">schedule</span>
                        <span class="detail-label">Duration</span>
                        <span class="detail-value">{formatTime(songDuration)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="material-icons">speed</span>
                        <span class="detail-label">BPM</span>
                        <span class="detail-value">{formatBPM(mapData.beatsaverData.metadata?.bpm || 0)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="material-icons">star</span>
                        <span class="detail-label">Difficulty</span>
                        <span class="detail-value difficulty-badge difficulty-{mapData.taData.gameplayParameters?.beatmap?.difficulty}">
                            {getDifficultyName(mapData.taData.gameplayParameters?.beatmap?.difficulty || 0)}
                        </span>
                    </div>
                </div>
                
                {#if activeModifiers.length > 0}
                    <div class="modifiers-section">
                        <h4>Active Modifiers</h4>
                        <div class="modifiers-list">
                            {#each activeModifiers as modifier}
                                <span class="modifier-tag">
                                    <span class="material-icons">tune</span>
                                    {modifier}
                                </span>
                            {/each}
                        </div>
                    </div>
                {/if}
            </div>

            <!-- Copy Options -->
            <div class="copy-options-section">
                <h3>Copy Options</h3>
                <div class="copy-controls">
                    <div class="toggle-row">
                        <label class="toggle-label">
                            <input type="checkbox" bind:checked={includeMapInfo} />
                            <span class="toggle-slider"></span>
                            Include Map Info
                        </label>
                        <label class="toggle-label">
                            <input type="checkbox" bind:checked={includeAccuracy} />
                            <span class="toggle-slider"></span>
                            Include Accuracy
                        </label>
                    </div>
                    <div class="toggle-row">
                        <label class="toggle-label">
                            <input type="checkbox" bind:checked={includeMisses} />
                            <span class="toggle-slider"></span>
                            Include Misses
                        </label>
                        <label class="toggle-label">
                            <input type="checkbox" bind:checked={includeBadCuts} />
                            <span class="toggle-slider"></span>
                            Include Bad Cuts
                        </label>
                    </div>
                    <div class="toggle-row">
                        <label class="toggle-label">
                            <input type="checkbox" bind:checked={includeEndTime} />
                            <span class="toggle-slider"></span>
                            Include End Time
                        </label>
                    </div>
                </div>
                <button class="copy-button" on:click={copyScoresToClipboard}>
                    <span class="material-icons">content_copy</span>
                    Copy Scores to Clipboard
                </button>
            </div>

            <!-- Scores Section -->
            <div class="scores-section">
                <h3>Scores ({sortedScores.length})</h3>
                {#if sortedScores.length === 0}
                    <div class="no-scores">
                        <span class="material-icons">leaderboard</span>
                        <p>No scores available</p>
                    </div>
                {:else}
                    <div class="scores-list">
                        {#each sortedScores as score, index}
                            {@const position = index + 1}
                            {@const displayName = score.player?.name || score.player?.discordInfo?.username || 'Unknown Player'}
                            {@const completed = isCompleted(score, songDuration)}
                            <div class="score-card {completed ? 'completed' : 'exited-early'}">
                                <div class="score-position">
                                    <span class="position-number">{position}</span>
                                    <span class="position-suffix">{position === 1 ? 'st' : position === 2 ? 'nd' : position === 3 ? 'rd' : 'th'}</span>
                                </div>
                                <div class="score-info">
                                    <div class="player-name">{displayName}</div>
                                    <div class="score-stats">
                                        <div class="stat-item primary">
                                            <span class="material-icons">emoji_events</span>
                                            <span class="stat-value">{score.score.toLocaleString()}</span>
                                        </div>
                                        <div class="stat-item">
                                            <span class="material-icons">percent</span>
                                            <span class="stat-value">{score.accuracy}%</span>
                                        </div>
                                        <div class="stat-item error">
                                            <span class="material-icons">close</span>
                                            <span class="stat-value">{score.misses}</span>
                                        </div>
                                        <div class="stat-item error">
                                            <span class="material-icons">content_cut</span>
                                            <span class="stat-value">{score.badCuts}</span>
                                        </div>
                                    </div>
                                    <div class="completion-status">
                                        <span class="material-icons">
                                            {completed ? 'check_circle' : 'exit_to_app'}
                                        </span>
                                        <span class="status-text">
                                            {getCompletionStatus(score, songDuration)}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        {/each}
                    </div>
                {/if}
            </div>
        </div>
    </div>
{/if}

<style>
    .popup-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1000;
        padding: 1rem;
    }

    .popup-content {
        background-color: var(--bg-secondary);
        border-radius: 1rem;
        max-width: 800px;
        width: 100%;
        max-height: 90vh;
        overflow-y: auto;
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    }

    .popup-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 1.5rem;
        border-bottom: 1px solid var(--bg-tertiary);
    }

    .header-content {
        display: flex;
        align-items: center;
        gap: 1rem;
        flex: 1;
    }

    .map-cover {
        width: 4rem;
        height: 4rem;
        border-radius: 0.5rem;
        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: 1.5rem;
        font-weight: 600;
        margin: 0 0 0.25rem 0;
        color: var(--text-primary);
    }

    .map-artist {
        font-size: 1rem;
        color: var(--text-secondary);
        margin: 0 0 0.25rem 0;
    }

    .map-mapper {
        font-size: 0.875rem;
        color: var(--text-tertiary);
        margin: 0;
    }

    .close-button {
        background: none;
        border: none;
        color: var(--text-secondary);
        cursor: pointer;
        padding: 0.5rem;
        border-radius: 0.375rem;
        transition: all 0.2s ease;
    }

    .close-button:hover {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
    }

    .awaiting-scores {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 1rem 1.5rem;
        background-color: rgba(245, 158, 11, 0.1);
        border: 1px solid rgba(245, 158, 11, 0.2);
        border-left: 4px solid #F59E0B;
        margin: 0 1.5rem;
        border-radius: 0.5rem;
        color: #F59E0B;
        font-weight: 500;
    }

    .loader {
        width: 1rem;
        height: 1rem;
        border: 2px solid rgba(245, 158, 11, 0.3);
        border-top: 2px solid #F59E0B;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }

    .map-details-section,
    .copy-options-section,
    .scores-section {
        padding: 1.5rem;
        border-bottom: 1px solid var(--bg-tertiary);
    }

    .scores-section {
        border-bottom: none;
    }

    .map-details-section h3,
    .copy-options-section h3,
    .scores-section h3 {
        font-size: 1.25rem;
        font-weight: 600;
        margin: 0 0 1rem 0;
        color: var(--text-primary);
    }

    .details-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 1.5rem;
    }

    .detail-item {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.5rem;
    }

    .detail-item .material-icons {
        color: var(--accent-color);
        font-size: 1.25rem;
    }

    .detail-label {
        color: var(--text-secondary);
        font-size: 0.875rem;
        font-weight: 500;
        flex: 1;
    }

    .detail-value {
        color: var(--text-primary);
        font-weight: 600;
    }

    .difficulty-badge {
        padding: 0.25rem 0.75rem;
        border-radius: 0.375rem;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    .difficulty-0 { background-color: #10B981; color: white; }
    .difficulty-1 { background-color: #3B82F6; color: white; }
    .difficulty-2 { background-color: #F59E0B; color: white; }
    .difficulty-3 { background-color: #EF4444; color: white; }
    .difficulty-4 { background-color: #8B5CF6; color: white; }

    .modifiers-section h4 {
        font-size: 1rem;
        font-weight: 500;
        margin: 0 0 0.75rem 0;
        color: var(--text-primary);
    }

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

    .modifier-tag {
        display: flex;
        align-items: center;
        gap: 0.375rem;
        padding: 0.5rem 0.75rem;
        background-color: rgba(79, 70, 229, 0.1);
        color: var(--accent-color);
        border-radius: 0.375rem;
        font-size: 0.875rem;
        font-weight: 500;
        border: 1px solid rgba(79, 70, 229, 0.2);
    }

    .modifier-tag .material-icons {
        font-size: 1rem;
    }

    .copy-controls {
        margin-bottom: 1.5rem;
    }

    .toggle-row {
        display: flex;
        gap: 2rem;
        margin-bottom: 1rem;
    }

    .toggle-label {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        cursor: pointer;
        color: var(--text-primary);
        font-weight: 500;
    }

    .toggle-label input[type="checkbox"] {
        display: none;
    }

    .toggle-slider {
        position: relative;
        width: 2.5rem;
        height: 1.5rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.75rem;
        transition: background-color 0.2s ease;
    }

    .toggle-slider::before {
        content: '';
        position: absolute;
        top: 2px;
        left: 2px;
        width: 1.25rem;
        height: 1.25rem;
        background-color: white;
        border-radius: 50%;
        transition: transform 0.2s ease;
    }

    .toggle-label input[type="checkbox"]:checked + .toggle-slider {
        background-color: var(--accent-color);
    }

    .toggle-label input[type="checkbox"]:checked + .toggle-slider::before {
        transform: translateX(1rem);
    }

    .copy-button {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem 1.5rem;
        background-color: var(--accent-color);
        color: white;
        border: none;
        border-radius: 0.5rem;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
        box-shadow: 0 0 0 0 var(--accent-glow);
    }

    .copy-button:hover {
        background-color: var(--accent-hover);
        box-shadow: 0 0 15px var(--accent-glow);
        transform: translateY(-1px);
    }

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

    .no-scores .material-icons {
        font-size: 3rem;
        opacity: 0.6;
    }

    .scores-list {
        display: flex;
        flex-direction: column;
        gap: 1rem;
    }

    .score-card {
        display: flex;
        align-items: center;
        gap: 1rem;
        padding: 1rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.75rem;
        transition: all 0.2s ease;
        border-left: 4px solid transparent;
    }

    .score-card.completed {
        border-left-color: #10B981;
    }

    .score-card.exited-early {
        border-left-color: #EF4444;
    }

    .score-card:hover {
        background-color: var(--bg-primary);
        transform: translateY(-1px);
    }

    .score-position {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 3rem;
        height: 3rem;
        background-color: var(--bg-secondary);
        border-radius: 0.5rem;
        flex-shrink: 0;
    }

    .position-number {
        font-size: 1.25rem;
        font-weight: 700;
        color: var(--text-primary);
        line-height: 1;
    }

    .position-suffix {
        font-size: 0.625rem;
        color: var(--text-secondary);
        line-height: 1;
    }

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

    .player-name {
        font-size: 1rem;
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 0.5rem;
    }

    .score-stats {
        display: flex;
        flex-wrap: wrap;
        gap: 1rem;
        margin-bottom: 0.5rem;
    }

    .stat-item {
        display: flex;
        align-items: center;
        gap: 0.375rem;
        padding: 0.25rem 0.5rem;
        background-color: var(--bg-secondary);
        border-radius: 0.375rem;
        font-size: 0.875rem;
        font-weight: 500;
    }

    .stat-item.primary {
        background-color: rgba(251, 191, 36, 0.1);
        color: #F59E0B;
    }

    .stat-item.error {
        background-color: rgba(239, 68, 68, 0.1);
        color: #EF4444;
    }

    .stat-item .material-icons {
        font-size: 1rem;
    }

    .completion-status {
        display: flex;
        align-items: center;
        gap: 0.375rem;
        font-size: 0.75rem;
        color: var(--text-secondary);
    }

    .completion-status .material-icons {
        font-size: 1rem;
    }

    .score-card.completed .completion-status {
        color: #10B981;
    }

    .score-card.exited-early .completion-status {
        color: #EF4444;
    }

    .material-icons {
        font-family: 'Material Icons';
        font-weight: normal;
        font-style: normal;
        font-size: 24px;
        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 */
    .popup-content::-webkit-scrollbar {
        width: 0.5rem;
    }

    .popup-content::-webkit-scrollbar-track {
        background: var(--bg-tertiary);
        border-radius: 0.25rem;
    }

    .popup-content::-webkit-scrollbar-thumb {
        background: var(--text-secondary);
        border-radius: 0.25rem;
    }

    .popup-content::-webkit-scrollbar-thumb:hover {
        background: var(--text-primary);
    }

    /* Responsive Design */
    @media (max-width: 768px) {
        .popup-overlay {
            padding: 0.5rem;
        }

        .popup-content {
            max-height: 95vh;
        }

        .header-content {
            flex-direction: column;
            text-align: center;
            gap: 0.75rem;
        }

        .details-grid {
            grid-template-columns: 1fr;
        }

        .toggle-row {
            flex-direction: column;
            gap: 1rem;
        }

        .score-stats {
            flex-direction: column;
            gap: 0.5rem;
        }

        .score-card {
            flex-direction: column;
            text-align: center;
            gap: 0.75rem;
        }
    }
</style>