(function () {
    function ensureToastStack() {
        var stack = document.querySelector('[data-toast-stack]');
        if (stack) return stack;

        stack = document.createElement('div');
        stack.className = 'toast-stack';
        stack.dataset.toastStack = 'true';
        document.body.appendChild(stack);

        return stack;
    }

    function showToast(message, type, timeout) {
        if (!message) return;

        var toast = document.createElement('div');
        toast.className = 'toast-message';
        toast.dataset.type = type || 'info';
        toast.setAttribute('role', 'status');
        toast.textContent = message;

        ensureToastStack().appendChild(toast);

        window.setTimeout(function () {
            toast.remove();
        }, timeout || 4200);
    }

    window.ZaloroxToast = {
        show: showToast,
        success: function (message) { showToast(message, 'success'); },
        error: function (message) { showToast(message, 'error'); },
        warning: function (message) { showToast(message, 'warning'); },
        info: function (message) { showToast(message, 'info'); }
    };

    document.querySelectorAll('[data-menu]').forEach(function (button) {
        button.addEventListener('click', function () {
            var isOpen = document.body.classList.toggle('menu-open');
            button.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
        });
    });

    document.querySelectorAll('[data-dropdown]').forEach(function (button) {
        button.addEventListener('click', function (event) {
            var menu = button.closest('[data-user-menu]');
            if (!menu) return;

            event.stopPropagation();
            var isOpen = menu.classList.toggle('is-open');
            button.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
        });
    });

    function closeAccountMenus(except) {
        document.querySelectorAll('[data-user-menu].is-open').forEach(function (menu) {
            if (except && menu === except) return;

            menu.classList.remove('is-open');
            var button = menu.querySelector('[data-dropdown]');
            if (button) button.setAttribute('aria-expanded', 'false');
        });
    }

    function closeMegaMenus(except) {
        document.querySelectorAll('.menu-item.is-open').forEach(function (item) {
            if (except && item === except) return;

            item.classList.remove('is-open');
            var link = item.querySelector(':scope > .menu-link');
            if (link) link.setAttribute('aria-expanded', 'false');
        });
    }

    document.addEventListener('click', function (event) {
        closeAccountMenus(event.target.closest('[data-user-menu]'));
    });

    document.addEventListener('click', function (event) {
        var link = event.target.closest('.menu-item > .menu-link');
        if (!link) return;

        var item = link.parentElement;
        var dropdown = item ? item.querySelector('.menu-dropdown, .mega-menu') : null;

        if (!dropdown || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;

        if (item.classList.contains('is-open') && !window.matchMedia('(max-width: 760px)').matches) {
            closeMegaMenus();
            return;
        }

        if (item.classList.contains('is-open')) return;

        event.preventDefault();
        closeMegaMenus(item);
        item.classList.add('is-open');
        link.setAttribute('aria-expanded', 'true');
    }, true);

    document.addEventListener('click', function (event) {
        var menuItem = event.target.closest('.menu-item');
        if (menuItem) return;

        closeMegaMenus();
    });

    document.addEventListener('keydown', function (event) {
        if (event.key !== 'Escape') return;

        document.body.classList.remove('menu-open');
        document.querySelectorAll('[data-menu]').forEach(function (button) {
            button.setAttribute('aria-expanded', 'false');
        });
        closeAccountMenus();
        closeMegaMenus();
        if (document.activeElement && typeof document.activeElement.blur === 'function') {
            document.activeElement.blur();
        }
    });

    var themeMedia = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;

    function storedThemePreference() {
        var preference = '';
        try {
            preference = window.localStorage.getItem('zalorox_theme_preference') || '';
            if (!preference) {
                preference = window.localStorage.getItem('zalorox_dark_mode') === '0' ? 'light' : 'dark';
            }
        } catch (error) {
            preference = 'dark';
        }

        return /^(dark|light|system)$/.test(preference) ? preference : 'dark';
    }

    function resolveTheme(preference) {
        if (preference === 'system') {
            return themeMedia && themeMedia.matches ? 'dark' : 'light';
        }

        return preference === 'light' ? 'light' : 'dark';
    }

    function syncThemeButtons(preference) {
        document.querySelectorAll('[data-theme-option]').forEach(function (button) {
            var active = button.dataset.themeOption === preference;
            button.classList.toggle('is-active', active);
            button.setAttribute('aria-pressed', active ? 'true' : 'false');
        });

        document.querySelectorAll('[data-theme-toggle]').forEach(function (button) {
            var isDark = resolveTheme(preference) === 'dark';
            button.classList.toggle('is-active', isDark);
            button.setAttribute('aria-pressed', isDark ? 'true' : 'false');
        });
    }

    function applyThemePreference(preference, persist) {
        preference = /^(dark|light|system)$/.test(preference) ? preference : 'dark';
        var resolved = resolveTheme(preference);

        if (persist) {
            try {
                window.localStorage.setItem('zalorox_theme_preference', preference);
                window.localStorage.setItem('zalorox_dark_mode', resolved === 'dark' ? '1' : '0');
            } catch (error) {
                /* Preference storage is optional. */
            }
        }

        document.documentElement.dataset.theme = resolved;
        document.documentElement.dataset.themePreference = preference;
        document.documentElement.style.colorScheme = resolved;
        syncThemeButtons(preference);
    }

    applyThemePreference(storedThemePreference(), false);

    document.querySelectorAll('[data-theme-option]').forEach(function (button) {
        button.addEventListener('click', function () {
            var preference = button.dataset.themeOption || 'dark';
            applyThemePreference(preference, true);
            if (window.ZaloroxToast) {
                window.ZaloroxToast.info(preference === 'system' ? 'Sistem tema tercihi kullaniliyor.' : (preference === 'light' ? 'Aydinlik tema acik.' : 'Karanlik tema acik.'));
            }
        });
    });

    document.querySelectorAll('[data-theme-toggle]').forEach(function (button) {
        button.addEventListener('click', function () {
            applyThemePreference(button.getAttribute('aria-pressed') === 'true' ? 'light' : 'dark', true);
        });
    });

    if (themeMedia) {
        var systemThemeChanged = function () {
            if ((document.documentElement.dataset.themePreference || storedThemePreference()) === 'system') {
                applyThemePreference('system', false);
            }
        };

        if (typeof themeMedia.addEventListener === 'function') {
            themeMedia.addEventListener('change', systemThemeChanged);
        } else if (typeof themeMedia.addListener === 'function') {
            themeMedia.addListener(systemThemeChanged);
        }
    }

    document.querySelectorAll('[data-site-search-form], [data-music-search-form]').forEach(function (form) {
        form.addEventListener('submit', function () {
            var input = form.querySelector('input[name="q"]');
            if (input) input.value = input.value.trim();
        });
    });

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

    function formPost(endpoint, data) {
        data = data || {};
        if (!data._csrf && window.ZALOROX_CSRF_TOKEN) 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(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 };
            });
        });
    }

    function renderLiveSearchItem(item) {
        var image = item.image ? '<img src="' + escapeHtml(item.image) + '" alt="">' : '<span class="search-result-mark">MOD</span>';
        return '<a class="search-result" href="' + escapeHtml(item.url || '/arama') + '">' +
            image +
            '<span><strong>' + escapeHtml(item.title || 'Sonuc') + '</strong><small>' + escapeHtml(item.subtitle || item.type || 'Zalorox') + '</small></span>' +
            '</a>';
    }

    document.querySelectorAll('[data-site-search-form]').forEach(function (form) {
        var input = form.querySelector('[data-live-search]');
        var results = form.querySelector('[data-live-search-results]');
        var timer = null;
        var focused = false;
        if (!input || !results) return;

        function hideResults() {
            results.hidden = true;
            results.innerHTML = '';
        }

        function searchNow() {
            var q = input.value.trim();
            if (!focused || q.length < 2) {
                hideResults();
                return;
            }

            fetch('/api/search?q=' + encodeURIComponent(q), {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            }).then(function (response) {
                return response.json();
            }).then(function (json) {
                if (!focused || input.value.trim().length < 2) {
                    hideResults();
                    return;
                }

                var items = Array.isArray(json.items) ? json.items.slice(0, 6) : [];
                if (!items.length) {
                    results.innerHTML = '<div class="search-empty"><strong>Sonuc yok</strong><span>Farkli bir kelime veya mod adi dene.</span></div>';
                    results.hidden = false;
                    return;
                }

                results.innerHTML = items.map(renderLiveSearchItem).join('');
                results.hidden = false;
            }).catch(hideResults);
        }

        input.addEventListener('focus', function () {
            focused = true;
            if (input.value.trim().length >= 2 && results.innerHTML !== '') {
                results.hidden = false;
            } else if (input.value.trim().length >= 2) {
                searchNow();
            }
        });

        input.addEventListener('input', function () {
            window.clearTimeout(timer);
            if (input.value.trim().length < 2) {
                hideResults();
                return;
            }
            timer = window.setTimeout(searchNow, 240);
        });

        input.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') {
                hideResults();
                input.blur();
            }
        });

        form.addEventListener('submit', hideResults);
    });

    document.addEventListener('click', function (event) {
        document.querySelectorAll('[data-live-search-results]').forEach(function (results) {
            var form = results.closest('form');
            if (form && form.contains(event.target)) return;
            results.hidden = true;
        });
    });

    document.addEventListener('click', function (event) {
        var trigger = event.target.closest('[data-confirm]');
        if (!trigger || trigger.dataset.confirmed === '1') return;

        event.preventDefault();
        var message = trigger.dataset.confirm || 'Islemi onayliyor musun?';

        if (!window.ZaloroxModal || typeof window.ZaloroxModal.confirm !== 'function') {
            showToast(message, 'warning');
            return;
        }

        window.ZaloroxModal.confirm(message, {
            confirmLabel: trigger.dataset.confirmLabel || 'Onayla',
            cancelLabel: trigger.dataset.cancelLabel || 'Vazgec'
        }).then(function (ok) {
            if (!ok) return;

            if (trigger.tagName === 'A' && trigger.href) {
                window.location.href = trigger.href;
                return;
            }

            if (trigger.form && typeof trigger.form.requestSubmit === 'function') {
                trigger.dataset.confirmed = '1';
                trigger.form.requestSubmit(trigger);
                return;
            }

            trigger.dispatchEvent(new CustomEvent('zalorox:confirmed', { bubbles: true }));
        });
    });

    document.querySelectorAll('[data-slider-prev], [data-slider-next]').forEach(function (button) {
        button.addEventListener('click', function () {
            var wrap = button.closest('.game-slider-wrap');
            var slider = wrap ? wrap.querySelector('[data-slider]') : null;
            if (!slider) return;

            var direction = button.hasAttribute('data-slider-prev') ? -1 : 1;
            var distance = Math.max(220, Math.round(slider.clientWidth * 0.75));
            slider.scrollBy({ left: direction * distance, behavior: 'smooth' });
        });
    });

    document.querySelectorAll('img[loading="lazy"], .mod-gallery img').forEach(function (image) {
        image.addEventListener('error', function () {
            image.classList.add('is-missing');
            image.removeAttribute('src');
        }, { once: true });
    });

    document.querySelectorAll('[data-share]').forEach(function (button) {
        button.addEventListener('click', function () {
            var link = window.location.href;
            var title = button.dataset.shareTitle || document.title || 'Zalorox';

            if (navigator.share) {
                navigator.share({ title: title, url: link }).then(function () {
                    showToast('Paylasim penceresi acildi.', 'success');
                }).catch(function () {
                    showToast('Paylasim iptal edildi.', 'info');
                });
                return;
            }

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(link).then(function () {
                    showToast('Baglanti kopyalandi.', 'success');
                }).catch(function () {
                    showToast(link, 'info');
                });
                return;
            }

            showToast(link, 'info');
        });
    });

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

        event.preventDefault();
        var csrf = window.ZALOROX_CSRF_TOKEN || '';
        var body = new URLSearchParams({
            package_id: button.dataset.packageId || '',
            duration_months: button.dataset.duration || '1',
            _csrf: csrf
        });

        button.disabled = true;
        fetch('/api/subscription/preview', {
            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) {
            if (!json.ok) throw new Error(json.message || 'Paket onizlemesi hazirlanamadi.');
            var preview = json.preview || {};
            var message = (preview.package_name || 'Paket') + '\n' +
                (preview.duration_months || 1) + ' ay - ' + (preview.price || 0) + ' ' + (preview.currency || 'TRY') + '\n\n' +
                (preview.message || 'Odeme sistemi sonraki asamada aktif olacak.');

            if (window.ZaloroxModal) {
                window.ZaloroxModal.open('Abonelik onizlemesi', message, [
                    {
                        label: 'Kapat',
                        onClick: function () { window.ZaloroxModal.close(); }
                    },
                    {
                        label: 'Studio Aboneliklerim',
                        primary: true,
                        onClick: function () { window.location.href = '/studyo/abonelikler'; }
                    }
                ]);
            } else {
                showToast(preview.message || 'Odeme sistemi sonraki asamada aktif olacak.', 'info');
            }
        }).catch(function (error) {
            showToast(error.message || 'Paket onizlemesi hazirlanamadi.', 'error');
        }).finally(function () {
            button.disabled = false;
        });
    });

    document.querySelectorAll('[data-description]').forEach(function (box) {
        var button = box.querySelector('[data-description-toggle]');
        var body = box.querySelector('[data-description-body]');
        if (!button || !body) return;

        if (body.scrollHeight <= 230) {
            button.hidden = true;
            box.classList.add('is-expanded');
            return;
        }

        button.addEventListener('click', function () {
            var expanded = box.classList.toggle('is-expanded');
            button.textContent = expanded ? (button.dataset.less || 'Daha az') : (button.dataset.more || 'Daha fazla');
        });
    });

    document.addEventListener('click', function (event) {
        var authButton = event.target.closest('[data-auth-required]');
        if (!authButton) return;

        event.preventDefault();
        var title = authButton.dataset.authTitle || 'Giris gerekli';
        var message = authButton.dataset.authMessage || 'Bu aksiyon icin giris yapmalisin.';
        var redirect = authButton.dataset.authRedirect || authButton.getAttribute('href') || '/giris-yap';
        if (window.ZaloroxModal) {
            window.ZaloroxModal.open(title, message, [
                {
                    label: 'Kapat',
                    onClick: function () { window.ZaloroxModal.close(); }
                },
                {
                    label: 'Giris Yap',
                    primary: true,
                    onClick: function () { window.location.href = redirect; }
                }
            ]);
        } else {
            showToast(message, 'warning');
        }
    });

    document.addEventListener('click', function (event) {
        var tabButton = event.target.closest('[data-profile-tab-target]');
        if (!tabButton) return;

        var tabs = tabButton.closest('[data-profile-tabs]');
        if (!tabs) return;

        var target = tabButton.dataset.profileTabTarget || '';
        tabs.querySelectorAll('[data-profile-tab-target]').forEach(function (button) {
            var active = button === tabButton;
            button.classList.toggle('is-active', active);
            button.setAttribute('aria-selected', active ? 'true' : 'false');
        });
        tabs.querySelectorAll('[data-profile-tab-panel]').forEach(function (panel) {
            var active = panel.dataset.profileTabPanel === target;
            panel.hidden = !active;
            panel.classList.toggle('is-active', active);
        });
    });

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

        event.preventDefault();
        var action = button.dataset.profileFollowAction === 'unfollow' ? 'unfollow' : 'follow';
        var userId = button.dataset.userId || '';
        var csrf = window.ZALOROX_CSRF_TOKEN || '';
        var body = new URLSearchParams({ user_id: userId, _csrf: csrf });

        button.disabled = true;
        fetch('/api/profile/' + action, {
            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) {
            if (!json.ok) {
                if (json.httpStatus === 403 && window.ZaloroxModal) {
                    window.ZaloroxModal.confirm(json.message || 'Giris yapmalisin.', {
                        title: 'Giris gerekli',
                        confirmLabel: 'Giris Yap',
                        cancelLabel: 'Vazgec'
                    }).then(function (ok) {
                        if (ok) window.location.href = '/giris-yap';
                    });
                    return;
                }
                throw new Error(json.message || 'Takip islemi tamamlanamadi.');
            }

            var following = json.following === true;
            button.dataset.profileFollowAction = following ? 'unfollow' : 'follow';
            button.textContent = following ? 'Takip Ediliyor' : 'Takip Et';
            button.classList.toggle('is-active', following);
            showToast(json.message || (following ? 'Takip ediliyor.' : 'Takip birakildi.'), 'success');
        }).catch(function (error) {
            showToast(error.message || 'Takip islemi tamamlanamadi.', 'error');
        }).finally(function () {
            button.disabled = false;
        });
    });

    document.addEventListener('click', function (event) {
        var followButton = event.target.closest('[data-follow-placeholder]');
        if (!followButton) return;

        event.preventDefault();
        if (window.ZaloroxModal) {
            window.ZaloroxModal.open('Takip sistemi', 'Takip islemi bu hesap icin henuz aktif degil.');
        } else {
            showToast('Takip islemi henuz aktif degil.', 'info');
        }
    });

    document.querySelectorAll('[data-reaction]').forEach(function (button) {
        button.addEventListener('click', function () {
            var endpoint = button.dataset.endpoint;
            var reaction = button.dataset.reaction;
            var csrf = window.ZALOROX_CSRF_TOKEN || '';
            var body = new URLSearchParams({ reaction: reaction });
            if (csrf) body.append('_csrf', csrf);

            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) {
                if (!json.ok) {
                    if (json.httpStatus === 403 && window.ZaloroxModal) {
                        window.ZaloroxModal.confirm(json.message || 'Giris yapmalisin.', {
                            title: 'Giris gerekli',
                            confirmLabel: 'Giris Yap',
                            cancelLabel: 'Vazgec'
                        }).then(function (ok) {
                            if (ok) window.location.href = '/giris-yap';
                        });
                        return;
                    }
                    showToast(json.message || 'Reaksiyon kaydedilemedi.', 'warning');
                    return;
                }

                var wrap = button.closest('.mod-action-bar') || document;
                wrap.querySelectorAll('[data-reaction]').forEach(function (item) {
                    item.classList.toggle('is-active', item.dataset.reaction === json.reaction);
                });

                var like = document.querySelector('[data-like-count]');
                var dislike = document.querySelector('[data-dislike-count]');
                if (like) like.textContent = compactNumber(json.like_count || 0);
                if (dislike) dislike.textContent = compactNumber(json.dislike_count || 0);
                showToast('Reaksiyon kaydedildi.', 'success');
            }).catch(function () {
                showToast('Reaksiyon kaydedilemedi.', 'error');
            });
        });
    });

    function compactNumber(value) {
        value = Number(value || 0);
        if (value >= 1000000) return (Math.round(value / 100000) / 10).toString().replace(/\.0$/, '') + 'M';
        if (value >= 1000) return (Math.round(value / 100) / 10).toString().replace(/\.0$/, '') + 'K';
        return String(value);
    }

    function consentAllowsTracking() {
        var raw = '';
        try {
            raw = window.localStorage.getItem('zalorox_cookie_consent') || '';
        } catch (error) {
            raw = '';
        }

        if (!raw) {
            var match = document.cookie.match(/(?:^|;\s*)zalorox_cookie_consent=([^;]+)/);
            raw = match ? decodeURIComponent(match[1]) : '';
        }

        if (!raw) return false;

        try {
            var prefs = JSON.parse(raw);
            return prefs.analytics === true || prefs.personalization === true;
        } catch (error) {
            return false;
        }
    }

    document.querySelectorAll('[data-mod-page]').forEach(function (page) {
        if (!consentAllowsTracking()) return;

        try {
            var key = 'zalorox_recent_mods';
            var items = JSON.parse(window.localStorage.getItem(key) || '[]');
            items = Array.isArray(items) ? items : [];
            items = items.filter(function (item) { return item.slug !== page.dataset.modSlug; });
            items.unshift({
                id: page.dataset.modId || '',
                slug: page.dataset.modSlug || '',
                category: page.dataset.modCategory || '',
                visited_at: new Date().toISOString()
            });
            window.localStorage.setItem(key, JSON.stringify(items.slice(0, 12)));
        } catch (error) {
            /* Non-essential tracking can fail silently. */
        }
    });

    document.querySelectorAll('[data-notification-center]').forEach(function (center) {
        var toggle = center.querySelector('[data-notification-toggle]');
        var dropdown = center.querySelector('[data-notification-dropdown]');
        var list = center.querySelector('[data-notification-list]');
        var count = center.querySelector('[data-notification-count]');
        var readAll = center.querySelector('[data-notification-read-all]');
        var clearAll = center.querySelector('[data-notification-clear]');
        var loaded = false;
        if (!toggle || !dropdown || !list) return;

        function setOpen(open) {
            dropdown.hidden = !open;
            center.classList.toggle('is-open', open);
            toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
            if (open && !loaded) loadNotifications(true);
        }

        function updateCount(value) {
            value = Number(value || 0);
            if (!count) return;
            count.textContent = value > 9 ? '9+' : String(value);
            count.hidden = value < 1;
        }

        function renderNotifications(items) {
            if (!Array.isArray(items) || items.length === 0) {
                list.innerHTML = '<div class="notification-empty">Henuz bildirim yok.</div>';
                return;
            }

            list.innerHTML = items.map(function (item) {
                var unread = item.unread === true || item.read_at == null;
                return '<button class="notification-item' + (unread ? ' is-unread' : '') + '" type="button" data-notification-id="' + escapeHtml(item.id || '') + '" data-notification-url="' + escapeHtml(item.url || '') + '">' +
                    '<span><strong>' + escapeHtml(item.title || 'Bildirim') + '</strong><small>' + escapeHtml(item.body || '') + '</small></span>' +
                    '<em>' + escapeHtml(item.created_at || '') + '</em>' +
                    '</button>';
            }).join('');
        }

        function loadNotifications(silent) {
            return fetch('/api/notifications/list', {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            }).then(function (response) {
                if (response.status === 401) return { ok: false, unauthorized: true };
                return response.json();
            }).then(function (json) {
                if (!json.ok) {
                    if (!json.unauthorized && !silent) showToast(json.message || 'Bildirimler yuklenemedi.', 'error');
                    return;
                }

                loaded = true;
                updateCount(json.unread_count || 0);
                renderNotifications(json.notifications || []);
                if ((json.unread_count || 0) > 0 && !silent) {
                    showToast('Yeni bildirimin var.', 'info');
                }
            }).catch(function () {
                if (!silent) showToast('Bildirimler yuklenemedi.', 'error');
            });
        }

        toggle.addEventListener('click', function (event) {
            event.stopPropagation();
            setOpen(dropdown.hidden);
        });

        list.addEventListener('click', function (event) {
            var button = event.target.closest('[data-notification-id]');
            if (!button) return;

            var id = button.dataset.notificationId || '';
            var targetUrl = button.dataset.notificationUrl || '';
            formPost('/api/notifications/read', { id: id }).finally(function () {
                if (targetUrl) {
                    window.location.href = targetUrl;
                } else {
                    button.classList.remove('is-unread');
                    loadNotifications(true);
                }
            });
        });

        if (readAll) {
            readAll.addEventListener('click', function (event) {
                event.stopPropagation();
                formPost('/api/notifications/read-all', {}).then(function (json) {
                    if (!json.ok) throw new Error(json.message || 'Bildirimler guncellenemedi.');
                    updateCount(0);
                    center.querySelectorAll('.notification-item').forEach(function (item) {
                        item.classList.remove('is-unread');
                    });
                    showToast(json.message || 'Tum bildirimler okundu.', 'success');
                }).catch(function (error) {
                    showToast(error.message || 'Bildirimler guncellenemedi.', 'error');
                });
            });
        }

        if (clearAll) {
            clearAll.addEventListener('click', function (event) {
                event.stopPropagation();

                var runClear = function () {
                    formPost('/api/notifications/clear', {}).then(function (json) {
                        if (!json.ok) throw new Error(json.message || 'Bildirimler temizlenemedi.');
                        updateCount(0);
                        renderNotifications([]);
                        loaded = true;
                        showToast(json.message || 'Bildirimler temizlendi.', 'success');
                    }).catch(function (error) {
                        showToast(error.message || 'Bildirimler temizlenemedi.', 'error');
                    });
                };

                if (window.ZaloroxModal && window.ZaloroxModal.confirm) {
                    window.ZaloroxModal.confirm('Tum bildirimler temizlensin mi?', {
                        confirmLabel: 'Temizle',
                        cancelLabel: 'Vazgec',
                        danger: true
                    }).then(function (ok) { if (ok) runClear(); });
                    return;
                }

                runClear();
            });
        }

        document.addEventListener('click', function (event) {
            if (center.contains(event.target)) return;
            setOpen(false);
        });

        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') setOpen(false);
        });

        loadNotifications(true);
    });

    document.addEventListener('click', function (event) {
        var opener = event.target.closest('[data-open-notifications]');
        if (!opener) return;
        event.preventDefault();
        var toggle = document.querySelector('[data-notification-center] [data-notification-toggle]');
        if (toggle) toggle.click();
    });

    if (window.ZALOROX_TOAST) {
        showToast(window.ZALOROX_TOAST.message || window.ZALOROX_TOAST, window.ZALOROX_TOAST.type || 'info');
    }
})();
