;(() => {
    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 avatarUrl = user.avatar || "/public/assets/avatar.png"

        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) {
            navUser.style.display = "flex"
            navUsername.textContent = user.username
            navAvatar.src = avatarUrl
            if (dropdownAvatar) dropdownAvatar.src = avatarUrl
        }

        const titlebarAvatar = document.getElementById("titlebar-avatar")
        const titlebarActions = document.getElementById("titlebar-actions")

        if (titlebarAvatar) {
            titlebarAvatar.src = avatarUrl
        }

        if (titlebarActions) {
            titlebarActions.style.display = "flex"
        }

        setupDropdown()

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

let settingsModalLoaded = false;

const navSettingsBtn = document.getElementById('nav-settings');
const titlebarSettingsBtn = document.getElementById('titlebar-settings');

if (navSettingsBtn) navSettingsBtn.addEventListener('click', openSettings);
if (titlebarSettingsBtn) titlebarSettingsBtn.addEventListener('click', (e) => {
    e.stopPropagation();

    openSettings();
    document.getElementById("titlebar-dropdown")?.classList.remove("active");
});

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;
            await new Promise(resolve => setTimeout(resolve, 50));
            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 setupDropdown() {

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

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

            document.getElementById("titlebar-dropdown")?.classList.remove("active")
        })
        if (navLogout) {
            navLogout.addEventListener("click", () => {
                localStorage.removeItem("token")
                window.location.href = "/"
            })
        }
    }

    const titlebarUserBox = document.getElementById("titlebar-user-box")
    const titlebarDropdown = document.getElementById("titlebar-dropdown")
    const titlebarLogout = document.getElementById("titlebar-logout")

    if (titlebarUserBox && titlebarDropdown) {
        titlebarUserBox.addEventListener("click", (e) => {
            e.stopPropagation()
            titlebarDropdown.classList.toggle("active")

            document.getElementById("nav-dropdown")?.classList.remove("active")
        })

        if (titlebarLogout) {
            titlebarLogout.addEventListener("click", (e) => {
                e.stopPropagation()
                localStorage.removeItem("token")
                window.location.href = "/"
            })
        }

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

    document.addEventListener("click", (e) => {
        if (navDropdown && !navDropdown.contains(e.target)) {
            navDropdown.classList.remove("active")
        }
        if (titlebarDropdown && !titlebarDropdown.contains(e.target)) {
            titlebarDropdown.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();
    }
});

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