/**
 * SeaXPay Payment Page JavaScript
 */

(function($) {
    'use strict';
    
    var SeaXPayPayment = {
        
        pollInterval: null,
        pollCount: 0,
        maxPollCount: 360,
        
        init: function() {
            this.bindEvents();
            
            if (seaxpayPaymentData.platformOrderNo) {
                this.initPaymentStep();
            }
        },
        
        bindEvents: function() {
            var self = this;
            
            $('input[name="seaxpay_coin"]').on('change', function() {
                $('#seaxpay-continue-btn').prop('disabled', false);
            });
            
            $('#seaxpay-continue-btn').on('click', function() {
                self.createOrder();
            });
            
            $('.seaxpay-copy-btn').on('click', function() {
                self.copyToClipboard($(this).data('target'));
            });
            
            $('#seaxpay-check-status-btn').on('click', function() {
                self.checkOrderStatus();
            });
        },
        
        createOrder: function() {
            var self = this;
            var selectedCoin = $('input[name="seaxpay_coin"]:checked').val();
            
            if (!selectedCoin) {
                alert(seaxpayL10n.selectCoin);
                return;
            }
            
            var parts = selectedCoin.split('|');
            var coin = parts[0];
            var network = parts[1];
            
            $('#seaxpay-continue-btn').prop('disabled', true).text(seaxpayL10n.checkingStatus);
            
            $.ajax({
                url: seaxpayL10n.ajax_url,
                type: 'POST',
                data: {
                    action: 'seaxpay_create_order',
                    nonce: seaxpayL10n.nonce,
                    order_id: seaxpayPaymentData.orderId,
                    order_key: seaxpayPaymentData.orderKey,
                    coin: coin,
                    network: network
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert(response.data || 'Error creating order');
                        $('#seaxpay-continue-btn').prop('disabled', false).text(seaxpayL10n.payNow);
                    }
                },
                error: function() {
                    alert('Network error');
                    $('#seaxpay-continue-btn').prop('disabled', false).text(seaxpayL10n.payNow);
                }
            });
        },
        
        initPaymentStep: function() {
            this.loadPaymentAddress();
            this.startCountdown();
            this.startPolling();
        },
        
        loadPaymentAddress: function() {
            var self = this;
            
            $.ajax({
                url: seaxpayL10n.ajax_url,
                type: 'POST',
                data: {
                    action: 'seaxpay_get_payment_address',
                    nonce: seaxpayL10n.nonce,
                    platform_order_no: seaxpayPaymentData.platformOrderNo
                },
                success: function(response) {
                    if (response.success && response.data) {
                        $('#seaxpay-address').val(response.data.address);
                        
                        if (response.data.qrcode_data) {
                            self.generateQRCode(response.data.qrcode_data);
                        }
                    }
                }
            });
        },
        
        generateQRCode: function(data) {
            var qrcodeContainer = document.getElementById('seaxpay-qrcode');
            
            if (typeof QRCode !== 'undefined') {
                new QRCode(qrcodeContainer, {
                    text: data,
                    width: 256,
                    height: 256,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.H
                });
            } else if (qrcodeContainer) {
                qrcodeContainer.innerHTML = '<p class="seaxpay-qr-fallback">' + (seaxpayL10n.qrCodeUnavailable || 'QR code unavailable') + '</p>';
            }
        },
        
        startCountdown: function() {
            var self = this;
            
            if (!seaxpayPaymentData.expireTime) {
                return;
            }
            
            var updateCountdown = function() {
                var expireTime = new Date(seaxpayPaymentData.expireTime.replace(' ', 'T') + 'Z').getTime();
                var now = new Date().getTime();
                var remaining = Math.floor((expireTime - now) / 1000);
                
                if (remaining <= 0) {
                    $('#seaxpay-countdown').text(seaxpayL10n.expired);
                    $('#seaxpay-status .seaxpay-status-text').text(seaxpayL10n.paymentExpired);
                    $('#seaxpay-status .seaxpay-status-icon').text('⏱️');
                    self.stopPolling();
                    return;
                }
                
                var minutes = Math.floor(remaining / 60);
                var seconds = remaining % 60;
                $('#seaxpay-countdown').text(
                    String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0')
                );
            };
            
            updateCountdown();
            setInterval(updateCountdown, 1000);
        },
        
        startPolling: function() {
            var self = this;
            
            this.pollInterval = setInterval(function() {
                self.pollCount++;
                
                if (self.pollCount > self.maxPollCount) {
                    self.stopPolling();
                    return;
                }
                
                self.checkOrderStatus();
            }, 5000);
        },
        
        stopPolling: function() {
            if (this.pollInterval) {
                clearInterval(this.pollInterval);
                this.pollInterval = null;
            }
        },
        
        checkOrderStatus: function() {
            var self = this;
            
            $.ajax({
                url: seaxpayL10n.ajax_url,
                type: 'POST',
                data: {
                    action: 'seaxpay_check_order_status',
                    nonce: seaxpayL10n.nonce,
                    platform_order_no: seaxpayPaymentData.platformOrderNo
                },
                success: function(response) {
                    if (response.success && response.data) {
                        var st = response.data.status;
                        if (st === 'paid' || st === 'pending_withdraw' || st === 'confirming') {
                            self.stopPolling();
                            self.showSuccess();

                            setTimeout(function() {
                                window.location.href = seaxpayPaymentData.returnUrl;
                            }, 3000);
                        } else if (st === 'expired') {
                            self.stopPolling();
                            $('#seaxpay-status .seaxpay-status-text').text(seaxpayL10n.paymentExpired);
                            $('#seaxpay-status .seaxpay-status-icon').text('⏱️');
                        } else if (st === 'failed') {
                            self.stopPolling();
                            $('#seaxpay-status .seaxpay-status-text').text(seaxpayL10n.paymentFailed);
                            $('#seaxpay-status .seaxpay-status-icon').text('❌');
                        }
                    }
                }
            });
        },
        
        showSuccess: function() {
            $('#seaxpay-status .seaxpay-status-text').text(seaxpayL10n.paymentSuccess);
            $('#seaxpay-status .seaxpay-status-icon').text('✅');
            $('#seaxpay-status').addClass('success');
            
            var successHtml = '<div class="seaxpay-success-animation">' +
                '<div class="seaxpay-success-icon">✓</div>' +
                '<h3>' + seaxpayL10n.paymentSuccess + '</h3>' +
                '<p>Redirecting...</p>' +
                '</div>';
            
            $('.seaxpay-payment-info').prepend(successHtml);
        },
        
        copyToClipboard: function(targetId) {
            var input = document.getElementById(targetId);
            
            if (!input) {
                return;
            }
            
            input.select();
            input.setSelectionRange(0, 99999);
            
            try {
                document.execCommand('copy');
                
                var btn = $('[data-target="' + targetId + '"]');
                var originalText = btn.text();
                btn.text(seaxpayL10n.copied);
                
                setTimeout(function() {
                    btn.text(originalText);
                }, 2000);
            } catch (err) {
                console.error('Copy failed:', err);
            }
        }
    };
    
    $(document).ready(function() {
        if (typeof seaxpayPaymentData !== 'undefined') {
            SeaXPayPayment.init();
        }
    });
    
})(jQuery);
