/**
 * Dashboard Smooth Transitions
 * Handles slide in/out animations when navigating between pages and tabs
 */

(function () {
    'use strict';

    // Add transition-out animation before navigation
    function addExitAnimation(event) {
        const link = event.currentTarget;
        const href = link.getAttribute('href');

        // Skip if it's a hash link or external link
        if (!href || href.startsWith('#') || href.startsWith('http')) {
            return;
        }

        // Prevent default navigation
        event.preventDefault();

        // Get all animated elements
        const animatedElements = document.querySelectorAll(
            '.welcome-header, .metrics-grid, .analytics-section, .content-box, .matches-display-grid, .metric-card-fancy'
        );

        // Add exit animation class
        animatedElements.forEach((element, index) => {
            setTimeout(() => {
                element.style.animation = 'slideOutToLeft 0.4s cubic-bezier(0.4, 0, 1, 1) forwards';
            }, index * 50); // Stagger the exit
        });

        // Navigate after animation completes
        setTimeout(() => {
            window.location.href = href;
        }, 400 + (animatedElements.length * 50));
    }

    // Initialize on page load
    function init() {
        // Get all navigation links (menu links and tab buttons)
        const navLinks = document.querySelectorAll('.menu-link, .tab-btn, .filter-tabs a');

        navLinks.forEach(link => {
            link.addEventListener('click', addExitAnimation);
        });

        // Handle browser back/forward buttons
        window.addEventListener('pageshow', function (event) {
            if (event.persisted) {
                // Page was loaded from cache, re-trigger animations
                const animatedElements = document.querySelectorAll(
                    '.welcome-header, .metrics-grid, .analytics-section, .content-box, .matches-display-grid, .metric-card-fancy'
                );

                animatedElements.forEach(element => {
                    element.style.animation = 'none';
                    element.offsetHeight; // Trigger reflow
                    element.style.animation = '';
                });
            }
        });
    }

    // Run when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
