/**
 * Mapa del recinto en SweetAlert2: marcador SVG corporativo + respaldo iframe.
 * Requiere GOOGLE_MAPS_BROWSER_KEY y APIs: Maps JavaScript API; Geocoding si solo hay dirección.
 */
(function (global) {
    'use strict';

    var SCRIPT_ID = 'rt-google-maps-landing-js';

    function svgPinDataUri() {
        var svg =
            '<svg xmlns="http://www.w3.org/2000/svg" width="56" height="64" viewBox="0 0 56 64">' +
            '<defs>' +
            '<filter id="rtPinShadow" x="-25%" y="-25%" width="150%" height="150%">' +
            '<feDropShadow dx="0" dy="3" stdDeviation="2.5" flood-opacity="0.35"/>' +
            '</filter>' +
            '</defs>' +
            '<path filter="url(#rtPinShadow)" fill="#b72f27" d="M28 4C15.85 4 6 13.85 6 26c0 14 22 38 22 38s22-24 22-38C50 13.85 40.15 4 28 4z"/>' +
            '<circle fill="#ffffff" cx="28" cy="26" r="8"/>' +
            '<circle fill="#b72f27" cx="28" cy="26" r="4"/>' +
            '</svg>';
        return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
    }

    function loadMapsApi(apiKey, callback) {
        if (global.google && global.google.maps) {
            callback(true);
            return;
        }
        if (document.getElementById(SCRIPT_ID)) {
            var tries = 0;
            var poll = setInterval(function () {
                tries += 1;
                if (global.google && global.google.maps) {
                    clearInterval(poll);
                    callback(true);
                } else if (tries > 120) {
                    clearInterval(poll);
                    callback(false);
                }
            }, 50);
            return;
        }
        var s = document.createElement('script');
        s.id = SCRIPT_ID;
        s.async = true;
        s.src =
            'https://maps.googleapis.com/maps/api/js?key=' +
            encodeURIComponent(apiKey) +
            '&v=weekly';
        s.onload = function () {
            callback(!!(global.google && global.google.maps));
        };
        s.onerror = function () {
            callback(false);
        };
        document.head.appendChild(s);
    }

    function renderIframe(slot, embedUrl, title) {
        slot.innerHTML = '';
        var wrap = document.createElement('div');
        wrap.className = 'ratio ratio-16x9 rounded overflow-hidden border border-secondary rt-venue-map-fallback';
        wrap.style.minHeight = '280px';
        var iframe = document.createElement('iframe');
        iframe.src = embedUrl;
        iframe.title = title || 'Map';
        iframe.setAttribute('loading', 'lazy');
        iframe.setAttribute('referrerpolicy', 'no-referrer-when-downgrade');
        iframe.setAttribute('allowfullscreen', '');
        iframe.className = 'w-100 h-100 border-0';
        iframe.style.minHeight = '280px';
        wrap.appendChild(iframe);
        slot.appendChild(wrap);
    }

    function createStyledMap(container, lat, lng, title) {
        var center = { lat: lat, lng: lng };
        var map = new global.google.maps.Map(container, {
            center: center,
            zoom: 16,
            mapTypeControl: true,
            mapTypeControlOptions: {
                style: global.google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                position: global.google.maps.ControlPosition.TOP_LEFT
            },
            streetViewControl: false,
            fullscreenControl: true,
            zoomControl: true,
            gestureHandling: 'cooperative',
            styles: [
                { featureType: 'poi.business', stylers: [{ visibility: 'simplified' }] },
                { featureType: 'transit', stylers: [{ visibility: 'off' }] },
            ],
        });

        var icon = {
            url: svgPinDataUri(),
            scaledSize: new global.google.maps.Size(48, 54),
            anchor: new global.google.maps.Point(24, 54),
        };

        new global.google.maps.Marker({
            map: map,
            position: center,
            title: title || '',
            icon: icon,
            animation: global.google.maps.Animation.DROP,
            optimized: true,
        });

        return map;
    }

    /**
     * @param {{ slot: HTMLElement, apiKey: string, lat: string|null, lng: string|null, geocodeQuery: string, embedFallback: string, title: string, directionsUrl: string|null }} opts
     */
    function initModalMap(opts) {
        var slot = opts.slot;
        var embedUrl = opts.embedFallback || '';
        var title = opts.title || '';
        var directionsUrl = opts.directionsUrl || '';
        var iframeTitle = title || 'Mapa';

        if (!slot) {
            return;
        }

        function finishFallback() {
            if (embedUrl) {
                renderIframe(slot, embedUrl, iframeTitle);
                addDirectionsButton(slot, directionsUrl);
            } else {
                slot.innerHTML =
                    '<p class="small text-muted mb-0 text-center py-5">' +
                    'No se pudo mostrar el mapa.' +
                    '</p>';
            }
        }

        function addDirectionsButton(container, url) {
            if (!url) return;
            var div = document.createElement('div');
            div.className = 'mt-3 text-center';
            div.innerHTML = '<a href="' + url + '" target="_blank" rel="noopener noreferrer" class="btn btn-sm btn-outline-primary shadow-sm rounded-pill px-4 fw-bold">' +
                            '<i class="bi bi-sign-turn-right me-1"></i> Cómo llegar' +
                            '</a>';
            container.appendChild(div);
        }

        function mountInteractiveMap() {
            slot.innerHTML =
                '<div class="rt-venue-map-canvas rounded overflow-hidden border border-secondary bg-dark" style="width:100%;height:320px;min-height:280px"></div>';
            var canvas = slot.querySelector('.rt-venue-map-canvas');
            var lat = opts.lat ? parseFloat(String(opts.lat).replace(',', '.')) : NaN;
            var lng = opts.lng ? parseFloat(String(opts.lng).replace(',', '.')) : NaN;
            var hasCoords = !isNaN(lat) && !isNaN(lng);
            var query = (opts.geocodeQuery || '').trim();

            if (hasCoords) {
                createStyledMap(canvas, lat, lng, title);
                addDirectionsButton(slot, directionsUrl || 'https://www.google.com/maps/dir/?api=1&destination=' + lat + ',' + lng);
                return;
            }

            if (query !== '' && global.google.maps.Geocoder) {
                var geocoder = new global.google.maps.Geocoder();
                geocoder.geocode({ address: query }, function (results, status) {
                    if (status !== 'OK' || !results || !results[0]) {
                        finishFallback();
                        return;
                    }
                    var loc = results[0].geometry.location;
                    createStyledMap(canvas, loc.lat(), loc.lng(), title);
                    addDirectionsButton(slot, directionsUrl || 'https://www.google.com/maps/dir/?api=1&destination=' + encodeURIComponent(query));
                });
                return;
            }

            finishFallback();
        }

        var apiKey = opts.apiKey || '';

        if (!apiKey) {
            finishFallback();
            return;
        }

        if (!global.google || !global.google.maps) {
            slot.innerHTML =
                '<p class="small text-secondary mb-0 text-center py-5 px-3">' +
                '<span class="spinner-border spinner-border-sm text-secondary me-2" role="status" aria-hidden="true"></span>' +
                'Cargando mapa…' +
                '</p>';
            loadMapsApi(apiKey, function (ok) {
                if (!ok || !global.google || !global.google.maps) {
                    finishFallback();
                    return;
                }
                mountInteractiveMap();
            });
            return;
        }

        mountInteractiveMap();
    }

    global.rtLandingVenueMapModal = {
        initModalMap: initModalMap,
        renderIframe: renderIframe,
    };
})(typeof window !== 'undefined' ? window : this);
