/* Müfəttiş xəritə — Google Maps (normal/peyk), statusa görə rəngli markerlər,
   klasterləmə, "məni tap", info-pəncərə → obyekt kartı. */
Vue.component('map-view', {
    data: function () {
        return {
            objects: window.MOCK.objects,
            regions: window.MOCK.lookups.regions,
            region: '', locating: false, loading: true, error: false
        };
    },
    created: function () {
        // non-reactive map internals (Vue must not observe Google Maps objects)
        this.gmaps = null; this._map = null; this._markers = []; this._cluster = null; this._info = null; this._me = null;
    },
    computed: {
        filtered: function () {
            var r = this.region;
            return this.objects.filter(function (o) {
                return (!r || o.RegionName === r || o.RegionCode === r) && o.Meridian && o.Parallel;
            });
        }
    },
    watch: { region: function () { this.renderMarkers(true); } },
    mounted: function () { this.boot(); },
    beforeDestroy: function () { if (this._cluster) this._cluster.clearMarkers(); },
    methods: {
        async boot() {
            try { this.gmaps = await window.GMap.load(); this.loading = false; this.$nextTick(this.initMap); }
            catch (e) { this.loading = false; this.error = true; }
        },
        initMap: function () {
            var g = this.gmaps;
            this._map = new g.Map(this.$refs.map, {
                center: { lat: 40.4093, lng: 49.8671 }, zoom: 11,
                mapTypeControl: true, streetViewControl: false, fullscreenControl: false,
                gestureHandling: 'greedy', clickableIcons: false,
                mapTypeControlOptions: { position: g.ControlPosition.TOP_RIGHT },
                zoomControlOptions: { position: g.ControlPosition.LEFT_TOP }
            });
            this._info = new g.InfoWindow();
            this.renderMarkers(true);
        },
        renderMarkers: function (fit) {
            if (!this._map) return;
            var g = this.gmaps, self = this;
            if (this._cluster) this._cluster.clearMarkers();
            this._markers.forEach(function (m) { m.setMap(null); });
            this._markers = this.filtered.map(function (o) {
                var m = new g.Marker({
                    position: { lat: Number(o.Parallel), lng: Number(o.Meridian) },
                    icon: window.GMap.dotIcon(g, window.GMap.colorFor(o)), title: o.ObjectName
                });
                m.addListener('click', function () { self.openInfo(o, m); });
                return m;
            });
            this._cluster = new markerClusterer.MarkerClusterer({ map: this._map, markers: this._markers, renderer: window.GMap.clusterRenderer(g) });
            if (fit && this._markers.length) {
                var b = new g.LatLngBounds();
                this._markers.forEach(function (m) { b.extend(m.getPosition()); });
                this._map.fitBounds(b);
                if (this._markers.length === 1) this._map.setZoom(15);
            }
        },
        openInfo: function (o, m) {
            var self = this;
            this._info.setContent(
                '<div class="gm-pop"><div class="gm-pop__id">№ ' + o.Id + '</div>' +
                '<div class="gm-pop__name">' + (o.ObjectName || '') + '</div>' +
                '<div class="gm-pop__meta">' + (o.CustomerName || '') + ' · ' + (o.DistrictName || '') + ' r.</div>' +
                '<button type="button" id="gmOpenBtn" class="gm-pop__btn">Obyekt kartını aç</button></div>'
            );
            this._info.open(this._map, m);
            this.gmaps.event.addListenerOnce(this._info, 'domready', function () {
                var b = document.getElementById('gmOpenBtn');
                if (b) b.onclick = function () { self.$emit('open-object', o); };
            });
        },
        locateMe: function () {
            var g = this.gmaps, self = this;
            if (!navigator.geolocation || !this._map) { toastr.warning('GPS dəstəklənmir'); return; }
            this.locating = true;
            navigator.geolocation.getCurrentPosition(function (pos) {
                self.locating = false;
                var p = { lat: pos.coords.latitude, lng: pos.coords.longitude };
                self._map.setCenter(p); self._map.setZoom(15);
                if (self._me) self._me.setMap(null);
                self._me = new g.Marker({ position: p, map: self._map, icon: { path: g.SymbolPath.CIRCLE, scale: 7, fillColor: '#2f7bf6', fillOpacity: 1, strokeColor: '#fff', strokeWeight: 3 } });
                toastr.success('Mövqeyiniz tapıldı');
            }, function () { self.locating = false; toastr.error('Mövqe alınmadı'); }, { enableHighAccuracy: true, timeout: 8000 });
        }
    },
    template: `
    <div class="map-view">
        <div class="chips u-mb">
            <div class="chip" :class="{active:!region}" @click="region=''"><i class="fa-light fa-globe"></i>Bütün</div>
            <div v-for="r in regions" :key="r.id" class="chip" :class="{active:region===r.name}" @click="region=r.name">{{ r.name }}</div>
        </div>
        <div class="map-view__wrap">
            <div v-if="loading" class="map-fallback"><i class="fa-light fa-spinner fa-spin"></i> Xəritə yüklənir...</div>
            <div v-else-if="error" class="map-fallback"><i class="fa-light fa-triangle-exclamation"></i> Xəritə yüklənmədi<br><small>API açarını / internet bağlantısını yoxlayın</small></div>
            <div v-show="!loading && !error" ref="map" class="map-box"></div>
            <button v-if="!loading && !error" class="map-locate" :disabled="locating" @click="locateMe" title="Məni tap">
                <i class="fa-light" :class="locating ? 'fa-spinner fa-spin' : 'fa-location-crosshairs'"></i>
            </button>
            <div v-if="!loading && !error" class="map-legend">
                <span><i class="dot dot--ok"></i>Normal</span>
                <span><i class="dot dot--warn"></i>Borclu</span>
                <span><i class="dot dot--danger"></i>Gecikən</span>
            </div>
        </div>
        <p class="note-hint u-center"><i class="fa-light fa-circle-info"></i> {{ filtered.length }} obyekt · marker toxunuşla açılır</p>
    </div>`
});
