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

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

    function brand(number) {
        var clean = String(number || '').replace(/\D+/g, '');
        if (/^4/.test(clean)) return 'Visa';
        if (/^(5[1-5]|2[2-7])/.test(clean)) return 'Mastercard';
        if (/^9792/.test(clean)) return 'Troy';
        return 'Card';
    }

    function formatCard(value) {
        return String(value || '')
            .replace(/\D+/g, '')
            .slice(0, 19)
            .replace(/(.{4})/g, '$1 ')
            .trim();
    }

    function formatExpiry(value) {
        var clean = String(value || '').replace(/\D+/g, '').slice(0, 4);
        if (clean.length <= 2) return clean;
        return clean.slice(0, 2) + '/' + clean.slice(2);
    }

    function validExpiry(value) {
        var match = String(value || '').match(/^(\d{2})\/(\d{2})$/);
        if (!match) return false;
        var month = Number(match[1]);
        var year = 2000 + Number(match[2]);
        if (month < 1 || month > 12) return false;
        var now = new Date();
        var expiry = new Date(year, month, 0, 23, 59, 59);
        return expiry >= now;
    }

    function validCard(number) {
        var clean = String(number || '').replace(/\D+/g, '');
        return clean.length >= 13 && clean.length <= 19;
    }

    function validCvv(cvv) {
        return /^\d{3,4}$/.test(String(cvv || ''));
    }

    document.querySelectorAll('[data-card-number]').forEach(function (input) {
        var form = input.closest('[data-payment-form]');
        var brandBox = form ? form.querySelector('[data-card-brand]') : null;

        input.addEventListener('input', function () {
            input.value = formatCard(input.value);
            if (brandBox) brandBox.textContent = brand(input.value);
        });
    });

    document.querySelectorAll('[data-card-expiry]').forEach(function (input) {
        input.addEventListener('input', function () {
            input.value = formatExpiry(input.value);
        });
    });

    document.querySelectorAll('[data-card-cvv]').forEach(function (input) {
        input.addEventListener('input', function () {
            input.value = String(input.value || '').replace(/\D+/g, '').slice(0, 4);
        });
    });

    document.querySelectorAll('[data-payment-form]').forEach(function (form) {
        form.querySelectorAll('[data-test-card]').forEach(function (button) {
            button.addEventListener('click', function () {
                var success = button.dataset.testCard === 'success';
                var values = {
                    card_holder: 'Zalorox Test',
                    card_number: success ? '4242 4242 4242 4242' : '4000 0000 0000 0002',
                    expiry: '12/30',
                    cvv: '123'
                };
                Object.keys(values).forEach(function (name) {
                    var input = form.querySelector('[name="' + name + '"]');
                    if (input) {
                        input.value = values[name];
                        input.dispatchEvent(new Event('input', { bubbles: true }));
                    }
                });
                toast(success ? 'Basarili test karti forma yazildi.' : 'Basarisiz test karti forma yazildi.', 'info');
            });
        });

        form.addEventListener('submit', function (event) {
            event.preventDefault();
            var button = form.querySelector('[data-payment-submit]');
            if (button && button.classList.contains('is-loading')) return;

            var cardNumber = form.querySelector('[name="card_number"]');
            var expiry = form.querySelector('[name="expiry"]');
            var cvv = form.querySelector('[name="cvv"]');
            var holder = form.querySelector('[name="card_holder"]');

            if (!holder || holder.value.trim().length < 2) {
                toast('Kart uzerindeki isim gerekli.', 'error');
                return;
            }

            if (!cardNumber || !validCard(cardNumber.value)) {
                toast('Kart numarasi gecersiz gorunuyor.', 'error');
                return;
            }

            if (!expiry || !validExpiry(expiry.value)) {
                toast('Son kullanma tarihi gecersiz.', 'error');
                return;
            }

            if (!cvv || !validCvv(cvv.value)) {
                toast('CVV gecersiz.', 'error');
                return;
            }

            var formData = new FormData(form);
            formData.set('package_id', form.dataset.packageId || '');
            formData.set('period_type', form.dataset.periodType || 'monthly');
            formData.set('card_number', cardNumber.value.replace(/\D+/g, ''));
            formData.set('card_brand', brand(cardNumber.value).toLowerCase());

            if (button) {
                button.classList.add('is-loading');
                button.disabled = true;
                button.dataset.originalText = button.textContent;
                button.textContent = 'Odeme Isleniyor...';
            }

            fetch('/api/payment/create-session', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': window.ZALOROX_CSRF_TOKEN || '',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: new URLSearchParams(formData)
            }).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 || 'Odeme baslatilamadi.');

                form.reset();
                var target = json.redirect_url || '/';
                var title = json.payment_status === 'paid' ? 'Odeme basarili' : (json.payment_status === 'failed' ? 'Odeme basarisiz' : 'Odeme beklemede');
                var message = json.message || 'Odeme sonucu alindi.';

                if (window.ZaloroxModal) {
                    window.ZaloroxModal.open(title, message, [
                        {
                            label: 'Devam et',
                            primary: true,
                            onClick: function () { window.location.href = target; }
                        }
                    ]);
                } else {
                    toast(message, json.payment_status === 'paid' ? 'success' : 'info');
                    window.setTimeout(function () { window.location.href = target; }, 650);
                }
            }).catch(function (error) {
                toast(error.message || 'Odeme baslatilamadi.', 'error');
            }).finally(function () {
                if (button) {
                    button.classList.remove('is-loading');
                    button.disabled = false;
                    button.textContent = button.dataset.originalText || 'Odemeyi Tamamla';
                }
            });
        });
    });

    document.querySelectorAll('[data-provider-form]').forEach(function (form) {
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            var button = form.querySelector('button[type="submit"]');
            if (button) {
                button.disabled = true;
                button.dataset.originalText = button.textContent;
                button.textContent = 'Kaydediliyor...';
            }

            fetch('/api/zpanel/payment-providers/update', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': window.ZALOROX_CSRF_TOKEN || '',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: new URLSearchParams(new FormData(form))
            }).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 || 'Ayarlar kaydedilemedi.');
                toast(json.message || 'Ayarlar kaydedildi.', 'success');
                window.setTimeout(function () { window.location.reload(); }, 700);
            }).catch(function (error) {
                toast(error.message || 'Ayarlar kaydedilemedi.', 'error');
            }).finally(function () {
                if (button) {
                    button.disabled = false;
                    button.textContent = button.dataset.originalText || 'Kaydet';
                }
            });
        });
    });

    var statusRoot = document.querySelector('[data-payment-status]');
    if (statusRoot && statusRoot.dataset.paymentStatus) {
        var orderNo = statusRoot.dataset.paymentStatus;
        var text = statusRoot.querySelector('[data-payment-status-text]');
        var tries = 0;
        var poll = window.setInterval(function () {
            tries += 1;
            if (tries > 20) {
                window.clearInterval(poll);
                return;
            }

            fetch('/api/payment/status/' + encodeURIComponent(orderNo), {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            }).then(function (response) {
                return response.json();
            }).then(function (json) {
                if (!json.ok) return;
                if (text) text.textContent = json.payment_status || json.order_status || 'pending';
                if (json.payment_status === 'paid' || json.order_status === 'completed' || json.payment_status === 'failed' || json.order_status === 'failed') {
                    window.clearInterval(poll);
                    if (json.redirect_url && window.location.pathname !== new URL(json.redirect_url, window.location.origin).pathname) {
                        window.location.href = json.redirect_url;
                    }
                }
            }).catch(function () {});
        }, 4000);
    }
})();
