<script lang="ts">
    import { fetchMapByHashOrKey, type BeatSaverMap } from '$lib/services/beatsaver';
    import { createEventDispatcher } from 'svelte';
    import { type Modifier, allGameModifiers } from '$lib/services/gamePlayModifiers';
    import { GameplayModifiers_GameOptions } from 'moons-ta-client';
    import type { CustomMap } from '$lib/interfaces/match.interfaces';
    import { v4 as uuidv4 } from "uuid";

    interface PlaylistSong {
        songName: string;
        levelAuthorName: string;
        levelid: string;
        hash: string;
        difficulties?: Array<{
            characteristic: string;
            name: string;
        }>;
    }

    interface PlaylistFile {
        playlistTitle: string;
        playlistAuthor: string;
        image: string;
        songs: PlaylistSong[];
    }

    interface ProcessedMap {
        beatsaverData: BeatSaverMap;
        author: string;
        mapper: string;
        hash: string;
        key: string;
        songName: string;
        difficulty: string;
    }

    export let isOpen = false;

    // Game modifiers with proper grouping and mode restrictions
    let gameModifiers: Modifier[] = allGameModifiers;

    // Tournament Assistant settings for both modes
    let disableFail = false;
    let disablePause = false;
    let disableScoresaberSubmission = false;
    let showScoreboard = false;

    // Playing-specific settings
    let disableCustomNotesOnStream = false;

    const dispatch = createEventDispatcher();

    let dragActive = false;
    let isProcessing = false;
    let errorMessage = '';
    let processedMaps: ProcessedMap[] = [];
    let fileInputRef: HTMLInputElement;

    const difficultyOrder = ['Easy', 'Normal', 'Hard', 'Expert', 'ExpertPlus'];

    function convertDifficultyName(diffName: string): string {
        // Convert Expert+ to ExpertPlus and other variants
        const normalizedName = diffName.replace(/[\s\+]/g, '');
        switch (normalizedName.toLowerCase()) {
            case 'expert+':
            case 'expertplus':
            case 'expert_plus':
                return 'ExpertPlus';
            case 'expert':
                return 'Expert';
            case 'hard':
                return 'Hard';
            case 'normal':
                return 'Normal';
            case 'easy':
                return 'Easy';
            default:
                return diffName;
        }
    }

    function getHighestDifficulty(difficulties: Array<{ difficulty: string; characteristic: string }>): string {
        if (!difficulties || difficulties.length === 0) return 'ExpertPlus';
        
        const standardDiffs = difficulties.filter(d => d.characteristic === 'Standard');
        const diffsToCheck = standardDiffs.length > 0 ? standardDiffs : difficulties;
        
        let highest = 'Easy';
        let highestIndex = 0;
        
        for (const diff of diffsToCheck) {
            const convertedName = convertDifficultyName(diff.difficulty);
            const index = difficultyOrder.indexOf(convertedName);
            if (index > highestIndex) {
                highestIndex = index;
                highest = convertedName;
            }
        }
        
        return highest;
    }

    async function processPlaylistFile(file: File): Promise<void> {
        try {
            isProcessing = true;
            errorMessage = '';
            processedMaps = [];

            const text = await file.text();
            let playlistData: PlaylistFile;

            try {
                playlistData = JSON.parse(text);
            } catch (e) {
                throw new Error('Invalid JSON format');
            }

            if (!playlistData.songs || !Array.isArray(playlistData.songs)) {
                throw new Error('Invalid playlist format: missing songs array');
            }

            let maps: ProcessedMap[] = [];

            for (const song of playlistData.songs) {
                try {
                    let difficulty = 'ExpertPlus';
                    let mapBeatSaverData: BeatSaverMap | null = null;
                    
                    // If difficulties exist and are not empty, try to find ExpertPlus or get highest
                    if (song.difficulties && song.difficulties.length > 0) {
                        const expertPlus = song.difficulties.find(d => 
                            convertDifficultyName(d.name) === 'ExpertPlus' && d.characteristic === 'Standard'
                        );
                        
                        if (expertPlus) {
                            difficulty = 'ExpertPlus';
                            // Still need to fetch BeatSaver data for complete map info
                            try {
                                mapBeatSaverData = await fetchMapByHashOrKey(song.hash);
                            } catch (e) {
                                console.warn(`Failed to fetch BeatSaver data for ${song.songName}:`, e);
                                continue; // Skip this song if we can't get BeatSaver data
                            }
                        } else {
                            // Fetch from BeatSaver to get all difficulties
                            try {
                                const beatSaverData = await fetchMapByHashOrKey(song.hash);
                                if (!beatSaverData) {
                                    console.warn(`No BeatSaver data found for ${song.songName}`);
                                    continue; // Skip this song
                                }
                                
                                if (beatSaverData?.versions?.[0]?.diffs) {
                                    difficulty = song.difficulties[0].name;
                                }
                                mapBeatSaverData = beatSaverData;
                            } catch (e) {
                                console.warn(`Failed to fetch BeatSaver data for ${song.songName}:`, e);
                                continue; // Skip this song
                            }
                        }
                    } else {
                        // No difficulties in playlist, fetch from BeatSaver
                        try {
                            const beatSaverData = await fetchMapByHashOrKey(song.hash);
                            if (!beatSaverData) {
                                console.warn(`No BeatSaver data found for ${song.songName}`);
                                continue; // Skip this song
                            }
                            
                            if (beatSaverData?.versions?.[0]?.diffs) {
                                difficulty = getHighestDifficulty(beatSaverData.versions[0].diffs);
                            }
                            mapBeatSaverData = beatSaverData;
                        } catch (e) {
                            console.warn(`Failed to fetch BeatSaver data for ${song.songName}:`, e);
                            continue; // Skip this song
                        }
                    }

                    // Only proceed if we have valid BeatSaver data
                    if (!mapBeatSaverData) {
                        console.warn(`Skipping ${song.songName}: no BeatSaver data available`);
                        continue;
                    }

                    maps = [
                        ...maps,
                        {
                            beatsaverData: mapBeatSaverData,
                            author: song.levelAuthorName || 'Unknown Artist',
                            mapper: song.levelAuthorName || 'Unknown Mapper',
                            hash: song.hash,
                            key: song.levelid?.replace('custom_level_', '') || song.hash,
                            songName: song.songName || 'Unknown Song',
                            difficulty
                        }
                    ];
                } catch (e) {
                    console.warn(`Failed to process song ${song.songName}:`, e);
                    // Continue processing other songs instead of breaking
                }
            }

            processedMaps = maps;
        } catch (error) {
            errorMessage = error instanceof Error ? error.message : 'An error occurred while processing the file';
        } finally {
            isProcessing = false;
        }
    }

    function handleDragOver(e: DragEvent) {
        e.preventDefault();
        dragActive = true;
    }

    function handleDragLeave(e: DragEvent) {
        e.preventDefault();
        dragActive = false;
    }

    function handleDrop(e: DragEvent) {
        e.preventDefault();
        dragActive = false;
        
        const files = e.dataTransfer?.files;
        if (files && files.length > 0) {
            handleFileSelect(files[0]);
        }
    }

    function handleFileInputChange(e: Event) {
        const target = e.target as HTMLInputElement;
        const files = target.files;
        if (files && files.length > 0) {
            handleFileSelect(files[0]);
        }
    }

    function handleFileSelect(file: File) {
        const extension = file.name.toLowerCase().split('.').pop();
        if (extension !== 'bplist' && extension !== 'json') {
            errorMessage = 'Please select a .bplist or .json file';
            return;
        }
        
        processPlaylistFile(file);
    }

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

    function handleAddMaps() {
        if (processedMaps.length > 0) {
            const modifiersBitmap = getActiveModifiersAsBitmap();
            let finalisedMaps: CustomMap[] = processedMaps.map((map) => {
                const mapObject: CustomMap = {
                    beatsaverData: map.beatsaverData,
                    taData: {
                        guid: uuidv4(),
                        gameplayParameters: {
                            beatmap: {
                                name: map.songName,
                                levelId: `custom_level_${map.hash.toUpperCase()}`,
                                difficulty: getDifficultyNumber(map.difficulty),
                                characteristic: {
                                    serializedName: 'Standard',
                                    difficulties: []
                                }
                            },
                            gameplayModifiers: {
                                options: modifiersBitmap
                            },
                            attempts: 3,
                            disableCustomNotesOnStream: disableCustomNotesOnStream,
                            disableFail: disableFail,
                            disablePause: disablePause,
                            disableScoresaberSubmission: disableScoresaberSubmission,
                            showScoreboard: showScoreboard,
                            useSync: false,
                            target: 0,
                            playerSettings: {
                                options: 0,
                                playerHeight: 0,
                                sfxVolume: 0,
                                saberTrailIntensity: 0,
                                noteJumpStartBeatOffset: 0,
                                noteJumpFixedDuration: 0,
                                noteJumpDurationTypeSettings: 0,
                                arcVisibilityType: 0,
                            }
                        }
                    }
                }
                return mapObject;
            })
            dispatch('addMaps', { maps: finalisedMaps });
        }
    }

    // Get modifiers filtered by current mode
    function getFilteredModifiers(): Modifier[] {
        return gameModifiers.filter(modifier => 
            !modifier.allowedInMode || modifier.allowedInMode.includes('playing')
        );
    }

    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;
    }

    // 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);
    }

    // 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;
            });
        }
    }

    // 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;
        });
    }

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

    $: 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>

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

            <div class="popup-content">
                {#if errorMessage}
                    <div class="error-message">
                        <span class="material-icons">error</span>
                        <p>{errorMessage}</p>
                    </div>
                {/if}

                <div class="form-sections">
                    <!-- svelte-ignore a11y-click-events-have-key-events -->
                    <div class="form-section">
                        <h4>Select Playlist File</h4>
                        <p class="section-desc">Choose a .bplist or .json playlist file to import maps from</p>
                        
                        <div 
                            class="file-drop-zone" 
                            class:drag-active={dragActive}
                            on:dragover={handleDragOver}
                            on:dragleave={handleDragLeave}
                            on:drop={handleDrop}
                            on:click={() => fileInputRef?.click()}
                        >
                            <input 
                                bind:this={fileInputRef}
                                type="file" 
                                accept=".bplist,.json"
                                style="display: none;"
                                on:change={handleFileInputChange}
                            />
                            
                            {#if isProcessing}
                                <div class="drop-zone-content">
                                    <span class="material-icons loading-icon">refresh</span>
                                    <p>Processing playlist...</p>
                                </div>
                            {:else}
                                <div class="drop-zone-content">
                                    <span class="material-icons">cloud_upload</span>
                                    <p>Drop your playlist file here or click to browse</p>
                                    <small>Supports .bplist and .json files</small>
                                </div>
                            {/if}
                        </div>
                    </div>

                    {#if processedMaps.length > 0}
                        <div class="form-section">
                            <h4>Maps to Import ({processedMaps.length})</h4>
                            <p class="section-desc">Review the maps that will be imported</p>
                            
                            <div class="maps-list">
                                {#each processedMaps as map}
                                    <div class="map-item">
                                        <div class="map-info">
                                            <div class="map-title">{map.songName}</div>
                                            <div class="map-details">
                                                <span class="map-author">{map.author}</span>
                                                <span class="map-separator">•</span>
                                                <span class="map-mapper">{map.mapper}</span>
                                            </div>
                                            <div class="map-meta">
                                                <span class="map-difficulty">{map.difficulty}</span>
                                                <span class="map-separator">•</span>
                                                <span class="map-hash">{map.hash.substring(0, 8)}...</span>
                                            </div>
                                        </div>
                                    </div>
                                {/each}
                            </div>

                            <div class="form-section modifiers-section">
                                <h4>Game Modifiers</h4>
                                <p class="section-desc">Select which modifiers are enabled for all maps</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>
                                    
                                    <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>
                                </div>
                            </div>
                        </div>
                    {/if}
                </div>

                <div class="form-actions">
                    <button class="action-button cancel" on:click={handleClose}>
                        Cancel
                    </button>
                    <button 
                        class="action-button save" 
                        disabled={processedMaps.length === 0 || isProcessing}
                        on:click={handleAddMaps}
                    >
                        {#if isProcessing}
                            <span class="material-icons loading-icon">refresh</span>
                        {:else}
                            <span class="material-icons">add</span>
                        {/if}
                        Add Maps ({processedMaps.length})
                    </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: 800px;
        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;
    }
    
    .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;
        animation: fadeIn 0.3s ease-out;
    }
    
    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .error-message .material-icons {
        color: #ff5555;
    }
    
    .error-message p {
        margin: 0;
        color: #ff5555;
    }
    
    .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;
    }
    
    .file-drop-zone {
        border: 2px dashed var(--bg-tertiary);
        border-radius: 0.5rem;
        padding: 2rem;
        text-align: center;
        cursor: pointer;
        transition: all 0.2s ease;
        background-color: var(--bg-primary);
    }
    
    .file-drop-zone:hover,
    .file-drop-zone.drag-active {
        border-color: var(--accent-color);
        background-color: rgba(var(--accent-color-rgb, 59, 130, 246), 0.05);
    }
    
    .drop-zone-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 0.75rem;
    }
    
    .drop-zone-content .material-icons {
        font-size: 3rem;
        color: var(--text-secondary);
    }
    
    .drop-zone-content p {
        margin: 0;
        font-size: 1rem;
        font-weight: 500;
        color: var(--text-primary);
    }
    
    .drop-zone-content small {
        color: var(--text-secondary);
        font-size: 0.875rem;
    }
    
    .loading-icon {
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    .maps-list {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
        max-height: 300px;
        overflow-y: auto;
    }
    
    .map-item {
        background-color: var(--bg-primary);
        border-radius: 0.375rem;
        padding: 1rem;
        border: 1px solid var(--bg-tertiary);
    }
    
    .map-info {
        display: flex;
        flex-direction: column;
        gap: 0.25rem;
    }
    
    .map-title {
        font-size: 1rem;
        font-weight: 600;
        color: var(--text-primary);
        margin-bottom: 0.25rem;
    }
    
    .map-details,
    .map-meta {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-size: 0.875rem;
        color: var(--text-secondary);
    }
    
    .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;
    }
    
    .map-hash {
        font-family: monospace;
        font-size: 0.8125rem;
    }
    
    .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;
    }

    /* 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;
    }

    /* 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;
    }
    
    @media (max-width: 768px) {
        .popup-container {
            width: 95%;
            max-height: 95vh;
        }
        
        .form-actions {
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .action-button {
            width: 100%;
            justify-content: center;
        }
    }
    
    @media (max-width: 480px) {
        .file-drop-zone {
            padding: 1.5rem;
        }
        
        .drop-zone-content .material-icons {
            font-size: 2rem;
        }
        
        .drop-zone-content p {
            font-size: 0.875rem;
        }
        
        .map-details,
        .map-meta {
            flex-wrap: wrap;
        }
        
        .maps-list {
            max-height: 200px;
        }
    }
</style>