document.addEventListener('DOMContentLoaded', () => {
    const contentContainer = document.getElementById('content-container');
    const updateContent = async (content) => {
        if (content === 'settings') {
            contentContainer.innerHTML = '<div class="loading">Loading settings...</div>';

            try {
                const themes = await fetchThemes();
                const userTheme = await fetchUserTheme();
                contentContainer.innerHTML = `
                    <div class="settings-container">
                        <h2>Iestatījumi</h2>
                        <div class="theme-selection">
                            <h3>Izvēlies tematiku</h3>
                            ${themes
                                .map(
                                    (theme) => `
                                    <label>
                                        <input type="radio" name="theme" value="${theme.id}" ${
                                            parseInt(userTheme, 10) === theme.id ? 'checked' : ''
                                        }>
                                        ${theme.description}
                                    </label>
                                `
                                )
                                .join('')}
                        </div>
                        <button id="save-settings">Saglabāt</button>
                        <div id="settings-message" class="settings-message hidden"></div>
                    </div>
                `;
                attachSettingsListeners();
            } catch (error) {
                console.error('Error loading settings:', error);
                contentContainer.innerHTML = `
                    <div class="error">
                        <p>Failed to load settings. Please try again later.</p>
                        <p>Error: ${error.message || 'Unknown error occurred.'}</p>
                    </div>
                `;
            }
        }
    };
    const fetchThemes = async () => {
        try {
            const response = await fetch('../php/get_themes.php');
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error('Error fetching themes:', error);
            throw new Error('Could not fetch themes.');
        }
    };
    const fetchUserTheme = async () => {
        try {
            const response = await fetch('../php/get_session_user.php');
            const data = await response.json();

            if (data.error) {
                console.error('Session error:', data.error);
                applyTheme(1);
                return 1;
            }
            applyTheme(data.theme_id || 1);
            return data.theme_id || 1;
        } catch (error) {
            console.error('Error fetching user theme:', error);
            applyTheme(1);
            return 1;
        }
    };
    const attachSettingsListeners = () => {
        const saveSettingsButton = document.getElementById('save-settings');
        saveSettingsButton.addEventListener('click', async () => {
            const selectedThemeId = document.querySelector('input[name="theme"]:checked').value;
            try {
                const response = await fetch('../php/update_user_theme.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ theme_id: selectedThemeId }),
                });
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                const data = await response.json();

                if (data.success) {
					fetchUserTheme();
                    showMessage('Theme updated successfully!', 'success');
                    applyTheme(selectedThemeId);
                } else {
                    showMessage(data.message || 'Failed to save settings.', 'error');
                }
            } catch (error) {
                console.error('Error saving theme:', error);
                showMessage(`An error occurred. ${error.message || 'Please try again.'}`, 'error');
            }
        });
    };
    const showMessage = (message, type) => {
        const messageContainer = document.getElementById('settings-message');
        messageContainer.textContent = message;
        messageContainer.className = `settings-message ${type}`;
        messageContainer.classList.remove('hidden');
        setTimeout(() => messageContainer.classList.add('hidden'), 3000);
    };
    const applyTheme = (themeId) => {
        const themeName = themeId === 2 ? 'dark' : 'light';
        document.documentElement.setAttribute('data-theme', themeName);
    };
    fetchUserTheme();
    document.querySelectorAll('.sidebar button').forEach((button) => {
        button.addEventListener('click', (event) => {
            const content = event.target.getAttribute('data-content');
            if (content) {
                updateContent(content);
                localStorage.setItem('selectedContent', content);
            }
        });
    });
    const savedContent = localStorage.getItem('selectedContent') || 'feed';
    updateContent(savedContent);
});
