<?php
/**
 * Event map component - OpenStreetMap integration with Leaflet.js
 */
if (!defined('ABSPATH')) exit;

// Get map settings
$em_venue = $event_settings['em_venue'] ?? '';
$em_map_enabled = $event_settings['em_map_enabled'] ?? 'yes';
$em_map_zoom = $event_settings['em_map_zoom'] ?? '15';
$em_map_type = $event_settings['em_map_type'] ?? 'roadmap';
$em_map_height = $event_settings['em_map_height'] ?? '400';
$em_map_latitude = $event_settings['em_map_latitude'] ?? '';
$em_map_longitude = $event_settings['em_map_longitude'] ?? '';

// Only show if map is enabled
if ($em_map_enabled !== 'yes') {
    return;
}

// Check if we have manual coordinates or venue address
$has_manual_coords = !empty($em_map_latitude) && !empty($em_map_longitude);
$has_venue = !empty($em_venue);

// If no venue address and no manual coordinates, don't show map
if (!$has_venue && !$has_manual_coords) {
    return;
}

// Generate unique map ID for this event
$map_id = 'em-map-' . $event_id;

// Check if magazine layout
$layout_preference = $event_settings['em_layout_preference'] ?? 'default';
$rounded_class = ($layout_preference === 'magazine') ? 'em-rounded-2xl' : '';
?>
<div class="em-bg-white em-p-5 em-border em-border-slate-200 em-shadow-sm em-h-full em-flex em-flex-col <?php echo esc_attr($rounded_class); ?>">
    <div class="em-flex em-items-center em-gap-3 em-mb-4">
       
        <div>
            <h2 class="em-text-lg em-font-bold em-text-slate-900">
                <?php _e('Venue Location', 'event-monster'); ?>
            </h2>
            <p class="em-text-sm em-text-slate-600"><?php echo esc_html($em_venue); ?></p>
        </div>
    </div>

    <!-- Map Container -->
    <div id="<?php echo esc_attr($map_id); ?>"
         class="em-rounded-lg em-overflow-hidden em-border em-border-slate-200"
         style="height: <?php echo esc_attr($em_map_height); ?>px; width: 100%;"
         data-address="<?php echo esc_attr($em_venue); ?>"
         data-latitude="<?php echo esc_attr($em_map_latitude); ?>"
         data-longitude="<?php echo esc_attr($em_map_longitude); ?>"
         data-zoom="<?php echo esc_attr($em_map_zoom); ?>"
         data-map-type="<?php echo esc_attr($em_map_type); ?>">
        <!-- Map will be rendered here by JavaScript -->
        <div class="em-flex em-items-center em-justify-center em-h-full em-bg-slate-100">
            <div class="em-text-center">
                <svg class="em-animate-spin em-h-8 em-w-8 em-text-slate-400 em-mx-auto em-mb-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="em-opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="em-opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <p class="em-text-sm em-text-slate-500"><?php _e('Loading map...', 'event-monster'); ?></p>
            </div>
        </div>
    </div>

   
</div>

<!-- Load Leaflet.js CSS and JS (only once globally) -->
<script>
// Load Leaflet.js CSS if not already loaded
if (!document.getElementById('leaflet-css')) {
    const leafletCSS = document.createElement('link');
    leafletCSS.id = 'leaflet-css';
    leafletCSS.rel = 'stylesheet';
    leafletCSS.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
    leafletCSS.integrity = 'sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=';
    leafletCSS.crossOrigin = '';
    document.head.appendChild(leafletCSS);
}

// Load Leaflet.js if not already loaded
if (typeof L === 'undefined' && !document.getElementById('leaflet-js')) {
    const leafletJS = document.createElement('script');
    leafletJS.id = 'leaflet-js';
    leafletJS.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
    leafletJS.integrity = 'sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=';
    leafletJS.crossOrigin = '';
    document.head.appendChild(leafletJS);
}
</script>

<script>
// Global object to store map instances
if (typeof window.eventMaps === 'undefined') {
    window.eventMaps = {};
}

/**
 * Global function to destroy a specific map instance
 */
window.destroyEventMap = function(mapId) {
    if (window.eventMaps[mapId]) {
        console.log('🗑️ Destroying existing map:', mapId);
        try {
            window.eventMaps[mapId].remove();
            delete window.eventMaps[mapId];

            // Remove the initialized class
            const mapContainer = document.getElementById(mapId);
            if (mapContainer) {
                mapContainer.classList.remove('em-map-initialized');
                // Clear the _leaflet_id to allow re-initialization
                mapContainer._leaflet_id = null;
            }
            console.log('✅ Map destroyed successfully:', mapId);
        } catch (error) {
            console.error('❌ Error destroying map:', error);
        }
    }
};

/**
 * Global function to destroy all event maps
 */
window.destroyAllEventMaps = function() {
    console.log('🗑️ Destroying all event maps...');
    Object.keys(window.eventMaps).forEach(function(mapId) {
        window.destroyEventMap(mapId);
    });
};

/**
 * Try geocoding with fallback strategy
 * If full address fails, try progressively simpler versions
 */
function tryGeocoding(address, mapId, zoom, mapType, mapContainer, attemptNumber = 1) {
    // Create fallback addresses
    let addressToTry = address;
    const addressParts = address.split(',').map(part => part.trim());

    if (attemptNumber === 2 && addressParts.length > 2) {
        // Try without the first part (street address)
        addressToTry = addressParts.slice(1).join(', ');
        console.log('🔄 Retry attempt 2: Trying without street address:', addressToTry);
    } else if (attemptNumber === 3 && addressParts.length > 3) {
        // Try with just city, state, country
        addressToTry = addressParts.slice(-3).join(', ');
        console.log('🔄 Retry attempt 3: Trying city, state, country only:', addressToTry);
    } else if (attemptNumber === 4 && addressParts.length > 2) {
        // Try with just state and country
        addressToTry = addressParts.slice(-2).join(', ');
        console.log('🔄 Retry attempt 4: Trying state and country only:', addressToTry);
    }

    const geocodeUrl = 'https://nominatim.openstreetmap.org/search?format=json&q=' + encodeURIComponent(addressToTry) + '&limit=1&addressdetails=1';

    fetch(geocodeUrl, {
        headers: {
            'User-Agent': 'EventMonsterPlugin/1.0'
        }
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Geocoding service returned status: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            console.log('🗺️ Geocoding response (attempt ' + attemptNumber + '):', data);

            if (data && data.length > 0) {
                const lat = parseFloat(data[0].lat);
                const lon = parseFloat(data[0].lon);

                console.log('✅ Geocoded address:', { lat, lon, display_name: data[0].display_name });

                if (attemptNumber > 1) {
                    console.log('⚠️ Note: Using approximate location based on: ' + addressToTry);
                }

                initializeMap(mapId, lat, lon, zoom, mapType, mapContainer);
            } else {
                // Try fallback if we haven't exhausted all attempts
                if (attemptNumber < 4 && addressParts.length > 2) {
                    console.log('⚠️ Attempt ' + attemptNumber + ' failed, trying fallback...');
                    setTimeout(function() {
                        tryGeocoding(address, mapId, zoom, mapType, mapContainer, attemptNumber + 1);
                    }, 500); // Small delay to respect rate limits
                } else {
                    console.error('❌ Geocoding failed: No results found after ' + attemptNumber + ' attempts');
                    mapContainer.innerHTML = '<div class="em-flex em-items-center em-justify-center em-h-full em-bg-yellow-50"><div class="em-text-center em-p-4"><svg class="em-h-8 em-w-8 em-text-yellow-600 em-mx-auto em-mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg><p class="em-text-sm em-text-yellow-800 em-font-medium"><?php _e('Unable to locate address on map', 'event-monster'); ?></p><p class="em-text-xs em-text-yellow-600 em-mt-1"><?php _e('Please use the manual coordinates option in the event settings', 'event-monster'); ?></p><p class="em-text-xs em-text-yellow-600 em-mt-2 em-font-mono em-bg-yellow-100 em-px-2 em-py-1 em-rounded">' + address + '</p><p class="em-text-xs em-text-blue-600 em-mt-2"><strong><?php _e('Suggested coordinates for Kota, Rajasthan:', 'event-monster'); ?></strong><br>Lat: 25.18, Lon: 75.83</p></div></div>';
                }
            }
        })
        .catch(error => {
            console.error('❌ Geocoding error:', error);
            mapContainer.innerHTML = '<div class="em-flex em-items-center em-justify-center em-h-full em-bg-red-50"><div class="em-text-center em-p-4"><svg class="em-h-8 em-w-8 em-text-red-400 em-mx-auto em-mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg><p class="em-text-sm em-text-red-600 em-font-medium"><?php _e('Error loading map', 'event-monster'); ?></p><p class="em-text-xs em-text-red-500 em-mt-1">' + error.message + '</p></div></div>';
        });
}

/**
 * Helper function to initialize the map with coordinates
 */
function initializeMap(mapId, lat, lon, zoom, mapType, mapContainer) {
    console.log('🗺️ Initializing map with coordinates:', { mapId, lat, lon, zoom, mapType });

    // Initialize the map
    const map = L.map(mapId).setView([lat, lon], zoom);

    // Force map to recalculate size (fixes modal display issues)
    setTimeout(function() {
        map.invalidateSize();
    }, 100);

    // Choose tile layer based on map type
    let tileLayer;
    switch(mapType) {
        case 'satellite':
            // Satellite imagery
            tileLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
                attribution: 'Tiles &copy; Esri',
                maxZoom: 19
            });
            break;
        case 'hybrid':
            // Satellite with labels
            const satelliteLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
                attribution: 'Tiles &copy; Esri'
            });
            const labelsLayer = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_only_labels/{z}/{x}/{y}.png', {
                attribution: '&copy; CARTO'
            });
            tileLayer = L.layerGroup([satelliteLayer, labelsLayer]);
            break;
        case 'terrain':
            // Terrain map
            tileLayer = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
                attribution: 'Map data: &copy; OpenStreetMap contributors, SRTM | Map style: &copy; OpenTopoMap',
                maxZoom: 17
            });
            break;
        case 'roadmap':
        default:
            // Standard roadmap
            tileLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
                maxZoom: 19
            });
            break;
    }

    tileLayer.addTo(map);

    // Add marker with custom icon
    const markerIcon = L.divIcon({
        className: 'custom-marker',
        html: '<div style="background-color: #10B981; width: 32px; height: 32px; border-radius: 50% 50% 50% 0; transform: rotate(-45deg); border: 3px solid white; box-shadow: 0 2px 8px rgba(0,0,0,0.3);"><div style="width: 10px; height: 10px; background: white; border-radius: 50%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"></div></div>',
        iconSize: [32, 32],
        iconAnchor: [16, 32],
        popupAnchor: [0, -32]
    });

    const marker = L.marker([lat, lon], { icon: markerIcon }).addTo(map);

    // Store map instance globally for cleanup
    window.eventMaps[mapId] = map;

    // Mark as initialized
    mapContainer.classList.add('em-map-initialized');

    console.log('✅ Map initialized successfully:', mapId);
}

/**
 * Global function to initialize a specific map
 * Can be called from anywhere, including after AJAX content loads
 */
window.initEventMap = function(mapId) {
    console.log('🗺️ initEventMap called for:', mapId);

    // Wait for Leaflet.js to be loaded
    if (typeof L === 'undefined') {
        console.log('⏳ Waiting for Leaflet.js to load...');
        setTimeout(function() {
            window.initEventMap(mapId);
        }, 100);
        return;
    }

    const mapContainer = document.getElementById(mapId);

    if (!mapContainer) {
        console.error('❌ Map container not found:', mapId);
        return;
    }

    // Check if map is already initialized - if so, destroy it first
    if (window.eventMaps[mapId]) {
        console.log('ℹ️ Map already exists, destroying old instance:', mapId);
        window.destroyEventMap(mapId);
    }

    // Also check the class-based flag
    if (mapContainer.classList.contains('em-map-initialized')) {
        console.log('ℹ️ Map container marked as initialized, cleaning up:', mapId);
        mapContainer.classList.remove('em-map-initialized');
        mapContainer._leaflet_id = null;
    }

    const address = mapContainer.dataset.address;
    const manualLat = mapContainer.dataset.latitude;
    const manualLon = mapContainer.dataset.longitude;
    const zoom = parseInt(mapContainer.dataset.zoom) || 15;
    const mapType = mapContainer.dataset.mapType || 'roadmap';

    console.log('🗺️ Initializing map:', { mapId, address, manualLat, manualLon, zoom, mapType });

    // Check if manual coordinates are provided
    if (manualLat && manualLon && manualLat.trim() !== '' && manualLon.trim() !== '') {
        console.log('✅ Using manual coordinates:', { lat: manualLat, lon: manualLon });

        const lat = parseFloat(manualLat);
        const lon = parseFloat(manualLon);

        if (!isNaN(lat) && !isNaN(lon)) {
            initializeMap(mapId, lat, lon, zoom, mapType, mapContainer);
        } else {
            console.error('❌ Invalid manual coordinates:', { lat: manualLat, lon: manualLon });
            mapContainer.innerHTML = '<div class="em-flex em-items-center em-justify-center em-h-full em-bg-red-50"><div class="em-text-center em-p-4"><svg class="em-h-8 em-w-8 em-text-red-400 em-mx-auto em-mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg><p class="em-text-sm em-text-red-600 em-font-medium"><?php _e('Invalid coordinates', 'event-monster'); ?></p><p class="em-text-xs em-text-red-500 em-mt-1"><?php _e('Please check the latitude and longitude values', 'event-monster'); ?></p></div></div>';
        }
        return;
    }

    // If no manual coordinates, try geocoding the address
    if (!address || address.trim() === '') {
        console.error('❌ No address or coordinates provided');
        mapContainer.innerHTML = '<div class="em-flex em-items-center em-justify-center em-h-full em-bg-yellow-50"><div class="em-text-center em-p-4"><svg class="em-h-8 em-w-8 em-text-yellow-600 em-mx-auto em-mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg><p class="em-text-sm em-text-yellow-800 em-font-medium"><?php _e('No location specified', 'event-monster'); ?></p></div></div>';
        return;
    }

    // Try geocoding with fallback strategy
    tryGeocoding(address, mapId, zoom, mapType, mapContainer);
};

// Initialize map on page load (for non-AJAX contexts)
jQuery(document).ready(function($) {
    const mapId = '<?php echo esc_js($map_id); ?>';
    window.initEventMap(mapId);
});

// Also initialize immediately if jQuery is not available
if (typeof jQuery === 'undefined') {
    window.initEventMap('<?php echo esc_js($map_id); ?>');
}
</script>
