{% extends "base.html" %}

{% block title %}Keyboard Shortcuts Settings - {{ super() }}{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{{ url_for('static', filename='keyboard-shortcuts.css') }}">
<style>
    .setting-card {
        transition: all 0.2s ease;
    }
    .setting-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 16px -4px rgba(0, 0, 0, 0.1);
    }
</style>
{% endblock %}

{% block content %}
<div id="mainContentAnchor" class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <!-- Header -->
    <div class="mb-8">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-3xl font-bold text-text-light dark:text-text-dark flex items-center gap-3">
                    <i class="fas fa-keyboard text-primary"></i>
                    Keyboard Shortcuts
                </h1>
                <p class="mt-2 text-text-muted-light dark:text-text-muted-dark">
                    Customize and manage your keyboard shortcuts for faster navigation
                </p>
            </div>
            <div class="flex gap-3">
                <button type="button" id="view-all-shortcuts-btn"
                        class="px-4 py-2 bg-background-light dark:bg-background-dark border border-border-light dark:border-border-dark rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
                    <i class="fas fa-list mr-2"></i>View All Shortcuts
                </button>
                <button type="button" onclick="resetToDefaults()" 
                        class="px-4 py-2 bg-background-light dark:bg-background-dark border border-border-light dark:border-border-dark rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
                    <i class="fas fa-undo mr-2"></i>Reset to Defaults
                </button>
            </div>
        </div>
    </div>

    <!-- Quick Stats -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark">Total Shortcuts</p>
                    <p class="text-2xl font-bold text-text-light dark:text-text-dark mt-1" id="total-shortcuts">0</p>
                </div>
                <div class="w-12 h-12 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex items-center justify-center">
                    <i class="fas fa-keyboard text-blue-600 dark:text-blue-400 text-xl"></i>
                </div>
            </div>
        </div>

        <div class="bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark">Custom Shortcuts</p>
                    <p class="text-2xl font-bold text-text-light dark:text-text-dark mt-1" id="custom-shortcuts">0</p>
                </div>
                <div class="w-12 h-12 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
                    <i class="fas fa-magic text-purple-600 dark:text-purple-400 text-xl"></i>
                </div>
            </div>
        </div>

        <div class="bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark">Most Used</p>
                    <p class="text-sm font-semibold text-text-light dark:text-text-dark mt-1" id="most-used">-</p>
                </div>
                <div class="w-12 h-12 bg-green-100 dark:bg-green-900/30 rounded-lg flex items-center justify-center">
                    <i class="fas fa-chart-line text-green-600 dark:text-green-400 text-xl"></i>
                </div>
            </div>
        </div>

        <div class="bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark">Total Uses</p>
                    <p class="text-2xl font-bold text-text-light dark:text-text-dark mt-1" id="total-uses">0</p>
                </div>
                <div class="w-12 h-12 bg-amber-100 dark:bg-amber-900/30 rounded-lg flex items-center justify-center">
                    <i class="fas fa-fire text-amber-600 dark:text-amber-400 text-xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Settings Tabs -->
    <div class="mb-6">
        <div class="border-b border-border-light dark:border-border-dark">
            <nav class="flex space-x-8" aria-label="Tabs">
                <button type="button" onclick="window.keyboardShortcutsSwitchTab('general')" 
                        data-tab="general"
                        class="tab-button border-b-2 border-primary text-primary py-3 px-1 font-medium">
                    <i class="fas fa-cog mr-2"></i>General Settings
                </button>
                <button onclick="switchTab('customization')" 
                        data-tab="customization"
                        class="tab-button border-b-2 border-transparent text-text-muted-light dark:text-text-muted-dark hover:text-text-light dark:hover:text-text-dark py-3 px-1 font-medium">
                    <i class="fas fa-edit mr-2"></i>Customize Shortcuts
                </button>
                <button type="button" onclick="window.keyboardShortcutsSwitchTab('statistics')" 
                        data-tab="statistics"
                        class="tab-button border-b-2 border-transparent text-text-muted-light dark:text-text-muted-dark hover:text-text-light dark:hover:text-text-dark py-3 px-1 font-medium">
                    <i class="fas fa-chart-bar mr-2"></i>Usage Statistics
                </button>
            </nav>
        </div>
    </div>

    <!-- Tab Content -->
    <div id="general-tab" class="tab-content">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- Enable/Disable Shortcuts -->
            <div class="setting-card bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <h3 class="text-lg font-semibold text-text-light dark:text-text-dark flex items-center gap-2">
                            <i class="fas fa-power-off text-primary"></i>
                            Enable Keyboard Shortcuts
                        </h3>
                        <p class="text-sm text-text-muted-light dark:text-text-muted-dark mt-2">
                            Turn keyboard shortcuts on or off globally
                        </p>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer ml-4">
                        <input type="checkbox" id="shortcuts-enabled" class="sr-only peer" checked>
                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
                    </label>
                </div>
            </div>

            <!-- Show Hints -->
            <div class="setting-card bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <h3 class="text-lg font-semibold text-text-light dark:text-text-dark flex items-center gap-2">
                            <i class="fas fa-lightbulb text-primary"></i>
                            Show Shortcut Hints
                        </h3>
                        <p class="text-sm text-text-muted-light dark:text-text-muted-dark mt-2">
                            Display keyboard shortcut hints next to buttons
                        </p>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer ml-4">
                        <input type="checkbox" id="show-hints" class="sr-only peer" checked>
                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
                    </label>
                </div>
            </div>

            <!-- Sequence Timeout -->
            <div class="setting-card bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
                <h3 class="text-lg font-semibold text-text-light dark:text-text-dark flex items-center gap-2 mb-4">
                    <i class="fas fa-clock text-primary"></i>
                    Sequence Timeout
                </h3>
                <p class="text-sm text-text-muted-light dark:text-text-muted-dark mb-4">
                    Time to wait between key presses in a sequence (e.g., 'g d')
                </p>
                <div class="flex items-center gap-4">
                    <input type="range" id="sequence-timeout" min="500" max="3000" step="100" value="1000" 
                           class="flex-1 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700">
                    <span id="timeout-value" class="text-sm font-semibold text-text-light dark:text-text-dark w-16 text-right">1000ms</span>
                </div>
            </div>

            <!-- Context Awareness -->
            <div class="setting-card bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
                <div class="flex items-start justify-between">
                    <div class="flex-1">
                        <h3 class="text-lg font-semibold text-text-light dark:text-text-dark flex items-center gap-2">
                            <i class="fas fa-layer-group text-primary"></i>
                            Context-Aware Shortcuts
                        </h3>
                        <p class="text-sm text-text-muted-light dark:text-text-muted-dark mt-2">
                            Enable different shortcuts based on current context
                        </p>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer ml-4">
                        <input type="checkbox" id="context-aware" class="sr-only peer" checked>
                        <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
                    </label>
                </div>
            </div>
        </div>

        <!-- Quick Access -->
        <div class="mt-6 bg-gradient-to-br from-blue-50 to-purple-50 dark:from-blue-900/20 dark:to-purple-900/20 p-6 rounded-lg border border-blue-200 dark:border-blue-800">
            <h3 class="text-lg font-semibold text-text-light dark:text-text-dark flex items-center gap-2 mb-4">
                <i class="fas fa-rocket text-primary"></i>
                Quick Tips
            </h3>
            <ul class="space-y-2 text-sm text-text-light dark:text-text-dark">
                <li class="flex items-start gap-2">
                    <i class="fas fa-check-circle text-green-600 dark:text-green-400 mt-0.5"></i>
                    <span>Press <kbd class="px-2 py-1 bg-card-light dark:bg-card-dark border border-gray-300 dark:border-gray-600 rounded text-xs">Shift</kbd> + <kbd class="px-2 py-1 bg-card-light dark:bg-card-dark border border-gray-300 dark:border-gray-600 rounded text-xs">?</kbd> to view all keyboard shortcuts</span>
                </li>
                <li class="flex items-start gap-2">
                    <i class="fas fa-check-circle text-green-600 dark:text-green-400 mt-0.5"></i>
                    <span>Use <kbd class="px-2 py-1 bg-card-light dark:bg-card-dark border border-gray-300 dark:border-gray-600 rounded text-xs">Ctrl</kbd> + <kbd class="px-2 py-1 bg-card-light dark:bg-card-dark border border-gray-300 dark:border-gray-600 rounded text-xs">K</kbd> to open the command palette</span>
                </li>
                <li class="flex items-start gap-2">
                    <i class="fas fa-check-circle text-green-600 dark:text-green-400 mt-0.5"></i>
                    <span>Navigate quickly with sequences like <kbd class="px-2 py-1 bg-card-light dark:bg-card-dark border border-gray-300 dark:border-gray-600 rounded text-xs">g</kbd> <kbd class="px-2 py-1 bg-card-light dark:bg-card-dark border border-gray-300 dark:border-gray-600 rounded text-xs">d</kbd> for dashboard</span>
                </li>
                <li class="flex items-start gap-2">
                    <i class="fas fa-check-circle text-green-600 dark:text-green-400 mt-0.5"></i>
                    <span>Context-aware shortcuts change based on what you're doing (table, form, etc.)</span>
                </li>
            </ul>
        </div>
    </div>

    <div id="customization-tab" class="tab-content hidden">
        <div class="bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h3 class="text-lg font-semibold text-text-light dark:text-text-dark">{{ _('Customize Shortcuts') }}</h3>
                    <p class="text-sm text-text-muted-light dark:text-text-muted-dark mt-1">
                        Click on a shortcut to record a new key combination
                    </p>
                </div>
                <div class="flex gap-2">
                    <input type="text" 
                           id="customization-search" 
                           placeholder="{{ _('Search shortcuts...') }}" 
                           class="px-4 py-2 bg-background-light dark:bg-background-dark border border-border-light dark:border-border-dark rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
                </div>
            </div>

            <div id="shortcut-feedback" class="hidden mb-4 p-4 rounded-lg" role="alert"></div>
            <div id="customization-list" class="space-y-2">
                <!-- Populated by JavaScript from API -->
            </div>
            <div class="mt-4 flex gap-2">
                <button type="button" id="save-shortcuts-btn" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90">
                    <i class="fas fa-save mr-2"></i>{{ _('Save changes') }}
                </button>
            </div>
        </div>
    </div>

    <div id="statistics-tab" class="tab-content hidden">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- Most Used Shortcuts -->
            <div class="bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
                <h3 class="text-lg font-semibold text-text-light dark:text-text-dark flex items-center gap-2 mb-4">
                    <i class="fas fa-trophy text-amber-500"></i>
                    Most Used Shortcuts
                </h3>
                <div id="most-used-list" class="space-y-3">
                    <!-- Populated by JavaScript -->
                </div>
            </div>

            <!-- Recent Usage -->
            <div class="bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
                <h3 class="text-lg font-semibold text-text-light dark:text-text-dark flex items-center gap-2 mb-4">
                    <i class="fas fa-history text-blue-500"></i>
                    Recently Used
                </h3>
                <div id="recent-usage-list" class="space-y-3">
                    <!-- Populated by JavaScript -->
                </div>
            </div>
        </div>

        <!-- Usage Chart -->
        <div class="mt-6 bg-card-light dark:bg-card-dark p-6 rounded-lg border border-border-light dark:border-border-dark">
            <h3 class="text-lg font-semibold text-text-light dark:text-text-dark flex items-center gap-2 mb-4">
                <i class="fas fa-chart-area text-green-500"></i>
                Usage Over Time
            </h3>
            <div class="h-64 flex items-center justify-center text-text-muted-light dark:text-text-muted-dark">
                <div class="text-center">
                    <i class="fas fa-chart-line text-4xl mb-4 opacity-30"></i>
                    <p>Usage statistics will appear here as you use keyboard shortcuts</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Tab switching
function switchTab(tabName) {
    // Update tab buttons
    document.querySelectorAll('.tab-button').forEach(btn => {
        const isActive = btn.dataset.tab === tabName;
        btn.classList.toggle('border-primary', isActive);
        btn.classList.toggle('text-primary', isActive);
        btn.classList.toggle('border-transparent', !isActive);
        btn.classList.toggle('text-text-muted-light', !isActive);
        btn.classList.toggle('dark:text-text-muted-dark', !isActive);
    });

    // Update tab content
    document.querySelectorAll('.tab-content').forEach(content => {
        content.classList.add('hidden');
    });
    document.getElementById(`${tabName}-tab`).classList.remove('hidden');

    // Load content
    if (tabName === 'customization') {
        loadCustomizationList();
    } else if (tabName === 'statistics') {
        loadStatistics();
    }
}

// API URLs (injected by Flask)
const KEYBOARD_SHORTCUTS_API_GET = {{ url_for('settings.api_keyboard_shortcuts_get') | tojson }};
const KEYBOARD_SHORTCUTS_API_POST = {{ url_for('settings.api_keyboard_shortcuts_save') | tojson }};
const KEYBOARD_SHORTCUTS_API_RESET = {{ url_for('settings.api_keyboard_shortcuts_reset') | tojson }};
let shortcutsData = { shortcuts: [], overrides: {} };

function getCsrfHeaders() {
    const h = { 'Content-Type': 'application/json' };
    const tok = document.querySelector('meta[name="csrf-token"]');
    if (tok && tok.getAttribute('content')) h['X-CSRFToken'] = tok.getAttribute('content');
    return h;
}

function normalizeKey(key) {
    if (!key || typeof key !== 'string') return '';
    return key.trim().toLowerCase().replace(/\s+/g, ' ').replace(/command|cmd/gi, 'ctrl');
}

function formatKeyDisplay(key) {
    if (!key) return '';
    return key.split('+').map(p => {
        const k = p.trim();
        if (k === 'ctrl') return navigator.platform.toUpperCase().indexOf('MAC') >= 0 ? '⌘' : 'Ctrl';
        if (k === 'shift') return '⇧'; if (k === 'alt') return '⌥';
        if (k === 'enter') return '↵'; if (k === ' ') return '␣';
        return k.length === 1 ? k.toUpperCase() : k;
    }).join(' + ');
}

function showShortcutFeedback(msg, isError) {
    const el = document.getElementById('shortcut-feedback');
    if (el) {
        el.textContent = msg;
        el.className = 'mb-4 p-4 rounded-lg ' + (isError ? 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-200' : 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-200');
        el.classList.remove('hidden');
        setTimeout(function() { el.classList.add('hidden'); }, 5000);
    }
    if (window.toastManager) { isError ? window.toastManager.error(msg) : window.toastManager.success(msg); }
}

async function fetchShortcutsConfig() {
    const res = await fetch(KEYBOARD_SHORTCUTS_API_GET, { credentials: 'same-origin' });
    if (!res.ok) throw new Error(res.status === 401 ? 'Unauthorized' : 'Failed to load');
    return res.json();
}

function updateOverviewStats() {
    var s = shortcutsData.shortcuts || [];
    var total = s.length;
    var custom = s.filter(function(x) { return x.current_key !== x.default_key; }).length;
    var el = document.getElementById('total-shortcuts'); if (el) el.textContent = total;
    el = document.getElementById('custom-shortcuts'); if (el) el.textContent = custom;
    el = document.getElementById('most-used'); if (el) el.textContent = custom > 0 ? (custom + ' customized') : '-';
    el = document.getElementById('total-uses'); if (el) el.textContent = '0';
}

function escapeHtml(str) {
    var d = document.createElement('div'); d.textContent = str; return d.innerHTML;
}

var recordingId = null;
function startRecording(btn) {
    if (recordingId) return;
    recordingId = btn.dataset.id;
    btn.textContent = '{{ _("Press keys...") }}';
    btn.classList.add('ring-2', 'ring-primary');
    var handler = function(e) {
        e.preventDefault(); e.stopPropagation();
        var parts = [];
        if (e.ctrlKey || e.metaKey) parts.push('Ctrl');
        if (e.altKey) parts.push('Alt');
        if (e.shiftKey && e.key.length > 1) parts.push('Shift');
        var key = e.key; if (key === ' ') key = 'Space';
        parts.push(key);
        var normalized = normalizeKey(parts.join('+'));
        document.removeEventListener('keydown', handler);
        recordingId = null;
        btn.classList.remove('ring-2', 'ring-primary');
        setShortcutKey(btn.dataset.id, normalized);
        renderCustomizationList();
    };
    document.addEventListener('keydown', handler, { once: true });
    setTimeout(function() {
        if (recordingId === btn.dataset.id) {
            document.removeEventListener('keydown', handler);
            recordingId = null;
            btn.classList.remove('ring-2', 'ring-primary');
            renderCustomizationList();
        }
    }, 10000);
}

function setShortcutKey(id, normalizedKey) {
    var s = shortcutsData.shortcuts.find(function(x) { return x.id === id; });
    if (!s) return;
    s.current_key = normalizedKey;
    var overrides = {};
    shortcutsData.shortcuts.forEach(function(x) {
        if (x.current_key !== x.default_key) overrides[x.id] = x.current_key;
    });
    shortcutsData.overrides = overrides;
}

function revertShortcut(id) {
    var s = shortcutsData.shortcuts.find(function(x) { return x.id === id; });
    if (!s) return;
    s.current_key = s.default_key;
    delete shortcutsData.overrides[id];
    renderCustomizationList();
    updateOverviewStats();
}

function renderCustomizationList() {
    var list = document.getElementById('customization-list');
    if (!list) return;
    var shortcuts = shortcutsData.shortcuts || [];
    list.innerHTML = shortcuts.map(function(s) {
        var isCustom = s.current_key !== s.default_key;
        var displayKey = formatKeyDisplay(s.current_key);
        return '<div class="shortcut-customization-row flex items-center justify-between p-4 bg-background-light dark:bg-background-dark rounded-lg border border-border-light dark:border-border-dark" data-id="' + s.id + '">' +
            '<div class="flex-1">' +
            '<div class="font-medium text-text-light dark:text-text-dark flex items-center gap-2"><i class="fas fa-keyboard text-primary"></i>' + escapeHtml(s.name) + '</div>' +
            '<div class="text-sm text-text-muted-light dark:text-text-muted-dark mt-1">' + escapeHtml(s.description) + '</div></div>' +
            '<div class="flex items-center gap-3">' +
            '<button type="button" class="shortcut-key-btn px-3 py-2 bg-card-light dark:bg-card-dark border rounded font-mono text-sm min-w-[8rem] text-left" data-id="' + s.id + '" title="{{ _("Click then press a key combination") }}">' + (displayKey || '{{ _("Click to record") }}') + '</button>' +
            (isCustom ? '<button type="button" class="shortcut-revert-btn px-2 py-1 text-xs text-amber-600 dark:text-amber-400 hover:underline" data-id="' + s.id + '">{{ _("Revert") }}</button>' : '') +
            '</div></div>';
    }).join('');
    list.querySelectorAll('.shortcut-key-btn').forEach(function(btn) { btn.addEventListener('click', function() { startRecording(btn); }); });
    list.querySelectorAll('.shortcut-revert-btn').forEach(function(btn) { btn.addEventListener('click', function() { revertShortcut(btn.dataset.id); }); });
}

function checkConflicts() {
    var keyToIds = {};
    shortcutsData.shortcuts.forEach(function(s) {
        (keyToIds[s.current_key] = keyToIds[s.current_key] || []).push(s.id);
    });
    for (var key in keyToIds) { if (keyToIds[key].length > 1) return '{{ _("Conflict: the same key is assigned to multiple actions.") }}'; }
    return null;
}

async function saveShortcuts() {
    var err = checkConflicts();
    if (err) { showShortcutFeedback(err, true); return; }
    var overrides = {};
    shortcutsData.shortcuts.forEach(function(s) {
        if (s.current_key !== s.default_key) overrides[s.id] = s.current_key;
    });
    var saveBtn = document.getElementById('save-shortcuts-btn');
    if (window.setSubmitButtonLoading && saveBtn) window.setSubmitButtonLoading(saveBtn, true, '{{ _("Saving...") }}');
    try {
        var res = await fetch(KEYBOARD_SHORTCUTS_API_POST, { method: 'POST', credentials: 'same-origin', headers: getCsrfHeaders(), body: JSON.stringify({ overrides: overrides }) });
        var data = await res.json().catch(function() { return {}; });
        if (!res.ok) { showShortcutFeedback(data.error || '{{ _("Failed to save") }}', true); return; }
        shortcutsData = data;
        updateOverviewStats();
        renderCustomizationList();
        showShortcutFeedback('{{ _("Shortcuts saved.") }}', false);
    } catch (e) { showShortcutFeedback('{{ _("Failed to save shortcuts.") }}', true); }
    finally { if (window.setSubmitButtonLoading && saveBtn) window.setSubmitButtonLoading(saveBtn, false); }
}

async function resetToDefaults() {
    var confirmed = window.showConfirm ? await window.showConfirm('{{ _("This will reset all keyboard shortcuts to their default values. Continue?") }}',
        { title: '{{ _("Reset to Defaults") }}', confirmText: '{{ _("Reset") }}', cancelText: '{{ _("Cancel") }}', variant: 'warning' }) : confirm('{{ _("Reset all shortcuts to defaults?") }}');
    if (!confirmed) return;
    try {
        var res = await fetch(KEYBOARD_SHORTCUTS_API_RESET, { method: 'POST', credentials: 'same-origin', headers: getCsrfHeaders() });
        var data = await res.json().catch(function() { return {}; });
        if (!res.ok) { showShortcutFeedback(data.error || '{{ _("Failed to reset") }}', true); return; }
        shortcutsData = data;
        updateOverviewStats();
        renderCustomizationList();
        showShortcutFeedback('{{ _("Shortcuts reset to defaults.") }}', false);
    } catch (e) { showShortcutFeedback('{{ _("Failed to reset shortcuts.") }}', true); }
}

function loadStatistics() {
    var mostUsedList = document.getElementById('most-used-list');
    var recentList = document.getElementById('recent-usage-list');
    if (mostUsedList) mostUsedList.innerHTML = '<p class="text-sm text-text-muted-light dark:text-text-muted-dark">Use shortcuts to see usage stats (when available).</p>';
    if (recentList) recentList.innerHTML = '<p class="text-sm text-text-muted-light dark:text-text-muted-dark">No recent usage data.</p>';
}

function loadCustomizationList() {
    fetchShortcutsConfig().then(function(data) {
        shortcutsData = data;
        renderCustomizationList();
        updateOverviewStats();
    }).catch(function() {
        var list = document.getElementById('customization-list');
        if (list) list.innerHTML = '<p class="text-sm text-red-600 dark:text-red-400">{{ _("Failed to load shortcuts.") }}</p>';
    });
}

window.resetToDefaults = resetToDefaults;
window.keyboardShortcutsSwitchTab = switchTab;

document.addEventListener('DOMContentLoaded', function() {
    var timeoutSlider = document.getElementById('sequence-timeout');
    var timeoutValue = document.getElementById('timeout-value');
    if (timeoutSlider && timeoutValue) timeoutSlider.addEventListener('input', function() { timeoutValue.textContent = this.value + 'ms'; });
    var search = document.getElementById('customization-search');
    if (search) search.addEventListener('input', function() {
        var q = this.value.toLowerCase();
        document.querySelectorAll('.shortcut-customization-row').forEach(function(row) { row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none'; });
    });
    var saveBtn = document.getElementById('save-shortcuts-btn');
    if (saveBtn) saveBtn.addEventListener('click', saveShortcuts);
    var viewAllBtn = document.getElementById('view-all-shortcuts-btn');
    if (viewAllBtn) viewAllBtn.addEventListener('click', function() {
        if (window.shortcutManager && typeof window.shortcutManager.showShortcutsPanel === 'function') window.shortcutManager.showShortcutsPanel();
        else switchTab('customization');
    });
    fetchShortcutsConfig().then(function(data) {
        shortcutsData = data;
        updateOverviewStats();
    }).catch(function() { updateOverviewStats(); });
});
</script>
{% endblock %}

