(function () {
    document.documentElement.dataset.zpanelReady = 'true';

    var sidebar = document.querySelector('[data-zpanel-sidebar]');
    var toggle = document.querySelector('[data-zpanel-menu-toggle]');
    if (sidebar && toggle) {
        toggle.addEventListener('click', function () {
            var open = !sidebar.classList.contains('is-open');
            sidebar.classList.toggle('is-open', open);
            toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
        });
    }

    function toast(message, type) {
        if (window.ZaloroxToast && typeof window.ZaloroxToast.show === 'function') {
            window.ZaloroxToast.show(message, type || 'info');
            return;
        }

        var stack = document.querySelector('[data-toast-stack]');
        if (!stack) {
            stack = document.createElement('div');
            stack.className = 'toast-stack';
            stack.dataset.toastStack = 'true';
            document.body.appendChild(stack);
        }
        var node = document.createElement('div');
        node.className = 'toast-message';
        node.dataset.type = type || 'info';
        node.textContent = message || 'Islem tamamlandi.';
        stack.appendChild(node);
        window.setTimeout(function () { node.remove(); }, 4200);
    }

    function confirm(message, options) {
        options = options || {};
        return new Promise(function (resolve) {
            var backdrop = document.createElement('div');
            backdrop.className = 'zpanel-confirm-backdrop';
            backdrop.innerHTML = '' +
                '<div class="zpanel-confirm-box" role="dialog" aria-modal="true">' +
                    '<strong>' + escapeHtml(options.title || 'Onay') + '</strong>' +
                    '<p>' + escapeHtml(message || 'Bu islemi onayliyor musun?') + '</p>' +
                    '<div>' +
                        '<button type="button" data-confirm-cancel>' + escapeHtml(options.cancelLabel || 'Vazgec') + '</button>' +
                        '<button type="button" class="' + (options.danger ? 'danger' : 'primary') + '" data-confirm-ok>' + escapeHtml(options.confirmLabel || 'Onayla') + '</button>' +
                    '</div>' +
                '</div>';
            document.body.appendChild(backdrop);
            var done = function (value) {
                backdrop.remove();
                resolve(value);
            };
            backdrop.addEventListener('click', function (event) {
                if (event.target === backdrop || event.target.closest('[data-confirm-cancel]')) done(false);
                if (event.target.closest('[data-confirm-ok]')) done(true);
            });
            window.setTimeout(function () {
                var ok = backdrop.querySelector('[data-confirm-ok]');
                if (ok) ok.focus();
            }, 0);
        });
    }

    function cssEscape(value) {
        if (window.CSS && typeof window.CSS.escape === 'function') return window.CSS.escape(value);
        return String(value).replace(/["\\]/g, '\\$&');
    }

    function clearErrors(form) {
        form.querySelectorAll('.field-error').forEach(function (node) { node.remove(); });
        form.querySelectorAll('.is-invalid').forEach(function (node) { node.classList.remove('is-invalid'); });
    }

    function showErrors(form, errors) {
        if (!errors || typeof errors !== 'object') return;
        Object.keys(errors).forEach(function (name) {
            var field = form.querySelector('[name="' + cssEscape(name) + '"]');
            if (!field) return;
            field.classList.add('is-invalid');
            var message = Array.isArray(errors[name]) ? errors[name][0] : errors[name];
            var target = field.closest('label') || field.parentElement || field;
            var error = document.createElement('small');
            error.className = 'field-error';
            error.textContent = message || 'Bu alan gecersiz.';
            target.appendChild(error);
        });
    }

    function formHasFiles(form) {
        return Array.prototype.some.call(form.querySelectorAll('input[type="file"]'), function (input) {
            return input.files && input.files.length > 0;
        });
    }

    function escapeHtml(value) {
        return String(value == null ? '' : value).replace(/[&<>"']/g, function (char) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            }[char];
        });
    }

    function serializeNodes(nodes) {
        var bucket = document.createElement('div');
        nodes.forEach(function (node) { bucket.appendChild(node.cloneNode(true)); });
        return bucket.innerHTML.trim();
    }

    function parsePageSections(html) {
        var wrapper = document.createElement('div');
        wrapper.innerHTML = html || '';
        var sections = [];
        var current = null;
        var bodyNodes = [];

        function pushCurrent() {
            if (!current) return;
            current.body = serializeNodes(bodyNodes);
            sections.push(current);
            bodyNodes = [];
        }

        Array.prototype.forEach.call(wrapper.childNodes, function (node) {
            var isHeading = node.nodeType === 1 && /^(H2|H3)$/i.test(node.tagName || '');
            if (isHeading) {
                pushCurrent();
                current = {
                    level: String(node.tagName).toLowerCase(),
                    title: (node.textContent || '').replace(/#/g, '').trim() || 'Yeni bolum',
                    body: ''
                };
                return;
            }

            if (!current) {
                var hasContent = node.nodeType === 1 || String(node.textContent || '').trim() !== '';
                if (!hasContent) return;
                current = { level: 'h2', title: 'Giris', body: '' };
            }
            bodyNodes.push(node);
        });
        pushCurrent();

        if (!sections.length) {
            sections.push({ level: 'h2', title: 'Yeni bolum', body: '<p>Bolum icerigini yaz.</p>' });
        }

        return sections;
    }

    function sectionBodyToHtml(value) {
        value = String(value || '').trim();
        if (!value) return '<p></p>';
        if (/<\s*(p|h[2-4]|ul|ol|li|blockquote|pre|img|br|strong|em|a|code)\b/i.test(value)) {
            return value;
        }
        return '<p>' + escapeHtml(value).replace(/\n{2,}/g, '</p><p>').replace(/\n/g, '<br>') + '</p>';
    }

    function renderPageSection(root, section) {
        var item = document.createElement('article');
        item.className = 'page-section-item';
        item.innerHTML = '' +
            '<div class="page-section-row">' +
                '<label>Baslik<input type="text" data-section-title maxlength="180"></label>' +
                '<label>Seviye<select data-section-level><option value="h2">Ana bolum</option><option value="h3">Alt bolum</option></select></label>' +
            '</div>' +
            '<label>Icerik<textarea data-section-body rows="4"></textarea></label>' +
            '<div class="page-section-tools">' +
                '<button type="button" data-section-up>Yukari</button>' +
                '<button type="button" data-section-down>Asagi</button>' +
                '<button type="button" class="danger" data-section-remove>Sil</button>' +
            '</div>';
        item.querySelector('[data-section-title]').value = section.title || '';
        item.querySelector('[data-section-level]').value = section.level === 'h3' ? 'h3' : 'h2';
        item.querySelector('[data-section-body]').value = section.body || '';
        root.querySelector('[data-page-section-list]').appendChild(item);
    }

    function syncPageSectionEditor(root) {
        var content = root.closest('form') ? root.closest('form').querySelector('[data-page-content]') : null;
        if (!content) return;
        var html = Array.prototype.map.call(root.querySelectorAll('.page-section-item'), function (item) {
            var level = item.querySelector('[data-section-level]').value === 'h3' ? 'h3' : 'h2';
            var title = item.querySelector('[data-section-title]').value.trim() || 'Yeni bolum';
            var body = sectionBodyToHtml(item.querySelector('[data-section-body]').value);
            return '<' + level + '>' + escapeHtml(title) + '</' + level + '>' + body;
        }).join('\n');
        content.value = html;
    }

    function syncPageSectionEditors(scope) {
        (scope || document).querySelectorAll('[data-page-section-editor]').forEach(syncPageSectionEditor);
    }

    function loadPageSectionEditor(root, fromContent) {
        var form = root.closest('form');
        var content = form ? form.querySelector('[data-page-content]') : null;
        var list = root.querySelector('[data-page-section-list]');
        if (!content || !list) return;
        list.innerHTML = '';
        parsePageSections(fromContent == null ? content.value : fromContent).forEach(function (section) {
            renderPageSection(root, section);
        });
        syncPageSectionEditor(root);
    }

    function responseJson(response) {
        return response.json().then(function (json) {
            json.httpStatus = response.status;
            return json;
        }).catch(function () {
            return { ok: false, message: 'Gecersiz JSON cevabi.', httpStatus: response.status };
        });
    }

    function submitForm(form) {
        syncPageSectionEditors(form);
        var formData = new FormData(form);
        if (!formData.has('_csrf') && window.ZALOROX_CSRF_TOKEN) formData.append('_csrf', window.ZALOROX_CSRF_TOKEN);
        var csrf = formData.get('_csrf') || window.ZALOROX_CSRF_TOKEN || '';
        var body = formHasFiles(form) || (form.enctype || '').toLowerCase() === 'multipart/form-data'
            ? formData
            : new URLSearchParams(formData);

        return fetch(form.getAttribute('action') || window.location.href, {
            method: (form.getAttribute('method') || 'POST').toUpperCase(),
            headers: {
                'X-CSRF-TOKEN': csrf,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: body
        }).then(responseJson);
    }

    function requestAction(endpoint, data) {
        data = data || {};
        if (!data._csrf) data._csrf = window.ZALOROX_CSRF_TOKEN || '';
        return fetch(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-TOKEN': data._csrf,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: new URLSearchParams(data)
        }).then(responseJson);
    }

    function setLoading(button, loading) {
        if (!button) return;
        if (loading) {
            button.dataset.originalText = button.textContent;
            button.disabled = true;
            button.classList.add('is-loading');
            button.textContent = button.dataset.loadingText || 'Kaydediliyor...';
            return;
        }

        button.disabled = false;
        button.classList.remove('is-loading');
        button.textContent = button.dataset.originalText || button.textContent;
    }

    document.addEventListener('submit', function (event) {
        var form = event.target.closest('form[data-zpanel-form]');
        if (!form) return;
        event.preventDefault();
        var message = form.dataset.confirm || '';
        var run = function () {
            var button = form.querySelector('button[type="submit"], button:not([type])');
            clearErrors(form);
            setLoading(button, true);
            submitForm(form).then(function (json) {
                if (!json.ok && json.errors) showErrors(form, json.errors);
                toast(json.message || (json.ok ? 'Islem tamamlandi.' : 'Islem tamamlanamadi.'), json.ok ? 'success' : 'error');
                if (!json.ok) return;
                if (form.dataset.redirectOnSuccess === 'true' && json.redirect) {
                    window.location.href = json.redirect;
                    return;
                }
                if (form.dataset.reloadOnSuccess !== 'false') {
                    window.setTimeout(function () { window.location.reload(); }, 500);
                }
            }).catch(function (error) {
                toast(error.message || 'Islem tamamlanamadi.', 'error');
            }).finally(function () {
                setLoading(button, false);
            });
        };

        if (message) {
            confirm(message, { confirmLabel: 'Onayla', cancelLabel: 'Vazgec', danger: /sil|cope|reddet|pasif|block/i.test(message) }).then(function (ok) {
                if (ok) run();
            });
            return;
        }

        run();
    });

    document.addEventListener('click', function (event) {
        var button = event.target.closest('[data-zpanel-action]');
        if (!button) return;
        event.preventDefault();

        var endpoint = button.dataset.zpanelAction || '';
        if (!endpoint) return;
        var data = {};
        ['id', 'target', 'filePath', 'mediaId', 'value', 'status'].forEach(function (key) {
            if (button.dataset[key] !== undefined) {
                var param = key.replace(/[A-Z]/g, function (char) { return '_' + char.toLowerCase(); });
                data[param] = button.dataset[key];
            }
        });

        var run = function () {
            setLoading(button, true);
            requestAction(endpoint, data).then(function (json) {
                toast(json.message || (json.ok ? 'Islem tamamlandi.' : 'Islem tamamlanamadi.'), json.ok ? 'success' : 'error');
                if (json.ok && button.dataset.reloadOnSuccess !== 'false') {
                    window.setTimeout(function () { window.location.reload(); }, 450);
                }
            }).catch(function (error) {
                toast(error.message || 'Islem tamamlanamadi.', 'error');
            }).finally(function () {
                setLoading(button, false);
            });
        };

        if (button.dataset.confirm) {
            confirm(button.dataset.confirm, {
                confirmLabel: 'Onayla',
                cancelLabel: 'Vazgec',
                danger: button.classList.contains('danger') || /sil|pasif|reddet|block|cope/i.test(button.dataset.confirm)
            }).then(function (ok) { if (ok) run(); });
            return;
        }

        run();
    });

    document.addEventListener('click', function (event) {
        var input = event.target.closest('[data-copy-value]');
        if (!input) return;
        input.select();
        var value = input.dataset.copyValue || input.value || '';
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(value).then(function () {
                toast('URL kopyalandi.', 'success');
            }).catch(function () {});
        }
    });

    document.querySelectorAll('[data-zpanel-filter]').forEach(function (input) {
        input.addEventListener('input', function () {
            var target = document.querySelector(input.dataset.zpanelFilter || '');
            if (!target) return;
            var needle = input.value.trim().toLowerCase();
            target.querySelectorAll('tbody tr').forEach(function (row) {
                row.hidden = needle !== '' && row.textContent.toLowerCase().indexOf(needle) === -1;
            });
        });
    });

    document.querySelectorAll('[data-page-section-editor]').forEach(function (root) {
        loadPageSectionEditor(root);
        root.addEventListener('input', function () { syncPageSectionEditor(root); });
        root.addEventListener('change', function () { syncPageSectionEditor(root); });
        root.addEventListener('click', function (event) {
            var add = event.target.closest('[data-page-section-add]');
            var parse = event.target.closest('[data-page-sections-parse]');
            var remove = event.target.closest('[data-section-remove]');
            var up = event.target.closest('[data-section-up]');
            var down = event.target.closest('[data-section-down]');
            var item = event.target.closest('.page-section-item');
            var list = root.querySelector('[data-page-section-list]');

            if (add) {
                renderPageSection(root, { level: 'h2', title: 'Yeni bolum', body: '<p>Bolum icerigini yaz.</p>' });
                syncPageSectionEditor(root);
                return;
            }

            if (parse) {
                var form = root.closest('form');
                var content = form ? form.querySelector('[data-page-content]') : null;
                loadPageSectionEditor(root, content ? content.value : '');
                return;
            }

            if (!item || !list) return;
            if (remove) {
                item.remove();
                if (!list.querySelector('.page-section-item')) {
                    renderPageSection(root, { level: 'h2', title: 'Yeni bolum', body: '<p>Bolum icerigini yaz.</p>' });
                }
                syncPageSectionEditor(root);
                return;
            }

            if (up && item.previousElementSibling) {
                list.insertBefore(item, item.previousElementSibling);
                syncPageSectionEditor(root);
                return;
            }

            if (down && item.nextElementSibling) {
                list.insertBefore(item.nextElementSibling, item);
                syncPageSectionEditor(root);
            }
        });
    });

    window.ZPanelAdmin = {
        request: requestAction,
        toast: toast,
        confirm: confirm
    };
})();

(function () {
    document.documentElement.dataset.zpanelReady = 'true';

    var root = document.querySelector('[data-security-bot]');
    if (!root) return;

    var apiBase = (root.dataset.apiBase || window.ZALOROX_API_BASE || '/api').replace(/\/$/, '');
    var csrf = root.dataset.csrf || window.ZALOROX_CSRF_TOKEN || '';
    var logsBody = root.querySelector('[data-security-logs]');

    function toast(message, type) {
        if (window.ZaloroxToast) {
            window.ZaloroxToast.show(message, type || 'info');
        }
    }

    function endpoint(path) {
        return apiBase + '/' + String(path || '').replace(/^\//, '');
    }

    function withCsrf(params) {
        if (!params.has('_csrf')) params.append('_csrf', csrf);
        return params;
    }

    function request(path, params, method) {
        return fetch(endpoint(path), {
            method: method || 'POST',
            headers: { 'X-CSRF-TOKEN': csrf },
            body: method === 'GET' ? undefined : withCsrf(params || new URLSearchParams())
        }).then(function (response) {
            return response.json().catch(function () {
                return { ok: false, message: 'Gecersiz JSON cevabi.' };
            });
        });
    }

    function escapeHtml(value) {
        return String(value == null ? '' : value).replace(/[&<>"']/g, function (char) {
            return {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            }[char];
        });
    }

    function statusLabel(status) {
        if (status === 'blocked') return 'Engellendi';
        if (status === 'review') return 'Inceleme';
        return 'Guvenli';
    }

    function renderLogs(logs) {
        if (!logsBody) return;

        if (!Array.isArray(logs) || logs.length === 0) {
            logsBody.innerHTML = '<tr><td colspan="8">Henuz bot logu yok.</td></tr>';
            return;
        }

        logsBody.innerHTML = logs.map(function (log) {
            var reasons = Array.isArray(log.reasons) ? log.reasons.join(', ') : '';
            var status = log.status || 'safe';

            return '<tr>' +
                '<td>' + escapeHtml(log.id) + '</td>' +
                '<td>' + escapeHtml(log.scan_type) + '</td>' +
                '<td>' + escapeHtml(log.target_type || '-') + '</td>' +
                '<td>' + escapeHtml(log.risk_score || 0) + '</td>' +
                '<td><span class="status-pill status-' + escapeHtml(status) + '">' + escapeHtml(statusLabel(status)) + '</span></td>' +
                '<td>' + escapeHtml(log.action_taken || 'allow') + '</td>' +
                '<td>' + escapeHtml(reasons) + '</td>' +
                '<td>' + escapeHtml(log.created_at || '') + '</td>' +
                '</tr>';
        }).join('');
    }

    function refreshLogs() {
        return fetch(endpoint('/zpanel/security/logs'), {
            method: 'GET',
            headers: { 'X-CSRF-TOKEN': csrf }
        }).then(function (response) {
            return response.json();
        }).then(function (data) {
            if (!data.ok) {
                toast(data.message || 'Loglar yenilenemedi.', 'error');
                return;
            }

            renderLogs(data.logs || []);
        }).catch(function () {
            toast('Loglar yenilenemedi.', 'error');
        });
    }

    var settingsForm = root.querySelector('[data-security-settings]');
    if (settingsForm) {
        settingsForm.addEventListener('submit', function (event) {
            event.preventDefault();
            request('/zpanel/security/settings', new URLSearchParams(new FormData(settingsForm))).then(function (data) {
                toast(data.message || (data.ok ? 'Ayarlar kaydedildi.' : 'Ayarlar kaydedilemedi.'), data.ok ? 'success' : 'error');
            }).catch(function () {
                toast('Ayarlar kaydedilemedi.', 'error');
            });
        });
    }

    root.querySelectorAll('[data-security-create]').forEach(function (form) {
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            request(form.dataset.securityCreate, new URLSearchParams(new FormData(form))).then(function (data) {
                toast(data.message || (data.ok ? 'Kayit eklendi.' : 'Kayit eklenemedi.'), data.ok ? 'success' : 'error');
                if (data.ok && !data.duplicate) {
                    window.setTimeout(function () { window.location.reload(); }, 450);
                }
            }).catch(function () {
                toast('Kayit eklenemedi.', 'error');
            });
        });
    });

    root.querySelectorAll('[data-security-delete]').forEach(function (button) {
        button.addEventListener('click', function () {
            if (!window.ZaloroxModal || typeof window.ZaloroxModal.confirm !== 'function') {
                toast('Modal sistemi henuz yuklenmedi.', 'warning');
                return;
            }

            window.ZaloroxModal.confirm('Bu kaydi silmek istiyor musun?', {
                title: 'Silme Onayi',
                confirmLabel: 'Sil',
                cancelLabel: 'Vazgec',
                danger: true
            }).then(function (ok) {
                if (!ok) return;

                var params = new URLSearchParams();
                params.append('id', button.dataset.id || '');
                request(button.dataset.securityDelete, params).then(function (data) {
                    toast(data.message || (data.ok ? 'Kayit silindi.' : 'Kayit silinemedi.'), data.ok ? 'success' : 'error');
                    if (data.ok) {
                        window.setTimeout(function () { window.location.reload(); }, 450);
                    }
                }).catch(function () {
                    toast('Kayit silinemedi.', 'error');
                });
            });
        });
    });

    var scanForm = root.querySelector('[data-security-scan]');
    if (scanForm) {
        scanForm.addEventListener('submit', function (event) {
            event.preventDefault();
            request('/security/scan-link', new URLSearchParams(new FormData(scanForm))).then(function (data) {
                var reasons = Array.isArray(data.reasons) ? data.reasons.join(', ') : '-';
                var message = 'Risk: ' + (data.risk_score || 0) + ' | Durum: ' + statusLabel(data.status || 'safe') + ' | Aksiyon: ' + (data.action_taken || 'allow') + ' | Sebepler: ' + reasons;

                if (window.ZaloroxModal && typeof window.ZaloroxModal.alert === 'function') {
                    window.ZaloroxModal.alert(message, { title: 'Tarama Sonucu' });
                } else {
                    toast(message, data.ok ? 'info' : 'error');
                }

                refreshLogs();
            }).catch(function () {
                toast('Link taramasi tamamlanamadi.', 'error');
            });
        });
    }

    root.querySelectorAll('[data-security-refresh]').forEach(function (button) {
        button.addEventListener('click', function () {
            refreshLogs();
        });
    });
})();

(function () {
    var roots = document.querySelectorAll('[data-zpanel-withdrawals], [data-zpanel-site-banks], [data-zpanel-financial-settings]');
    if (!roots.length) return;

    var csrf = window.ZALOROX_CSRF_TOKEN || '';

    function toast(message, type) {
        if (window.ZaloroxToast) window.ZaloroxToast.show(message, type || 'info');
    }

    function request(endpoint, form) {
        var data = new URLSearchParams(new FormData(form));
        if (!data.has('_csrf')) data.append('_csrf', csrf);
        return fetch(endpoint, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': csrf,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: data
        }).then(function (response) {
            return response.json().then(function (json) {
                json.httpStatus = response.status;
                return json;
            }).catch(function () {
                return { ok: false, message: 'Gecersiz JSON cevabi.', httpStatus: response.status };
            });
        });
    }

    roots.forEach(function (root) {
        csrf = root.dataset.csrf || csrf;
        root.addEventListener('click', function (event) {
            var button = event.target.closest('[data-zpanel-endpoint]');
            if (!button) return;
            var form = button.closest('[data-zpanel-finance-form]');
            if (!form) return;

            var run = function () {
                button.disabled = true;
                request(button.dataset.zpanelEndpoint || '', form).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Islem tamamlanamadi.');
                    toast(json.message || 'Islem tamamlandi.', 'success');
                    window.setTimeout(function () { window.location.reload(); }, 500);
                }).catch(function (error) {
                    toast(error.message || 'Islem tamamlanamadi.', 'error');
                }).finally(function () {
                    button.disabled = false;
                });
            };

            if (button.dataset.confirm && window.ZaloroxModal) {
                window.ZaloroxModal.confirm(button.dataset.confirm, {
                    confirmLabel: 'Onayla',
                    cancelLabel: 'Vazgec',
                    danger: button.classList.contains('danger')
                }).then(function (ok) { if (ok) run(); });
                return;
            }

            run();
        });
    });
})();

(function () {
    var root = document.querySelector('[data-test-tools]');
    if (!root) return;

    var endpoint = root.dataset.endpoint || '/api/zpanel/test-tools/run';
    var csrf = root.dataset.csrf || window.ZALOROX_CSRF_TOKEN || '';
    var output = root.querySelector('[data-test-output]');

    function toast(message, type) {
        if (window.ZaloroxToast) window.ZaloroxToast.show(message, type || 'info');
    }

    function write(data) {
        if (!output) return;
        output.textContent = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
    }

    function run(action) {
        var body = new URLSearchParams({ action: action, _csrf: csrf });
        var scanUrl = root.querySelector('[data-test-scan-url]');
        if (action === 'security_scan' && scanUrl) body.append('url', scanUrl.value || '');

        write('Calisiyor: ' + action);
        return fetch(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRF-TOKEN': csrf,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: body
        }).then(function (response) {
            return response.json().then(function (json) {
                json.httpStatus = response.status;
                return json;
            });
        }).then(function (json) {
            write(json);
            if (!json.ok) {
                toast(json.message || 'Test aksiyonu basarisiz.', 'error');
                return;
            }

            (json.client_reset || []).forEach(function (key) {
                try {
                    window.localStorage.removeItem(key);
                    document.cookie = key + '=; Max-Age=0; path=/';
                } catch (error) {}
            });
            toast(json.message || 'Test aksiyonu tamamlandi.', 'success');
        }).catch(function (error) {
            write(error.message || 'Test aksiyonu basarisiz.');
            toast('Test aksiyonu basarisiz.', 'error');
        });
    }

    root.addEventListener('click', function (event) {
        var button = event.target.closest('[data-test-action]');
        if (!button) return;
        button.disabled = true;
        run(button.dataset.testAction || '').finally(function () {
            button.disabled = false;
        });
    });
})();
