;(function($) {
    'use strict';

    /**
     * Initialize Advanced Google Map Widget
     */
    function initAdvancedGoogleMap($scope) {
        const $mapContainer = $scope.find('.unlockafe-google-map-container');
        
        if ($mapContainer.length === 0) {
            return;
        }

        const apiKey = $mapContainer.data('api-key');
        const centerLat = parseFloat($mapContainer.data('center-lat')) || 40.7128;
        const centerLng = parseFloat($mapContainer.data('center-lng')) || -74.0060;
        const centerAddress = $mapContainer.data('center-address') || '';
        const zoom = parseInt($mapContainer.data('zoom')) || 12;
        const mapType = $mapContainer.data('map-type') || 'roadmap';
        const mapStyle = $mapContainer.data('map-style') || '[]';
        const showZoom = $mapContainer.data('show-zoom') === 'yes';
        const showMapType = $mapContainer.data('show-map-type') === 'yes';
        const showStreetView = $mapContainer.data('show-street-view') === 'yes';
        const showFullscreen = $mapContainer.data('show-fullscreen') === 'yes';
        const enableScroll = $mapContainer.data('enable-scroll') === 'yes';
        const enableDragging = $mapContainer.data('enable-dragging') === 'yes';
        const markers = $mapContainer.data('markers') || [];
        const mapId = $mapContainer.attr('id');

        if (!apiKey) {
            return;
        }

        // Check if Google Maps is already loaded
        if (typeof google !== 'undefined' && google.maps) {
            initMap();
        } else {
            // Load Google Maps API
            const script = document.createElement('script');
            script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&callback=initUnlockafeGoogleMap${mapId.replace(/-/g, '')}`;
            script.async = true;
            script.defer = true;
            
            // Create global callback function
            window[`initUnlockafeGoogleMap${mapId.replace(/-/g, '')}`] = function() {
                initMap();
            };
            
            document.head.appendChild(script);
        }

        function initMap() {
            try {
                // Parse map style
                let parsedStyle = [];
                try {
                    parsedStyle = typeof mapStyle === 'string' ? JSON.parse(mapStyle) : mapStyle;
                } catch (e) {
                    parsedStyle = [];
                }

                // Create geocoder
                const geocoder = new google.maps.Geocoder();

                // Geocode address if provided
                if (centerAddress) {
                    geocoder.geocode({ address: centerAddress }, function(results, status) {
                        if (status === 'OK' && results[0]) {
                            const location = results[0].geometry.location;
                            createMap(location.lat(), location.lng(), geocoder);
                        } else {
                            createMap(centerLat, centerLng, geocoder);
                        }
                    });
                } else {
                    createMap(centerLat, centerLng, geocoder);
                }

                function createMap(lat, lng, geocoder) {
                    try {
                        // Map options
                        const mapOptions = {
                            zoom: zoom,
                            center: { lat: lat, lng: lng },
                            mapTypeId: mapType,
                            zoomControl: showZoom,
                            mapTypeControl: showMapType,
                            streetViewControl: showStreetView,
                            fullscreenControl: showFullscreen,
                            scrollwheel: enableScroll,
                            draggable: enableDragging,
                            disableDefaultUI: false,
                        };

                        // Apply custom style if not default
                        if (parsedStyle.length > 0) {
                            mapOptions.styles = parsedStyle;
                        }

                        // Get the map element
                        const mapElement = document.getElementById(mapId);
                        if (!mapElement) {
                            console.error('Map element not found:', mapId);
                            $mapContainer.addClass('loaded');
                            return;
                        }

                        // Create map
                        const map = new google.maps.Map(mapElement, mapOptions);

                        // Wait for map to be fully loaded
                        google.maps.event.addListenerOnce(map, 'idle', function() {
                            // Mark as loaded after map is fully rendered
                            $mapContainer.addClass('loaded');
                        });

                        // Add markers
                        if (markers && markers.length > 0) {
                            let markersAdded = 0;
                            markers.forEach(function(markerData) {
                                addMarker(markerData, map, geocoder, function() {
                                    markersAdded++;
                                    // If all markers are added and map is idle, ensure loaded class is set
                                    if (markersAdded === markers.length) {
                                        $mapContainer.addClass('loaded');
                                    }
                                });
                            });
                        }

                        // Fallback: Remove loading after 5 seconds even if map doesn't fire idle event
                        setTimeout(function() {
                            $mapContainer.addClass('loaded');
                        }, 5000);
                    } catch (error) {
                        console.error('Error creating map:', error);
                        $mapContainer.addClass('loaded');
                        $mapContainer.html('<div class="unlockafe-google-map-error">Error loading map. Please check your API key and settings.</div>');
                    }
                }

                function addMarker(markerData, map, geocoder, callback) {
                    const markerLat = parseFloat(markerData.marker_latitude) || centerLat;
                    const markerLng = parseFloat(markerData.marker_longitude) || centerLng;
                    const markerAddress = markerData.marker_address || '';
                    const markerTitle = markerData.marker_title || '';
                    const markerDescription = markerData.marker_description || '';
                    const markerIcon = markerData.marker_icon?.url || '';
                    const markerIconColor = markerData.marker_icon_color || '#ef4444';

                    let position = { lat: markerLat, lng: markerLng };

                    // Geocode address if provided
                    if (markerAddress) {
                        geocoder.geocode({ address: markerAddress }, function(results, status) {
                            if (status === 'OK' && results[0]) {
                                position = results[0].geometry.location;
                                createMarker(position, markerTitle, markerDescription, markerIcon, markerIconColor, map);
                            } else {
                                createMarker(position, markerTitle, markerDescription, markerIcon, markerIconColor, map);
                            }
                            if (callback) callback();
                        });
                    } else {
                        createMarker(position, markerTitle, markerDescription, markerIcon, markerIconColor, map);
                        if (callback) callback();
                    }
                }

                function createMarker(position, title, description, iconUrl, iconColor, map) {
                    // Marker options
                    const markerOptions = {
                        position: position,
                        map: map,
                        title: title,
                    };

                    // Custom icon
                    if (iconUrl) {
                        markerOptions.icon = {
                            url: iconUrl,
                            scaledSize: new google.maps.Size(40, 40),
                        };
                    } else if (iconColor) {
                        // Use default marker with custom color
                        markerOptions.icon = {
                            path: google.maps.SymbolPath.CIRCLE,
                            scale: 10,
                            fillColor: iconColor,
                            fillOpacity: 1,
                            strokeColor: '#ffffff',
                            strokeWeight: 2,
                        };
                    }

                    // Create marker
                    const marker = new google.maps.Marker(markerOptions);

                    // Info window
                    if (title || description) {
                        const infoWindow = new google.maps.InfoWindow({
                            content: '<div class="unlockafe-map-info-window">' +
                                    (title ? '<h3>' + title + '</h3>' : '') +
                                    (description ? '<p>' + description + '</p>' : '') +
                                    '</div>',
                        });

                        marker.addListener('click', function() {
                            infoWindow.open(map, marker);
                        });
                    }
                }
            } catch (error) {
                console.error('Error initializing Google Map:', error);
                $mapContainer.addClass('loaded');
                $mapContainer.html('<div class="unlockafe-google-map-error">Error loading map. Please check your API key and settings.</div>');
            }
        }
    }

    // Initialize on Elementor frontend
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-advanced-google-map.default', function($scope) {
            initAdvancedGoogleMap($scope);
        });
    });

    // Also initialize on document ready (for non-Elementor pages)
    $(document).ready(function() {
        $('.elementor-widget-unlockafe-advanced-google-map').each(function() {
            var $scope = $(this);
            initAdvancedGoogleMap($scope);
        });
    });

    // Re-initialize on Elementor preview refresh
    if (typeof elementorFrontend !== 'undefined') {
        elementorFrontend.hooks.addAction('frontend/element_ready/global', function($scope) {
            if ($scope.find('.unlockafe-google-map-container').length) {
                setTimeout(function() {
                    initAdvancedGoogleMap($scope);
                }, 100);
            }
        });
    }

})(jQuery);

