/**
 * Map Initialization Script
 * 
 * This script initializes the map and category filter components,
 * ensuring they're properly connected and work together.
 */

document.addEventListener('DOMContentLoaded', function() {
    console.log('Initializing map components...');
    
    // Check if dependencies are loaded
    const dependenciesLoaded = typeof MapController !== 'undefined' && 
                              typeof MapApiAdapter !== 'undefined' && 
                              typeof MapHandler !== 'undefined';
    
    if (!dependenciesLoaded) {
        console.error('Map dependencies failed to load - falling back to basic functionality');
        // The map-fallback.js script will handle this case
        return;
    }
    
    try {
        // Initialize map controller
        const mapController = new MapController({
            mapContainerId: 'map',                    // Container for the map
            categorySelectId: 'category-select',      // Optional dropdown for categories
            searchInputId: 'search-input',            // Optional search input
            includeChildrenId: 'include-children',    // Optional checkbox for including children
            locationListId: 'location-list',          // Optional container for location list
            debug: true                               // Enable debug logging
        });
        
        // Initialize map controller
        mapController.init()
            .then(() => {
                console.log('Map controller initialized successfully');
                
                // Check if CategoryFilter is already initialized (it self-initializes)
                if (window.categoryFilter) {
                    console.log('CategoryFilter found, connecting to MapController');
                    
                    // If we have locations with count data, update the category filter
                    if (mapController.state.locations && mapController.state.locations.length > 0) {
                        // Request count update from API
                        mapController.apiAdapter.getLocations({count_by_category: 1})
                            .then(result => {
                                if (result.meta && result.meta.counts) {
                                    window.categoryFilter.updateCategoryCounts(result.meta.counts);
                                }
                            })
                            .catch(err => console.error('Error fetching category counts:', err));
                    }
                }
            })
            .catch(error => {
                console.error('Error initializing map controller:', error);
            });
    } catch (error) {
        console.error('Failed to initialize map components:', error);
        // The map-fallback.js script will handle this case
    }
}); 