/* Oikolog CRM - Keyboard Shortcuts & Utilities */

document.addEventListener('DOMContentLoaded', function() {
    // Ctrl+K -> Suche fokussieren
    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
            e.preventDefault();
            var searchInput = document.getElementById('global-search');
            if (searchInput) {
                searchInput.focus();
                searchInput.select();
            }
        }
        // Escape -> Suchergebnisse schliessen
        if (e.key === 'Escape') {
            var dropdown = document.getElementById('search-dropdown');
            if (dropdown) dropdown.innerHTML = '';
            var searchInput = document.getElementById('global-search');
            if (searchInput) searchInput.blur();
        }
    });

    // Enter-Taste in Suche → Suchergebnisseite
    var searchInput = document.getElementById('global-search');
    if (searchInput) {
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                var q = searchInput.value.trim();
                if (q) window.location = '/suche?q=' + encodeURIComponent(q);
            }
        });
    }

    // Klick ausserhalb schliesst Dropdowns
    document.addEventListener('click', function(e) {
        var dropdown = document.getElementById('search-dropdown');
        var searchBox = document.querySelector('.search-box');
        if (dropdown && searchBox && !searchBox.contains(e.target)) {
            dropdown.innerHTML = '';
        }
        // Search-Dropdowns (Tags etc.) schliessen
        document.querySelectorAll('.search-dropdown-menu.open').forEach(function(menu) {
            if (!menu.parentElement.contains(e.target)) {
                menu.classList.remove('open');
            }
        });
    });
});

/* Toast-Benachrichtigungen */
function showToast(message, type) {
    type = type || 'info';
    var container = document.getElementById('toast-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'toast-container';
        document.body.appendChild(container);
    }
    var toast = document.createElement('div');
    toast.className = 'toast toast-' + type;
    toast.textContent = message;
    container.appendChild(toast);
    setTimeout(function() {
        toast.classList.add('toast-fade');
        setTimeout(function() { toast.remove(); }, 300);
    }, 3000);
}

/* HTMX Event Listener fuer Toasts */
document.addEventListener('htmx:afterRequest', function(e) {
    var msg = e.detail.xhr.getResponseHeader('X-Toast-Message');
    var type = e.detail.xhr.getResponseHeader('X-Toast-Type') || 'info';
    if (msg) showToast(msg, type);
});
