(function () {
    window.ZaloroxSecurity = {
        scanLink: function (url) {
            var apiBase = window.ZALOROX_API_BASE || '/api';
            var csrf = window.ZALOROX_CSRF_TOKEN || '';
            var body = new URLSearchParams({ url: url });

            if (csrf) body.append('_csrf', csrf);

            return fetch(apiBase.replace(/\/$/, '') + '/security/scan-link', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRF-TOKEN': csrf
                },
                body: body
            }).then(function (response) {
                return response.json();
            });
        }
    };

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

    function postDownload(endpoint, confirm) {
        var csrf = window.ZALOROX_CSRF_TOKEN || '';
        var body = new URLSearchParams();
        if (csrf) body.append('_csrf', csrf);
        if (confirm) body.append('confirm', '1');

        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;
            });
        });
    }

    function updateDownloadCount(button, count) {
        var target = button.querySelector('[data-download-count]') || document.querySelector('[data-download-count]');
        if (!target) return;

        count = Number(count || 0);
        if (count >= 1000000) {
            target.textContent = (Math.round(count / 100000) / 10).toString().replace(/\.0$/, '') + 'M';
        } else if (count >= 1000) {
            target.textContent = (Math.round(count / 100) / 10).toString().replace(/\.0$/, '') + 'K';
        } else {
            target.textContent = String(count);
        }
    }

    document.addEventListener('click', function (event) {
        var premiumGate = event.target.closest('[data-premium-gate]');
        if (!premiumGate) return;

        event.preventDefault();
        var go = function () { window.location.href = premiumGate.dataset.cta || '/checkout'; };

        if (window.ZaloroxModal) {
            window.ZaloroxModal.confirm('Bu mod premium. Erisim icin abone ol.', {
                title: 'Premium mod',
                confirmLabel: 'Abone Ol',
                cancelLabel: 'Vazgec'
            }).then(function (ok) {
                if (ok) go();
            });
        } else {
            toast('Bu mod premium. Erisim icin abone ol.', 'warning');
        }
    });

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

        event.preventDefault();
        if (button.disabled) return;

        var endpoint = button.dataset.endpoint;
        if (!endpoint) return;

        button.disabled = true;
        postDownload(endpoint, false).then(function (json) {
            if (!json.ok) {
                if (json.code === 'subscription_required' && window.ZaloroxModal) {
                    window.ZaloroxModal.confirm(json.message || 'Bu mod premium.', {
                        title: 'Premium mod',
                        confirmLabel: 'Abone Ol',
                        cancelLabel: 'Vazgec'
                    }).then(function (ok) {
                        if (ok) window.location.href = json.cta_url || '/checkout';
                    });
                    return;
                }

                toast(json.message || 'Indirme linki guvenli degil.', json.code === 'blocked_link' ? 'error' : 'warning');
                return;
            }

            var provider = json.provider ? ' (' + json.provider + ')' : '';
            var message = (json.message || 'Harici baglantiya yonlendiriliyorsun.') + provider;

            if (!window.ZaloroxModal) {
                postDownload(endpoint, true).then(function (confirmed) {
                    if (confirmed.ok && confirmed.external_url) {
                        updateDownloadCount(button, confirmed.download_count);
                        window.location.href = confirmed.external_url;
                    } else {
                        toast(confirmed.message || 'Indirme baslatilamadi.', 'warning');
                    }
                });
                return;
            }

            window.ZaloroxModal.confirm(message, {
                title: 'Harici indirme',
                confirmLabel: 'Devam Et',
                cancelLabel: 'Vazgec'
            }).then(function (ok) {
                if (!ok) return;

                button.disabled = true;
                postDownload(endpoint, true).then(function (confirmed) {
                    if (confirmed.ok && confirmed.external_url) {
                        updateDownloadCount(button, confirmed.download_count);
                        window.location.href = confirmed.external_url;
                        return;
                    }

                    toast(confirmed.message || 'Indirme baslatilamadi.', 'warning');
                }).catch(function () {
                    toast('Indirme baslatilamadi.', 'error');
                }).finally(function () {
                    button.disabled = false;
                });
            });
        }).catch(function () {
            toast('Indirme linki kontrol edilemedi.', 'error');
        }).finally(function () {
            button.disabled = false;
        });
    });
})();
