window.loadHeader(function(headerContainer) {
    const rankButton = headerContainer.querySelector('.menu-item.rank');
    if (rankButton) {
        rankButton.classList.add('active');
    }

    const logoutForm = document.getElementById("logout-form");
    
    if (logoutForm) {
        logoutForm.action = "/api/v1/spfn/logout";
        const originInput = document.getElementById("logout_frontend_origin");
        if (originInput) originInput.value = window.location.origin;
        
        logoutForm.addEventListener('submit', () => {
            sessionStorage.removeItem('user_cache');
        });
    }

    const renderData = (data) => {
        if (typeof data === 'string') {
            try { data = JSON.parse(data); } catch (e) { console.error(e); }
        }
        
        const nameEl = document.getElementById('mii-name');
        const imgEl = document.getElementById('mii-img');
        
        if (nameEl) {
            nameEl.textContent = (data.mii && data.mii.name) || data.nickname || data.user_id || data.username || "User";
        }
        
        if (imgEl) {
            const miiBlob = (data.mii && data.mii.data) || data.mii_data;
            if (miiBlob) {
                imgEl.src = `https://mii-unsecure.ariankordi.net/miis/image.png?erri=s6u7r-rsp&data=${encodeURIComponent(miiBlob)}&type=face&width=270`;
                imgEl.style.display = 'block';
            }
        }
    };

    const cached = sessionStorage.getItem('user_cache');
    if (cached) renderData(JSON.parse(cached));

    fetch("/api/v1/me", { credentials: 'include' })
        .then(res => res.ok ? res.json() : Promise.reject(res))
        .then(data => {
            sessionStorage.setItem('user_cache', JSON.stringify(data));
            renderData(data);
        })
        .catch(err => {
            if (!cached) {
                const nameEl = document.getElementById('mii-name');
                if (nameEl) nameEl.textContent = "Guest";
            }
            console.error("Profile fetch failed:", err);
        });

    const urlParams = new URLSearchParams(window.location.search);
    const mode = urlParams.get('mode');
    const images = {
        regular: "../assets/en/svg/ui/btn_tab_regular_selected-b636e3d21ace9434120061a32658b21a34feb6468553b6d6da30ce890b85ec1f.svg",
        gachi: "../assets/en/svg/ui/btn_tab_gachi_selected-4796f167399dca12cb274dcb0348cdf709a1f722ddd241210e55a3e04fdb6ff4.svg"
    };

    if (mode === 'regular') {
        const regImg = document.getElementById('img-regular');
        if (regImg) regImg.src = images.regular;
    } else if (mode === 'gachi') {
        const gachiImg = document.getElementById('img-gachi');
        if (gachiImg) gachiImg.src = images.gachi;
    }

    if (typeof loadRankings === 'function') {
        loadRankings();
    }

    const loadingOverlay = document.getElementById("loading-overlay");
    if (loadingOverlay) {
        loadingOverlay.style.display = "none";
    }
});