/**
 * Hierarchy Data Navigation Wrappers
 * Wraps navigation functions to wait for hierarchy data
 */

// Store original navigation functions
let originalNavigationFunctions = {};

/**
 * Wrap navigation functions to wait for hierarchy data
 */
function wrapNavigationFunctions() {
    // Wait for the main js.js to load and define navigation functions
    if (typeof navigateToCountries === 'undefined') {
        setTimeout(wrapNavigationFunctions, 100);
        return;
    }

    // Store original functions
    originalNavigationFunctions.navigateToCountries = window.navigateToCountries;
    originalNavigationFunctions.navigateToLeagues = window.navigateToLeagues;
    originalNavigationFunctions.navigateToTeams = window.navigateToTeams;
    originalNavigationFunctions.generateContinentContent = window.generateContinentContent;
    originalNavigationFunctions.generateCountryContent = window.generateCountryContent;
    originalNavigationFunctions.generateLeagueContent = window.generateLeagueContent;

    // Create wrapped versions
    window.navigateToCountries = function(continent, updateHistory = true) {
        whenHierarchyReady(() => {
            originalNavigationFunctions.navigateToCountries(continent, updateHistory);
        });
    };

    window.navigateToLeagues = function(continent, country, updateHistory = true) {
        whenHierarchyReady(() => {
            originalNavigationFunctions.navigateToLeagues(continent, country, updateHistory);
        });
    };

    window.navigateToTeams = function(continent, country, league, updateHistory = true) {
        whenHierarchyReady(() => {
            originalNavigationFunctions.navigateToTeams(continent, country, league, updateHistory);
        });
    };

    window.generateContinentContent = function(continent, countries) {
        // Data should be loaded by the time this is called
        return originalNavigationFunctions.generateContinentContent(continent, countries);
    };

    window.generateCountryContent = function(continent, country, leagues) {
        // Data should be loaded by the time this is called
        return originalNavigationFunctions.generateCountryContent(continent, country, leagues);
    };

    window.generateLeagueContent = function(continent, country, league, teams) {
        // Data should be loaded by the time this is called
        return originalNavigationFunctions.generateLeagueContent(continent, country, league, teams);
    };

    console.log('Navigation functions wrapped for hierarchy data loading');
}

// Also wrap any functions that use hierarchyData directly
function wrapHierarchyDataUsage() {
    // Listen for hierarchy data loaded event
    window.addEventListener('hierarchyDataLoaded', function() {
        // Remove any loading placeholders
        const loadingElements = document.querySelectorAll('.loading-hierarchy');
        loadingElements.forEach(el => {
            el.style.display = 'none';
        });
        
        // Initialize navigation once hierarchy data is loaded
        initializeNavigation();
    });
}

/**
 * Initialize navigation menu with hierarchy data
 */
function initializeNavigation() {
    // Find the sidebar navigation container
    const continentsSection = document.getElementById('continents-section');
    if (!continentsSection) {
        console.log('Continents section not found, skipping navigation initialization');
        return;
    }
    
    // Make sure the continents section is visible
    continentsSection.classList.add('active');
    
    const countriesList = continentsSection.querySelector('.nav-list');
    if (!countriesList) {
        console.log('Countries list not found in continents section');
        return;
    }
    
    // Check if navigation is already populated server-side
    const existingItems = countriesList.querySelectorAll('.nav-item[data-continent]');
    if (existingItems.length > 0) {
        console.log('Navigation already populated server-side with', existingItems.length, 'continents');
        
        // Just add event listeners to existing items
        existingItems.forEach(item => {
            const continent = item.getAttribute('data-continent');
            const link = item.querySelector('.nav-link');
            if (link && continent) {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (typeof window.navigateToCountries === 'function') {
                        window.navigateToCountries(continent);
                    } else {
                        console.log('navigateToCountries function not available');
                    }
                });
            }
        });
        return;
    }
    
    // Only populate if we have hierarchy data and no existing items
    if (!window.hierarchyData || typeof window.hierarchyData !== 'object') {
        console.log('Hierarchy data not available and no server-side navigation found');
        return;
    }
    
    // Clear existing navigation content
    countriesList.innerHTML = '';
    
    // Generate continent navigation
    const continents = Object.keys(window.hierarchyData).sort();
    
    continents.forEach(continent => {
        const countries = window.hierarchyData[continent];
        const countryCount = Object.keys(countries).length;
        
        // Create continent navigation item
        const continentItem = document.createElement('li');
        continentItem.className = 'nav-item';
        continentItem.setAttribute('data-continent', continent);
        
        // Create continent slug for URL
        const continentSlug = continent.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
        
        continentItem.innerHTML = `
            <a href="/${continentSlug}" class="nav-link">
                <span>${continent}</span>
                <svg class="chevron-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="m9 18 6-6-6-6"></path>
                </svg>
            </a>
        `;
        
        // Add event listener for continent navigation
        continentItem.addEventListener('click', function(e) {
            e.preventDefault();
            if (typeof window.navigateToCountries === 'function') {
                window.navigateToCountries(continent);
            } else {
                console.log('navigateToCountries function not available');
            }
        });
        
        countriesList.appendChild(continentItem);
    });
    
    console.log('Navigation initialized with', continents.length, 'continents');
}

// Initialize wrapping when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    // Start wrapping process
    wrapNavigationFunctions();
    wrapHierarchyDataUsage();
    
    // Initialize navigation if hierarchy data is already loaded
    if (window.isHierarchyDataLoaded && window.isHierarchyDataLoaded()) {
        initializeNavigation();
    }
    
    // Add loading indicator CSS
    const style = document.createElement('style');
    style.textContent = `
        .loading-hierarchy {
            padding: 20px;
            text-align: center;
            color: #888;
            font-style: italic;
        }
        
        .loading-hierarchy::after {
            content: '';
            display: inline-block;
            width: 20px;
            height: 20px;
            margin-left: 10px;
            border: 2px solid #888;
            border-radius: 50%;
            border-top-color: transparent;
            animation: hierarchy-spin 1s linear infinite;
        }
        
        @keyframes hierarchy-spin {
            to { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);
});