/**
 * SeaXPay Admin JavaScript
 */

(function($) {
    'use strict';
    
    var SeaXPayAdmin = {
        coinsData: {},
        enabledCoins: {},
        enabledNetworks: {},
        
        init: function() {
            console.log('[SeaXPay Admin] Initializing...');
            this.bindEvents();
            this.checkMerchantId();
        },
        
        bindEvents: function() {
            var self = this;
            
            $('#seaxpay-test-connection').on('click', this.testConnection);
            
            // Merchant NO
            var merchantIdSelector = '#woocommerce_seaxpay_merchant_no, #seaxpay_merchant_no, input[name="woocommerce_seaxpay_merchant_no"]';
            
        
            $(document).on('blur', merchantIdSelector, function() {
                console.log('[SeaXPay Admin] Merchant NO blur event triggered');
                var merchantNo = $(this).val();
                if (merchantNo) {
                    self.loadCoinsData(merchantNo);
                }
            });
            
            var inputTimer;
            $(document).on('input', merchantIdSelector, function() {
                var $input = $(this);
                clearTimeout(inputTimer);
                inputTimer = setTimeout(function() {
                    var merchantNo = $input.val();
                    console.log('[SeaXPay Admin] Merchant ID input event, value:', merchantNo);
                    if (merchantNo) {
                        self.loadCoinsData(merchantNo);
                    }
                }, 500);
            });
            
            $(document).on('change', '.seaxpay-coin-toggle', function() {
                var coin = $(this).data('coin');
                var enabled = $(this).is(':checked');
                self.enabledCoins[coin] = enabled;
                
                var $label = $(this).siblings('.seaxpay-toggle-label');
                $label.text(enabled ? 'ON' : 'OFF');
                
                self.updateNetworksDisplay();
                self.updateHiddenFields();
            });
            
            $(document).on('change', '.seaxpay-network-toggle', function() {
                var coin = $(this).data('coin');
                var network = $(this).data('network');
                var enabled = $(this).is(':checked');
                
                if (!self.enabledNetworks[coin]) {
                    self.enabledNetworks[coin] = {};
                }
                self.enabledNetworks[coin][network] = enabled;
                
                var $label = $(this).siblings('.seaxpay-toggle-label');
                $label.text(enabled ? 'ON' : 'OFF');
                
                self.updateHiddenFields();
            });
        },
        
        checkMerchantId: function() {
            var $merchantNoInput = $('#woocommerce_seaxpay_merchant_no, #seaxpay_merchant_no, input[name="woocommerce_seaxpay_merchant_no"]');
            console.log('[SeaXPay Admin] checkMerchantId - found inputs:', $merchantNoInput.length);
            var merchantNo = $merchantNoInput.val();
            console.log('[SeaXPay Admin] checkMerchantId - merchantNo:', merchantNo);
            if (merchantNo) {
                this.loadCoinsData(merchantNo);
            }
        },
        
        loadCoinsData: function(merchantNo) {
            var self = this;
            var $coinsContainer = $('#seaxpay-coins-list');
            var $networksContainer = $('#seaxpay-networks-list');
            
            console.log('[SeaXPay Admin] loadCoinsData - merchantId:', merchantNo);
            console.log('[SeaXPay Admin] loadCoinsData - coinsContainer found:', $coinsContainer.length);
            console.log('[SeaXPay Admin] loadCoinsData - networksContainer found:', $networksContainer.length);
            
            if ($coinsContainer.length === 0) {
                console.log('[SeaXPay Admin] loadCoinsData - No coins container found, skipping');
                return;
            }
            
            $coinsContainer.html('<p class="seaxpay-loading">Loading coins data...</p>');
            $networksContainer.html('<p class="seaxpay-hint">Loading...</p>');
            
            $.ajax({
                url: seaxpayAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'seaxpay_get_coins_for_settings',
                    nonce: seaxpayAdmin.nonce,
                    merchant_no: merchantNo
                },
                success: function(response) {
                    if (response.success && response.data && !$.isEmptyObject(response.data)) {
                        self.coinsData = response.data;
                        
                        var hasSavedCoins = response.enabled_coins && !$.isEmptyObject(response.enabled_coins);
                        var hasSavedNetworks = response.enabled_networks && !$.isEmptyObject(response.enabled_networks);
                        
                        if (hasSavedCoins) {
                            self.enabledCoins = {};
                            $.each(response.enabled_coins, function(coin, enabled) {
                                self.enabledCoins[coin] = (enabled === true || enabled === 'true' || enabled === 1 || enabled === '1');
                            });
                        } else {
                            self.enabledCoins = {};
                            $.each(self.coinsData, function(coin, config) {
                                self.enabledCoins[coin] = false;
                            });
                        }
                        
                        if (hasSavedNetworks) {
                            self.enabledNetworks = {};
                            $.each(response.enabled_networks, function(coin, networks) {
                                if (networks && typeof networks === 'object') {
                                    self.enabledNetworks[coin] = {};
                                    $.each(networks, function(network, enabled) {
                                        self.enabledNetworks[coin][network] = (enabled === true || enabled === 'true' || enabled === 1 || enabled === '1');
                                    });
                                }
                            });
                        } else {
                            self.enabledNetworks = {};
                            $.each(self.coinsData, function(coin, config) {
                                self.enabledNetworks[coin] = {};
                                if (config.networks) {
                                    $.each(config.networks, function(network, netConfig) {
                                        self.enabledNetworks[coin][network] = false;
                                    });
                                }
                            });
                        }
                        
                        self.renderCoinToggles();
                        self.updateNetworksDisplay();
                        self.updateHiddenFields();
                    } else {
                        self.showNoCoinsWarning();
                    }
                },
                error: function() {
                    $coinsContainer.html('<p style="color:red;">Failed to load coins data. Please check API connection.</p>');
                }
            });
        },
        
        renderCoinToggles: function() {
            var self = this;
            var $container = $('#seaxpay-coins-list');
            var html = '';
            
            html += '<style>';
            html += '.seaxpay-toggle-container { background: #fff; border: 1px solid #e0e0e0; border-radius: 8px; padding: 15px; max-width: 600px; }';
            html += '.seaxpay-toggle-row { display: flex; justify-content: space-between; align-items: center; padding: 12px 15px; border-bottom: 1px solid #f0f0f0; }';
            html += '.seaxpay-toggle-row:last-child { border-bottom: none; }';
            html += '.seaxpay-toggle-name { font-size: 14px; color: #333; }';
            html += '.seaxpay-network-group { margin-bottom: 10px; }';
            html += '.seaxpay-network-group-title { font-size: 13px; font-weight: 500; color: #555; padding: 8px 15px; background: #f8f9fa; border-radius: 4px; margin-bottom: 5px; }';
            html += '.seaxpay-hint { color: #888; font-style: italic; text-align: center; padding: 20px; }';
            html += '.seaxpay-loading { color: #666; text-align: center; padding: 20px; }';
            
            // ON/OFF
            html += '.seaxpay-switch { position: relative; display: inline-flex; align-items: center; width: 65px; height: 28px; cursor: pointer; }';
            html += '.seaxpay-switch input { opacity: 0; width: 0; height: 0; position: absolute; }';
            html += '.seaxpay-switch-track { position: relative; width: 100%; height: 100%; border-radius: 14px; transition: all 0.3s ease; display: flex; align-items: center; }';
            // OFF
            html += '.seaxpay-switch input:not(:checked) + .seaxpay-switch-track { background: #e0e0e0; }';
            html += '.seaxpay-switch input:not(:checked) + .seaxpay-switch-track .seaxpay-toggle-label { color: #999; margin-left: auto; margin-right: 8px; }';
            html += '.seaxpay-switch input:not(:checked) + .seaxpay-switch-track .seaxpay-switch-thumb { left: 2px; }';
            // ON
            html += '.seaxpay-switch input:checked + .seaxpay-switch-track { background: #4CAF50; }';
            html += '.seaxpay-switch input:checked + .seaxpay-switch-track .seaxpay-toggle-label { color: #fff; margin-left: 8px; }';
            html += '.seaxpay-switch input:checked + .seaxpay-switch-track .seaxpay-switch-thumb { left: calc(100% - 26px); }';
            
            html += '.seaxpay-switch-thumb { position: absolute; width: 24px; height: 24px; background: #fff; border-radius: 50%; transition: all 0.3s ease; box-shadow: 0 1px 3px rgba(0,0,0,0.2); }';
            
            html += '.seaxpay-toggle-label { font-size: 11px; font-weight: 600; transition: all 0.3s ease; }';
            html += '</style>';
            
            $.each(this.coinsData, function(coin, config) {
                var coinEnabled = self.enabledCoins[coin] === true;
                var coinName = config.name || coin;
                
                html += '<div class="seaxpay-toggle-row">';
                html += '<span class="seaxpay-toggle-name">' + coinName + ' (' + coin + ')</span>';
                html += '<label class="seaxpay-switch">';
                html += '<input type="checkbox" class="seaxpay-coin-toggle" data-coin="' + coin + '"' + (coinEnabled ? ' checked' : '') + '>';
                html += '<span class="seaxpay-switch-track">';
                html += '<span class="seaxpay-toggle-label">' + (coinEnabled ? 'ON' : 'OFF') + '</span>';
                html += '<span class="seaxpay-switch-thumb"></span>';
                html += '</span>';
                html += '</label>';
                html += '</div>';
            });
            
            $container.html(html);
        },
        
        updateNetworksDisplay: function() {
            var self = this;
            var $container = $('#seaxpay-networks-list');
            var html = '';
            var hasEnabledCoin = false;
            
            $.each(this.coinsData, function(coin, config) {
                var coinEnabled = self.enabledCoins[coin] === true;
                
                if (!coinEnabled || !config.networks) {
                    return;
                }
                
                hasEnabledCoin = true;
                var coinName = config.name || coin;
                
                html += '<div class="seaxpay-network-group">';
                html += '<div class="seaxpay-network-group-title">' + coinName + ' Networks</div>';
                
                $.each(config.networks, function(network, netConfig) {
                    var networkEnabled = self.enabledNetworks[coin] && self.enabledNetworks[coin][network] === true;
                    var networkName = netConfig.name || network;
                    
                    html += '<div class="seaxpay-toggle-row">';
                    html += '<span class="seaxpay-toggle-name">' + networkName + ' (' + network + ')</span>';
                    html += '<label class="seaxpay-switch">';
                    html += '<input type="checkbox" class="seaxpay-network-toggle" data-coin="' + coin + '" data-network="' + network + '"' + (networkEnabled ? ' checked' : '') + '>';
                    html += '<span class="seaxpay-switch-track">';
                    html += '<span class="seaxpay-toggle-label">' + (networkEnabled ? 'ON' : 'OFF') + '</span>';
                    html += '<span class="seaxpay-switch-thumb"></span>';
                    html += '</span>';
                    html += '</label>';
                    html += '</div>';
                });
                
                html += '</div>';
            });
            
            if (!hasEnabledCoin) {
                html = '<p class="seaxpay-hint">Enable coins above to see available networks.</p>';
            }
            
            $container.html(html);
        },
        
        updateHiddenFields: function() {
            var enabledCoinsJson = JSON.stringify(this.enabledCoins);
            var enabledNetworksJson = JSON.stringify(this.enabledNetworks);
            
            if ($('#seaxpay_enabled_coins').length === 0) {
                $('form').append('<input type="hidden" id="seaxpay_enabled_coins" name="seaxpay_enabled_coins" value="">');
            }
            if ($('#seaxpay_enabled_networks').length === 0) {
                $('form').append('<input type="hidden" id="seaxpay_enabled_networks" name="seaxpay_enabled_networks" value="">');
            }
            
            $('#seaxpay_enabled_coins').val(enabledCoinsJson);
            $('#seaxpay_enabled_networks').val(enabledNetworksJson);
        },
        
        saveCoinsSettings: function(merchantNo) {
            var enabledCoinsJson = JSON.stringify(this.enabledCoins);
            var enabledNetworksJson = JSON.stringify(this.enabledNetworks);
            
            console.log('[SeaXPay Admin] Saving coins settings for merchant:', merchantNo);
            
            $.ajax({
                url: seaxpayAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'seaxpay_save_coins_settings',
                    nonce: seaxpayAdmin.nonce,
                    merchant_no: merchantNo,
                    enabled_coins: enabledCoinsJson,
                    enabled_networks: enabledNetworksJson
                },
                success: function(response) {
                    console.log('[SeaXPay Admin] Save response:', response);
                },
                error: function() {
                    console.error('[SeaXPay Admin] Failed to save coins settings');
                }
            });
        },
        
        showNoCoinsWarning: function() {
            var $container = $('#seaxpay-coins-list');
            $container.html('<p style="color:#856404;background:#fff3cd;padding:15px;border-radius:4px;">No coins available. Please check your API connection and merchant configuration.</p>');
        },
        
        testConnection: function(e) {
            e.preventDefault();
            
            var $btn = $(this);
            var originalText = $btn.text();
            
            $btn.prop('disabled', true).text('Testing...');
            
            $.ajax({
                url: seaxpayAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'seaxpay_test_connection',
                    nonce: seaxpayAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        alert('Success: ' + response.data);
                    } else {
                        alert('Error: ' + response.data);
                    }
                },
                error: function() {
                    alert('Network error');
                },
                complete: function() {
                    $btn.prop('disabled', false).text(originalText);
                }
            });
        }
    };
    
    $(document).ready(function() {
        SeaXPayAdmin.init();
    });
    
})(jQuery);
