let map;
let infowindow;
let mapData;
let isInitialized = false;

function initMap() {
    console.log('initMap function called');
    
    if (isInitialized) {
        console.log('Map already initialized');
        return;
    }

    try {
        // Get map data from localized script
        mapData = window.dacdbMapData || {};
        console.log('Map data:', mapData);
        
        // Check if map container exists
        const mapContainer = document.getElementById('map');
        if (!mapContainer) {
            console.error('Map container not found');
            return;
        }
        console.log('Map container found with dimensions:', {
            width: mapContainer.offsetWidth,
            height: mapContainer.offsetHeight,
            visible: mapContainer.offsetParent !== null
        });

        // Initialize map with default center
        const defaultCenter = { lat: 37.0902, lng: -95.7129 }; // Center of US
        console.log('Creating map with center:', defaultCenter);
        
        const mapOptions = {
            zoom: 4,
            center: defaultCenter,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true,
            scaleControl: true,
            streetViewControl: true,
            rotateControl: true,
            fullscreenControl: true
        };

        // Create the map
        map = new google.maps.Map(mapContainer, mapOptions);

        // Add a marker at the center to verify map is working
        new google.maps.Marker({
            position: defaultCenter,
            map: map,
            title: 'Center Marker'
        });

        // Initialize info window
        infowindow = new google.maps.InfoWindow({
            maxWidth: 400
        });

        // Add event listener to verify map is responding
        map.addListener('idle', () => {
            console.log('Map is ready and idle');
            isInitialized = true;
            // Load club data after map is ready
            loadClubData();
        });

    } catch (error) {
        console.error('Error initializing map:', error, error.stack);
    }
}

// Make initMap available globally
window.initMap = initMap;

// Add initialization check on page load
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM loaded, checking map initialization');
    if (!isInitialized && typeof google !== 'undefined' && typeof google.maps !== 'undefined') {
        console.log('Google Maps API available, initializing map');
        initMap();
    }
});

function loadClubData() {
    if (!mapData || !mapData.dataPath || !mapData.accountId) {
        console.error('Map data not properly initialized');
        return;
    }

    // Load club data using JSONP
    const script = document.createElement('script');
    script.src = `${mapData.dataPath}MapClub.cfm?AccountID=${mapData.accountId}&xsl=ClubData.xsl&callback=showClubData&zlevel=0`;
    document.body.appendChild(script);
}

function showClubData(data) {
    if (!data || !data.clubs) {
        console.error('No club data received');
        return;
    }

    const bounds = new google.maps.LatLngBounds();

    data.clubs.forEach(club => {
        if (!club.lat || !club.lng) return;

        const position = {
            lat: parseFloat(club.lat),
            lng: parseFloat(club.lng)
        };

        const marker = new google.maps.Marker({
            position: position,
            map: map,
            title: club.name
        });

        bounds.extend(position);

        marker.addListener('click', () => {
            loadClubPopup(club.id, marker);
        });
    });

    // Fit map to show all markers
    map.fitBounds(bounds);
}

function loadClubPopup(clubId, marker) {
    if (!mapData || !mapData.dataPath || !mapData.accountId) {
        console.error('Map data not properly initialized');
        return;
    }

    // Load popup data using JSONP
    const script = document.createElement('script');
    script.src = `${mapData.dataPath}MapPopUp.cfm?AccountID=${mapData.accountId}&xsl=ClubData.xsl&callback=showPopUpData&zlevel=0&ClubID=${clubId}`;
    document.body.appendChild(script);

    // Store current marker for popup positioning
    loadClubPopup.currentMarker = marker;
}

function showPopUpData(data) {
    if (!data || !data.content) {
        console.error('No popup data received');
        return;
    }
    
    infowindow.setContent(data.content);
    
    if (loadClubPopup.currentMarker) {
        infowindow.open(map, loadClubPopup.currentMarker);
    } else {
        infowindow.open(map);
    }
}