{{define "hotkeys"}}
<!DOCTYPE html>
<html lang="en">
<head>
    {{template "head-common" .}}
    <title>{{.Title}}</title>
    <style>
        /* Keyboard key styling */
        .kbd {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 1.75rem;
            padding: 0.25rem 0.5rem;
            background: linear-gradient(180deg, #4a4a4a 0%, #3a3a3a 100%);
            border: 1px solid #5a5a5a;
            border-radius: 4px;
            box-shadow: 0 2px 0 #2a2a2a, inset 0 1px 0 rgba(255,255,255,0.1);
            font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
            font-size: 0.75rem;
            font-weight: 500;
            color: #fff;
            text-shadow: 0 1px 0 rgba(0,0,0,0.3);
            white-space: nowrap;
        }
        .kbd-group {
            display: inline-flex;
            align-items: center;
            gap: 0.375rem;
            flex-wrap: wrap;
        }
        .kbd-separator {
            color: #6b7280;
            font-weight: normal;
        }
        
        /* Hotkey card styling */
        .hotkey-card {
            transition: background-color 0.15s ease;
        }
        .hotkey-card:hover {
            background-color: rgba(75, 85, 99, 0.3);
        }
        
        /* Category section */
        .category-section {
            scroll-margin-top: 80px;
        }
        
        /* Search highlight */
        .highlight {
            background-color: rgba(251, 191, 36, 0.3);
            padding: 0 2px;
            border-radius: 2px;
        }
    </style>
</head>
<body class="bg-gray-900 text-gray-100">
    {{template "accessibility-common" .}}
    {{template "main-layout-start" .}}
    {{template "hotkeys-content" .}}
    {{template "main-layout-end" .}}
    {{template "body-common-scripts" .}}
    <script>
        // Search functionality
        const searchInput = document.getElementById('hotkey-search');
        const categoryButtons = document.querySelectorAll('.category-btn');
        const hotkeyCards = document.querySelectorAll('.hotkey-card');
        const categorySections = document.querySelectorAll('.category-section');
        const resultsCount = document.getElementById('results-count');
        const clearBtn = document.getElementById('clear-search');
        const totalCount = {{.TotalCount}};
        
        let currentCategory = 'all';
        let currentSearch = '';
        
        function filterHotkeys() {
            const search = currentSearch.toLowerCase().trim();
            let visibleCount = 0;
            
            categorySections.forEach(section => {
                const category = section.dataset.category;
                const cards = section.querySelectorAll('.hotkey-card');
                let categoryVisible = 0;
                
                cards.forEach(card => {
                    const keys = card.dataset.keys.toLowerCase();
                    const description = card.dataset.description.toLowerCase();
                    const categoryLower = category.toLowerCase();
                    
                    const matchesSearch = !search || 
                        keys.includes(search) || 
                        description.includes(search) ||
                        categoryLower.includes(search);
                    
                    const matchesCategory = currentCategory === 'all' || category === currentCategory;
                    
                    const isVisible = matchesSearch && matchesCategory;
                    card.style.display = isVisible ? '' : 'none';
                    
                    if (isVisible) {
                        categoryVisible++;
                        visibleCount++;
                    }
                });
                
                // Hide category section if no visible items
                section.style.display = categoryVisible > 0 ? '' : 'none';
            });
            
            // Update results count
            if (search || currentCategory !== 'all') {
                resultsCount.textContent = visibleCount + ' of ' + totalCount + ' shortcuts';
                resultsCount.classList.remove('hidden');
            } else {
                resultsCount.classList.add('hidden');
            }
        }
        
        // Search input handler
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                currentSearch = e.target.value;
                filterHotkeys();
                
                // Show/hide clear button
                clearBtn.style.display = currentSearch ? 'flex' : 'none';
            });
        }
        
        // Clear search button
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                searchInput.value = '';
                currentSearch = '';
                filterHotkeys();
                clearBtn.style.display = 'none';
                searchInput.focus();
            });
        }
        
        // Category filter buttons
        categoryButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                // Update active state
                categoryButtons.forEach(b => {
                    b.classList.remove('bg-purple-600', 'text-white');
                    b.classList.add('bg-gray-700', 'text-gray-300');
                });
                btn.classList.remove('bg-gray-700', 'text-gray-300');
                btn.classList.add('bg-purple-600', 'text-white');
                
                currentCategory = btn.dataset.category;
                filterHotkeys();
                
                // Scroll to top of results
                document.getElementById('hotkeys-container').scrollIntoView({ behavior: 'smooth' });
            });
        });
        
        // Keyboard shortcut for search (/)
        document.addEventListener('keydown', (e) => {
            if (e.key === '/' && document.activeElement !== searchInput) {
                e.preventDefault();
                searchInput.focus();
            }
            if (e.key === 'Escape' && document.activeElement === searchInput) {
                searchInput.blur();
            }
        });

        // ============================================================
        // Preset Management
        // ============================================================
        const presetSelect = document.getElementById('preset-select');
        const applyPresetBtn = document.getElementById('apply-preset-btn');
        const resetPresetBtn = document.getElementById('reset-preset-btn');
        const activePresetBadge = document.getElementById('active-preset-badge');
        const presetModal = document.getElementById('preset-confirm-modal');
        const presetModalTitle = document.getElementById('preset-modal-title');
        const presetModalMessage = document.getElementById('preset-modal-message');
        const presetModalClose = document.getElementById('preset-modal-close');
        const presetModalCancel = document.getElementById('preset-modal-cancel');
        const presetModalConfirm = document.getElementById('preset-modal-confirm');

        const presetNames = {
            'default': 'mpv Default',
            'vlc': 'VLC',
            'mpc-hc': 'MPC-HC'
        };

        let pendingPreset = null;

        // Load active preset on page load
        async function loadActivePreset() {
            try {
                const resp = await fetch('/api/hotkeys/presets');
                if (!resp.ok) return;
                const data = await resp.json();
                if (data.active_preset) {
                    const name = presetNames[data.active_preset] || data.active_preset;
                    activePresetBadge.textContent = 'Active: ' + name;
                    activePresetBadge.classList.remove('bg-gray-700', 'text-gray-300');
                    activePresetBadge.classList.add('bg-purple-900', 'text-purple-200');
                } else {
                    activePresetBadge.textContent = 'Active: Custom';
                    activePresetBadge.classList.remove('bg-gray-700', 'text-gray-300');
                    activePresetBadge.classList.add('bg-amber-900', 'text-amber-200');
                }
            } catch (err) {
                activePresetBadge.textContent = 'Active: Unknown';
            }
        }
        loadActivePreset();

        // Show confirmation modal
        function showPresetModal(presetId) {
            pendingPreset = presetId;
            const name = presetNames[presetId] || presetId;
            presetModalTitle.textContent = 'Apply ' + name + ' Keybindings';
            presetModalMessage.textContent = 'Apply ' + name + ' keybindings? This will replace your current keybindings. A backup of your existing configuration will be created.';
            presetModalConfirm.textContent = 'Apply ' + name;
            presetModal.classList.remove('hidden');
            presetModal.classList.add('flex');
        }

        function hidePresetModal() {
            pendingPreset = null;
            presetModal.classList.add('hidden');
            presetModal.classList.remove('flex');
        }

        // Apply preset via API
        async function applyPreset(presetId) {
            const btn = applyPresetBtn;
            const originalHTML = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i class="bx bx-loader-alt bx-spin"></i> Applying...';

            try {
                const resp = await fetch('/api/hotkeys/apply', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({preset: presetId})
                });
                const data = await resp.json();

                if (resp.ok && data.success) {
                    if (window.showToast) {
                        showToast(data.message, 'success');
                    }
                    // Refresh active preset badge
                    loadActivePreset();
                } else {
                    if (window.showToast) {
                        showToast(data.message || 'Failed to apply preset', 'error');
                    }
                }
            } catch (err) {
                if (window.showToast) {
                    showToast('Network error: ' + err.message, 'error');
                }
            } finally {
                btn.disabled = false;
                btn.innerHTML = originalHTML;
            }
        }

        // Event listeners for preset management
        if (applyPresetBtn) {
            applyPresetBtn.addEventListener('click', () => {
                const presetId = presetSelect.value;
                if (presetId) {
                    showPresetModal(presetId);
                }
            });
        }

        if (resetPresetBtn) {
            resetPresetBtn.addEventListener('click', () => {
                pendingPreset = 'default';
                presetModalTitle.textContent = 'Reset Keybindings';
                presetModalMessage.textContent = 'Reset keybindings to mpv defaults? This will replace your current keybindings. A backup will be created.';
                presetModalConfirm.textContent = 'Reset to Default';
                presetModal.classList.remove('hidden');
                presetModal.classList.add('flex');
            });
        }

        // Modal close/cancel
        if (presetModalClose) presetModalClose.addEventListener('click', hidePresetModal);
        if (presetModalCancel) presetModalCancel.addEventListener('click', hidePresetModal);
        if (presetModal) {
            presetModal.addEventListener('click', (e) => {
                if (e.target === presetModal) hidePresetModal();
            });
        }

        // Modal confirm
        if (presetModalConfirm) {
            presetModalConfirm.addEventListener('click', () => {
                const preset = pendingPreset;
                hidePresetModal();
                if (preset) {
                    applyPreset(preset);
                }
            });
        }

        // Escape key closes preset modal
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && presetModal && !presetModal.classList.contains('hidden')) {
                hidePresetModal();
            }
        });
    </script>
</body>
</html>
{{end}}

{{define "hotkeys-content"}}
<div class="space-y-6" id="hotkeys-container">
    <div class="mb-6">
        <h2 class="text-3xl font-bold text-white">MPV Keyboard Shortcuts</h2>
        <p class="text-gray-400 mt-1">All available keyboard shortcuts for MPV media player</p>
    </div>

    <!-- Preset Management Section -->
    <div class="bg-gray-800 rounded-lg p-6 mb-6">
        <h3 class="text-xl font-semibold text-purple-400 mb-4">
            <i class="bx bx-grid-alt mr-2"></i>Keybinding Presets
        </h3>
        <div class="flex flex-col sm:flex-row sm:items-center gap-4">
            <div class="flex-1">
                <label for="preset-select" class="block text-sm text-gray-400 mb-1">Choose a preset profile</label>
                <select id="preset-select"
                        class="w-full bg-gray-700 text-white rounded-lg px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-purple-500 border border-gray-600">
                    <option value="default">mpv Default — Standard mpv keybindings</option>
                    <option value="vlc">VLC — VLC media player keybindings</option>
                    <option value="mpc-hc">MPC-HC — Media Player Classic keybindings</option>
                </select>
            </div>
            <div class="flex items-end gap-2 pt-5 sm:pt-0">
                <button id="apply-preset-btn"
                        class="bg-purple-600 hover:bg-purple-700 text-white px-5 py-2.5 rounded-lg font-medium transition flex items-center gap-2 focus:outline-none focus:ring-2 focus:ring-purple-500">
                    <i class="bx bx-compare"></i>
                    Apply Preset
                </button>
                <button id="reset-preset-btn"
                        class="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2.5 rounded-lg font-medium transition flex items-center gap-2 focus:outline-none focus:ring-2 focus:ring-gray-500"
                        title="Reset to mpv default keybindings">
                    <i class="bx bx-undo"></i>
                    Reset
                </button>
            </div>
        </div>
        <div class="flex items-center gap-2 mt-3">
            <span id="active-preset-badge"
                  class="text-xs px-2.5 py-1 rounded-full bg-gray-700 text-gray-300">
                Loading...
            </span>
            <p class="text-xs text-gray-500">This will replace your current keybindings. A backup will be created automatically.</p>
        </div>
    </div>

    <!-- Preset Confirmation Modal -->
    <div id="preset-confirm-modal"
         class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50"
         style="backdrop-filter: blur(4px);">
        <div class="bg-gray-800 rounded-lg shadow-2xl max-w-md w-full mx-4" style="animation: modalSlideIn 0.3s ease-out;">
            <div class="p-6 border-b border-gray-700">
                <div class="flex items-center justify-between">
                    <h3 id="preset-modal-title" class="text-xl font-semibold text-white">Apply Preset</h3>
                    <button id="preset-modal-close" class="text-gray-400 hover:text-white transition focus:outline-none focus:ring-2 focus:ring-purple-500 rounded" aria-label="Close modal">
                        <i class="bx bx-x text-2xl"></i>
                    </button>
                </div>
            </div>
            <div class="p-6">
                <p id="preset-modal-message" class="text-gray-300"></p>
            </div>
            <div class="p-6 border-t border-gray-700 flex justify-end gap-3">
                <button id="preset-modal-cancel" class="bg-gray-700 hover:bg-gray-600 text-white px-4 py-2 rounded transition focus:outline-none focus:ring-2 focus:ring-gray-500">
                    Cancel
                </button>
                <button id="preset-modal-confirm" class="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded transition focus:outline-none focus:ring-2 focus:ring-purple-500">
                    Apply
                </button>
            </div>
        </div>
    </div>

    <!-- Search and Filter Section -->
    <div class="bg-gray-800 rounded-lg p-4 mb-6">
        <div class="flex flex-col md:flex-row gap-4">
            <!-- Search Input -->
            <div class="flex-1 relative">
                <div class="relative">
                    <input type="text" 
                           id="hotkey-search" 
                           placeholder="Search shortcuts... (press / to focus)"
                           class="w-full bg-gray-700 text-white rounded-lg pl-10 pr-20 py-3 focus:outline-none focus:ring-2 focus:ring-purple-500"
                           aria-label="Search keyboard shortcuts">
                    <i class="bx bx-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
                    <div class="absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-2">
                        <span id="results-count" class="hidden text-xs text-gray-400 bg-gray-600 px-2 py-1 rounded"></span>
                        <button id="clear-search" 
                                class="hidden text-gray-400 hover:text-white p-1 rounded"
                                title="Clear search">
                            <i class="bx bx-x text-lg"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Category Filter Buttons -->
        <div class="flex flex-wrap gap-2 mt-4">
            <button class="category-btn bg-purple-600 text-white px-3 py-1.5 rounded-lg text-sm font-medium transition-colors" 
                    data-category="all">
                All ({{.TotalCount}})
            </button>
            {{range .CategoryCounts}}
            <button class="category-btn bg-gray-700 text-gray-300 hover:bg-gray-600 px-3 py-1.5 rounded-lg text-sm font-medium transition-colors" 
                    data-category="{{.Category}}">
                {{.Category}} ({{.Count}})
            </button>
            {{end}}
        </div>
    </div>

    <!-- Hotkeys List by Category -->
    {{range .Categories}}
    <div class="category-section mb-6" data-category="{{.Category}}">
        <h3 class="text-xl font-semibold text-purple-400 mb-3 flex items-center gap-2">
            <i class="bx {{categoryIcon .Category}}"></i>
            {{.Category}}
            <span class="text-sm text-gray-500 font-normal">({{.Count}} shortcuts)</span>
        </h3>
        
        <div class="bg-gray-800 rounded-lg overflow-hidden">
            {{range .Hotkeys}}
            <div class="hotkey-card flex flex-col md:flex-row md:items-center gap-3 p-4 border-b border-gray-700 last:border-b-0"
                 data-keys="{{.Keys}}"
                 data-description="{{.Description}}">
                <!-- Keys -->
                <div class="flex-shrink-0 md:w-48">
                    <div class="kbd-group">
                        {{formatKeys .Keys}}
                    </div>
                </div>
                
                <!-- Description -->
                <div class="flex-1">
                    <p class="text-gray-200">{{.Description}}</p>
                </div>
            </div>
            {{end}}
        </div>
    </div>
    {{end}}

    <!-- Info Box -->
    <div class="bg-blue-900/30 border border-blue-700 rounded-lg p-4 mt-6">
        <p class="text-sm text-blue-200">
            <i class="bx bx-info-circle mr-2"></i>
            <strong>Tip:</strong> Press <kbd class="kbd text-xs">/</kbd> to quickly search shortcuts. 
            Press <kbd class="kbd text-xs">?</kbd> in MPV to show key bindings overlay.
        </p>
    </div>
</div>
{{end}}
