<script lang="ts">
    import { createEventDispatcher } from "svelte";
    //@ts-ignore
    import { Response_ResponseType, Map, Characteristic, GameplayModifiers_GameOptions } from 'moons-ta-client';
    import { TAServerPort, TAServerUrl, authTokenStore } from "$lib/stores";
    import { v4 as uuidv4 } from "uuid";
    import { onMount } from "svelte";
    import type { BeatSaverMap } from "$lib/services/beatsaver";
    import { type Modifier, allGameModifiers } from "$lib/services/gamePlayModifiers";
    
    export let tournamentGuid: string;
    export let mode: 'qualifier' | 'playing' = 'playing';
    export let map: {
        taData: Map,
        beatsaverData: BeatSaverMap
    } | null = null;
    
    const dispatch = createEventDispatcher();
    
    // Form state
    let isLoading = false;
    let error: string | null = null;
    let mapId = map?.taData.guid || "";
    let mapName = map?.taData.gameplayParameters?.beatmap?.name || "";
    let mapAuthor = map?.beatsaverData?.metadata?.songAuthorName || "";
    let mapDifficulty = map?.taData.gameplayParameters?.beatmap?.difficulty || "";
    let mapLength = map?.beatsaverData?.metadata?.duration || 0;
    let mapBeatmapId = map?.taData.gameplayParameters?.beatmap?.levelId || "";
    let beatSaverKey = "";
    let isLoadingMap = false;
    let mapLoadError: string | null = null;
    let selectedCharacteristic = "";
    let selectedDifficulty = "";
    let availableCharacteristics: string[] = [];
    let availableDifficulties: { [characteristic: string]: string[] } = {};
    let mapImageUrl = "";
    let beatSaverUrl = "";

    // Qualifier-specific settings
    let limitAttemptsEnabled = false;
    let numberOfAttempts = 1;
    let showScoreboard = false;
    
    // Tournament Assistant settings for both modes
    let disableFail = false;
    let disablePause = false;
    let disableScoresaberSubmission = false;

    // Playing-specific settings
    let disableCustomNotesOnStream = false;
    
    // Game modifiers with proper grouping and mode restrictions
    let gameModifiers: Modifier[] = allGameModifiers;
    
    // Initialize from existing map data
    function initializeFromMap() {
        if (!map) return;
        
        // Initialize attempts
        if (map.taData.gameplayParameters?.attempts && map.taData.gameplayParameters.attempts > 0) {
            limitAttemptsEnabled = true;
            numberOfAttempts = map.taData.gameplayParameters.attempts;
        }
        
        // Initialize other settings
        disableScoresaberSubmission = map.taData.gameplayParameters?.disableScoresaberSubmission || false;
        showScoreboard = map.taData.gameplayParameters?.showScoreboard || false;
        disableFail = map.taData.gameplayParameters?.disableFail || false;
        disablePause = map.taData.gameplayParameters?.disablePause || false;
        
        // Initialize modifiers - create new array for reactivity
        if (map.taData.gameplayParameters?.gameplayModifiers?.options) {
            const modifierValue = map.taData.gameplayParameters.gameplayModifiers.options;
            
            gameModifiers = gameModifiers.map(modifier => ({
                ...modifier,
                enabled: (modifierValue & modifier.id) === modifier.id
            }));
        }
    }
    
    // Get modifiers filtered by current mode
    function getFilteredModifiers(): Modifier[] {
        return gameModifiers.filter(modifier => 
            !modifier.allowedInMode || modifier.allowedInMode.includes(mode)
        );
    }
    
    // Group modifiers by their group
    function getGroupedModifiers() {
        const filtered = getFilteredModifiers();
        const groups: {[key: string]: Modifier[]} = {};
        
        filtered.forEach(modifier => {
            const group = modifier.group;
            if (!groups[group]) {
                groups[group] = [];
            }
            groups[group].push(modifier);
        });
        
        return groups;
    }
    
    // Handle modifier changes with proper incompatibility checking
    function handleModifierChange(changedModifier: Modifier) {
        // Find the modifier and toggle it
        const modifierIndex = gameModifiers.findIndex(m => m.id === changedModifier.id);
        if (modifierIndex === -1) return;
        
        const newEnabled = !gameModifiers[modifierIndex].enabled;
        
        // Special case: If enabling No Fail, disable Disable Fail
        if (changedModifier.id === GameplayModifiers_GameOptions.NoFail && newEnabled) {
            disableFail = false;
        }
        
        // Create new array for reactivity
        gameModifiers = gameModifiers.map((modifier, index) => {
            // If this is the modifier being changed, update its enabled state
            if (index === modifierIndex) {
                return { ...modifier, enabled: newEnabled };
            }
            
            // If the changed modifier was enabled and has an incompatibility group,
            // disable other modifiers in the same group
            if (newEnabled && 
                changedModifier.incompatibilityGroup && 
                modifier.incompatibilityGroup === changedModifier.incompatibilityGroup && 
                modifier.id !== changedModifier.id) {
                return { ...modifier, enabled: false };
            }
            
            return modifier;
        });
    }
    
    // Handle disable fail toggle
    function handleDisableFailChange() {
        if (disableFail) {
            // If enabling disable fail, disable No Fail modifier
            gameModifiers = gameModifiers.map(modifier => {
                if (modifier.id === GameplayModifiers_GameOptions.NoFail) {
                    return { ...modifier, enabled: false };
                }
                return modifier;
            });
        }
    }
    
    // Check if a modifier should be disabled due to incompatibilities
    function isModifierDisabled(modifier: Modifier): boolean {
        // Special case: No Fail is disabled when Disable Fail is enabled
        if (modifier.id === GameplayModifiers_GameOptions.NoFail && disableFail) {
            return true;
        }
        
        if (!modifier.incompatibilityGroup) return false;
        
        // Check if any other modifier in the same incompatibility group is enabled
        // and this modifier isn't the currently enabled one
        return gameModifiers.some(m => 
            m.id !== modifier.id && 
            m.enabled && 
            m.incompatibilityGroup === modifier.incompatibilityGroup
        );
    }
    
    function getActiveModifiersAsBitmap(): number {
        return gameModifiers
            .filter(modifier => modifier.enabled)
            .reduce((bitmap, modifier) => bitmap | modifier.id, 0);
    }

    function handleCharacteristicChange() {
        if (selectedCharacteristic && availableDifficulties[selectedCharacteristic]) {
            if (!availableDifficulties[selectedCharacteristic].includes(selectedDifficulty)) {
                selectedDifficulty = availableDifficulties[selectedCharacteristic][0] || "";
            }
        } else {
            selectedDifficulty = "";
        }
    }

    async function fetchMapFromBeatSaver(key: string) {
        if (!key.trim()) return;
        
        isLoadingMap = true;
        mapLoadError = null;
        
        try {
            const isHash = /^[0-9a-fA-F]{40}$/.test(key);
            const endpoint = isHash 
                ? `https://api.beatsaver.com/maps/hash/${key}`
                : `https://api.beatsaver.com/maps/id/${key}`;
                
            const response = await fetch(endpoint);
            
            if (!response.ok) {
                throw new Error(`Failed to fetch map (${response.status}): ${response.statusText}`);
            }
            
            const data: BeatSaverMap = await response.json();
            const latestVersion = data.versions[0];
            
            // Map basic details - ensure reactivity
            mapName = data.metadata.songName;
            mapAuthor = data.metadata.songAuthorName;
            mapLength = data.metadata.duration;
            mapImageUrl = latestVersion.coverURL;
            beatSaverUrl = `https://beatsaver.com/maps/${data.id}`;
            
            // Extract characteristics and difficulties - create new objects for reactivity
            const newCharacteristics = Array.from(
                new Set(latestVersion.diffs.map(diff => diff.characteristic))
            );
            
            const newDifficulties: { [key: string]: string[] } = {};
            latestVersion.diffs.forEach(diff => {
                if (!newDifficulties[diff.characteristic]) {
                    newDifficulties[diff.characteristic] = [];
                }
                if (!newDifficulties[diff.characteristic].includes(diff.difficulty)) {
                    newDifficulties[diff.characteristic].push(diff.difficulty);
                }
            });
            
            // Sort difficulties in proper order
            const difficultyOrder = ["Easy", "Normal", "Hard", "Expert", "Expert+", "ExpertPlus"];
            Object.keys(newDifficulties).forEach(char => {
                newDifficulties[char].sort((a, b) => {
                    const aIndex = difficultyOrder.indexOf(a);
                    const bIndex = difficultyOrder.indexOf(b);
                    return aIndex - bIndex;
                });
            });
            
            // Assign new objects to trigger reactivity
            availableCharacteristics = newCharacteristics;
            availableDifficulties = newDifficulties;
            
            selectedCharacteristic = availableCharacteristics[0] || "";
            selectedDifficulty = availableDifficulties[selectedCharacteristic]?.[0] || "";
            
            mapBeatmapId = `custom_level_${latestVersion.hash.toUpperCase()}`;
            
            return data;
        } catch (err) {
            console.error("Error fetching map:", err);
            mapLoadError = err instanceof Error ? err.message : "Failed to fetch map details";
            return null;
        } finally {
            isLoadingMap = false;
        }
    }
    
    function getDifficultyNumber(difficulty: string): number {
        const difficultyMap: { [key: string]: number } = {
            "Easy": 0,
            "Normal": 1,
            "Hard": 2,
            "Expert": 3,
            "Expert+": 4,
            "ExpertPlus": 4
        };
        return difficultyMap[difficulty] || 0;
    }
    
    async function handleSubmit() {
        if (!mapName || !mapBeatmapId) {
            error = "Map name and beatmap ID are required";
            return;
        }
        
        if (!selectedCharacteristic || !selectedDifficulty) {
            error = "Please select both characteristic and difficulty";
            return;
        }
        
        isLoading = true;
        error = null;
        
        try {
            const modifiersBitmap = getActiveModifiersAsBitmap();
            const mapData: Map = {
                guid: map?.taData.guid || uuidv4(),
                gameplayParameters: {
                    beatmap: {
                        name: mapName,
                        levelId: mapBeatmapId.toUpperCase().replace('CUSTOM_LEVEL_', 'custom_level_'),
                        difficulty: getDifficultyNumber(selectedDifficulty),
                        characteristic: {
                            serializedName: selectedCharacteristic,
                            difficulties: []
                        }
                    },
                    gameplayModifiers: {
                        options: modifiersBitmap
                    },
                    attempts: (mode === 'qualifier' && limitAttemptsEnabled) ? numberOfAttempts : 0,
                    disableCustomNotesOnStream: disableCustomNotesOnStream,
                    disableFail: disableFail,
                    disablePause: disablePause,
                    disableScoresaberSubmission: mode === 'playing' ? disableScoresaberSubmission : false,
                    showScoreboard: mode === 'playing' ? showScoreboard : false,
                    useSync: false,
                    target: 0,
                    playerSettings: {
                        options: 0,
                        playerHeight: 0,
                        sfxVolume: 0,
                        saberTrailIntensity: 0,
                        noteJumpStartBeatOffset: 0,
                        noteJumpFixedDuration: 0,
                        noteJumpDurationTypeSettings: 0,
                        arcVisibilityType: 0,
                    }
                }
            };
            if (map) {
                dispatch('mapUpdated', { map: mapData });
            } else {
                dispatch('mapAdded', { map: mapData });
            }

            isLoading = false;
            return dispatch('close');
        } catch (err) {
            console.error('Error saving map:', err);
            error = err instanceof Error ? err.message : 'An unknown error occurred';
        } finally {
            isLoading = false;
        }
    }
    
    function closeModal() {
        dispatch('close');
    }

    // Get the mode display text
    function getModeDisplayText(): string {
        return mode === 'qualifier' ? 'Qualifier Map' : 'Tournament Map';
    }

    onMount(() => {
        // Initialize from existing map data
        initializeFromMap();
        
        // If editing an existing map, try to load BeatSaver data
        if (map?.taData.gameplayParameters?.beatmap?.levelId) {
            const levelIdParts = map.taData.gameplayParameters.beatmap.levelId.split('_');
            if (levelIdParts.length === 3) {
                beatSaverKey = levelIdParts[2];
                fetchMapFromBeatSaver(beatSaverKey);
                
                if (map.taData.gameplayParameters?.beatmap?.characteristic) {
                    selectedCharacteristic = map.taData.gameplayParameters.beatmap.characteristic.serializedName;
                }
                
                if (map.taData.gameplayParameters?.beatmap?.difficulty !== undefined) {
                    const difficultyNames = ["Easy", "Normal", "Hard", "Expert", "Expert+"];
                    selectedDifficulty = difficultyNames[map.taData.gameplayParameters.beatmap.difficulty] || "Easy";
                }
            }
        }
    });

    // Reactive statements
    $: if (selectedCharacteristic && availableDifficulties[selectedCharacteristic]) {
        if (!availableDifficulties[selectedCharacteristic].includes(selectedDifficulty)) {
            selectedDifficulty = availableDifficulties[selectedCharacteristic][0] || "";
        }
    }

    $: filteredModifiers = gameModifiers.filter(modifier => 
        !modifier.allowedInMode || modifier.allowedInMode.includes(mode)
    );

    $: groupedModifiers = (() => {
        const groups: {[key: string]: Modifier[]} = {};
        
        filteredModifiers.forEach(modifier => {
            const group = modifier.group;
            if (!groups[group]) {
                groups[group] = [];
            }
            groups[group].push(modifier);
        });
        
        return groups;
    })();

    // Watch for disable fail changes to handle No Fail incompatibility
    $: if (disableFail) {
        handleDisableFailChange();
    }
</script>

<div class="popup-overlay">
    <div class="popup-container">
        <div class="popup-header">
            <div class="header-content">
                <h3>{map ? 'Edit' : 'Add'} {getModeDisplayText()}</h3>
                <div class="mode-indicator mode-{mode}">
                    <span class="mode-text">{mode === 'qualifier' ? 'Qualifier' : 'Tournament'}</span>
                </div>
            </div>
            <button class="close-button" on:click={closeModal}>
                <span class="material-icons">close</span>
            </button>
        </div>
        
        <div class="popup-content">
            {#if error}
                <div class="error-message">
                    <span class="material-icons">error_outline</span>
                    <p>{error}</p>
                </div>
            {/if}
            
            <form on:submit|preventDefault={handleSubmit}>
                <div class="form-sections">
                    <div class="form-section">
                        <h4>Map Details</h4>
                        
                        {#if !map}
                            <div class="form-group beatsaver-lookup">
                                <label for="beatSaverKey">BeatSaver Key or Hash</label>
                                <div class="beatsaver-input-container">
                                    <input 
                                        type="text" 
                                        id="beatSaverKey" 
                                        bind:value={beatSaverKey} 
                                        placeholder="Enter key or hash"
                                        disabled={isLoadingMap}
                                    />
                                    <button 
                                        type="button" 
                                        class="lookup-button" 
                                        on:click={() => fetchMapFromBeatSaver(beatSaverKey)}
                                        disabled={!beatSaverKey.trim() || isLoadingMap}
                                    >
                                        {#if isLoadingMap}
                                            <span class="material-icons loading-icon">sync</span>
                                        {:else}
                                            <span class="material-icons">search</span>
                                        {/if}
                                    </button>
                                </div>
                                {#if mapLoadError}
                                    <p class="error-text">{mapLoadError}</p>
                                {/if}
                            </div>
                        {/if}
                        
                        {#if mapName}
                            <div class="map-details-container">
                                {#if mapImageUrl}
                                    <div class="map-image-container">
                                        <img src={mapImageUrl} alt={mapName} class="map-cover-image"/>
                                    </div>
                                {/if}
                                
                                <div class="map-info">
                                    <h5 class="map-title">{mapName}</h5>
                                    {#if mapAuthor}
                                        <p class="map-author">by {mapAuthor}</p>
                                    {/if}
                                    
                                    {#if beatSaverUrl}
                                        <a href={beatSaverUrl} target="_blank" rel="noopener noreferrer" class="beatsaver-link">
                                            <span class="material-icons">open_in_new</span>
                                            View on BeatSaver
                                        </a>
                                    {/if}
                                    
                                    {#if beatSaverKey}
                                        <p class="map-id">ID: {beatSaverKey}</p>
                                    {/if}
                                </div>
                            </div>
                            
                            <div class="map-selection-container">
                                <div class="form-group">
                                    <label for="mapCharacteristic">Characteristic</label>
                                    <select 
                                        id="mapCharacteristic" 
                                        bind:value={selectedCharacteristic}
                                        on:change={handleCharacteristicChange}
                                        class="map-select"
                                    >
                                        {#each availableCharacteristics as characteristic}
                                            <option value={characteristic}>{characteristic}</option>
                                        {/each}
                                    </select>
                                </div>
                                
                                <div class="form-group">
                                    <label for="mapDifficulty">Difficulty</label>
                                    <select 
                                        id="mapDifficulty" 
                                        bind:value={selectedDifficulty}
                                        class="map-select"
                                        disabled={!selectedCharacteristic}
                                    >
                                        {#if selectedCharacteristic && availableDifficulties[selectedCharacteristic]}
                                            {#each availableDifficulties[selectedCharacteristic] as difficulty}
                                                <option value={difficulty}>{difficulty}</option>
                                            {/each}
                                        {/if}
                                    </select>
                                </div>
                            </div>
                        {/if}
                    </div>
                    
                    <div class="form-section modifiers-section">
                        <h4>Game Modifiers</h4>
                        <p class="section-desc">Select which modifiers are enabled for this {mode} map</p>
                        
                        {#each Object.entries(groupedModifiers) as [group, modifiers]}
                            <div class="modifier-group">
                                <h5>{group}</h5>
                                <div class="modifiers-grid">
                                    {#each modifiers as modifier}
                                        <div class="modifier-toggle">
                                            <label class="switch-label" title={modifier.description}>
                                                <input 
                                                    type="checkbox" 
                                                    checked={modifier.enabled}
                                                    on:click={() => handleModifierChange(modifier)}
                                                    disabled={isModifierDisabled(modifier)}
                                                />
                                                <span class="switch" class:disabled={isModifierDisabled(modifier)}></span>
                                                <span class="label-text">{modifier.name}</span>
                                            </label>
                                        </div>
                                    {/each}
                                </div>
                            </div>
                        {/each}
                    </div>
                    
                    <!-- Tournament Assistant Settings - now for both modes -->
                    <div class="form-section qualifier-features-section">
                        <h4>Tournament Assistant Settings</h4>
                        <p class="section-desc">Configure game behavior options</p>
                        
                        <div class="qualifier-options">                            
                            <div class="qualifier-toggle">
                                <label class="switch-label">
                                    <input 
                                        type="checkbox" 
                                        bind:checked={disablePause}
                                    />
                                    <span class="switch"></span>
                                    <span class="label-text">Disable Pause</span>
                                </label>
                            </div>
                            
                            {#if mode === 'playing'}
                                <div class="qualifier-toggle">
                                    <label class="switch-label">
                                        <input 
                                            type="checkbox" 
                                            bind:checked={disableFail}
                                            on:change={handleDisableFailChange}
                                        />
                                        <span class="switch"></span>
                                        <span class="label-text">Disable Fail</span>
                                    </label>
                                </div>
                                
                                <div class="qualifier-toggle">
                                    <label class="switch-label">
                                        <input 
                                            type="checkbox" 
                                            bind:checked={disableScoresaberSubmission}
                                        />
                                        <span class="switch"></span>
                                        <span class="label-text">Disable ScoreSaber Submission</span>
                                    </label>
                                </div>
                                
                                <div class="qualifier-toggle">
                                    <label class="switch-label">
                                        <input 
                                            type="checkbox" 
                                            bind:checked={showScoreboard}
                                        />
                                        <span class="switch"></span>
                                        <span class="label-text">Show Scoreboard</span>
                                    </label>
                                </div>

                                <div class="qualifier-toggle">
                                    <label class="switch-label">
                                        <input 
                                            type="checkbox" 
                                            bind:checked={disableCustomNotesOnStream}
                                        />
                                        <span class="switch"></span>
                                        <span class="label-text">Disable Custom Notes On Stream</span>
                                    </label>
                                </div>
                            {/if}
                            
                            {#if mode === 'qualifier'}
                                <div class="qualifier-toggle">
                                    <label class="switch-label">
                                        <input 
                                            type="checkbox" 
                                            bind:checked={limitAttemptsEnabled}
                                        />
                                        <span class="switch"></span>
                                        <span class="label-text">Limit Attempts</span>
                                    </label>
                                </div>
                                
                                {#if limitAttemptsEnabled}
                                    <div class="form-group attempts-input">
                                        <label for="numberOfAttempts">Number of Attempts</label>
                                        <input 
                                            type="number" 
                                            id="numberOfAttempts" 
                                            bind:value={numberOfAttempts}
                                            min="1" 
                                            max="10000"
                                            step="1"
                                        />
                                        <p class="setting-description">Maximum number of attempts allowed (1-10000)</p>
                                    </div>
                                {/if}
                            {/if}
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="button" class="action-button cancel" on:click={closeModal}>
                        <span class="material-icons">cancel</span>
                        Cancel
                    </button>
                    <button 
                        type="submit" 
                        class="action-button save" 
                        disabled={isLoading || !mapName || !mapBeatmapId || !selectedCharacteristic || !selectedDifficulty}
                    >
                        {#if isLoading}
                            <span class="material-icons loading-icon">sync</span>
                            Saving...
                        {:else}
                            <span class="material-icons">save</span>
                            {map ? 'Save Changes' : `Add ${getModeDisplayText()}`}
                        {/if}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<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: 800px;
        max-height: 90vh;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
        display: flex;
        flex-direction: column;
    }
    
    .popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid var(--bg-secondary);
    }
    
    .popup-header 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;
    }
    
    .error-message {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem 1rem;
        background-color: rgba(255, 85, 85, 0.1);
        border-left: 3px solid #ff5555;
        border-radius: 0.25rem;
        margin-bottom: 1.5rem;
    }
    
    .error-message .material-icons {
        color: #ff5555;
    }
    
    .error-message p {
        margin: 0;
        color: #ff5555;
    }
    
    /* Form styling */
    .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;
    }
    
    .form-group {
        margin-bottom: 1rem;
    }
    
    .form-row {
        display: flex;
        gap: 1rem;
        margin-bottom: 1rem;
    }
    
    .form-row .form-group {
        flex: 1;
        margin-bottom: 0;
    }
    
    label {
        display: block;
        margin-bottom: 0.5rem;
        font-size: 0.875rem;
        font-weight: 500;
    }
    
    input[type="text"],
    input[type="number"] {
        width: 100%;
        padding: 0.75rem;
        border: 1px solid var(--bg-tertiary);
        border-radius: 0.375rem;
        background-color: var(--bg-primary);
        color: var(--text-primary);
        font-size: 0.875rem;
    }
    
    input[type="text"]:focus,
    input[type="number"]:focus {
        border-color: var(--accent-color);
        outline: none;
    }
    
    /* File input styling */
    .file-input-wrapper {
        position: relative;
    }
    
    .file-input-wrapper input[type="file"] {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        cursor: pointer;
        z-index: 1;
    }
    
    .file-input-display {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem;
        border: 1px solid var(--bg-tertiary);
        border-radius: 0.375rem;
        background-color: var(--bg-primary);
        color: var(--text-secondary);
        font-size: 0.875rem;
    }
    
    .file-input-wrapper:hover .file-input-display {
        border-color: var(--accent-color);
    }
    
    /* Modifier section styling */
    .modifiers-section {
        overflow: hidden;
    }
    
    .modifier-group {
        margin-bottom: 1.5rem;
    }
    
    .modifier-group h5 {
        margin: 0 0 0.75rem 0;
        font-size: 0.9375rem;
        font-weight: 500;
        color: var(--text-secondary);
    }
    
    .modifiers-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
        gap: 0.75rem;
    }
    
    /* Switch styling */
    .switch-label {
        display: flex;
        align-items: center;
        cursor: pointer;
        user-select: none;
    }
    
    .switch-label input {
        opacity: 0;
        width: 0;
        height: 0;
        position: absolute;
    }
    
    .switch {
        position: relative;
        display: inline-block;
        width: 2.5rem;
        height: 1.25rem;
        background-color: var(--bg-tertiary);
        border-radius: 1.25rem;
        margin-right: 0.75rem;
        transition: background-color 0.2s;
    }
    
    .switch:before {
        position: absolute;
        content: "";
        height: 0.875rem;
        width: 0.875rem;
        left: 0.1875rem;
        bottom: 0.1875rem;
        background-color: white;
        border-radius: 50%;
        transition: transform 0.2s;
    }

    .switch:disabled {
        opacity: 50%;
        background-color: grey;
        cursor: not-allowed;
    }
    
    input:checked + .switch {
        background-color: var(--accent-color);
    }
    
    input:checked + .switch:before {
        transform: translateX(1.25rem);
    }
    
    .label-text {
        font-size: 0.875rem;
    }
    
    /* TA Features section */
    .ta-features-toggle {
        margin-bottom: 1rem;
    }
    
    .ta-options {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
        gap: 0.75rem;
        padding: 0.75rem;
        background-color: var(--bg-tertiary);
        border-radius: 0.375rem;
        margin-top: 0.5rem;
    }
    
    /* Form actions */
    .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;
    }
    
    .loading-icon {
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    /* Responsive design */
    @media (max-width: 768px) {
        .popup-container {
            width: 95%;
            max-height: 95vh;
        }
        
        .form-row {
            flex-direction: column;
            gap: 1rem;
        }
        
        .modifiers-grid {
            grid-template-columns: 1fr 1fr;
        }
        
        .ta-options {
            grid-template-columns: 1fr 1fr;
        }
    }
    
    @media (max-width: 480px) {
        .modifiers-grid,
        .ta-options {
            grid-template-columns: 1fr;
        }
        
        .form-actions {
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .action-button {
            width: 100%;
            justify-content: center;
        }
    }

    /* BeatSaver lookup styling */
    .beatsaver-input-container {
        display: flex;
        gap: 0.5rem;
    }

    .beatsaver-input-container input {
        flex: 1;
    }

    .lookup-button {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: var(--accent-color);
        color: white;
        border: none;
        border-radius: 0.375rem;
        padding: 0 1rem;
        cursor: pointer;
        transition: background-color 0.2s;
    }

    .lookup-button:hover {
        background-color: var(--accent-hover);
    }

    .lookup-button:disabled {
        background-color: var(--bg-tertiary);
        cursor: not-allowed;
        opacity: 0.7;
    }

    .error-text {
        color: #ff5555;
        font-size: 0.8125rem;
        margin-top: 0.375rem;
        margin-bottom: 0;
    }

    /* Map details styling */
    .map-details-container {
        display: flex;
        gap: 1rem;
        margin-bottom: 1.5rem;
        background-color: var(--bg-primary);
        border-radius: 0.5rem;
        padding: 1rem;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }

    .map-image-container {
        flex-shrink: 0;
        width: 80px;
        height: 80px;
        border-radius: 0.25rem;
        overflow: hidden;
    }

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

    .map-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }

    .map-title {
        margin: 0 0 0.25rem 0;
        font-size: 1.125rem;
        font-weight: 600;
        line-height: 1.3;
    }

    .map-author {
        margin: 0 0 0.5rem 0;
        font-size: 0.875rem;
        color: var(--text-secondary);
    }

    .map-id {
        margin: 0.25rem 0 0 0;
        font-size: 0.75rem;
        color: var(--text-secondary);
        font-family: monospace;
    }

    .beatsaver-link {
        display: inline-flex;
        align-items: center;
        gap: 0.25rem;
        color: var(--accent-color);
        font-size: 0.8125rem;
        text-decoration: none;
        margin-top: 0.25rem;
    }

    .beatsaver-link:hover {
        text-decoration: underline;
    }

    .beatsaver-link .material-icons {
        font-size: 1rem;
    }

    /* Map selection styling */
    .map-selection-container {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 1rem;
        margin-top: 1rem;
    }

    .map-select {
        width: 100%;
        padding: 0.75rem;
        border: 1px solid var(--bg-tertiary);
        border-radius: 0.375rem;
        background-color: var(--bg-primary);
        color: var(--text-primary);
        font-size: 0.875rem;
        appearance: none;
        background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
        background-repeat: no-repeat;
        background-position: right 0.5rem center;
        background-size: 1rem;
        padding-right: 2rem;
    }

    .map-select:focus {
        border-color: var(--accent-color);
        outline: none;
    }

    .map-select:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }

    /* Responsive adjustments */
    @media (max-width: 480px) {
        .map-selection-container {
            grid-template-columns: 1fr;
        }
        
        .map-details-container {
            flex-direction: column;
            align-items: center;
            text-align: center;
        }
        
        .map-image-container {
            width: 120px;
            height: 120px;
        }
    }
    .header-content {
        display: flex;
        align-items: center;
        gap: 1rem;
    }
    
    .header-content h3 {
        margin: 0;
        font-size: 1.25rem;
        font-weight: 600;
    }
    
    .mode-indicator {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.375rem 0.75rem;
        border-radius: 1rem;
        font-size: 0.8125rem;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }
    
    .mode-indicator.mode-qualifier {
        background-color: rgba(255, 193, 7, 0.15);
        color: #ffc107;
        border: 1px solid rgba(255, 193, 7, 0.3);
    }
    
    .mode-indicator.mode-playing {
        background-color: rgba(40, 167, 69, 0.15);
        color: #28a745;
        border: 1px solid rgba(40, 167, 69, 0.3);
    }
    
    .mode-icon {
        font-size: 1rem;
        line-height: 1;
    }
    
    .mode-text {
        font-size: 0.75rem;
        font-weight: 600;
    }
    
    /* Qualifier-specific styling */
    .qualifier-features-section {
        border-left: 3px solid #ffc107;
        background-color: rgba(255, 193, 7, 0.05);
    }
    
    .qualifier-options {
        display: flex;
        flex-direction: column;
        gap: 1rem;
    }
    
    .qualifier-toggle {
        display: flex;
        align-items: center;
    }
    
    .attempts-input {
        margin-left: 3.25rem;
        margin-top: 0.75rem;
        max-width: 200px;
    }
    
    .attempts-input input {
        padding: 0.5rem 0.75rem;
        font-size: 0.875rem;
    }
    
    /* Header content and mode indicator */
    .header-content {
        display: flex;
        align-items: center;
        gap: 1rem;
    }
    
    .header-content h3 {
        margin: 0;
        font-size: 1.25rem;
        font-weight: 600;
    }
    
    .mode-indicator {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.375rem 0.75rem;
        border-radius: 1rem;
        font-size: 0.8125rem;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }
    
    .mode-indicator.mode-qualifier {
        background-color: rgba(255, 193, 7, 0.15);
        color: #ffc107;
        border: 1px solid rgba(255, 193, 7, 0.3);
    }
    
    .mode-indicator.mode-playing {
        background-color: rgba(40, 167, 69, 0.15);
        color: #28a745;
        border: 1px solid rgba(40, 167, 69, 0.3);
    }
    
    .mode-icon {
        font-size: 1rem;
        line-height: 1;
    }
    
    .mode-text {
        font-size: 0.75rem;
        font-weight: 600;
    }
    
    /* Modifier toggle improvements */
    .modifier-toggle {
        background-color: var(--bg-primary);
        border-radius: 0.375rem;
        padding: 0.75rem;
        border: 1px solid var(--bg-tertiary);
        transition: all 0.2s ease;
    }
    
    .modifier-toggle:hover {
        background-color: var(--bg-tertiary);
        border-color: var(--accent-color);
    }
    
    .modifier-toggle .switch-label {
        margin: 0;
        width: 100%;
    }
    
    .modifier-toggle .label-text {
        font-weight: 500;
        line-height: 1.2;
    }
    
    /* Disabled state improvements */
    .switch.disabled {
        opacity: 0.5;
        background-color: var(--bg-tertiary);
    }
    
    .switch.disabled:before {
        background-color: #ccc;
    }
    
    .modifier-toggle:has(.switch.disabled) {
        opacity: 0.6;
        cursor: not-allowed;
    }
    
    .modifier-toggle:has(.switch.disabled):hover {
        background-color: var(--bg-primary);
        border-color: var(--bg-tertiary);
    }
    
    /* Beatsaver lookup improvements */
    .beatsaver-lookup {
        background-color: var(--bg-primary);
        border-radius: 0.5rem;
        padding: 1rem;
        border: 1px solid var(--bg-tertiary);
    }
    
    .beatsaver-lookup label {
        font-weight: 600;
        color: var(--text-primary);
    }
    
    /* Enhanced responsive design */
    @media (max-width: 768px) {
        .header-content {
            flex-direction: column;
            align-items: flex-start;
            gap: 0.5rem;
        }
        
        .mode-indicator {
            align-self: flex-start;
        }
        
        .attempts-input {
            margin-left: 0;
            max-width: 100%;
        }
        
        .qualifier-options {
            gap: 0.75rem;
        }
    }
    
    @media (max-width: 480px) {
        .header-content h3 {
            font-size: 1.125rem;
        }
        
        .mode-indicator {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
        
        .mode-icon {
            font-size: 0.875rem;
        }
        
        .mode-text {
            font-size: 0.6875rem;
        }
        
        .modifier-toggle {
            padding: 0.5rem;
        }
        
        .modifier-toggle .label-text {
            font-size: 0.8125rem;
        }
    }
    
    /* Focus and accessibility improvements */
    .switch-label:focus-within .switch {
        box-shadow: 0 0 0 2px rgba(var(--accent-color-rgb), 0.2);
    }
    
    .lookup-button:focus {
        outline: 2px solid var(--accent-color);
        outline-offset: 2px;
    }
    
    .close-button:focus {
        outline: 2px solid var(--accent-color);
        outline-offset: 2px;
    }
    
    /* Animation improvements */
    .popup-container {
        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);
        }
    }
    
    /* Loading state improvements */
    .loading-icon {
        animation: spin 1s linear infinite;
    }
    
    .beatsaver-lookup:has(.loading-icon) {
        opacity: 0.8;
    }
    
    /* Section dividers */
    .form-section:not(:last-child) {
        border-bottom: 1px solid var(--bg-tertiary);
        padding-bottom: 1.5rem;
        margin-bottom: 1.5rem;
    }
    
    .form-section:last-child {
        margin-bottom: 0;
    }
    
    /* Error state improvements */
    .error-message {
        animation: fadeIn 0.3s ease-out;
    }
    
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    /* Tooltip-like description on hover */
    .modifier-toggle:hover::after {
        content: attr(title);
        position: absolute;
        bottom: 100%;
        left: 50%;
        transform: translateX(-50%);
        background-color: var(--bg-primary);
        color: var(--text-primary);
        padding: 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.75rem;
        white-space: nowrap;
        z-index: 1001;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        border: 1px solid var(--bg-tertiary);
        pointer-events: none;
    }
    
    /* Improved form validation states */
    .form-group:has(input:invalid) label {
        color: #ff5555;
    }
    
    .form-group:has(input:invalid) input {
        border-color: #ff5555;
    }
    
    .form-group:has(input:valid) input {
        border-color: #28a745;
    }
    
    /* Dark theme adjustments */
    @media (prefers-color-scheme: dark) {
        .mode-indicator.mode-qualifier {
            background-color: rgba(255, 193, 7, 0.2);
            border-color: rgba(255, 193, 7, 0.4);
        }
        
        .mode-indicator.mode-playing {
            background-color: rgba(40, 167, 69, 0.2);
            border-color: rgba(40, 167, 69, 0.4);
        }
        
        .qualifier-features-section {
            background-color: rgba(255, 193, 7, 0.08);
        }
    }
</style>