(function($) {
    'use strict';

    function copyField(id, btn) {
        var input = document.getElementById(id);
        if (!input || !btn) {
            return;
        }
        input.select();
        input.setSelectionRange(0, 99999);
        document.execCommand('copy');
        var orig = btn.textContent;
        btn.textContent = seaxpayPageL10n.copied;
        btn.style.background = '#28a745';
        setTimeout(function() {
            btn.textContent = orig;
            btn.style.background = '';
        }, 2000);
    }

    function copyAmountOnly() {
        var input = document.getElementById('seaxpay-amount');
        if (!input) {
            return;
        }
        var amount = input.value;
        var tempInput = document.createElement('textarea');
        tempInput.value = amount;
        document.body.appendChild(tempInput);
        tempInput.select();
        tempInput.setSelectionRange(0, 99999);
        document.execCommand('copy');
        document.body.removeChild(tempInput);
        var btn = document.querySelector('.seaxpay-copy-amount');
        if (btn) {
            var orig = btn.textContent;
            btn.textContent = seaxpayPageL10n.copied;
            btn.style.background = '#28a745';
            setTimeout(function() {
                btn.textContent = orig;
                btn.style.background = '#dc3545';
            }, 2000);
        }
        alert(seaxpayPageL10n.amountCopiedAlert);
    }

    window.seaxpayCopyField = copyField;
    window.seaxpayCopyAmountOnly = copyAmountOnly;

    function initPaymentPage() {
        if (typeof seaxpayPageData === 'undefined') {
            return;
        }

        if (seaxpayPageData.isExpired) {
            return;
        }

        var expireDate = null;
        var partialShown = false;
        var qrEl = document.getElementById('seaxpay-qrcode');

        if (qrEl && seaxpayPageData.address && typeof QRCode !== 'undefined') {
            new QRCode(qrEl, {
                text: seaxpayPageData.address,
                width: 180,
                height: 180,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
            });
        }

        var countdownEl = document.getElementById('seaxpay-countdown');
        var statusEl = document.getElementById('seaxpay-status');

        if (countdownEl && seaxpayPageData.expireTime) {
            var expireTimeStr = seaxpayPageData.expireTime.replace(' ', 'T') + 'Z';
            expireDate = new Date(expireTimeStr).getTime();
            var countdownInterval = setInterval(function() {
                var now = Date.now();
                var diff = expireDate - now;
                if (diff < 0) {
                    clearInterval(countdownInterval);
                    countdownEl.textContent = seaxpayPageL10n.expired;
                    countdownEl.style.color = '#dc3545';
                    if (statusEl) {
                        statusEl.innerHTML = seaxpayPageL10n.paymentExpiredStatus;
                        statusEl.style.color = '#dc3545';
                    }
                    var elementsToHide = document.querySelectorAll('.seaxpay-qr, .seaxpay-field, .seaxpay-warnings, .seaxpay-notice, .seaxpay-actions');
                    elementsToHide.forEach(function(el) {
                        el.style.display = 'none';
                    });
                    var container = document.querySelector('.seaxpay-container');
                    if (container) {
                        var expiredDiv = document.createElement('div');
                        expiredDiv.className = 'seaxpay-expired';
                        expiredDiv.innerHTML = '<div class="seaxpay-expired-icon">⏰</div>' +
                            '<h2>' + seaxpayPageL10n.paymentExpiredTitle + '</h2>' +
                            '<p>' + seaxpayPageL10n.paymentExpiredMessage + '</p>' +
                            '<a href="' + seaxpayPageData.checkoutUrl + '">' + seaxpayPageL10n.returnCheckout + '</a>';
                        var timerEl = document.querySelector('.seaxpay-timer');
                        if (timerEl) {
                            timerEl.parentNode.insertBefore(expiredDiv, timerEl.nextSibling);
                        }
                    }
                    return;
                }
                var m = Math.floor((diff % 3600000) / 60000);
                var s = Math.floor((diff % 60000) / 1000);
                countdownEl.textContent = (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
            }, 1000);
        }

        var platformOrderNo = seaxpayPageData.platformOrderNo;
        var pollTimer = null;
        var pollCount = 0;
        var maxPollCount = 360;

        function checkPaymentStatus() {
            if (!platformOrderNo) {
                return;
            }
            var currentStatusEl = document.getElementById('seaxpay-status');

            $.ajax({
                url: seaxpayL10n.ajax_url,
                type: 'POST',
                data: {
                    action: 'seaxpay_check_order_status',
                    nonce: seaxpayL10n.nonce,
                    platform_order_no: platformOrderNo
                },
                success: function(response) {
                    if (response.success && response.data) {
                        if (response.data.status === 'paid' || response.data.status === 'pending_withdraw' || response.data.status === 'confirming' || response.data.status === 'completed') {
                            if (pollTimer) {
                                clearInterval(pollTimer);
                            }
                            if (currentStatusEl) {
                                currentStatusEl.innerHTML = seaxpayPageL10n.paymentSuccessRedirect;
                                currentStatusEl.style.color = '#28a745';
                            }
                            setTimeout(function() {
                                window.location.href = seaxpayPageData.returnUrl;
                            }, 3000);
                        } else if (response.data.status === 'expired') {
                            if (pollTimer) {
                                clearInterval(pollTimer);
                            }
                            if (currentStatusEl) {
                                currentStatusEl.innerHTML = seaxpayPageL10n.paymentExpiredStatus;
                                currentStatusEl.style.color = '#dc3545';
                            }
                        } else if (response.data.status === 'failed') {
                            if (pollTimer) {
                                clearInterval(pollTimer);
                            }
                            if (currentStatusEl) {
                                currentStatusEl.innerHTML = seaxpayPageL10n.paymentFailed;
                                currentStatusEl.style.color = '#dc3545';
                            }
                        } else {
                            if (response.data.expire_time) {
                                var newExpire = parseInt(response.data.expire_time, 10);
                                if (!isNaN(newExpire) && (expireDate === null || newExpire > expireDate)) {
                                    expireDate = newExpire;
                                }
                            }
                            var received = response.data.received_amount;
                            var remaining = response.data.remaining_amount;
                            var amountEl = document.getElementById('seaxpay-amount');
                            if (received !== undefined && remaining !== undefined &&
                                parseFloat(received) > 0 && parseFloat(remaining) > 0) {
                                partialShown = true;
                                if (amountEl) {
                                    amountEl.value = remaining;
                                    amountEl.style.color = '#d63384';
                                    amountEl.style.background = '#fff3cd';
                                }
                                if (currentStatusEl) {
                                    currentStatusEl.innerHTML = '⚠️ ' + seaxpayPageL10n.partialPayment + ' ' + remaining + ' ' + seaxpayPageData.coin;
                                    currentStatusEl.style.color = '#856404';
                                }
                            } else if (currentStatusEl) {
                                currentStatusEl.innerHTML = seaxpayPageL10n.waitingPayment;
                            }
                        }
                    }
                },
                error: function() {
                    if (currentStatusEl) {
                        currentStatusEl.innerHTML = seaxpayPageL10n.waitingPayment;
                    }
                }
            });
        }

        if (platformOrderNo) {
            pollTimer = setInterval(function() {
                pollCount++;
                if (pollCount > maxPollCount) {
                    clearInterval(pollTimer);
                    return;
                }
                checkPaymentStatus();
            }, 5000);
        }

        var checkBtn = document.getElementById('seaxpay-check-btn');
        if (checkBtn) {
            checkBtn.addEventListener('click', function() {
                var currentStatusEl = document.getElementById('seaxpay-status');
                if (currentStatusEl) {
                    currentStatusEl.innerHTML = seaxpayPageL10n.checking;
                }
                checkPaymentStatus();
            });
        }

        document.querySelectorAll('.seaxpay-copy-field-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                copyField(btn.getAttribute('data-target'), btn);
            });
        });

        var copyAmountBtn = document.querySelector('.seaxpay-copy-amount');
        if (copyAmountBtn) {
            copyAmountBtn.addEventListener('click', copyAmountOnly);
        }
    }

    document.addEventListener('DOMContentLoaded', initPaymentPage);
})(jQuery);
