/**
 * Google Maps + Places para el modal «Nueva sede» (formulario de evento).
 * Requiere GOOGLE_MAPS_BROWSER_KEY en el servidor y librerías habilitadas en Google Cloud:
 * Maps JavaScript API, Places API (legacy Autocomplete).
 */
(function (global) {
    'use strict';

    var loadState = { loading: false, loaded: false, callbacks: [] };

    function loadMapsScript(apiKey, done) {
        if (global.google && global.google.maps && global.google.maps.places) {
            done();
            return;
        }
        loadState.callbacks.push(done);
        if (loadState.loading) {
            return;
        }
        loadState.loading = true;
        var s = document.createElement('script');
        s.async = true;
        s.defer = true;
        s.src =
            'https://maps.googleapis.com/maps/api/js?key=' +
            encodeURIComponent(apiKey) +
            '&libraries=places&v=weekly';
        s.onload = function () {
            loadState.loaded = true;
            loadState.loading = false;
            var q = loadState.callbacks.splice(0);
            for (var i = 0; i < q.length; i++) {
                q[i]();
            }
        };
        s.onerror = function () {
            loadState.loading = false;
            loadState.callbacks = [];
        };
        document.head.appendChild(s);
    }

    function parseAddressComponents(components) {
        var streetNumber = '';
        var route = '';
        var out = {
            street: '',
            city: '',
            region: '',
            postal: '',
            country: '',
        };
        if (!components || !components.length) {
            return out;
        }
        for (var i = 0; i < components.length; i++) {
            var c = components[i];
            var types = c.types || [];
            if (types.indexOf('street_number') !== -1) {
                streetNumber = c.long_name || '';
            }
            if (types.indexOf('route') !== -1) {
                route = c.long_name || '';
            }
            if (types.indexOf('locality') !== -1) {
                out.city = c.long_name || '';
            }
            if (types.indexOf('administrative_area_level_1') !== -1 && !out.region) {
                out.region = c.short_name || c.long_name || '';
            }
            if (types.indexOf('postal_code') !== -1) {
                out.postal = c.long_name || '';
            }
            if (types.indexOf('country') !== -1) {
                out.country = (c.short_name || '').toUpperCase();
            }
        }
        if (!out.city) {
            for (var j = 0; j < components.length; j++) {
                var cj = components[j];
                if ((cj.types || []).indexOf('sublocality') !== -1 || (cj.types || []).indexOf('neighborhood') !== -1) {
                    out.city = cj.long_name || out.city;
                    break;
                }
            }
        }
        out.street = [streetNumber, route].filter(Boolean).join(' ').trim();
        return out;
    }

    var picker = {
        _map: null,
        _marker: null,
        _autocomplete: null,
        _vue: null,

        teardown: function () {
            var g = global.google;
            if (this._marker && g && g.maps) {
                g.maps.event.clearInstanceListeners(this._marker);
            }
            if (this._map && g && g.maps) {
                g.maps.event.clearInstanceListeners(this._map);
            }
            if (this._autocomplete && g && g.maps) {
                g.maps.event.clearInstanceListeners(this._autocomplete);
            }
            this._map = null;
            this._marker = null;
            this._autocomplete = null;
            this._vue = null;
            var el = document.getElementById('rt-catalog-venue-map');
            if (el) {
                el.innerHTML = '';
            }
        },

        /**
         * @param {object} vueCtx — instancia Vue del modal (Options API)
         * @param {string} apiKey
         */
        bootstrap: function (vueCtx, apiKey) {
            var self = this;
            if (!apiKey || !vueCtx) {
                return;
            }
            this.teardown();
            this._vue = vueCtx;
            loadMapsScript(apiKey, function () {
                self._build(vueCtx);
            });
        },

        _build: function (vueCtx) {
            var g = global.google;
            var el = document.getElementById('rt-catalog-venue-map');
            if (!el || !g || !g.maps) {
                return;
            }

            var lat = parseFloat(vueCtx.latV);
            var lng = parseFloat(vueCtx.lngV);
            var center = { lat: 18.2208, lng: -66.5901 };
            var hasCoords = !isNaN(lat) && !isNaN(lng);
            if (hasCoords) {
                center = { lat: lat, lng: lng };
            }

            this._map = new g.maps.Map(el, {
                center: center,
                zoom: hasCoords ? 16 : 8,
                mapTypeControl: false,
                streetViewControl: false,
                fullscreenControl: true,
            });

            this._marker = new g.maps.Marker({
                position: center,
                map: this._map,
                draggable: true,
            });

            var vm = vueCtx;
            var pickerRef = this;

            g.maps.event.addListener(this._marker, 'dragend', function () {
                var p = pickerRef._marker.getPosition();
                vm.latV = p.lat().toFixed(7);
                vm.lngV = p.lng().toFixed(7);
            });

            g.maps.event.addListener(this._map, 'click', function (e) {
                pickerRef._marker.setPosition(e.latLng);
                vm.latV = e.latLng.lat().toFixed(7);
                vm.lngV = e.latLng.lng().toFixed(7);
            });

            var input = vm.$refs.addrInput;
            if (input && g.maps.places) {
                this._autocomplete = new g.maps.places.Autocomplete(input, {
                    fields: ['geometry', 'address_components', 'formatted_address'],
                });
                this._autocomplete.addListener('place_changed', function () {
                    var place = pickerRef._autocomplete.getPlace();
                    if (!place.geometry || !place.geometry.location) {
                        return;
                    }
                    var loc = place.geometry.location;
                    pickerRef._marker.setPosition(loc);
                    pickerRef._map.panTo(loc);
                    pickerRef._map.setZoom(16);
                    vm.latV = loc.lat().toFixed(7);
                    vm.lngV = loc.lng().toFixed(7);
                    if (place.formatted_address) {
                        vm.addr1 = place.formatted_address;
                    }
                    var fields = parseAddressComponents(place.address_components || []);
                    if (fields.street && !place.formatted_address) {
                        vm.addr1 = fields.street;
                    }
                    if (fields.city) {
                        vm.cityV = fields.city;
                    }
                    if (fields.region) {
                        vm.regionV = fields.region;
                    }
                    if (fields.postal) {
                        vm.postalV = fields.postal;
                    }
                    if (fields.country) {
                        vm.countryV = fields.country;
                    }
                });
            }
        },
    };

    global.rtCatalogVenuePicker = picker;
})(typeof window !== 'undefined' ? window : this);
