/**
 * SeaXPay Admin JavaScript
 */

(function($) {
    'use strict';
    
    var SeaXPayAdmin = {
        coinsData: {},
        enabledCoins: {},
        enabledNetworks: {},
        
        init: function() {
            this.bindEvents();
            this.loadCoinsData();
        },
        
        bindEvents: function() {
            var self = this;
            
            $('#seaxpay-test-connection').on('click', this.testConnection);
            
        
            $(document).on('change', '.seaxpay-coin-toggle', function() {
                var coin = $(this).data('coin');
                var enabled = $(this).is(':checked');
                self.enabledCoins[coin] = enabled;
                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;
                self.updateHiddenFields();
            });
        },
        
        loadCoinsData: function() {
            var self = this;
            var $container = $('#seaxpay-coins-container');
            
            if ($container.length === 0) {
                return;
            }
            
            $container.html('<p style="padding:15px;color:#666;">Loading coins data...</p>');
            
            $.ajax({
                url: seaxpayAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'seaxpay_get_coins_for_settings',
                    nonce: seaxpayAdmin.nonce
                },
                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.updateHiddenFields();
                    } else {
                        self.showNoCoinsWarning($container);
                    }
                },
                error: function() {
                    $container.html('<p style="color:red;padding:15px;">Failed to load coins data. Please check API connection.</p>');
                }
            });
        },
        
        renderCoinToggles: function() {
            var self = this;
            var $container = $('#seaxpay-coins-container');
            var html = '';
            
            
            html += '<style>';
            
            html += '.seaxpay-toggle-section { background: #fff; border: 1px solid #e0e0e0; border-radius: 8px; padding: 20px; margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }';
            html += '.seaxpay-toggle-section-title { font-size: 15px; font-weight: 600; color: #333; margin: 0 0 15px 0; padding-bottom: 10px; border-bottom: 1px solid #f0f0f0; }';
            html += '.seaxpay-toggle-list { }';
            html += '.seaxpay-toggle-row { display: flex; justify-content: space-between; align-items: center; padding: 12px 15px; border-bottom: 1px solid #f5f5f5; }';
            html += '.seaxpay-toggle-row:last-child { border-bottom: none; }';
            html += '.seaxpay-toggle-row:hover { background: #fafafa; }';
            html += '.seaxpay-toggle-label { font-size: 14px; color: #333; }';
            html += '.seaxpay-toggle-hint { font-size: 13px; color: #888; font-style: italic; margin-top: 12px; padding-top: 12px; border-top: 1px solid #f0f0f0; }';
            
            
            html += '.seaxpay-network-group { margin-bottom: 15px; }';
            html += '.seaxpay-network-group:last-child { margin-bottom: 0; }';
            html += '.seaxpay-network-group-title { font-size: 13px; font-weight: 500; color: #555; padding: 8px 15px; background: #f8f9fa; border-radius: 4px; margin-bottom: 5px; }';
            
            // ON/OFF
            html += '.seaxpay-onoff { position: relative; display: inline-block; width: 60px; height: 28px; }';
            html += '.seaxpay-onoff input { opacity: 0; width: 0; height: 0; position: absolute; }';
            html += '.seaxpay-onoff-track { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; border-radius: 14px; cursor: pointer; transition: all 0.3s ease; background: #e0e0e0; box-shadow: inset 0 1px 3px rgba(0,0,0,0.1); }';
            html += '.seaxpay-onoff-text { font-size: 11px; font-weight: 600; letter-spacing: 0.5px; transition: all 0.3s ease; }';
            html += '.seaxpay-onoff input:not(:checked) + .seaxpay-onoff-track { background: linear-gradient(to bottom, #e8e8e8, #d8d8d8); }';
            html += '.seaxpay-onoff input:not(:checked) + .seaxpay-onoff-track .seaxpay-onoff-text { color: #999; }';
            html += '.seaxpay-onoff input:checked + .seaxpay-onoff-track { background: linear-gradient(to bottom, #5cb85c, #4cae4c); box-shadow: inset 0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.1); }';
            html += '.seaxpay-onoff input:checked + .seaxpay-onoff-track .seaxpay-onoff-text { color: #fff; }';
            html += '</style>';
            
            // Enabled Coins 
            html += '<div class="seaxpay-toggle-section">';
            html += '<h4 class="seaxpay-toggle-section-title">Enabled Coins</h4>';
            html += '<div class="seaxpay-toggle-list">';
            
            $.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-label">' + coinName + ' (' + coin + ')</span>';
                html += '<label class="seaxpay-onoff">';
                html += '<input type="checkbox" class="seaxpay-coin-toggle" data-coin="' + coin + '"' + (coinEnabled ? ' checked' : '') + '>';
                html += '<span class="seaxpay-onoff-track"><span class="seaxpay-onoff-text">' + (coinEnabled ? 'ON' : 'OFF') + '</span></span>';
                html += '</label>';
                html += '</div>';
            });
            
            html += '</div>';
            html += '<p class="seaxpay-toggle-hint">Toggle ON/OFF to enable or disable each cryptocurrency.</p>';
            html += '</div>';
            
            // Enabled Networks 
            html += '<div class="seaxpay-toggle-section">';
            html += '<h4 class="seaxpay-toggle-section-title">Enabled Networks</h4>';
            html += '<div class="seaxpay-toggle-list" id="seaxpay-networks-list">';
            html += '</div>';
            html += '<p class="seaxpay-toggle-hint">Toggle ON/OFF to enable or disable networks for each enabled coin.</p>';
            html += '</div>';
            
            $container.html(html);
            
        
            $(document).on('change', '.seaxpay-coin-toggle, .seaxpay-network-toggle', function() {
                var $track = $(this).siblings('.seaxpay-onoff-track');
                var isChecked = $(this).is(':checked');
                $track.find('.seaxpay-onoff-text').text(isChecked ? 'ON' : 'OFF');
            });
            
            this.updateNetworksDisplay();
        },
        
        updateNetworksDisplay: function() {
            var self = this;
            var $networksContainer = $('#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-label">' + networkName + ' (' + network + ')</span>';
                    html += '<label class="seaxpay-onoff">';
                    html += '<input type="checkbox" class="seaxpay-network-toggle" data-coin="' + coin + '" data-network="' + network + '"' + (networkEnabled ? ' checked' : '') + '>';
                    html += '<span class="seaxpay-onoff-track"><span class="seaxpay-onoff-text">' + (networkEnabled ? 'ON' : 'OFF') + '</span></span>';
                    html += '</label>';
                    html += '</div>';
                });
                
                html += '</div>';
            });
            
            if (!hasEnabledCoin) {
                html = '<p style="color:#888;padding:15px 0;text-align:center;">Please enable at least one coin to configure networks.</p>';
            }
            
            $networksContainer.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);
        },
        
        showNoCoinsWarning: function($container) {
            $container.html('<div style="background:#fff3cd;border:1px solid #ffc107;border-radius:8px;padding:15px;">' +
                '<p style="margin:0;color:#856404;"><strong>No coins available.</strong></p>' +
                '<p style="margin:8px 0 0 0;color:#856404;font-size:13px;">Please check your API connection and merchant configuration.</p>' +
                '</div>');
        },
        
        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);
