// JavaScript to handle opening and closing of the change password popup
const changePasswordButton = document.getElementById('changePasswordButton');
const changePasswordPopup = document.getElementById('changePasswordPopup');
const closeChangePasswordPopupButton = document.getElementById('closeChangePasswordPopupButton');

if (changePasswordButton) { // Überprüfen, ob das Element vorhanden ist
    changePasswordButton.addEventListener('click', function () {
        if (changePasswordPopup) {
            changePasswordPopup.classList.remove('hidden');
        }
    });
}
if (closeChangePasswordPopupButton) {
    closeChangePasswordPopupButton.addEventListener('click', function () {
        if (changePasswordPopup) {
            changePasswordPopup.classList.add('hidden');
        }
    });
}

window.addEventListener('click', function (event) {
    if (event.target === changePasswordPopup) {
        changePasswordPopup.classList.add('hidden');
    }
});

// Close popup with ESC key
document.addEventListener('keydown', function (event) {
    if (event.key === "Escape" && !changePasswordPopup.classList.contains('hidden')) {
        changePasswordPopup.classList.add('hidden');
    }
});

// Zeige Fehlermeldung beim Passwort ändern an
window.addEventListener('DOMContentLoaded', () => {
    const urlParams = new URLSearchParams(window.location.search);

    if (urlParams.has('password_error')) {
        const changePasswordPopup = document.getElementById('changePasswordPopup');
        const changePasswordErrorMessage = document.getElementById('changePasswordErrorMessage');
        const errorType = urlParams.get('password_error');

        changePasswordPopup.classList.remove('hidden');
        changePasswordErrorMessage.classList.remove('hidden');

        switch (errorType) {
            case 'wrong_current_password':
                changePasswordErrorMessage.textContent = 'Das aktuelle Passwort ist falsch.';
                break;
            case 'password_mismatch':
                changePasswordErrorMessage.textContent = 'Die neuen Passwörter stimmen nicht überein.';
                break;
            default:
                changePasswordErrorMessage.textContent = 'Fehler beim Ändern des Passworts.';
        }
    }
});

// Zeige Erfolgspopup beim Passwortwechsel an
window.addEventListener('DOMContentLoaded', (event) => {
    const urlParams = new URLSearchParams(window.location.search);

    if (urlParams.has('password_success')) {
        const passwordSuccessPopup = document.getElementById('passwordSuccessPopup');
        if (passwordSuccessPopup) {
            passwordSuccessPopup.classList.remove('hidden');
        }
        const closeSuccessPopup = document.getElementById('closeSuccessPopup');
        if (closeSuccessPopup) {
            closeSuccessPopup.addEventListener('click', () => {
                passwordSuccessPopup.classList.add('hidden');
                // Optional: Entferne den URL-Parameter ohne Neuladen
                const newUrl = window.location.href.split('?')[0];
                window.history.replaceState({}, document.title, newUrl);
            });
        }
    }
});

// Dropdown öffnen/schließen
const userDropdownToggle = document.getElementById('userDropdownToggle');
const userDropdownMenu = document.getElementById('userDropdownMenu');

if (userDropdownToggle && userDropdownMenu) {
    userDropdownToggle.addEventListener('click', (event) => {
        event.stopPropagation(); // Verhindert das Schließen des Menüs bei Klick auf den Button
        userDropdownMenu.classList.toggle('hidden');
    });

    // Schließe Dropdown, wenn außerhalb geklickt wird
    window.addEventListener('click', () => {
        if (!userDropdownMenu.classList.contains('hidden')) {
            userDropdownMenu.classList.add('hidden');
        }
    });

    // Schließe Dropdown mit ESC
    document.addEventListener('keydown', (event) => {
        if (event.key === "Escape" && !userDropdownMenu.classList.contains('hidden')) {
            userDropdownMenu.classList.add('hidden');
        }
    });
}

// Passwort ändern über Dropdown öffnen
const dropdownChangePasswordButton = document.getElementById('dropdownChangePasswordButton');
if (dropdownChangePasswordButton) {
    dropdownChangePasswordButton.addEventListener('click', () => {
        const changePasswordPopup = document.getElementById('changePasswordPopup');
        if (changePasswordPopup) {
            changePasswordPopup.classList.remove('hidden');
        }
    });
}
document.getElementById('openSearchDialog').addEventListener('click', function () {
    document.getElementById('searchDialog').classList.remove('hidden');
});

document.getElementById('closeSearchDialog').addEventListener('click', function () {
    document.getElementById('searchDialog').classList.add('hidden');
});

function debounce(func, delay) {
    let debounceTimer;
    return function () {
        const context = this;
        const args = arguments;
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => func.apply(context, args), delay);
    };
}

const searchInput = document.getElementById('searchInput');
const resultsContainer = document.getElementById('searchResults');

searchInput.addEventListener('input', debounce(function () {
    const query = this.value.toLowerCase();
    resultsContainer.innerHTML = '';

    if (query.length > 0) {
        fetch('search.php?query=' + query)
            .then(response => response.json())
            .then(data => {
                data.forEach(item => {
                    const resultItem = document.createElement('div');
                    resultItem.classList.add('p-4', 'mb-2', 'rounded-lg', 'bg-white', 'hover:bg-gray-100', 'transition', 'duration-100', 'flex', 'items-center', 'space-x-2', 'cursor-pointer');

                    const subjectSpan = document.createElement('span');
                    subjectSpan.classList.add('font-bold');
                    subjectSpan.textContent = item.displayName.split(' - ')[0];

                    const breadcrumbSpan = document.createElement('span');
                    breadcrumbSpan.classList.add('text-gray-500');
                    breadcrumbSpan.textContent = item.displayName.split(' - ').slice(1).join(' > ');

                    resultItem.appendChild(subjectSpan);
                    resultItem.appendChild(breadcrumbSpan);

                    resultItem.addEventListener('click', function () {
                        if (item.type === 'subject') {
                            window.location.href = 'subject.php?subject=' + item.id;
                        } else {
                            window.location.href = 'topic.php?subject=' + item.subjectId + '&topic=' + item.id;
                        }
                    });

                    resultsContainer.appendChild(resultItem);
                });
            });
    }
}, 300));