// ==========================================================================
// Google Translate Initialization and Custom Logic
// ==========================================================================
function googleTranslateElementInit() {
    new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element');
}

function translateLanguage(lang, flagUrl) {
    const googleFrame = document.querySelector(".goog-te-combo");

    if (googleFrame) {
        // Change language
        googleFrame.value = lang;
        googleFrame.dispatchEvent(new Event("change"));

        // Change flag icon
        const selectedFlag = document.getElementById("selectedLangFlag");
        if (selectedFlag) {
            selectedFlag.src = flagUrl;
        }
    } else {
        alert("Translation tool is loading. Please try again shortly.");
    }
}

// ==========================================================================
// DOM Interactions (Mobile Menu Dropdown)
// ==========================================================================
document.addEventListener("DOMContentLoaded", function() {
    const rankingsLink = document.querySelector(".nav-link");
    const dropdown = document.querySelector(".dropdown-content");

    // Only activate toggle for small screens
    if (window.innerWidth <= 768 && rankingsLink && dropdown) {
        rankingsLink.addEventListener("click", function(e) {
            e.preventDefault();
            dropdown.classList.toggle("show");
        });
    }
});

// --- EA Tools Filter Function ---
function initEaCarousel() {
    const carousel = document.getElementById('ea-list');
    if (!carousel) return;

    if (carousel._autoCarouselTimer) {
        clearInterval(carousel._autoCarouselTimer);
        carousel._autoCarouselTimer = null;
    }

    const getStep = () => {
        const firstCard = carousel.querySelector('.ea-card');
        if (!firstCard) return 0;
        const style = window.getComputedStyle(carousel);
        const gap = parseInt(style.columnGap || style.gap || '0', 10) || 0;
        return firstCard.offsetWidth + gap;
    };

    const slideNext = () => {
        const step = getStep();
        if (!step) return;

        const maxLeft = carousel.scrollWidth - carousel.clientWidth;
        if (carousel.scrollLeft >= maxLeft - 2) {
            carousel.scrollTo({ left: 0, behavior: 'smooth' });
        } else {
            carousel.scrollBy({ left: step, behavior: 'smooth' });
        }
    };

    const start = () => {
        if (carousel._autoCarouselTimer) return;
        carousel._autoCarouselTimer = setInterval(slideNext, 2800);
    };

    const stop = () => {
        if (!carousel._autoCarouselTimer) return;
        clearInterval(carousel._autoCarouselTimer);
        carousel._autoCarouselTimer = null;
    };

    carousel.addEventListener('mouseenter', stop);
    carousel.addEventListener('mouseleave', start);
    carousel.addEventListener('touchstart', stop, { passive: true });
    carousel.addEventListener('touchend', start, { passive: true });

    start();
}

function filterEA(category) {
    fetch('ea_fetch.php?filter=' + encodeURIComponent(category))
        .then(response => response.text())
        .then(data => {
            document.getElementById('ea-list').innerHTML = data;
            initEaCarousel();

            // Update active tab highlight
            document.querySelectorAll('.wiki-nav-item').forEach(item => {
                item.classList.remove('active');
            });
            const activeTab = document.querySelector(`.wiki-nav-item[data-tab="${category}"]`);
            if (activeTab) activeTab.classList.add('active');
        })
        .catch(error => console.error('Error fetching data:', error));
}

// --- DOM Loaded Interactions ---
document.addEventListener('DOMContentLoaded', function() {
    // Rights Protection Center Tabs
    const rpcTabs = document.querySelectorAll('.wiki-nav-item');
    rpcTabs.forEach(tab => {
        tab.addEventListener('click', function() {
            rpcTabs.forEach(t => t.classList.remove('rpc-active'));
            this.classList.add('rpc-active');
        });
    });

    // Initialize Swiper (Broker Slider)
    var swiper = new Swiper(".brokerSwiper", {
        slidesPerView: 5,
        spaceBetween: 20,
        loop: true,
        autoplay: {
            delay: 2500,
            disableOnInteraction: false,
        },
        breakpoints: {
            320: { slidesPerView: 2 },
            768: { slidesPerView: 3 },
            1024: { slidesPerView: 5 },
        }
    });

    initEaCarousel();
});

// ==========================================================================
// Risk Warning Modal Logic
// ==========================================================================
function openRiskWarning(e) {
    e.preventDefault();
    document.getElementById("riskWarningModal").style.display = "flex";
}

function closeRiskWarning() {
    document.getElementById("riskWarningModal").style.display = "none";
}

// Close modal when clicking outside the box
window.onclick = function(event) {
    const modal = document.getElementById("riskWarningModal");
    if (event.target === modal) {
        modal.style.display = "none";
    }
};

// ==========================================================================
// Footer
// ==========================================================================

function openRiskWarning(e) {
    e.preventDefault();
    document.getElementById('riskWarningModal').style.display = 'flex';
}

function closeRiskWarning() {
    document.getElementById('riskWarningModal').style.display = 'none';
}

// Close modal when clicking outside of it
window.onclick = function(event) {
    const modal = document.getElementById('riskWarningModal');
    if (event.target === modal) {
        modal.style.display = "none";
    }
}