/* Mock data source — indi REAL Inspector DB ixracından (js/data.js) qidalanır.
   Sahə adları/dəyərləri real view sütunları ilə eynidir. Xəritə üçün koordinat
   və "gün fərqi" real ixracda olmadığından deterministik sintez olunur. */
window.MOCK = (function () {
    var D = window.INSPECTOR_DATA || {};
    var L = D.lookups || {};

    function money(n) { if (n == null || n === '') return '—'; return new Intl.NumberFormat('az-AZ').format(n) + ' ₼'; }
    function trim(s) { return (s == null ? '' : String(s)).replace(/ /g, ' ').trim(); }
    function flag(v) { v = trim(v); return v === '+' || v === '1' || v === 'true'; }
    function daysFromNow(d) { var t = new Date(); t.setDate(t.getDate() + d); return t.toISOString().slice(0, 10); }

    // Status adına görə rəng tonu (real statuslar üçün)
    function tone(s) {
        s = (s || '').toLowerCase();
        if (/başa çatıb|istismar|müsbət|aktiv|təsdiq|hazırdır|tamamlan|icra olun|verilib|var\b/.test(s)) return 'success';
        if (/dayan|mənfi|ləğv|gecik|yoxdur|qanunsuz|söküntü/.test(s)) return 'danger';
        if (/gözlə|baxış|qaralama|başlamayıb|natamam|tələb/.test(s)) return 'warning';
        if (/gedir|icrada|başlan|davam/.test(s)) return 'info';
        return '';
    }

    // ---- Obyektlər: real sahələr + sintetik koordinat/müddət/ton ----
    var OBJECTS = (D.objects || []).map(function (o) {
        // real koordinat varsa onu işlət (Meridian=uzunluq, Parallel=enlik), yoxdursa sintez
        var hasReal = o.Meridian != null && o.Parallel != null && Number(o.Parallel) > 38 && Number(o.Parallel) < 42;
        var lat = hasReal ? Number(o.Parallel) : 40.30 + ((o.Id * 13) % 520) / 1000;
        var lng = hasReal ? Number(o.Meridian) : 49.70 + ((o.Id * 29) % 600) / 1000;
        var due = ((o.Id * 7) % 80) - 30;
        return Object.assign({}, o, {
            ObjectName: trim(o.ObjectName) || ('Obyekt № ' + o.Id),
            CustomerName: trim(o.CustomerName) || '—',
            ApplicantName: trim(o.ApplicantName),
            DistrictName: trim(o.DistrictName),
            DestinationName: trim(o.DestinationName),
            StatusName: trim(o.StatusName),
            StatusTone: tone(o.StatusName),
            DebtAmount: Number(o.DebtAmount) || 0,
            Meridian: lng, Parallel: lat,
            DueDayDifference: due, DueDate: daysFromNow(due)
        });
    });

    // ---- Alt-qeyd hovuzları (real sütunlarla) ----
    var STAGES = (D.stages || []).map(function (r) { return Object.assign({}, r, { StageName: trim(r.StageName), Text: trim(r.Text) }); });
    var DOCS = (D.documents || []).map(function (r) { return Object.assign({}, r, { DocumentName: trim(r.DocumentName), StatusName: trim(r.StatusName), StatusTone: tone(r.StatusName), Text: trim(r.Text) }); });
    var VIOL = (D.violations || []).map(function (r) {
        var done = flag(r.IsCompleted) || r.IsCompleted === true || r.IsCompleted === 1;
        return Object.assign({}, r, { Text: trim(r.Text) || 'Pozuntu', StatusName: done ? 'Aradan qaldırılıb' : 'Aradan qaldırılmayıb', StatusTone: done ? 'success' : 'danger' });
    });
    var TR = (D.technicalReviews || []).map(function (r) { return Object.assign({}, r, { ActiveStatusName: trim(r.ActiveStatusName), StatusTone: tone(r.ActiveStatusName), EmployeeName: trim(r.EmployeeName), InspectorTypeName: trim(r.InspectorTypeName), Title: 'Texniki baxış № ' + r.Id }); });
    var MEAS = (D.measures || []).map(function (r) {
        return Object.assign({}, r, {
            MeasureTypeName: trim(r.MeasureTypeName) || 'Tədbir', ReasonName: trim(r.ReasonName), Text: trim(r.Text),
            letters: [['DİN', r.LetterDin], ['RİH', r.LetterRih], ['Su', r.LetterSu], ['Qaz', r.LetterQaz], ['İşıq', r.LetterIsiq]].filter(function (x) { return flag(x[1]); }).map(function (x) { return x[0]; })
        });
    });
    var EXP = (D.expertiseLinks || []).map(function (r) { return Object.assign({}, r, { FolderName: trim(r.FolderName) || ('Ekspertiza işi ' + r.FolderId), ReviewName: trim(r.ReviewName), StatusName: trim(r.ReviewName), StatusTone: tone(r.ReviewName) }); });
    var COMP = (D.companies || []).map(function (r) { return Object.assign({}, r, { CompanyName: trim(r.CompanyName) || '—', LicenseNumber: trim(r.LicenseNumber), TaxNumber: trim(r.TaxNumber), StatusName: trim(r.LicenseStatusName), StatusTone: tone(r.LicenseStatusName), IsMainContractor: flag(r.IsMainContractor) }); });

    var POOLS = { stages: STAGES, documents: DOCS, violations: VIOL, inspections: TR, measures: MEAS, expertise: EXP, licenses: COMP };

    // Bir obyekt üçün alt-qeydləri seç (real ObjectId varsa ona görə, yoxdursa hovuzdan kəs)
    function subFor(pool, oIndex, objId) {
        var byId = pool.filter(function (r) { return r.ObjectId === objId; });
        if (byId.length) return byId;
        var start = (oIndex * 3) % Math.max(1, pool.length);
        return pool.slice(start, start + (2 + (oIndex % 4)));
    }

    function objDetail(id) {
        var oi = OBJECTS.findIndex(function (x) { return x.Id === id; });
        var o = oi >= 0 ? OBJECTS[oi] : OBJECTS[0]; oi = Math.max(0, oi);
        return {
            object: o,
            stages: subFor(STAGES, oi, o.Id), documents: subFor(DOCS, oi, o.Id),
            violations: subFor(VIOL, oi, o.Id), inspections: subFor(TR, oi, o.Id),
            measures: subFor(MEAS, oi, o.Id), expertise: subFor(EXP, oi, o.Id), licenses: subFor(COMP, oi, o.Id)
        };
    }

    function matches(o, q) {
        if (!q) return true; q = q.toLowerCase();
        return String(o.Id).indexOf(q) >= 0 || (o.ObjectName || '').toLowerCase().indexOf(q) >= 0 ||
            (o.CustomerName || '').toLowerCase().indexOf(q) >= 0 || (o.DistrictName || '').toLowerCase().indexOf(q) >= 0;
    }

    function list(key, opts) {
        var q = opts.query || {}, all;
        if (key === 'objects') {
            all = OBJECTS.filter(function (o) { return matches(o, q.search); });
            if (q.district) all = all.filter(function (o) { return o.DistrictName === q.district; });
            if (q.status) all = all.filter(function (o) { return o.StatusName === q.status; });
        } else if (POOLS[key]) {
            all = POOLS[key].map(function (r, i) { return Object.assign({ ObjectId: r.ObjectId || OBJECTS[i % OBJECTS.length].Id }, r); });
            if (q.search) all = all.filter(function (r) { return JSON.stringify(r).toLowerCase().indexOf(q.search.toLowerCase()) >= 0; });
        } else if (key === 'gisH3') {
            all = OBJECTS.map(function (o) { return { Id: o.Id, Meridian: o.Meridian, Parallel: o.Parallel, Region: o.RegionCode }; });
        } else all = [];
        var skip = opts.skip || 0, take = opts.take || 25;
        return { items: all.slice(skip, skip + take), total: all.length };
    }

    function get(url, params) {
        if (url.indexOf('GetLookups') >= 0) return L;
        if (url.indexOf('GetObjectInfo') >= 0) return OBJECTS.find(function (x) { return x.Id === Number(params.id); }) || OBJECTS[0];
        return {};
    }

    // Formalar üçün {id,name} lookuplar (real dəyərlər)
    var idn = function (a) { return (a || []).map(function (x) { return { id: x.id, name: (x.name || '').replace(/ /g, ' ').trim() }; }); };
    var lookups = {
        districts: idn(L.districts), regions: idn(L.regions), destinations: idn(L.destinations),
        financeSources: idn(L.financeSources), objectTypes: idn(L.objectTypes), statuses: idn(L.statuses),
        registrationTypes: idn(L.registrationTypes)
    };
    var filterLookups = {
        types: idn(L.objectTypes), registrationTypes: idn(L.registrationTypes), destinations: idn(L.destinations),
        statuses: idn(L.statuses), conclusions: idn(L.conclusions), regions: idn(L.regions), districts: idn(L.districts),
        financeSources: idn(L.financeSources), customerTypes: idn(L.customerTypes), ownershipTypes: idn(L.ownershipTypes),
        results: idn(L.results), permitIssuers: idn(L.permitIssuers), dnjStatuses: idn(L.dnjStatuses),
        extractStatuses: idn(L.extractStatuses),
        tqrAvailability: [{ id: 1, name: 'Var' }, { id: 0, name: 'Yoxdur' }],
        ihaAvailability: [{ id: 1, name: 'Var' }, { id: 0, name: 'Yoxdur' }]
    };

    return { list: list, get: get, objDetail: objDetail, objects: OBJECTS, lookups: lookups, filterLookups: filterLookups, fmtMoney: money };
})();
