<script>
(() => {
    const $ = (selector, root = document) => root.querySelector(selector);
    const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
    const csrf = <?= json_encode(csrf_token()) ?>;
    const adminBase = <?= json_encode(parse_url(ADMIN_URL, PHP_URL_PATH) . '/') ?>;

    // ---------- Bildirim ve ilerleme çubuğu ----------
    function toast(message, ok = true) {
        if (!message) return;
        const box = $('#toasts');
        if (!box) return;
        const item = document.createElement('div');
        item.className = 'pointer-events-auto flex items-center gap-3 rounded-full bg-zinc-900 py-3 pr-5 pl-3 text-sm font-medium text-white shadow-2xl transition duration-300 translate-y-3 opacity-0';
        item.innerHTML = `<span class="flex size-6 items-center justify-center rounded-full text-xs font-bold ${ok ? 'bg-emerald-500' : 'bg-rose-500'}">${ok ? '✓' : '!'}</span><span></span>`;
        item.lastElementChild.textContent = message;
        box.append(item);
        requestAnimationFrame(() => item.classList.remove('translate-y-3', 'opacity-0'));
        setTimeout(() => { item.classList.add('opacity-0'); setTimeout(() => item.remove(), 300); }, 3200);
    }

    const progress = {
        timer: null,
        busy: null,
        start() {
            clearTimeout(this.busy);
            this.busy = setTimeout(() => document.documentElement.toggleAttribute('data-busy', true), 150);
            const bar = $('#progress');
            if (!bar) return;
            clearInterval(this.timer);
            let width = 8;
            bar.style.opacity = '1';
            bar.style.width = width + '%';
            this.timer = setInterval(() => { width = Math.min(90, width + (90 - width) * 0.12); bar.style.width = width + '%'; }, 120);
        },
        done() {
            clearTimeout(this.busy);
            document.documentElement.removeAttribute('data-busy');
            const bar = $('#progress');
            if (!bar) return;
            clearInterval(this.timer);
            bar.style.width = '100%';
            setTimeout(() => { bar.style.opacity = '0'; setTimeout(() => { bar.style.width = '0'; }, 200); }, 150);
        },
    };

    // JSON isteği: düz nesne ya da FormData gönderir
    async function post(url, data) {
        if (!(data instanceof FormData)) {
            const form = new FormData();
            Object.entries(data).forEach(([key, value]) => Array.isArray(value) ? value.forEach(item => form.append(key + '[]', item)) : form.append(key, value));
            data = form;
        }
        if (!data.has('_csrf')) data.append('_csrf', csrf);
        const response = await fetch(url, { method: 'POST', body: data, headers: { 'X-Requested-With': 'fetch' } });
        return response.json();
    }

    const reloadPreview = () => {
        // Özelleştiricide titremesiz (çift çerçeveli) yenileme kullanılır
        if (window.customizerReload) return window.customizerReload();
        const frame = $('[data-preview-frame]');
        if (!frame) return;
        const target = frame.dataset.anchor;
        frame.contentWindow.location.reload();
        if (target) frame.addEventListener('load', () => frame.contentWindow.document.getElementById(target)?.scrollIntoView({ block: 'start' }), { once: true });
    };

    // ---------- PJAX: sayfalar yenilenmeden açılır, formlar arka planda gönderilir ----------
    const isAdminUrl = url => url.origin === location.origin && url.pathname.startsWith(adminBase) && !url.pathname.endsWith('/giris') && !url.pathname.endsWith('/cikis');

    async function visit(url, { method = 'GET', body = null, push = true, form = null } = {}) {
        const app = $('#admin-app');
        if (!app && method === 'GET') { location.href = url; return; }
        progress.start();
        try {
            const response = await fetch(url, { method, body, headers: { 'X-Requested-With': method === 'GET' ? 'pjax' : 'fetch' } });
            const type = response.headers.get('content-type') || '';

            if (type.includes('application/json')) {
                handleJson(await response.json(), form);
                return;
            }
            if (!type.includes('text/html')) {
                location.href = url;
                return;
            }

            const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
            const next = doc.getElementById('admin-app');
            if (!next || !app) {
                location.href = response.url;
                return;
            }
            app.replaceWith(next);
            document.title = doc.title;
            if (push || response.url !== location.href) {
                history[push ? 'pushState' : 'replaceState']({ pjax: true }, '', response.url);
            }
            window.scrollTo(0, 0);
            init(next);
        } catch (error) {
            location.href = url;
        } finally {
            progress.done();
        }
    }

    function handleJson(json, form) {
        if (json.redirect) {
            visit(json.redirect);
            return;
        }
        toast(json.message, json.ok);
        if (!json.ok || !form) return;
        $$('input[type=file]', form).forEach(input => { input.value = ''; });
        if (json.images) Object.entries(json.images).forEach(([path, image]) => {
            const field = $(`input[name="file__${path}"]`, form)?.closest('[data-image-field]');
            if (field) setImage(field, image.value, image.src);
        });
        reloadPreview();
        // Özelleştiricinin içine gömülü editörse önizlemeyi yenilemesi için haber ver
        if (window.parent !== window) window.parent.postMessage({ type: 'customize-saved', section: form.dataset.section || null }, location.origin);
    }

    // Onay isteyen işlemler (önce bu çalışır)
    document.addEventListener('submit', event => {
        const message = event.submitter?.dataset.confirm || event.target.dataset.confirm;
        if (message && !confirm(message)) {
            event.preventDefault();
            event.stopImmediatePropagation();
        }
    }, true);

    // Tüm yönetim formları arka planda gönderilir
    document.addEventListener('submit', event => {
        const form = event.target;
        if (event.defaultPrevented || form.hasAttribute('data-no-pjax') || form.target === '_blank') return;
        const action = new URL(form.getAttribute('action') || location.href, location.href);
        if (!isAdminUrl(action) && !form.hasAttribute('data-admin-ajax')) return;
        event.preventDefault();

        const data = new FormData(form);
        if (event.submitter?.name) data.append(event.submitter.name, event.submitter.value);

        if ((form.getAttribute('method') || 'get').toLowerCase() === 'get') {
            const params = new URLSearchParams();
            for (const [key, value] of data) if (String(value) !== '') params.append(key, value);
            action.search = params.toString();
            visit(action.href);
            return;
        }

        const button = event.submitter;
        const restore = buttonLoading(button);
        visit(action.href, { method: 'POST', body: data, form }).finally(restore);
    });

    // Gönderilen butonun içinde dönen ikon gösterir, bitince eski hâline döner
    function buttonLoading(button) {
        if (!button || !button.isConnected || button.hasAttribute('aria-busy')) return () => {};
        button.setAttribute('aria-busy', 'true');
        const html = button.innerHTML;
        const width = button.offsetWidth;
        button.disabled = true;
        button.style.minWidth = width + 'px';
        button.innerHTML = '<svg class="size-4 animate-spin" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="3" opacity=".25"/><path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" stroke-width="3" stroke-linecap="round"/></svg>';
        return () => {
            if (!button.isConnected) return;
            button.innerHTML = html;
            button.disabled = false;
            button.removeAttribute('aria-busy');
            button.style.minWidth = '';
        };
    }

    // Yönetim linkleri yenilenmeden açılır
    document.addEventListener('click', event => {
        const link = event.target.closest('a[href]');
        if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
        if (link.target === '_blank' || link.hasAttribute('download') || link.hasAttribute('data-no-pjax')) return;
        const url = new URL(link.href, location.href);
        if (!isAdminUrl(url) || (url.pathname === location.pathname && url.search === location.search && url.hash)) return;
        if (url.pathname.endsWith('/tema')) { if (/\bbtn/.test(link.className)) buttonLoading(link); return; }
        event.preventDefault();
        const restore = /\bbtn/.test(link.className) ? buttonLoading(link) : () => {};
        visit(url.href).finally(restore);
    });

    window.addEventListener('popstate', () => { if ($('#admin-app')) visit(location.href, { push: false }); });

    // ---------- Sürükle-bırak sıralama: [data-sortable="adres"] > [data-id] ----------
    let dragged = null;
    document.addEventListener('dragstart', event => {
        const item = event.target.closest('[data-sortable] > [data-id]');
        if (!item) return;
        dragged = item;
        item.classList.add('opacity-40');
        event.dataTransfer.effectAllowed = 'move';
    });
    document.addEventListener('dragover', event => {
        if (!dragged) return;
        const over = event.target.closest('[data-sortable] > [data-id]');
        if (!over || over === dragged || over.parentElement !== dragged.parentElement) return;
        event.preventDefault();
        const box = over.getBoundingClientRect();
        over.parentElement.insertBefore(dragged, event.clientY > box.top + box.height / 2 ? over.nextSibling : over);
    });
    document.addEventListener('dragend', async () => {
        if (!dragged) return;
        const list = dragged.parentElement;
        dragged.classList.remove('opacity-40');
        dragged = null;
        const ids = $$(':scope > [data-id]', list).map(item => item.dataset.id);
        const json = await post(list.dataset.sortable, { action: 'sort', ids });
        toast(json.message || 'Sıralama kaydedildi', json.ok !== false);
        reloadPreview();
    });

    // Tek tıklık açma/kapama anahtarları
    document.addEventListener('change', async event => {
        const input = event.target.closest('[data-quick]');
        if (!input) return;
        const json = await post(input.dataset.quick, { action: input.dataset.quickAction, id: input.dataset.quickId, value: input.checked ? 1 : 0 });
        toast(json.message, json.ok);
        input.closest('[data-id]')?.classList.toggle('opacity-60', !input.checked);
        reloadPreview();
    });

    // ---------- Tıklamalar ----------
    document.addEventListener('click', event => {
        if (event.target.closest('[data-add-variant]')) {
            const html = $('#variant-row').innerHTML.replaceAll('__i__', Date.now());
            $('[data-variant-list]').insertAdjacentHTML('beforeend', html);
            $('[data-variant-empty]')?.classList.add('hidden');
        }
        const removeVariant = event.target.closest('[data-remove-variant]');
        if (removeVariant) removeVariant.closest('[data-variant]').remove();

        const add = event.target.closest('[data-repeater-add]');
        if (add) {
            const repeater = add.closest('[data-repeater]');
            const template = $(':scope > template[data-repeater-template]', repeater);
            const list = $(':scope > [data-repeater-list]', repeater);
            list.insertAdjacentHTML('beforeend', template.innerHTML.replaceAll('%i%', 'n' + Date.now()));
            updateCount(repeater);
            list.lastElementChild.querySelector('input:not([type=hidden]), textarea')?.focus();
        }
        const row = event.target.closest('[data-repeater-row]');
        if (row && event.target.closest('[data-row-remove]') && confirm('Bu öğe silinsin mi?')) {
            const repeater = row.closest('[data-repeater]');
            row.remove();
            updateCount(repeater);
            return;
        }
        if (row && event.target.closest('[data-row-up]') && row.previousElementSibling) row.parentElement.insertBefore(row, row.previousElementSibling);
        if (row && event.target.closest('[data-row-down]') && row.nextElementSibling) row.parentElement.insertBefore(row.nextElementSibling, row);
        if (row && event.target.closest('[data-row-toggle]')) $(':scope > [data-row-body]', row).classList.toggle('hidden');

        const clear = event.target.closest('[data-image-clear]');
        if (clear) {
            const field = clear.closest('[data-image-field]');
            setImage(field, '', '');
            $('input[type=file]', field).value = '';
            field.dispatchEvent(new Event('change', { bubbles: true }));
        }

        const toggle = event.target.closest('[data-toggle]');
        if (toggle) $(toggle.dataset.toggle)?.classList.toggle('hidden');

        const device = event.target.closest('[data-device]');
        if (device) {
            $('[data-preview-frame]').style.width = device.dataset.device;
            $$('[data-device]').forEach(item => item.toggleAttribute('data-active', item === device));
        }
    });

    function updateCount(repeater) {
        const count = $(':scope > div > p [data-repeater-count]', repeater);
        if (count) count.textContent = $$(':scope > [data-repeater-list] > [data-repeater-row]', repeater).length;
    }

    function setImage(field, value, src) {
        $('[data-image-value]', field).value = value;
        $('[data-image-preview]', field).innerHTML = src ? `<img src="${src}" alt="" class="h-full w-full object-cover">` : '<span class="text-xs text-zinc-400">Yok</span>';
        $('[data-image-clear]', field).classList.toggle('hidden', !value);
    }

    // ---------- Yazarken ----------
    document.addEventListener('input', event => {
        const picker = event.target.closest('[data-color-for]');
        if (picker) {
            const text = document.getElementById(picker.dataset.colorFor);
            text.value = picker.value;
            text.dispatchEvent(new Event('input', { bubbles: true }));
        }
        const text = event.target.closest('[data-color-text]');
        if (text && /^#[0-9a-f]{6}$/i.test(text.value)) {
            const swatch = $(`[data-color-for="${text.id}"]`);
            if (swatch) swatch.value = text.value;
        }

        const range = event.target.closest('input[type=range][data-range-output]');
        if (range) {
            const output = document.getElementById(range.dataset.rangeOutput);
            if (output) output.textContent = range.value;
        }

        const rowInput = event.target.closest('[data-repeater-row] [data-field="title"] input, [data-repeater-row] [data-field="question"] input');
        if (rowInput) $('[data-row-title]', rowInput.closest('[data-repeater-row]')).textContent = rowInput.value || 'Yeni öğe';

        const search = event.target.closest('[data-picker-search]');
        if (search) {
            const term = search.value.toLocaleLowerCase('tr-TR');
            $$('[data-picker-item]', search.closest('[data-product-picker]')).forEach(item => item.classList.toggle('hidden', !item.dataset.pickerItem.includes(term)));
        }
    });

    // Görsel seçilince önizleme
    document.addEventListener('change', event => {
        const input = event.target.closest('input[type=file]');
        if (!input || !input.files.length) return;
        const field = input.closest('[data-image-field]');
        if (field) {
            $('[data-image-preview]', field).innerHTML = `<img src="${URL.createObjectURL(input.files[0])}" alt="" class="h-full w-full object-cover">`;
            return;
        }
        const target = input.dataset.preview && $(input.dataset.preview);
        if (!target) return;
        target.innerHTML = '';
        [...input.files].forEach(file => {
            const image = document.createElement('img');
            image.src = URL.createObjectURL(file);
            image.className = target.dataset.imageClass || 'h-full w-full object-cover';
            target.append(image);
        });
    });

    // ---------- Sayfaya özel başlatmalar (her PJAX geçişinden sonra yeniden çalışır) ----------
    function init(root = document) {
        $$('[data-slug-source]', root).forEach(source => {
            const target = $(source.dataset.slugSource);
            if (!target || target.value) return;
            const map = { ç: 'c', ğ: 'g', ı: 'i', i: 'i', ö: 'o', ş: 's', ü: 'u' };
            source.addEventListener('input', () => {
                if (target.dataset.touched) return;
                target.value = source.value.toLocaleLowerCase('tr-TR').replace(/[çğıiöşü]/g, c => map[c]).replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
            });
            target.addEventListener('input', () => { target.dataset.touched = '1'; });
        });

        // data-show-if="alan=değer": alan o değerdeyken görünür (örn. seçili ödeme altyapısının bilgileri)
        $$('[data-show-if]', root).forEach(box => {
            const [name, value] = box.dataset.showIf.split('=');
            const form = box.closest('form') || document;
            const sync = () => {
                const input = form.querySelector(`[name="${name}"]:checked`) || form.querySelector(`select[name="${name}"]`);
                box.classList.toggle('hidden', (input ? input.value : '') !== value);
            };
            form.addEventListener('change', sync);
            sync();
        });

        $$('[data-menu-type]', root).forEach(select => {
            const form = select.closest('form');
            const sync = () => $$('[data-menu-target]', form).forEach(box => box.classList.toggle('hidden', box.dataset.menuTarget !== select.value));
            select.addEventListener('change', sync);
            sync();
        });
    }

    init();
    window.admin = { $, $$, post, toast, reloadPreview, setImage, progress, buttonLoading };
})();
</script>
