;(() => {
    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()

const mobileToggle = document.getElementById('mobile-menu-toggle');
const navCenter = document.querySelector('.nav-center');

let overlay = document.querySelector('.menu-overlay');
if (!overlay) {
    overlay = document.createElement('div');
    overlay.className = 'menu-overlay';
    document.body.appendChild(overlay);
}

function toggleMenu() {
    navCenter.classList.toggle('open');
    overlay.classList.toggle('active');

    const isOpen = navCenter.classList.contains('open');
    mobileToggle.innerHTML = isOpen
        ? '<svg width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>'
        : '<svg width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"/></svg>';
}

mobileToggle.addEventListener('click', toggleMenu);

overlay.addEventListener('click', () => {
    if (navCenter.classList.contains('open')) toggleMenu();
});

navCenter.querySelectorAll('.nav-button').forEach(btn => {
    btn.addEventListener('click', () => {
        if (navCenter.classList.contains('open')) toggleMenu();
    });
});

const searchWrapper = document.querySelector('.search-wrapper');
const searchInput = document.getElementById('search-input');

searchWrapper.addEventListener('click', (e) => {
    if (window.innerWidth <= 768) {
        searchWrapper.classList.add('active-mobile');
        searchInput.focus();
    }
});

// Cerrar el buscador si se hace clic fuera
document.addEventListener('click', (e) => {
    if (!searchWrapper.contains(e.target)) {
        searchWrapper.classList.remove('active-mobile');
    }
});

const createRoomModal = new CreateRoomModal();

const createBtn = document.getElementById('nav-create-party');
if (createBtn) {
    createBtn.addEventListener('click', (e) => {
        e.preventDefault();
        const dropdown = document.getElementById('nav-dropdown');
        if(dropdown) dropdown.classList.remove('active');

        createRoomModal.open();
    });
}