/**
 * DACdbPlus Map Functionality
 * Handles map display and interaction for Rotary club locations
 */
(function ($) {
    'use strict';

    // Initialize when document is ready
    $(document).ready(function () {
        
        
        // Find all map containers
        $('.dacdb-map-canvas').each(function () {
            var mapId = $(this).attr('id');
            if (!mapId) return;

            // Get configuration variable name
            var configVar = 'dacdbMap_' + mapId.replace(/-/g, '_');

            // Check if configuration exists
            if (typeof window[configVar] === 'undefined') {
                if (window.DACdbPlusDebug) {
                    window.DACdbPlusDebug.error('Map configuration not found for', mapId);
                }
                $('#' + mapId).html('<div class="error-msg">Map configuration not found. Please check the console for details.</div>');
                return;
            }

            // Initialize map with config
            initMap(window[configVar]);
        });
    });

    /**
     * Initialize map with configuration
     */
    function initMap(config) {


        // Show loading indicator
        $('#' + config.mapId).html('<div class="map-loading">Loading map data...</div>');

        // Load Google Maps API if not already loaded
        if (typeof google === 'undefined' || typeof google.maps === 'undefined') {
            var script = document.createElement('script');
            script.src = 'https://maps.googleapis.com/maps/api/js?key=' + config.apiKey +
                '&callback=initGoogleMap_' + config.mapId + '&libraries=marker&loading=async';
            script.async = true;
            script.defer = true;

            // Create global callback function
            window['initGoogleMap_' + config.mapId] = function () {
                loadMapData(config);
            };

            document.head.appendChild(script);
        } else {
            // API already loaded, continue with map data loading
            loadMapData(config);
        }
    }

    /**
     * Load map data via AJAX
     */
    function loadMapData(config) {
        // Load club map data from CFM server
        $.ajax({
            url: config.dataPath + 'wp_entityMap.cfm',
            data: {
                AccountID: config.accountId,
                xsl: 'wp_entityInteractive.xsl',
                t: new Date().getTime() // Add timestamp to bypass cache
            },
            dataType: 'html',
            success: function (response) {
                // Extract club data from response
                var clubs = extractClubData(response);

                if (clubs && clubs.length > 0) {
                    // Create map with clubs
                    createMap(config, clubs);
                } else {
                    // Show error if no clubs found
                    $('#' + config.mapId).html('<div class="error-msg">No club data found. Please check your configuration.</div>');
                }
            },
            error: function (xhr, status, error) {

                $('#' + config.mapId).html('<div class="error-msg">Error loading map data. Please try again later.</div>');
            }
        });
    }

    /**
     * Extract club data from HTML response
     */
    function extractClubData(response) {
        var clubs = [];

        try {
            // First try to find JSON data (new format)
            var jsonScript = $(response).find('#map-data-json script[type="application/json"]').html();
            if (jsonScript) {
                try {
                    var jsonData = JSON.parse(jsonScript);

                    return jsonData.clubs || [];
                } catch (e) {
                    console.error('Error parsing JSON data:', e);
                }
            }

            // Fallback: Extract from script content - look for LatLng patterns
            var latLngMatches = response.match(/temp(\d+)\s*=\s*new\s+google\.maps\.LatLng\(([^)]+)\)/g);
            if (latLngMatches && latLngMatches.length > 0) {
                for (var j = 0; j < latLngMatches.length; j++) {
                    var rowMatch = latLngMatches[j].match(/temp(\d+)/);
                    var coordMatch = latLngMatches[j].match(/LatLng\(([^)]+)\)/);

                    if (rowMatch && rowMatch[1] && coordMatch && coordMatch[1]) {
                        clubs.push({
                            row: rowMatch[1],
                            latlng: coordMatch[1]
                        });
                    }
                }

                return clubs;
            }

            // Last resort - look for any coordinates
            var coordMatches = response.match(/(\d+\.\d+),\s*(-?\d+\.\d+)/g);
            if (coordMatches && coordMatches.length > 0) {
                for (var k = 0; k < coordMatches.length; k++) {
                    clubs.push({
                        row: k + 1,
                        latlng: coordMatches[k]
                    });
                }

                return clubs;
            }
        } catch (e) {
            console.error('Error extracting club data:', e);
        }

        return clubs;
    }

    // In show-map.js, update the createMap function:

    /**
     * Create map and markers
     */
    function createMap(config, clubs) {
        var mapElement = document.getElementById(config.mapId);

        // Clear loading indicator
        $(mapElement).empty();

        // Create info window
        var infoWindow = new google.maps.InfoWindow({
            maxWidth: 350
        });

        // Calculate default center and bounds
        var bounds = new google.maps.LatLngBounds();
        var defaultCenter = { lat: 39.5, lng: -98.35 }; // USA center
        var defaultZoom = 4;

        // Create map with proper Map ID
        var map = new google.maps.Map(mapElement, {
            center: defaultCenter,
            zoom: defaultZoom,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapId: "44be97c5795092fc" // Add this line to fix the Map ID warning
        });

        // Create markers
        var markers = [];
        var validMarkers = 0;

        clubs.forEach(function (club) {
            // Parse coordinates
            var coords = club.latlng.split(',');
            if (coords.length !== 2) return;

            var lat = parseFloat(coords[0]);
            var lng = parseFloat(coords[1]);
            if (isNaN(lat) || isNaN(lng)) return;

            var position = { lat: lat, lng: lng };

            // Create marker
            var marker;
            if (google.maps.marker && google.maps.marker.AdvancedMarkerElement) {
                marker = new google.maps.marker.AdvancedMarkerElement({
                    map: map,
                    position: position
                });

                // Use the correct event listener for advanced markers
                marker.addEventListener('gmp-click', function () {
                    loadPopupContent(config, map, marker, infoWindow);
                });
            } else {
                marker = new google.maps.Marker({
                    map: map,
                    position: position
                });

                // Standard click event for regular markers
                marker.addListener('click', function () {
                    loadPopupContent(config, map, marker, infoWindow);
                });
            }

            // Store club row
            marker.clubRow = club.row;

            // Add to markers array and bounds
            markers.push(marker);
            bounds.extend(position);
            validMarkers++;
        });

        // Adjust map view based on markers
        if (validMarkers > 0) {
            if (validMarkers === 1) {
                // Single marker - zoom in more
                map.setCenter(bounds.getCenter());
                map.setZoom(14);
            } else {
                // Multiple markers - fit to bounds
                map.fitBounds(bounds);
            }
        }


    }

    /**
     * Load popup content on demand
     */
    function loadPopupContent(config, map, marker, infoWindow) {
        // Show loading content
        infoWindow.setContent('<div class="map-popup-loading">Loading...</div>');
        infoWindow.open(map, marker);
        console.info('DACdb Map Layout Mode:', config.layout || 'legacy');        
        // Load popup content
        $.ajax({
            url: config.dataPath + 'wp_entityMarker.cfm',
            data: {
                AccountID: config.accountId,
                xsl: 'wp_entityMarker.xsl',
                layout: config.layout || 'legacy',
                t: new Date().getTime() // Add timestamp to bypass cache
            },
            dataType: 'html',
            success: function (response) {
                try {
                    // Parse the HTML response
                    var tmpDiv = document.createElement('div');
                    tmpDiv.innerHTML = response;

                    // Look for the club element with matching row
                    var clubElement = tmpDiv.querySelector('#club' + marker.clubRow);
                    if (!clubElement) {
                        // Try with data-row attribute
                        clubElement = tmpDiv.querySelector('[data-row="' + marker.clubRow + '"]');
                    }

                    if (clubElement) {
                        // Set content and reopen info window
                        infoWindow.setContent(clubElement.outerHTML);
                        infoWindow.open(map, marker);
                    } else {
                        console.error('Club popup content not found for row:', marker.clubRow);
                        infoWindow.setContent('<div class="error-msg">Club information not available</div>');
                    }
                } catch (e) {
                    console.error('Error processing popup content:', e);
                    infoWindow.setContent('<div class="error-msg">Error loading club information</div>');
                }
            },
            error: function (xhr, status, error) {
                console.error('Error loading popup content:', error);
                infoWindow.setContent('<div class="error-msg">Error loading club information</div>');
            }
        });
    }

})(jQuery);