document.addEventListener('DOMContentLoaded', () => {
    const contentContainer = document.getElementById('content-container');
    let sessionUserId = null;
    let userLevel = null;
    let classId = null;

    const updateContent = async (content) => {
        if (content === 'user') {
            contentContainer.innerHTML = '<div class="loading">Loading user data...</div>';
            try {
                const response = await fetch('../php/get_user_profile.php');
                const data = await response.json();
                if (data.success) {
                    contentContainer.innerHTML = `
                        <div class="user-profile">
                            <h2 class="user-welcome">${data.username}</h2>
                            <div class="user-details">
                                <p><strong>E-pasts:</strong> <span id="email-display">${data.email}</span></p>
                                <p><strong>Grupa:</strong> ${data.class}</p>
                                <button id="edit-email-btn">Mainīt E-pastu</button>
                            </div>
                            <div id="email-edit-container" class="email-edit-container hidden">
                                <form id="email-edit-form">
                                    <label for="new-email">New Email:</label>
                                    <input type="email" id="new-email" name="new_email" required>
                                    <label for="current-password">Current Password:</label>
                                    <input type="password" id="current-password" name="current_password" required>
                                    <button type="submit">Submit</button>
                                    <button type="button" id="cancel-edit">Cancel</button>
                                </form>
                            </div>
                        </div>
                    `;

                    attachEmailEditListeners();
                } else {
                    contentContainer.innerHTML = `<div class="error">${data.message || 'Failed to load user data.'}</div>`;
                }
            } catch (error) {
                console.error('Error fetching user profile:', error);
                contentContainer.innerHTML = '<div class="error">Failed to load user data. Please try again later.</div>';
            }
        }
    };

    const getSessionUserData = async () => {
        try {
            const response = await fetch('../php/get_session_user.php');
            const data = await response.json();
            if (data.user_id && data.user_level) {
                sessionUserId = data.user_id;
                userLevel = data.user_level;
                classId = data.class_id || null;
            } else if (data.error) {
                console.error('Session Error:', data.error);
                window.location.href = '../php/logout.php';
            }
        } catch (error) {
            console.error('Error fetching session user data:', error);
            contentContainer.innerHTML = '<div class="error">Unable to retrieve session data. Please try again later.</div>';
        }
    };

    const attachEmailEditListeners = () => {
        const editEmailBtn = document.getElementById('edit-email-btn');
        const emailEditContainer = document.getElementById('email-edit-container');
        const cancelEditBtn = document.getElementById('cancel-edit');
        const emailEditForm = document.getElementById('email-edit-form');

        editEmailBtn.addEventListener('click', () => {
            emailEditContainer.classList.remove('hidden');
        });

        cancelEditBtn.addEventListener('click', () => {
            emailEditContainer.classList.add('hidden');
        });

        emailEditForm.addEventListener('submit', async (event) => {
            event.preventDefault();
            const newEmail = document.getElementById('new-email').value;
            const currentPassword = document.getElementById('current-password').value;

            try {
                const response = await fetch('../php/update_user_email.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ new_email: newEmail, current_password: currentPassword }),
                });

                const data = await response.json();

                if (data.success) {
                    document.getElementById('email-display').textContent = newEmail;
                    emailEditContainer.classList.add('hidden');
                    alert('Email updated successfully!');
                } else {
                    alert(data.message || 'Failed to update email.');
                }
            } catch (error) {
                console.error('Error updating email:', error);
                alert('An error occurred. Please try again.');
            }
        });
    };

    const savedContent = localStorage.getItem('selectedContent') || 'feed';

    getSessionUserData().then(() => {
        updateContent(savedContent);
    });

    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);
            }
        });
    });
});
