/* GIS Monitorinq — normal, detallı Google xəritəsi + KPI panel.
   Bütün obyektlər markerlə, statusa görə rəngli, klasterlənmiş göstərilir. */
Vue.component('gis-view', {
    data: function () {
        return {
            objects: window.MOCK.objects,
            regions: window.MOCK.lookups.regions,
            region: '', loading: true, error: false
        };
    },
    created: function () {
        this.gmaps = null; this._map = null; this._markers = []; this._cluster = null; this._info = 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;
            });
        },
        kpi: function () {
            var f = this.filtered, reg = {};
            f.forEach(function (o) { if (o.RegionName) reg[o.RegionName] = 1; });
            return {
                total: f.length,
                regions: Object.keys(reg).length || (this.region ? 1 : 0),
                debt: f.filter(function (o) { return o.DebtAmount > 0; }).length,
                overdue: f.filter(function (o) { return o.DueDayDifference < 0; }).length
            };
        }
    },
    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.5, lng: 49.5 }, zoom: 8,
                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._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.DistrictName || '') + ' r. · ' + (o.StatusName || '') + '</div>' +
                        '<button type="button" id="gmOpenBtn" class="gm-pop__btn">Obyekt kartını aç</button></div>');
                    self._info.open(self._map, m);
                    self.gmaps.event.addListenerOnce(self._info, 'domready', function () {
                        var b = document.getElementById('gmOpenBtn'); if (b) b.onclick = function () { self.$emit('open-object', o); };
                    });
                });
                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(14);
            }
        }
    },
    template: `
    <div>
        <div class="chips u-mb">
            <div class="chip" :class="{active:!region}" @click="region=''"><i class="fa-light fa-globe"></i>Bütün regionlar</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="stats">
            <div class="stat"><div class="stat__label"><i class="fa-light fa-buildings"></i>Obyekt</div><div class="stat__value">{{ kpi.total }}</div></div>
            <div class="stat"><div class="stat__label"><i class="fa-light fa-map"></i>Region</div><div class="stat__value">{{ kpi.regions }}</div></div>
            <div class="stat"><div class="stat__label"><i class="fa-light fa-coins"></i>Borclu</div><div class="stat__value t-warning">{{ kpi.debt }}</div></div>
            <div class="stat"><div class="stat__label"><i class="fa-light fa-clock"></i>Gecikən</div><div class="stat__value t-danger">{{ kpi.overdue }}</div></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>
            <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> Bütün obyektlər xəritədə · marker toxunuşla açılır</p>
    </div>`
});
