document.addEventListener('DOMContentLoaded', function () {
    // Define the updateSettings function first
    function updateSettings(settingKey, settingValue) {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '/updateSettings', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 300) {
                console.log('Settings updated successfully!');
            } else {
                console.log('Failed to update settings.');
            }
        };
        xhr.send(encodeURI(settingKey + '=' + settingValue));
    }

    const settingsIcon = document.querySelector('.settings-icon-link-search');
    const searchMenu = document.querySelector('.search-menu');

    settingsIcon.addEventListener('click', function () {
        searchMenu.classList.toggle('settings-menu-hidden');
        searchMenu.classList.toggle('settings-menu-visible');
    });

    // Theme change event listeners
    document.getElementById('dark_theme').addEventListener('click', function () {
        const currentUrl = new URL(window.location.href); // Get the current URL
        currentUrl.searchParams.set('theme', 'dark');    // Add or update the 'theme' parameter
        window.location.href = currentUrl.toString();    // Redirect to the updated URL
    });

    document.getElementById('light_theme').addEventListener('click', function () {
        const currentUrl = new URL(window.location.href); // Get the current URL
        currentUrl.searchParams.set('theme', 'light');   // Add or update the 'theme' parameter
        window.location.href = currentUrl.toString();    // Redirect to the updated URL
    });

    // Event listener for Safe Search Selection
    document.getElementById('safeSearchSelect').addEventListener('change', function () {
        updateSettings('safe', this.value);
    });

    // Event listener for Language Selection
    document.getElementById('languageSelect').addEventListener('change', function () {
        updateSettings('lang', this.value);
    });

    // Show/Hide About QGato
    document.getElementById('aboutQGatoBtn').addEventListener('click', function() {
        document.getElementById('aboutQGatoModal').style.display = 'block';
    });
    
    document.getElementById('close-button').addEventListener('click', function() {
        document.getElementById('aboutQGatoModal').style.display = 'none';
    });
});