<script lang="ts">
    import { createEventDispatcher } from 'svelte';
    import type { CustomTAMapPool, CustomMap } from '$lib/interfaces/match.interfaces';
    import { bufferToImageUrl } from '$lib/services/taImages';

    export let isOpen = false;
    export let mapPools: CustomTAMapPool[] = [];

    const dispatch = createEventDispatcher();

    // Track which pools are expanded
    let expandedPools: Set<string> = new Set();
    
    // Track selected maps by their guid
    let selectedMaps: Set<string> = new Set();
    
    // Track if entire pools are selected
    let selectedPools: Set<string> = new Set();

    function togglePoolExpansion(poolGuid: string) {
        const newExpanded = new Set(expandedPools);
        if (newExpanded.has(poolGuid)) {
            newExpanded.delete(poolGuid);
        } else {
            newExpanded.add(poolGuid);
        }
        expandedPools = newExpanded;
    }

    function togglePoolSelection(pool: CustomTAMapPool) {
        const newSelectedPools = new Set(selectedPools);
        const newSelectedMaps = new Set(selectedMaps);
        
        if (selectedPools.has(pool.guid)) {
            // Unselect pool and all its maps
            newSelectedPools.delete(pool.guid);
            pool.maps.forEach(map => {
                newSelectedMaps.delete(map.taData.guid);
            });
        } else {
            // Select pool and all its maps
            newSelectedPools.add(pool.guid);
            pool.maps.forEach(map => {
                newSelectedMaps.add(map.taData.guid);
            });
        }
        
        selectedPools = newSelectedPools;
        selectedMaps = newSelectedMaps;
    }

    function toggleMapSelection(map: CustomMap, poolGuid: string) {
        const newSelectedMaps = new Set(selectedMaps);
        const newSelectedPools = new Set(selectedPools);
        
        if (selectedMaps.has(map.taData.guid)) {
            newSelectedMaps.delete(map.taData.guid);
            // If pool was fully selected, unselect it
            newSelectedPools.delete(poolGuid);
        } else {
            newSelectedMaps.add(map.taData.guid);
            
            // Check if all maps in this pool are now selected
            const pool = mapPools.find(p => p.guid === poolGuid);
            if (pool && pool.maps.every(m => newSelectedMaps.has(m.taData.guid))) {
                newSelectedPools.add(poolGuid);
            }
        }
        
        selectedMaps = newSelectedMaps;
        selectedPools = newSelectedPools;
    }

    function getDifficultyName(difficulty: number): string {
        const difficultyMap: { [key: number]: string } = {
            0: "Easy",
            1: "Normal", 
            2: "Hard",
            3: "Expert",
            4: "Expert+"
        };
        return difficultyMap[difficulty] || "Unknown";
    }

    function getModifiersText(modifiersBitmap: number): string {
        // This would need your actual modifiers mapping
        // For now, just show if modifiers are present
        return modifiersBitmap > 0 ? "Modifiers Active" : "No Modifiers";
    }

    function calculateDuration(map: CustomMap): string {
        // You mentioned you have a function for this - placeholder implementation
        if (map.beatsaverData?.metadata?.duration) {
            const duration = map.beatsaverData.metadata.duration;
            const minutes = Math.floor(duration / 60);
            const seconds = duration % 60;
            return `${minutes}:${seconds.toString().padStart(2, '0')}`;
        }
        return "0:00";
    }

    function getCoverUrl(map: CustomMap): string {
        return map.beatsaverData?.versions?.[0]?.coverURL || '';
    }

    function handleClose() {
        dispatch('close');
    }

    function handleAddMaps() {
        const mapsToAdd: CustomMap[] = [];
        
        mapPools.forEach(pool => {
            pool.maps.forEach(map => {
                if (selectedMaps.has(map.taData.guid)) {
                    mapsToAdd.push(map);
                }
            });
        });
        
        if (mapsToAdd.length > 0) {
            dispatch('addMaps', { maps: mapsToAdd });
        }
    }

    $: selectedCount = selectedMaps.size;
</script>

{#if isOpen}
    <!-- svelte-ignore a11y-no-static-element-interactions -->
    <!-- svelte-ignore a11y-click-events-have-key-events -->
    <div class="popup-overlay" on:click={handleClose}>
        <div class="popup-container" on:click|stopPropagation>
            <div class="popup-header">
                <div class="header-content">
                    <h3>Add Maps from TA Pool</h3>
                </div>
                <button class="close-button" on:click={handleClose}>
                    <span class="material-icons">close</span>
                </button>
            </div>

            <div class="popup-content">
                <div class="form-sections">
                    <div class="form-section">
                        <h4>Map Pools</h4>
                        <p class="section-desc">Select individual maps or entire pools to add to your match</p>
                        
                        <div class="pools-list">
                            {#each mapPools as pool (pool.guid)}
                                <div class="pool-container">
                                    <div class="pool-header">
                                        <div class="pool-info">
                                            <div class="pool-image">
                                                <img src={bufferToImageUrl(pool.image)} alt={pool.name} />
                                            </div>
                                            <div class="pool-details">
                                                <h5 class="pool-name">{pool.name}</h5>
                                                <span class="pool-count">{pool.maps.length} maps</span>
                                            </div>
                                        </div>
                                        <div class="pool-controls">
                                            <label class="pool-checkbox">
                                                <input 
                                                    type="checkbox" 
                                                    checked={selectedPools.has(pool.guid)}
                                                    on:change={() => togglePoolSelection(pool)}
                                                />
                                                <span class="checkmark"></span>
                                            </label>
                                            <button 
                                                class="expand-button" 
                                                on:click={() => togglePoolExpansion(pool.guid)}
                                                class:expanded={expandedPools.has(pool.guid)}
                                            >
                                                <span class="material-icons">expand_more</span>
                                            </button>
                                        </div>
                                    </div>
                                    
                                    {#if expandedPools.has(pool.guid)}
                                        <div class="maps-list">
                                            {#each pool.maps as map (map.taData.guid)}
                                                <div class="map-item">
                                                    <div class="map-checkbox">
                                                        <label>
                                                            <input 
                                                                type="checkbox" 
                                                                checked={selectedMaps.has(map.taData.guid)}
                                                                on:change={() => toggleMapSelection(map, pool.guid)}
                                                            />
                                                            <span class="checkmark"></span>
                                                        </label>
                                                    </div>
                                                    <div class="map-cover">
                                                        <img src={getCoverUrl(map)} alt={map.taData.gameplayParameters?.beatmap?.name} />
                                                    </div>
                                                    <div class="map-info">
                                                        <div class="map-title">{map.taData.gameplayParameters?.beatmap?.name}</div>
                                                        <div class="map-details">
                                                            <span class="map-duration">{calculateDuration(map)}</span>
                                                            <span class="map-separator">•</span>
                                                            <span class="map-difficulty {getDifficultyName(map.taData.gameplayParameters?.beatmap?.difficulty || 4).toLowerCase()}">
                                                                {getDifficultyName(map.taData.gameplayParameters?.beatmap?.difficulty || 4)}
                                                            </span>
                                                            <span class="map-separator">•</span>
                                                            <span class="map-modifiers">{getModifiersText(map.taData.gameplayParameters?.gameplayModifiers?.options || 0)}</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            {/each}
                                        </div>
                                    {/if}
                                </div>
                            {/each}
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <button class="action-button cancel" on:click={handleClose}>
                        Cancel
                    </button>
                    <button 
                        class="action-button save" 
                        on:click={handleAddMaps}
                        disabled={selectedCount === 0}
                    >
                        <span class="material-icons">add</span>
                        Add {selectedCount} Maps
                    </button>
                </div>
            </div>
        </div>
    </div>
{/if}

<style>
    .popup-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1000;
    }
    
    .popup-container {
        background-color: var(--bg-primary);
        border-radius: 0.75rem;
        width: 90%;
        max-width: 900px;
        max-height: 90vh;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
        display: flex;
        flex-direction: column;
        animation: slideIn 0.2s ease-out;
    }
    
    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(-20px) scale(0.95);
        }
        to {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
    }
    
    .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid var(--bg-secondary);
    }
    
    .header-content h3 {
        margin: 0;
        font-size: 1.25rem;
        font-weight: 600;
    }
    
    .close-button {
        background: none;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-secondary);
        width: 2rem;
        height: 2rem;
        border-radius: 0.25rem;
    }
    
    .close-button:hover {
        background-color: var(--bg-secondary);
        color: var(--text-primary);
    }
    
    .popup-content {
        padding: 1.5rem;
        overflow-y: auto;
    }
    
    .form-sections {
        display: flex;
        flex-direction: column;
        gap: 2rem;
    }
    
    .form-section {
        background-color: var(--bg-secondary);
        border-radius: 0.5rem;
        padding: 1.25rem;
    }
    
    .form-section h4 {
        margin: 0 0 1rem 0;
        font-size: 1rem;
        font-weight: 600;
    }
    
    .section-desc {
        color: var(--text-secondary);
        font-size: 0.875rem;
        margin: -0.5rem 0 1rem 0;
    }
    
    .pools-list {
        display: flex;
        flex-direction: column;
        gap: 1rem;
    }
    
    .pool-container {
        background-color: var(--bg-primary);
        border-radius: 0.5rem;
        border: 1px solid var(--bg-tertiary);
        overflow: hidden;
    }
    
    .pool-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 1rem;
        cursor: pointer;
    }
    
    .pool-info {
        display: flex;
        align-items: center;
        gap: 1rem;
    }
    
    .pool-image {
        width: 3rem;
        height: 3rem;
        border-radius: 0.375rem;
        overflow: hidden;
        flex-shrink: 0;
    }
    
    .pool-image img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .pool-details {
        display: flex;
        flex-direction: column;
        gap: 0.25rem;
    }
    
    .pool-name {
        margin: 0;
        font-size: 1rem;
        font-weight: 600;
        color: var(--text-primary);
    }
    
    .pool-count {
        font-size: 0.875rem;
        color: var(--text-secondary);
    }
    
    .pool-controls {
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }
    
    .expand-button {
        background: none;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-secondary);
        width: 2rem;
        height: 2rem;
        border-radius: 0.25rem;
        transition: all 0.2s;
    }
    
    .expand-button:hover {
        background-color: var(--bg-secondary);
        color: var(--text-primary);
    }
    
    .expand-button.expanded {
        transform: rotate(180deg);
    }
    
    .maps-list {
        border-top: 1px solid var(--bg-tertiary);
        padding: 1rem;
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
        max-height: 400px;
        overflow-y: auto;
    }
    
    .map-item {
        display: flex;
        align-items: center;
        gap: 1rem;
        padding: 0.75rem;
        background-color: var(--bg-secondary);
        border-radius: 0.375rem;
        border: 1px solid var(--bg-tertiary);
    }
    
    .map-checkbox {
        flex-shrink: 0;
    }
    
    .map-cover {
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 0.25rem;
        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: 0.9375rem;
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 0.25rem;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    .map-details {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.8125rem;
        color: var(--text-secondary);
        flex-wrap: wrap;
    }
    
    .map-separator {
        opacity: 0.5;
    }
    
    .map-difficulty {
        background-color: var(--accent-color);
        color: white;
        padding: 0.125rem 0.5rem;
        border-radius: 1rem;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
    }
    
    .map-difficulty.easy {
        background-color: #4ade80;
    }
    
    .map-difficulty.normal {
        background-color: #3b82f6;
    }
    
    .map-difficulty.hard {
        background-color: #f59e0b;
    }
    
    .map-difficulty.expert {
        background-color: #ef4444;
    }
    
    .map-difficulty.expert\+ {
        background-color: #8b5cf6;
    }
    
    .map-duration,
    .map-modifiers {
        font-size: 0.8125rem;
    }
    
    /* Checkbox styling */
    .pool-checkbox,
    .map-checkbox label {
        display: flex;
        align-items: center;
        cursor: pointer;
        user-select: none;
    }
    
    .pool-checkbox input,
    .map-checkbox input {
        opacity: 0;
        width: 0;
        height: 0;
        position: absolute;
    }
    
    .checkmark {
        position: relative;
        display: inline-block;
        width: 1.25rem;
        height: 1.25rem;
        background-color: var(--bg-tertiary);
        border: 2px solid var(--bg-tertiary);
        border-radius: 0.25rem;
        transition: all 0.2s;
    }
    
    .checkmark:after {
        content: "";
        position: absolute;
        display: none;
        left: 0.3125rem;
        top: 0.125rem;
        width: 0.3125rem;
        height: 0.625rem;
        border: solid white;
        border-width: 0 2px 2px 0;
        transform: rotate(45deg);
    }
    
    input:checked + .checkmark {
        background-color: var(--accent-color);
        border-color: var(--accent-color);
    }
    
    input:checked + .checkmark:after {
        display: block;
    }
    
    .form-actions {
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
        margin-top: 2rem;
    }
    
    .action-button {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.625rem 1.25rem;
        border: none;
        border-radius: 0.375rem;
        font-weight: 500;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    
    .action-button.cancel {
        background-color: var(--bg-tertiary);
        color: var(--text-primary);
    }
    
    .action-button.cancel:hover {
        background-color: var(--bg-tertiary);
        filter: brightness(0.95);
    }
    
    .action-button.save {
        background-color: var(--accent-color);
        color: white;
    }
    
    .action-button.save:hover {
        background-color: var(--accent-hover);
    }
    
    .action-button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
    
    @media (max-width: 768px) {
        .popup-container {
            width: 95%;
            max-height: 95vh;
        }
        
        .pool-header {
            padding: 0.75rem;
        }
        
        .pool-info {
            gap: 0.75rem;
        }
        
        .pool-image {
            width: 2.5rem;
            height: 2.5rem;
        }
        
        .map-item {
            padding: 0.5rem;
            gap: 0.75rem;
        }
        
        .map-cover {
            width: 2rem;
            height: 2rem;
        }
        
        .form-actions {
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .action-button {
            width: 100%;
            justify-content: center;
        }
    }
</style>