;(() => {
    const token = localStorage.getItem("token")

    if (!token && window.location.pathname !== "/") {
        window.location.href = "/"
    }
})()

async function loadMeUI() {
    const token = localStorage.getItem("token")
    if (!token) return

    try {
        const res = await fetch("/api/me", {
            headers: {
                Authorization: `Bearer ${token}`,
            },
        })

        if (!res.ok) return

        const user = await res.json()

        const navUser = document.getElementById("nav-user")
        const navUsername = document.getElementById("nav-username")
        const navAvatar = document.getElementById("nav-avatar")
        const dropdownAvatar = document.getElementById("dropdown-avatar")

        if (!navUser || !navUsername || !navAvatar) return

        navUser.style.display = "flex"
        navUsername.textContent = user.username

        const avatarUrl = user.avatar || "/public/assets/avatar.png"
        navAvatar.src = avatarUrl
        if (dropdownAvatar) {
            dropdownAvatar.src = avatarUrl
        }

        setupDropdown()
    } catch (e) {
        console.error("Failed to load user UI:", e)
    }
}

// Variable para saber si el modal ya fue cargado
let settingsModalLoaded = false;

document.getElementById('nav-settings').addEventListener('click', openSettings)

async function openSettings() {
    if (!settingsModalLoaded) {
        try {
            const res = await fetch('/views/components/settings-modal.html')
            const html = await res.text()
            document.body.insertAdjacentHTML('beforeend', html)
            settingsModalLoaded = true;

            // Esperar un momento para que el DOM se actualice
            await new Promise(resolve => setTimeout(resolve, 50));

            // Ahora cargar los settings
            if (window.toggleSettingsModal) {
                await window.toggleSettingsModal(false);
            }
        } catch (err) {
            console.error('Error loading settings modal:', err);
        }
    } else {
        if (window.toggleSettingsModal) {
            await window.toggleSettingsModal(false);
        }
    }
}

function closeSettings() {
    const modal = document.getElementById('settings-modal');
    if (modal) {
        modal.classList.add('hidden');
    }
}

function setupDropdown() {
    const userAvatarBtn = document.querySelector(".user-avatar-btn")
    const navDropdown = document.getElementById("nav-dropdown")
    const navLogout = document.getElementById("nav-logout")

    if (!userAvatarBtn || !navDropdown || !navLogout) return

    userAvatarBtn.addEventListener("click", (e) => {
        e.stopPropagation()
        navDropdown.classList.toggle("active")
    })

    document.addEventListener("click", (e) => {
        if (!navDropdown.contains(e.target)) {
            navDropdown.classList.remove("active")
        }
    })

    navDropdown.addEventListener("click", (e) => {
        e.stopPropagation()
    })

    navLogout.addEventListener("click", () => {
        localStorage.removeItem("token")
        window.location.href = "/"
    })

    const dropdownLinks = navDropdown.querySelectorAll("a.dropdown-item")
    dropdownLinks.forEach((link) => {
        link.addEventListener("click", () => {
            navDropdown.classList.remove("active")
        })
    })
}

loadMeUI()