/* Obyekt kartı — hero + object-scoped tabs (Mərhələlər, Sənədlər, Pozuntular,
   Texniki baxış, Tədbirlər, Ekspertiza, Lisenziyalar, Xəritə). */
Vue.component('object-detail', {
    props: { params: Object },
    data: function () {
        return {
            loading: true,
            detail: null,
            tab: 'summary',
            tabs: [
                { id: 'summary',     label: 'Xülasə',      icon: 'fa-circle-info' },
                { id: 'stages',      label: 'Mərhələlər',  icon: 'fa-timeline' },
                { id: 'documents',   label: 'Sənədlər',    icon: 'fa-file-lines' },
                { id: 'violations',  label: 'Pozuntular',  icon: 'fa-triangle-exclamation' },
                { id: 'inspections', label: 'Texniki baxış', icon: 'fa-clipboard-check' },
                { id: 'measures',    label: 'Tədbirlər',   icon: 'fa-gavel' },
                { id: 'expertise',   label: 'Ekspertiza',  icon: 'fa-microscope' },
                { id: 'licenses',    label: 'Lisenziyalar', icon: 'fa-id-card-clip' },
                { id: 'media',       label: 'Fayllar',     icon: 'fa-images' },
                { id: 'map',         label: 'Xəritə',      icon: 'fa-map-location-dot' }
            ],
            reportOpen: false,
            reportTypes: [
                { id: 1, name: 'Obyekt kartı (PDF)', ext: 'pdf' },
                { id: 2, name: 'Pozuntular aktı (PDF)', ext: 'pdf' },
                { id: 3, name: 'Texniki rəy (Word)', ext: 'docx' },
                { id: 4, name: 'Tədbirlər hesabatı (Excel)', ext: 'xlsx' }
            ],
            downloading: 0
        };
    },
    computed: {
        o: function () { return this.detail ? this.detail.object : {}; }
    },
    watch: {
        'params.id': function () { this._miniMap = null; this.load(); },
        tab: function (t) { if (t === 'map') this.$nextTick(this.initMiniMap); }
    },
    created: function () { this.load(); },
    methods: {
        fmt: function () { return window.fmt; },
        editObject: function () { location.hash = '/new/' + this.o.Id; },
        async load() {
            this.loading = true;
            await new Promise(function (r) { setTimeout(r, 320); });
            this.detail = window.MOCK.objDetail(this.params.id);
            this.loading = false;
        },
        async initMiniMap() {
            var el = this.$refs.miniMap;
            if (!el || this._miniMap || !this.o.Parallel) return;
            var self = this;
            try {
                var g = await window.GMap.load();
                if (!this.$refs.miniMap || this._miniMap) return;
                var pos = { lat: Number(this.o.Parallel), lng: Number(this.o.Meridian) };
                this._miniMap = new g.Map(this.$refs.miniMap, {
                    center: pos, zoom: 15, mapTypeControl: true, streetViewControl: false,
                    fullscreenControl: false, gestureHandling: 'greedy', clickableIcons: false
                });
                new g.Marker({ position: pos, map: this._miniMap, icon: window.GMap.dotIcon(g, '#0f9d7f'), title: '№ ' + this.o.Id });
            } catch (e) { toastr.error('Xəritə yüklənmədi'); }
        },
        async downloadReport(rt) {
            // Mock: generate a small file locally. Real: GET /Objects/DownloadObjectReport
            this.downloading = rt.id;
            await new Promise(function (r) { setTimeout(r, 700); });
            var o = this.o;
            var text = 'INSPECTOR — ' + rt.name + '\n\nObyekt № ' + o.Id + '\n' + o.ObjectName +
                '\nSifarişçi: ' + o.CustomerName + '\nRayon: ' + o.DistrictName +
                '\nStatus: ' + o.StatusName + '\nTarix: ' + window.fmt.date(new Date()) +
                '\n\n(Demo sənəd — real backend PDF/Word qaytaracaq)';
            var mime = { pdf: 'application/pdf', docx: 'application/msword', xlsx: 'application/vnd.ms-excel' }[rt.ext] || 'text/plain';
            var blob = new Blob([text], { type: mime });
            var a = document.createElement('a');
            a.href = URL.createObjectURL(blob);
            a.download = 'Obyekt_' + o.Id + '_' + rt.name.replace(/[^\wƏÜÖĞŞÇİəüöğşçı]+/g, '_') + '.' + rt.ext;
            document.body.appendChild(a); a.click();
            setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 1000);
            this.downloading = 0;
            toastr.success('Yükləndi: ' + rt.name);
        }
    },
    template: `
    <div>
        <div v-if="loading"><div class="skel skel-hero"></div><ui-skeleton-list :rows="4" class="u-mt"></ui-skeleton-list></div>

        <div v-else>
            <div class="detail-hero">
                <div class="detail-hero__id">Obyekt № {{ o.Id }} · {{ o.RegionCode }}</div>
                <div class="detail-hero__name">{{ o.ObjectName }}</div>
                <div class="detail-hero__row">
                    <span v-if="o.CustomerName && o.CustomerName!=='—'"><i class="fa-solid fa-user"></i>{{ o.CustomerName }}</span>
                    <span v-if="o.DistrictName"><i class="fa-solid fa-location-dot"></i>{{ o.DistrictName }} r.</span>
                    <span><i class="fa-solid fa-circle-dot"></i>{{ o.StatusName }}</span>
                </div>
            </div>

            <div class="detail-tabs">
                <div v-for="t in tabs" :key="t.id" class="detail-tab" :class="{active: tab===t.id}" @click="tab=t.id">
                    <i class="fa-light" :class="t.icon"></i>{{ t.label }}
                </div>
            </div>

            <!-- Summary -->
            <div v-if="tab==='summary'">
                <div class="stats">
                    <div class="stat"><div class="stat__label">Borc</div><div class="stat__value fs-16" :class="{'t-danger': o.DebtAmount>0}">{{ fmt().money(o.DebtAmount) }}</div></div>
                    <div class="stat"><div class="stat__label">Tədbir</div><div class="stat__value">{{ o.MeasureCount || 0 }}</div></div>
                    <div class="stat"><div class="stat__label">Obyekt tipi</div><div class="stat__value fs-14">{{ o.ObjectTypeName || '—' }}</div></div>
                    <div class="stat"><div class="stat__label">Qeydiyyat</div><div class="stat__value fs-13">{{ o.RegistrationTypeName || '—' }}</div></div>
                </div>
                <div class="card"><div class="card__body kv">
                    <div class="kv__row"><span class="kv__k">Sifarişçi</span><span class="kv__v">{{ o.ApplicantName || '—' }}</span></div>
                    <div class="kv__row"><span class="kv__k">Podratçı</span><span class="kv__v">{{ o.ContractorName || '—' }}</span></div>
                    <div class="kv__row"><span class="kv__k">Ünvan</span><span class="kv__v">{{ o.Address || '—' }}</span></div>
                    <div class="kv__row"><span class="kv__k">Təyinat</span><span class="kv__v">{{ o.DestinationName || '—' }}</span></div>
                    <div class="kv__row"><span class="kv__k">Maliyyə mənbəyi</span><span class="kv__v">{{ o.FinanceSourceName || '—' }}</span></div>
                    <div class="kv__row"><span class="kv__k">Ekspertiza rəyi</span><span class="kv__v">{{ o.ResultName || '—' }}</span></div>
                    <div class="kv__row"><span class="kv__k">Nəticə (baza)</span><span class="kv__v">{{ o.ConclusionName || '—' }}</span></div>
                    <div class="kv__row"><span class="kv__k">Mülkiyyət</span><span class="kv__v">{{ o.OwnershipTypeName || '—' }}</span></div>
                    <div class="kv__row"><span class="kv__k">Tikintiyə icazə</span><span class="kv__v">{{ o.PermitIssuerName || '—' }}</span></div>
                    <div class="kv__row"><span class="kv__k">Son baxış</span><span class="kv__v">{{ fmt().date(o.LastVisitDate) }}</span></div>
                    <div class="kv__row" v-if="o.Note"><span class="kv__k">Qeyd</span><span class="kv__v">{{ o.Note }}</span></div>
                    <div class="kv__row"><span class="kv__k">Koordinat</span><span class="kv__v">{{ o.Parallel.toFixed(4) }}, {{ o.Meridian.toFixed(4) }}</span></div>
                </div></div>
                <div class="u-row u-mt g-8">
                    <button class="btn btn--brand u-grow" @click="editObject"><i class="fa-light fa-pen"></i>Redaktə</button>
                    <button class="btn btn--outline" @click="reportOpen=true"><i class="fa-light fa-file-arrow-down"></i>Hesabat</button>
                </div>
            </div>

            <!-- Mərhələlər (StageName, StageDate, Text) -->
            <div v-else-if="tab==='stages'" class="list">
                <div v-for="s in detail.stages" :key="s.Id" class="list-item">
                    <div class="list-item__lead"><i class="fa-light fa-timeline"></i></div>
                    <div class="list-item__main">
                        <span class="list-item__title">{{ s.StageName }}</span>
                        <div class="list-item__meta">
                            <span><i class="fa-solid fa-calendar"></i>{{ fmt().date(s.StageDate) }}</span>
                            <span v-if="s.Text"><i class="fa-solid fa-note-sticky"></i>{{ s.Text }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Sənədlər (DocumentName, StatusName, Text, UpdatedAt) -->
            <div v-else-if="tab==='documents'" class="list">
                <div v-for="d in detail.documents" :key="d.Id" class="list-item">
                    <div class="list-item__lead"><i class="fa-light fa-file-lines"></i></div>
                    <div class="list-item__main">
                        <div class="li-head li-head--pills"><span class="list-item__title">{{ d.DocumentName }}</span><status-pill v-if="d.StatusName" :text="d.StatusName" :tone="d.StatusTone"></status-pill></div>
                        <div class="list-item__meta">
                            <span v-if="d.Text"><i class="fa-solid fa-note-sticky"></i>{{ d.Text }}</span>
                            <span><i class="fa-solid fa-clock"></i>{{ fmt().date(d.UpdatedAt) }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Pozuntular -->
            <div v-else-if="tab==='violations'" class="list">
                <div v-for="v in detail.violations" :key="v.Id" class="list-item">
                    <div class="list-item__lead list-item__lead--danger"><i class="fa-light fa-triangle-exclamation"></i></div>
                    <div class="list-item__main">
                        <div class="li-head li-head--pills"><span class="list-item__title">{{ v.Text }}</span><status-pill :text="v.StatusName" :tone="v.StatusTone"></status-pill></div>
                        <div class="list-item__meta">
                            <span><i class="fa-solid fa-calendar"></i>Tarix: {{ fmt().date(v.ViolationDate) }}</span>
                            <span><i class="fa-solid fa-hourglass-half"></i>Müddət: {{ fmt().date(v.DueDate) }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Texniki baxış -->
            <div v-else-if="tab==='inspections'" class="list">
                <div v-for="r in detail.inspections" :key="r.Id" class="list-item">
                    <div class="list-item__lead"><i class="fa-light fa-clipboard-check"></i></div>
                    <div class="list-item__main">
                        <div class="li-head"><span class="list-item__title">№ {{ r.Id }} <span class="u-muted fw-500">v{{ r.Version }}</span></span><status-pill :text="r.ActiveStatusName" :tone="r.StatusTone"></status-pill></div>
                        <div class="list-item__meta">
                            <span><i class="fa-solid fa-user-tie"></i>{{ r.EmployeeName }}</span>
                            <span><i class="fa-solid fa-user-shield"></i>{{ r.InspectorTypeName }}</span>
                            <span><i class="fa-solid fa-calendar"></i>{{ fmt().date(r.CreatedAt) }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tədbirlər (MeasureTypeName, ReasonName, Number, MeasureDate, DeadlineDate, DeliveryDueDate, letters) -->
            <div v-else-if="tab==='measures'" class="list">
                <div v-for="m in detail.measures" :key="m.Id" class="list-item">
                    <div class="list-item__lead list-item__lead--warning"><i class="fa-light fa-gavel"></i></div>
                    <div class="list-item__main">
                        <div class="li-head li-head--pills"><span class="list-item__title">{{ m.MeasureTypeName }}</span>
                            <span v-if="m.Number" class="pill pill--num">№ {{ m.Number }}</span></div>
                        <div class="list-item__meta">
                            <span v-if="m.ReasonName"><i class="fa-solid fa-circle-info"></i>{{ m.ReasonName }}</span>
                            <span><i class="fa-solid fa-calendar"></i>{{ fmt().date(m.MeasureDate) }}</span>
                        </div>
                        <div class="list-item__meta mt-4">
                            <span><i class="fa-solid fa-clock"></i>Son müddət: {{ fmt().date(m.DeadlineDate) }}</span>
                            <span v-if="m.DeliveryDueDate"><i class="fa-solid fa-truck"></i>Çatdırılma: {{ fmt().date(m.DeliveryDueDate) }}</span>
                        </div>
                        <div v-if="m.letters && m.letters.length" class="u-row u-wrap g-5 mt-6">
                            <span v-for="lt in m.letters" :key="lt" class="pill pill--info fs-10"><i class="fa-solid fa-envelope"></i>{{ lt }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Ekspertiza (FolderName, StageNumber, ReviewName, FolderDate, ReviewDate) -->
            <div v-else-if="tab==='expertise'" class="list">
                <div v-for="e in detail.expertise" :key="e.Id" class="list-item">
                    <div class="list-item__lead"><i class="fa-light fa-microscope"></i></div>
                    <div class="list-item__main">
                        <div class="li-head li-head--pills"><span class="list-item__title">{{ e.FolderName }}</span>
                            <status-pill v-if="e.ReviewName" :text="e.ReviewName" :tone="e.StatusTone"></status-pill></div>
                        <div class="list-item__meta">
                            <span><i class="fa-solid fa-layer-group"></i>Mər. {{ e.StageNumber }}</span>
                            <span><i class="fa-solid fa-calendar"></i>{{ fmt().date(e.FolderDate) }}</span>
                            <span v-if="e.ReviewDate"><i class="fa-solid fa-file-signature"></i>Rəy: {{ fmt().date(e.ReviewDate) }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Lisenziyalar -->
            <div v-else-if="tab==='licenses'" class="list">
                <div v-for="l in detail.licenses" :key="l.Id" class="list-item">
                    <div class="list-item__lead"><i class="fa-light fa-id-card-clip"></i></div>
                    <div class="list-item__main">
                        <div class="li-head li-head--pills"><span class="list-item__title">{{ l.CompanyName }}</span>
                            <status-pill v-if="l.StatusName" :text="l.StatusName" :tone="l.StatusTone"></status-pill></div>
                        <div class="list-item__meta">
                            <span v-if="l.LicenseNumber"><i class="fa-solid fa-id-card"></i>Lisenziya: {{ l.LicenseNumber }}</span>
                            <span v-if="l.TaxNumber"><i class="fa-solid fa-building"></i>VÖEN: {{ l.TaxNumber }}</span>
                            <span v-if="l.LicenseDate"><i class="fa-solid fa-calendar"></i>{{ fmt().date(l.LicenseDate) }}</span>
                        </div>
                        <span v-if="l.IsMainContractor" class="pill pill--brand mt-6"><i class="fa-solid fa-star"></i>Baş podratçı</span>
                    </div>
                </div>
            </div>

            <!-- Map -->
            <div v-else-if="tab==='map'">
                <div class="card"><div class="card__body">
                    <div class="map-coord-card"><b>Koordinat</b><span class="pill pill--brand">{{ o.Parallel.toFixed(5) }}, {{ o.Meridian.toFixed(5) }}</span></div>
                </div></div>
                <div class="map-view__wrap u-mt">
                    <div ref="miniMap" class="map-box map-box--mini"></div>
                </div>
            </div>

            <!-- Media / files -->
            <div v-else-if="tab==='media'">
                <media-uploader></media-uploader>
            </div>
        </div>

        <!-- Report download sheet -->
        <template v-if="reportOpen">
            <div class="sheet-backdrop" @click="reportOpen=false"></div>
            <div class="sheet">
                <div class="sheet__grip"></div>
                <div class="sheet__head"><h3>Hesabat / Sənəd</h3>
                    <button class="appbar__btn btn-soft" @click="reportOpen=false"><i class="fa-light fa-xmark"></i></button>
                </div>
                <div class="list">
                    <div v-for="rt in reportTypes" :key="rt.id" class="list-item" @click="downloadReport(rt)">
                        <div class="list-item__lead"><i class="fa-light" :class="'fa-file-'+(rt.ext==='pdf'?'pdf':rt.ext==='xlsx'?'excel':'word')"></i></div>
                        <div class="list-item__main"><div class="list-item__title">{{ rt.name }}</div></div>
                        <i class="fa-light" :class="downloading===rt.id ? 'fa-spinner fa-spin' : 'fa-download'" class="dl-icon"></i>
                    </div>
                </div>
            </div>
        </template>
    </div>`
});
