(function () {
    'use strict';

    var ajaxHdr = { 'X-Requested-With': 'XMLHttpRequest' };
    var saatKey = 'skFirmaListeSaat';

    function syncSm() {
        var s = '';
        document.querySelectorAll('.s-chk').forEach(function (c) {
            if (c.checked) s += c.getAttribute('data-v');
        });
        var hid = document.getElementById('satisMask');
        if (hid) hid.value = s;
    }

    function parsePanelHtml(html) {
        return new DOMParser().parseFromString(html, 'text/html').getElementById('firmaListePanel');
    }

    function updateToplamFromPanel(nw) {
        var el = document.querySelector('.sk-filter-head-total__n');
        if (!el || !nw) return;
        var t = nw.getAttribute('data-toplam');
        if (t == null || t === '') return;
        var num = parseInt(t, 10);
        el.textContent = isNaN(num) ? t : num.toLocaleString('tr-TR');
    }

    function replaceListePanel(html) {
        var cur = document.getElementById('firmaListePanel');
        var nw = parsePanelHtml(html);
        if (!nw || !cur) return false;
        cur.replaceWith(nw);
        updateToplamFromPanel(nw);
        initSaatToggle();
        return true;
    }

    async function fetchHtml(url, opt) {
        var o = Object.assign({ credentials: 'same-origin', headers: Object.assign({}, ajaxHdr) }, opt || {});
        var res = await fetch(url, o);
        if (!res.ok) {
            var errTxt = await res.text().catch(function () { return ''; });
            throw new Error(errTxt || res.statusText || String(res.status));
        }
        var ct = (res.headers.get('content-type') || '').toLowerCase();
        if (!ct.includes('text/html')) throw new Error('Beklenmeyen yanıt');
        return res.text();
    }

    function alertErr(err, fallback) {
        alert((err && err.message) || fallback);
    }

    function initSaatToggle() {
        var root = document.querySelector('.firmalar-page');
        var chk = document.getElementById('chkSaatGoster');
        if (!root || !chk) return;
        chk.replaceWith(chk.cloneNode(true));
        chk = document.getElementById('chkSaatGoster');
        try { chk.checked = localStorage.getItem(saatKey) === '1'; } catch (e) { chk.checked = false; }
        function apply() {
            root.classList.toggle('firmalar-page--show-time', chk.checked);
            try { localStorage.setItem(saatKey, chk.checked ? '1' : '0'); } catch (e2) {}
        }
        apply();
        chk.addEventListener('change', apply);
    }

    function isListeNavHref(href) {
        return href && href.indexOf('Liste') >= 0;
    }

    function isPanelPostForm(action) {
        if (!action) return false;
        return action.indexOf('Firmalar/Sil') >= 0 || action.indexOf('Firmalar/KaldirilanlariTemizle') >= 0;
    }

    document.addEventListener('DOMContentLoaded', function () {
        var root = document.querySelector('.firmalar-page');
        var form = document.getElementById('frmAyarla');
        if (!root || !form) return;

        async function postAyarla() {
            syncSm();
            var html = await fetchHtml(form.action, { method: 'POST', body: new FormData(form) });
            replaceListePanel(html);
        }

        form.addEventListener('submit', function (ev) {
            ev.preventDefault();
            postAyarla().catch(function (err) { alertErr(err, 'Liste güncellenemedi.'); });
        });

        form.querySelectorAll('.sk-auto-ayarla, .sk-auto-ayarla-chk').forEach(function (el) {
            el.addEventListener('change', function () {
                syncSm();
                postAyarla().catch(function (err) { alertErr(err, 'Liste güncellenemedi.'); });
            });
        });

        document.querySelectorAll('.sk-chip').forEach(function (lab) {
            var inp = lab.querySelector('.s-chk');
            if (!inp) return;
            function syncChip() { lab.classList.toggle('sk-chip--on', inp.checked); }
            inp.addEventListener('change', syncChip);
            syncChip();
        });

        root.addEventListener('click', function (ev) {
            var a = ev.target.closest('a.sk-th-sort, .sk-pagination a.page-link[href]');
            if (!a || a.target === '_blank') return;
            var href = a.getAttribute('href') || '';
            if (!isListeNavHref(href)) return;
            ev.preventDefault();
            fetchHtml(href, { method: 'GET' })
                .then(replaceListePanel)
                .catch(function (err) { alertErr(err, 'Liste yüklenemedi.'); });
        });

        root.addEventListener('submit', function (ev) {
            var innerForm = ev.target && ev.target.closest ? ev.target.closest('form') : null;
            if (!innerForm && ev.target && ev.target.tagName === 'FORM') innerForm = ev.target;
            if (!innerForm || innerForm.id === 'frmAyarla') return;
            var act = innerForm.getAttribute('action') || '';
            if (!isPanelPostForm(act)) return;
            if (act.indexOf('KaldirilanlariTemizle') >= 0) {
                if (!confirm('Programı kaldıran tüm demo firmaları silmek istiyor musunuz?')) return;
            } else if (!confirm('Kaydı silmek istiyor musunuz?')) return;
            ev.preventDefault();
            fetchHtml(act, { method: 'POST', body: new FormData(innerForm) })
                .then(replaceListePanel)
                .catch(function (err) { alertErr(err, 'İşlem başarısız.'); });
        });

        initSaatToggle();

        var skCol = document.getElementById('skFilterCollapse');
        var skCard = document.querySelector('.sk-filter-card');
        var skHead = document.querySelector('.sk-filter-card__head--toggle');
        if (skCol && skCard) {
            skCol.addEventListener('hidden.bs.collapse', function () {
                skCard.classList.add('sk-filter-card--collapsed');
                if (skHead) skHead.setAttribute('aria-expanded', 'false');
            });
            skCol.addEventListener('shown.bs.collapse', function () {
                skCard.classList.remove('sk-filter-card--collapsed');
                if (skHead) skHead.setAttribute('aria-expanded', 'true');
            });
        }
    });
})();
