</main>

<?php $dark = theme('footer_style') !== 'light' ?>

<?php if (theme_on('trust_strip')): ?>
<section data-customize="footer" data-customize-label="Avantajlar şeridi" class="mt-24 border-y border-zinc-200/70 bg-soft">
    <div class="container-x grid grid-cols-2 gap-x-6 gap-y-8 py-10 lg:grid-cols-4">
        <?php foreach ([
            ['truck', 'Hızlı teslimat', setting('free_shipping_limit') > 0 ? money(setting('free_shipping_limit')) . ' üzeri ücretsiz kargo' : '1-3 iş gününde kargoda'],
            ['shield', 'Güvenli alışveriş', 'Bilgileriniz her zaman güvende'],
            ['refresh', 'Kolay iade', '14 gün içinde ücretsiz iade'],
            ['chat', 'Müşteri desteği', setting('store_phone') ?: 'Her zaman yanınızdayız'],
        ] as [$name, $heading, $text]): ?>
            <div class="flex items-start gap-4">
                <span class="flex size-11 shrink-0 items-center justify-center rounded-full bg-white text-ink ring-1 ring-zinc-200"><?= icon($name, 'size-5') ?></span>
                <div>
                    <p class="text-sm font-semibold text-ink"><?= $heading ?></p>
                    <p class="mt-0.5 text-[13px] text-zinc-500"><?= e($text) ?></p>
                </div>
            </div>
        <?php endforeach ?>
    </div>
</section>
<?php endif ?>

<footer data-customize="footer" data-customize-label="Alt bilgi" class="<?= theme_on('trust_strip') ? '' : 'mt-24' ?> <?= $dark ? 'bg-ink text-zinc-400' : 'border-t border-zinc-200 bg-soft text-zinc-600' ?>">
    <div class="container-x grid gap-12 py-16 lg:grid-cols-12">
        <div class="lg:col-span-4">
            <a href="<?= url() ?>" class="inline-flex <?= $dark ? 'text-white' : 'text-ink' ?>"><?= logo_html($dark) ?></a>
            <p class="mt-4 max-w-sm text-sm leading-6"><?= e(theme('footer_text') ?: site_setting('store_tagline', '')) ?></p>
            <?php if (social_links()): ?>
                <div class="mt-6 flex flex-wrap gap-2">
                    <?php foreach (social_links() as $label => $link): ?>
                        <a href="<?= e($link) ?>" target="_blank" rel="noopener" class="rounded-full border px-4 py-2 text-xs font-medium transition <?= $dark ? 'border-white/10 text-zinc-300 hover:border-white/30 hover:text-white' : 'border-zinc-300 text-zinc-600 hover:border-ink hover:text-ink' ?>"><?= $label ?></a>
                    <?php endforeach ?>
                </div>
            <?php endif ?>
        </div>

        <div class="grid grid-cols-2 gap-10 sm:grid-cols-4 lg:col-span-8">
            <?php foreach (['footer_1', 'footer_2', 'footer_3'] as $location): ?>
                <div>
                    <h3 class="eyebrow <?= $dark ? 'text-zinc-500' : '' ?>"><?= e(menu_column_title($location)) ?></h3>
                    <ul class="mt-5 space-y-3 text-sm">
                        <?php foreach (footer_menu($location) as $item): ?>
                            <li><a href="<?= e($item['href']) ?>" class="transition <?= $dark ? 'hover:text-white' : 'hover:text-ink' ?>"><?= e($item['label']) ?></a></li>
                        <?php endforeach ?>
                    </ul>
                </div>
            <?php endforeach ?>
            <div>
                <h3 class="eyebrow <?= $dark ? 'text-zinc-500' : '' ?>">İletişim</h3>
                <ul class="mt-5 space-y-3 text-sm">
                    <?php if (setting('store_phone')): ?><li><a href="tel:<?= e(setting('store_phone')) ?>" class="<?= $dark ? 'hover:text-white' : 'hover:text-ink' ?>"><?= e(setting('store_phone')) ?></a></li><?php endif ?>
                    <?php if (setting('store_email')): ?><li class="break-all"><a href="mailto:<?= e(setting('store_email')) ?>" class="<?= $dark ? 'hover:text-white' : 'hover:text-ink' ?>"><?= e(setting('store_email')) ?></a></li><?php endif ?>
                    <?php if (setting('store_address')): ?><li class="leading-6"><?= nl2br(e(setting('store_address'))) ?></li><?php endif ?>
                    <li><a href="<?= url('iletisim') ?>" class="font-medium <?= $dark ? 'text-white' : 'text-ink' ?> underline underline-offset-4">Bize yazın</a></li>
                </ul>
            </div>
        </div>
    </div>

    <div class="border-t <?= $dark ? 'border-white/10' : 'border-zinc-200' ?>">
        <div class="container-x flex flex-wrap items-center justify-between gap-4 py-6 text-xs">
            <p>© <?= date('Y') ?> <?= e(store_name()) ?>. Tüm hakları saklıdır.<?= tax_rate() > 0 ? ' Fiyatlara KDV dahildir.' : '' ?></p>
            <div class="flex flex-wrap items-center gap-2">
                <?php foreach (payment_methods() as [$label]): ?>
                    <span class="rounded-md border px-2.5 py-1 <?= $dark ? 'border-white/10 text-zinc-300' : 'border-zinc-300' ?>"><?= $label ?></span>
                <?php endforeach ?>
            </div>
        </div>
    </div>
</footer>

<div data-overlay class="pointer-events-none fixed inset-0 z-40 bg-zinc-950/40 opacity-0 backdrop-blur-[2px] transition duration-300 data-open:pointer-events-auto data-open:opacity-100"></div>

<aside data-drawer="cart" class="fixed inset-y-0 right-0 z-50 flex w-full max-w-md translate-x-full flex-col bg-white shadow-2xl transition duration-500 ease-out-soft data-open:translate-x-0" aria-label="Sepet">
    <div class="flex h-[72px] shrink-0 items-center justify-between border-b border-zinc-100 px-6">
        <p class="font-display text-lg font-semibold tracking-tight">Sepetim</p>
        <button type="button" data-close class="btn-ghost -mr-2 p-2" aria-label="Kapat"><?= icon('x', 'size-5') ?></button>
    </div>
    <div id="mini-cart" class="flex min-h-0 flex-1 flex-col"><?= render('mini-cart') ?></div>
</aside>

<aside data-drawer="favorites" class="fixed inset-y-0 right-0 z-50 flex w-full max-w-md translate-x-full flex-col bg-white shadow-2xl transition duration-500 ease-out-soft data-open:translate-x-0" aria-label="Favoriler">
    <div class="flex h-[72px] shrink-0 items-center justify-between border-b border-zinc-100 px-6">
        <p class="font-display text-lg font-semibold tracking-tight">Favorilerim</p>
        <button type="button" data-close class="btn-ghost -mr-2 p-2" aria-label="Kapat"><?= icon('x', 'size-5') ?></button>
    </div>
    <div id="mini-favorites" class="flex min-h-0 flex-1 flex-col"><?= render('mini-favorites') ?></div>
</aside>

<aside data-drawer="menu" class="fixed inset-y-0 left-0 z-50 flex w-full max-w-sm -translate-x-full flex-col bg-white shadow-2xl transition duration-500 ease-out-soft data-open:translate-x-0" aria-label="Menü">
    <div class="flex h-[72px] shrink-0 items-center justify-between border-b border-zinc-100 px-6">
        <span class="text-ink"><?= logo_html() ?></span>
        <button type="button" data-close class="btn-ghost -mr-2 p-2" aria-label="Kapat"><?= icon('x', 'size-5') ?></button>
    </div>
    <nav class="flex-1 overflow-y-auto px-6 py-6">
        <ul class="space-y-1">
            <?php foreach (header_menu() as $item): ?>
                <li>
                    <a href="<?= e($item['href']) ?>" class="flex items-center justify-between py-2.5 text-base font-medium text-ink"><?= e($item['label']) ?><?= icon('right', 'size-4 text-zinc-300') ?></a>
                    <?php foreach ($item['children'] as $child): ?>
                        <a href="<?= e($child['href']) ?>" class="block py-1.5 pl-4 text-sm text-zinc-500"><?= e($child['label']) ?></a>
                    <?php endforeach ?>
                </li>
            <?php endforeach ?>
        </ul>
        <p class="eyebrow mt-8">Hesabım</p>
        <ul class="mt-4 space-y-1 text-sm text-zinc-600">
            <?php if (is_customer()): ?>
                <?php foreach (account_menu() as [$file, $label, $name]): ?>
                    <li><a href="<?= url($file) ?>" class="flex items-center gap-3 py-2"><?= icon($name, 'size-5 text-zinc-400') ?><?= $label ?></a></li>
                <?php endforeach ?>
            <?php else: ?>
                <li><a href="<?= url('giris') ?>" class="flex items-center gap-3 py-2"><?= icon('user', 'size-5 text-zinc-400') ?>Giriş yap / Üye ol</a></li>
            <?php endif ?>
            <li><a href="<?= url('iletisim') ?>" class="flex items-center gap-3 py-2"><?= icon('mail', 'size-5 text-zinc-400') ?>İletişim</a></li>
        </ul>
    </nav>
</aside>

<?php if (popup_visible()): ?>
    <?php $popup = popup_settings() ?>
    <div data-popup data-delay="<?= $popup['delay'] ?>" data-repeat="<?= e($popup['repeat']) ?>" data-version="<?= e($popup['version']) ?>" class="pointer-events-none fixed inset-0 z-[55] flex items-center justify-center p-4 opacity-0 transition duration-300 data-open:pointer-events-auto data-open:opacity-100">
        <div data-popup-close class="absolute inset-0 bg-zinc-950/50 backdrop-blur-sm"></div>
        <div class="relative grid w-full max-w-3xl overflow-hidden rounded-[var(--radius-panel)] bg-white shadow-2xl <?= $popup['image'] ? 'sm:grid-cols-2' : 'max-w-md' ?>">
            <?php if ($popup['image']): ?>
                <img src="<?= e(upload_url($popup['image'])) ?>" alt="" class="h-56 w-full object-cover sm:h-full">
            <?php endif ?>
            <div class="p-8 sm:p-10">
                <h2 class="heading text-3xl <?= heading_weight_class() ?>"><?= e($popup['title']) ?></h2>
                <?php if ($popup['text']): ?><p class="mt-4 leading-7 text-zinc-600"><?= nl2br(e($popup['text'])) ?></p><?php endif ?>
                <?php if ($popup['button']): ?>
                    <a href="<?= e(section_link($popup['link']) ?: '#') ?>" data-popup-close class="btn-primary mt-8 w-full"><?= e($popup['button']) ?></a>
                <?php endif ?>
                <button type="button" data-popup-close class="mt-3 w-full text-center text-sm text-zinc-500 hover:text-ink">Hayır, teşekkürler</button>
            </div>
            <button type="button" data-popup-close class="absolute top-4 right-4 flex size-9 items-center justify-center rounded-full bg-white/90 text-ink shadow" aria-label="Kapat"><?= icon('x', 'size-4', '2') ?></button>
        </div>
    </div>
<?php endif ?>

<?php if (cookie_bar_visible()): ?>
    <div data-cookie-bar class="fixed inset-x-4 bottom-4 z-[54] hidden max-w-xl rounded-2xl bg-ink p-5 text-sm text-white shadow-2xl sm:left-6 sm:bottom-6 data-open:block">
        <p class="leading-6 text-white/80"><?= e(setting('cookie_text', 'Size daha iyi bir alışveriş deneyimi sunmak için çerezler kullanıyoruz.')) ?>
            <?php if (setting('cookie_link')): ?><a href="<?= e(section_link(setting('cookie_link'))) ?>" class="font-semibold text-white underline underline-offset-4">Ayrıntılı bilgi</a><?php endif ?>
        </p>
        <div class="mt-4 flex gap-2">
            <button type="button" data-cookie-accept="all" class="btn bg-white px-4 py-2 text-ink hover:bg-zinc-100">Kabul et</button>
            <button type="button" data-cookie-accept="essential" class="btn border border-white/20 px-4 py-2 text-white hover:bg-white/10">Sadece gerekli</button>
        </div>
    </div>
<?php endif ?>

<div id="site-progress" class="pointer-events-none fixed top-0 left-0 z-[80] h-[3px] w-0 bg-accent-600 opacity-0 shadow-[0_0_10px_var(--color-accent-600)] transition-all duration-300"></div>
<div id="toasts" class="pointer-events-none fixed inset-x-0 bottom-6 z-[60] flex flex-col items-center gap-2 px-4"></div>

<script>
(() => {
    const $ = (selector, root = document) => root.querySelector(selector);
    const $$ = (selector, root = document) => [...root.querySelectorAll(selector)];
    const overlay = $('[data-overlay]');
    const money = value => Number(value).toLocaleString('tr-TR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' ₺';

    // Çekmeceler (sepet, mobil menü)
    function openDrawer(name) {
        closeDrawers();
        const drawer = $(`[data-drawer="${name}"]`);
        if (!drawer) return;
        drawer.toggleAttribute('data-open', true);
        overlay.toggleAttribute('data-open', true);
        document.documentElement.classList.add('overflow-hidden');
    }

    function closeDrawers() {
        $$('[data-drawer][data-open]').forEach(drawer => drawer.removeAttribute('data-open'));
        overlay.removeAttribute('data-open');
        document.documentElement.classList.remove('overflow-hidden');
    }

    // Bildirimler
    function toast(message, ok = true) {
        if (!message) return;
        const item = document.createElement('div');
        item.className = 'pointer-events-auto flex max-w-md translate-y-3 items-center gap-3 rounded-full bg-ink py-3 pr-5 pl-3 text-sm font-medium text-white opacity-0 shadow-2xl shadow-zinc-900/30 transition duration-300';
        item.innerHTML = `<span class="flex size-6 shrink-0 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;
        $('#toasts').append(item);
        requestAnimationFrame(() => item.classList.remove('translate-y-3', 'opacity-0'));
        setTimeout(() => {
            item.classList.add('opacity-0');
            setTimeout(() => item.remove(), 300);
        }, 3200);
    }

    // Sunucudan dönen cevabı sayfaya uygular
    function apply(json, form) {
        if (json.redirect) {
            location.href = json.redirect;
            return;
        }
        if ('cart_count' in json) {
            $$('[data-cart-count]').forEach(badge => {
                badge.textContent = json.cart_count;
                badge.classList.toggle('hidden', !json.cart_count);
            });
        }
        if (json.mini_cart !== undefined) $('#mini-cart').innerHTML = json.mini_cart;
        if (json.cart_html !== undefined && $('#cart-content')) $('#cart-content').innerHTML = json.cart_html;
        if ('favorite' in json) {
            $$(`[data-favorite="${json.product_id}"]`).forEach(button => button.toggleAttribute('data-active', json.favorite));
            if (!json.favorite) {
                $$(`[data-favorite-item="${json.product_id}"]`).forEach(item => item.remove());
                const page = $('[data-favorite-page]');
                if (page && !$('[data-favorite-item]', page)) location.reload();
            }
        }
        if ('favorite_count' in json) {
            $$('[data-favorite-count]').forEach(badge => {
                badge.textContent = json.favorite_count;
                badge.classList.toggle('hidden', !json.favorite_count);
            });
        }
        if (json.mini_favorites !== undefined) $('#mini-favorites').innerHTML = json.mini_favorites;
        if (json.reset) form?.reset();
        if (json.open_cart) {
            openDrawer('cart');
        } else if (json.message) {
            toast(json.message, json.ok);
        }
    }

    // data-ajax formları sayfa yenilenmeden gönderilir
    async function send(form, submitter) {
        const data = new FormData(form);
        if (submitter?.name) data.append(submitter.name, submitter.value);
        form.setAttribute('aria-busy', 'true');
        progress.start();
        const restore = buttonLoading(submitter);
        try {
            const response = await fetch(form.action || location.href, {
                method: 'POST',
                body: data,
                headers: { 'X-Requested-With': 'fetch' },
            });
            apply(await response.json(), form);
        } catch (error) {
            toast('Bir sorun oluştu, lütfen tekrar deneyin.', false);
        } finally {
            form.removeAttribute('aria-busy');
            progress.done();
            restore();
        }
    }

    document.addEventListener('submit', event => {
        const form = event.target.closest('form[data-ajax]');
        if (!form) return;
        event.preventDefault();
        send(form, event.submitter);
    });

    let autosubmit;
    document.addEventListener('change', event => {
        const form = event.target.closest('form[data-autosubmit]');
        if (!form) return;
        clearTimeout(autosubmit);
        autosubmit = setTimeout(() => form.requestSubmit(), 350);
    });

    document.addEventListener('click', event => {
        const opener = event.target.closest('[data-open-drawer]');
        if (opener) {
            event.preventDefault();
            openDrawer(opener.dataset.openDrawer);
            return;
        }
        if (event.target.closest('[data-close]') || event.target === overlay) {
            closeDrawers();
            return;
        }

        const step = event.target.closest('[data-step]');
        if (step) {
            const input = step.parentElement.querySelector('input');
            const min = Number(input.min || 0);
            const max = Number(input.max || 9999);
            input.value = Math.min(max, Math.max(min, Number(input.value || 0) + Number(step.dataset.step)));
            input.dispatchEvent(new Event('change', { bubbles: true }));
            return;
        }

        if (event.target.closest('[data-search-toggle]')) {
            const panel = $('#search-panel');
            panel.toggleAttribute('data-open');
            if (panel.hasAttribute('data-open')) $('input', panel).focus();
            return;
        }

        const thumb = event.target.closest('[data-thumb]');
        if (thumb) {
            $('#main-image').src = thumb.dataset.thumb;
            $$('[data-thumb]').forEach(item => item.toggleAttribute('data-active', item === thumb));
            return;
        }

        const tab = event.target.closest('[data-tab]');
        if (tab) {
            const root = tab.closest('[data-tabs]');
            $$('[data-tab]', root).forEach(item => item.toggleAttribute('data-active', item === tab));
            $$('[data-panel]', root).forEach(panel => panel.classList.toggle('hidden', panel.dataset.panel !== tab.dataset.tab));
        }
    });

    document.addEventListener('keydown', event => {
        if (event.key !== 'Escape') return;
        closeDrawers();
        $('#search-panel')?.removeAttribute('data-open');
    });

    // Ürün sayfasında varyant seçimi: fiyat, stok ve adet sınırı güncellenir
    $$('[data-variants]').forEach(root => {
        const form = root.closest('form');
        const update = () => {
            const input = $('input[name="variant_id"]:checked', root);
            if (!input) return;
            const stock = Number(input.dataset.stock);
            const qty = $('input[name="qty"]', form);
            $('[data-price]').textContent = money(input.dataset.price);
            $('[data-selected-variant]').textContent = input.dataset.label;
            $('[data-stock-label]').textContent = stock < 1 ? 'Bu seçenek tükendi' : (stock <= 5 ? `Son ${stock} ürün` : 'Stokta, hemen kargoda');
            qty.max = Math.max(1, stock);
            if (Number(qty.value) > stock) qty.value = Math.max(1, stock);
            $('[data-add-button]', form).disabled = stock < 1;
        };
        root.addEventListener('change', update);
        update();
    });

    // Ödeme sayfası: yöntem değişince kapıda ödeme ücreti ve toplam güncellenir
    document.addEventListener('change', event => {
        const method = event.target.closest('input[name="payment"][data-fee]');
        if (!method) return;
        const fee = Number(method.dataset.fee);
        const total = $('[data-grand-total]');
        const row = $('[data-fee-row]');
        if (!total) return;
        total.textContent = money(Number(total.dataset.base) + fee);
        if (row) {
            row.classList.toggle('hidden', fee <= 0);
            row.classList.toggle('flex', fee > 0);
            $('[data-fee-amount]', row).textContent = money(fee);
        }
    });

    // Listeleme: filtre, sıralama ve sayfalama sayfa yenilenmeden çalışır
    const listing = $('#listing');
    if (listing) {
        let listingRequest;
        let listingTimer;
        const collapsed = new Set();

        const formUrl = form => {
            const params = new URLSearchParams();
            for (const [key, value] of new FormData(form)) {
                if (String(value).trim() !== '') params.append(key, value);
            }
            const query = params.toString();
            return location.pathname + (query ? '?' + query : '');
        };

        const load = async (url, { push = true, scroll = false } = {}) => {
            listingRequest?.abort();
            listingRequest = new AbortController();
            const results = $('[data-listing-results]', listing);
            const drawerOpen = $('[data-drawer="filters"]', listing)?.hasAttribute('data-open');
            results?.setAttribute('aria-busy', 'true');
            progress.start();
            try {
                const response = await fetch(url, { headers: { 'X-Requested-With': 'fetch' }, signal: listingRequest.signal });
                const json = await response.json();
                listing.innerHTML = json.html;
                if (drawerOpen) $('[data-drawer="filters"]', listing)?.setAttribute('data-open', '');
                collapsed.forEach(key => $(`[data-filter-section="${CSS.escape(key)}"]`, listing)?.setAttribute('data-collapsed', ''));
                if (json.title) document.title = json.title;
                if (push) history.pushState({ listing: true }, '', url);
                if (scroll) window.scrollTo({ top: listing.getBoundingClientRect().top + window.scrollY - 110, behavior: 'smooth' });
            } catch (error) {
                if (error.name !== 'AbortError') location.href = url;
            } finally {
                progress.done();
            }
        };

        listing.addEventListener('change', event => {
            const form = event.target.form;
            if (!form?.matches('[data-listing-form]')) return;
            clearTimeout(listingTimer);
            listingTimer = setTimeout(() => load(formUrl(form)), event.target.type === 'text' ? 0 : 150);
        });

        listing.addEventListener('keydown', event => {
            if (event.key !== 'Enter' || !event.target.form?.matches('[data-listing-form]')) return;
            event.preventDefault();
            load(formUrl(event.target.form));
        });

        listing.addEventListener('click', event => {
            const head = event.target.closest('[data-filter-head]');
            if (head) {
                const section = head.closest('[data-filter-section]');
                const key = section.dataset.filterSection;
                section.toggleAttribute('data-collapsed');
                section.hasAttribute('data-collapsed') ? collapsed.add(key) : collapsed.delete(key);
                return;
            }
            const link = event.target.closest('a[data-listing-link]');
            if (!link) return;
            event.preventDefault();
            load(link.href, { scroll: true });
        });

        window.addEventListener('popstate', () => load(location.href, { push: false }));
    }

    // Arama paneli: yazarken canlı sonuçlar
    const liveSearch = $('[data-live-search]');
    if (liveSearch) {
        let searchTimer;
        let searchRequest;
        liveSearch.addEventListener('input', () => {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(async () => {
                const query = liveSearch.value.trim();
                const box = $('#search-results');
                if (query.length < 2) {
                    box.innerHTML = '';
                    return;
                }
                searchRequest?.abort();
                searchRequest = new AbortController();
                try {
                    const action = liveSearch.form.getAttribute('action');
                    const response = await fetch(`${action}?canli=1&q=${encodeURIComponent(query)}`, {
                        headers: { 'X-Requested-With': 'fetch' },
                        signal: searchRequest.signal,
                    });
                    box.innerHTML = (await response.json()).html;
                } catch (error) {}
            }, 250);
        });
    }

    // Ödeme: şehir yazılınca kargo ücreti ve toplam yeniden hesaplanır
    const quoteInput = $('[data-quote]');
    if (quoteInput) {
        quoteInput.addEventListener('change', async () => {
            const form = quoteInput.form;
            const data = new FormData(form);
            data.set('action', 'quote');
            try {
                const response = await fetch(form.action, { method: 'POST', body: data, headers: { 'X-Requested-With': 'fetch' } });
                const json = await response.json();
                if (json.totals_html) $('[data-totals]').innerHTML = json.totals_html;
                const method = $('input[name="payment"]:checked', form);
                if (method) method.dispatchEvent(new Event('change', { bubbles: true }));
            } catch (error) {}
        });
    }

    // Yükleniyor göstergesi: üstte ilerleme çubuğu
    const progress = {
        timer: null,
        start() {
            const bar = $('#site-progress');
            if (!bar) return;
            clearInterval(this.timer);
            let width = 10;
            bar.style.opacity = '1';
            bar.style.width = width + '%';
            this.timer = setInterval(() => { width = Math.min(92, width + (92 - width) * 0.1); bar.style.width = width + '%'; }, 150);
        },
        done() {
            const bar = $('#site-progress');
            if (!bar) return;
            clearInterval(this.timer);
            bar.style.width = '100%';
            setTimeout(() => { bar.style.opacity = '0'; setTimeout(() => { bar.style.width = '0'; }, 300); }, 200);
        },
    };

    // Gönderilen butonun içinde dönen ikon; bitince eski hâline döner
    function buttonLoading(button) {
        if (!button || button.dataset.loadingHtml !== undefined) return () => {};
        const html = button.innerHTML;
        button.dataset.loadingHtml = html;
        button.style.minWidth = button.offsetWidth + 'px';
        button.disabled = true;
        button.setAttribute('aria-busy', 'true');
        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 () => restoreButton(button);
    }

    function restoreButton(button) {
        if (!button.isConnected || button.dataset.loadingHtml === undefined) return;
        button.innerHTML = button.dataset.loadingHtml;
        delete button.dataset.loadingHtml;
        button.disabled = false;
        button.removeAttribute('aria-busy');
        button.style.minWidth = '';
    }

    // Sayfadan ayrılırken (link, normal form) çubuk başlar; geri gelince kapanır
    document.addEventListener('click', event => {
        const link = event.target.closest('a[href]');
        if (!link || event.defaultPrevented || link.target === '_blank' || event.metaKey || event.ctrlKey || event.shiftKey) return;
        const url = new URL(link.href, location.href);
        if (url.origin !== location.origin || (url.pathname === location.pathname && url.hash)) return;
        setTimeout(() => {
            if (event.defaultPrevented) return;
            progress.start();
            // Buton görünümlü linklerde dönen ikon
            if (/\bbtn/.test(link.className)) buttonLoading(link);
        }, 0);
    });
    document.addEventListener('submit', event => {
        setTimeout(() => {
            if (event.defaultPrevented || event.target.hasAttribute('data-ajax')) return;
            progress.start();
            buttonLoading(event.submitter || event.target.querySelector('button:not([type=button])'));
        }, 0);
    });
    window.addEventListener('pageshow', () => {
        progress.done();
        $$('[data-loading-html]').forEach(restoreButton);
    });

    // Kart ödemesi: altyapıya otomatik yönlendirme
    const autoForm = $('[data-auto-submit]');
    if (autoForm) setTimeout(() => autoForm.submit(), 600);
    const autoLink = $('[data-auto-redirect]');
    if (autoLink) setTimeout(() => { location.href = autoLink.href; }, 600);

    // Kampanya sayacı
    $$('[data-countdown]').forEach(box => {
        const end = new Date(box.dataset.countdown).getTime();
        const pad = value => String(value).padStart(2, '0');
        const tick = () => {
            const left = Math.max(0, end - Date.now());
            const parts = { d: Math.floor(left / 864e5), h: Math.floor(left / 36e5) % 24, m: Math.floor(left / 6e4) % 60, s: Math.floor(left / 1e3) % 60 };
            Object.entries(parts).forEach(([unit, value]) => { const el = $(`[data-unit="${unit}"]`, box); if (el) el.textContent = pad(value); });
            if (left <= 0) clearInterval(timer);
        };
        const timer = setInterval(tick, 1000);
        tick();
    });

    // Kaydırmalı ürün vitrini
    $$('[data-carousel]').forEach(carousel => {
        const track = $('[data-carousel-track]', carousel);
        const step = () => track.clientWidth * 0.8;
        $('[data-carousel-prev]', carousel)?.addEventListener('click', () => track.scrollBy({ left: -step() }));
        $('[data-carousel-next]', carousel)?.addEventListener('click', () => track.scrollBy({ left: step() }));
    });

    // Tarayıcı deposu erişilemezse sessizce devam edilir
    const store = {
        get: (key, session) => { try { return (session ? sessionStorage : localStorage).getItem(key); } catch (e) { return null; } },
        set: (key, value, session) => { try { (session ? sessionStorage : localStorage).setItem(key, value); } catch (e) {} },
    };

    // Kampanya popup'ı
    const popup = $('[data-popup]');
    if (popup) {
        const key = 'popup-' + popup.dataset.version;
        const repeat = popup.dataset.repeat;
        const seen = repeat === 'always' ? null : store.get(key, repeat === 'session');
        if (!seen) {
            setTimeout(() => popup.toggleAttribute('data-open', true), Number(popup.dataset.delay) * 1000);
        }
        popup.addEventListener('click', event => {
            if (!event.target.closest('[data-popup-close]')) return;
            popup.removeAttribute('data-open');
            if (repeat !== 'always') store.set(key, '1', repeat === 'session');
        });
    }

    // Çerez onay bandı
    const cookieBar = $('[data-cookie-bar]');
    if (cookieBar && !store.get('cookie-consent')) {
        cookieBar.toggleAttribute('data-open', true);
        cookieBar.addEventListener('click', event => {
            const button = event.target.closest('[data-cookie-accept]');
            if (!button) return;
            store.set('cookie-consent', button.dataset.cookieAccept);
            cookieBar.removeAttribute('data-open');
        });
    }

    // Anasayfa slider
    $$('[data-slider]').forEach(slider => {
        const slides = $$('[data-slide]', slider);
        const dots = $$('[data-dot]', slider);
        if (slides.length < 2) return;
        let index = 0;
        let timer;
        const delay = (Number(slider.dataset.interval) || 6) * 1000;
        const show = next => {
            index = (next + slides.length) % slides.length;
            slides.forEach((slide, i) => slide.toggleAttribute('data-active', i === index));
            dots.forEach((dot, i) => dot.toggleAttribute('data-active', i === index));
        };
        const play = () => {
            clearInterval(timer);
            timer = setInterval(() => show(index + 1), delay);
        };
        dots.forEach((dot, i) => dot.addEventListener('click', () => { show(i); play(); }));
        $('[data-prev]', slider)?.addEventListener('click', () => { show(index - 1); play(); });
        $('[data-next]', slider)?.addEventListener('click', () => { show(index + 1); play(); });
        play();
    });
})();
</script>

<?php if (is_admin()) include PARTS . '/customize-bridge.php' ?>
</body>
</html>
