/**
 * Stablezact Settings Page - JavaScript
 *
 * Handles wallet address management, validation, and API communication
 *
 * @package Stablezact_Payment_Gateway
 * @version 1.0.0
 */

(function ($) {
    'use strict';

    const StablezactWalletSettings = {
        /**
         * Initialize the settings page
         */
        init: function () {
            this.fetchWallets();
            this.bindEvents();
        },

        /**
         * Bind event handlers
         */
        bindEvents: function () {
            // Save wallets form submission
            $('#stablezact-wallets-form').on('submit', this.handleSaveWallets.bind(this));

            // Validate all addresses button
            $('#stablezact-validate-all').on('click', this.validateAllAddresses.bind(this));

            // Real-time validation on input
            $('.stablezact-wallet-input').on('blur', this.validateSingleAddress);
            $('.stablezact-wallet-input').on('input', this.clearValidation);
        },

        /**
         * Fetch wallet addresses from API
         */
        fetchWallets: function () {
            $('#stablezact-loading').show();
            $('#stablezact-wallets-form').hide();

            $.ajax({
                url: stablezactWalletSettings.ajax_url,
                type: 'POST',
                data: {
                    action: 'stablezact_fetch_wallets',
                    nonce: stablezactWalletSettings.nonce
                },
                success: function (response) {
                    $('#stablezact-loading').hide();
                    $('#stablezact-wallets-form').fadeIn();

                    if (response.success && response.data.wallets) {
                        StablezactWalletSettings.populateWallets(response.data.wallets);
                    }
                },
                error: function (xhr, status, error) {
                    $('#stablezact-loading').hide();
                    $('#stablezact-wallets-form').fadeIn();
                    StablezactWalletSettings.showNotice('Failed to load wallet addresses. Please try refreshing the page.', 'error');
                }
            });
        },

        /**
         * Populate wallet input fields with fetched data
         */
        populateWallets: function (wallets) {
            Object.keys(wallets).forEach(function (network) {
                const address = wallets[network];
                const $input = $('#wallet_' + network);

                if ($input.length && address) {
                    $input.val(address);

                    // Update status
                    const $card = $input.closest('.stablezact-wallet-card');
                    $card.find('.status-icon').html('✓');
                    $card.find('.status-text').text('Configured');
                    $card.addClass('configured');
                }
            });

            // Show count of configured wallets
            const configuredCount = Object.keys(wallets).length;
            const totalCount = Object.keys(stablezactWalletSettings.networks).length;

            if (configuredCount > 0) {
                StablezactWalletSettings.showNotice(
                    `Loaded ${configuredCount} of ${totalCount} wallet addresses.`,
                    'info'
                );
            }
        },

        /**
         * Handle save wallets form submission
         */
        handleSaveWallets: function (e) {
            e.preventDefault();

            const $button = $('#stablezact-save-wallets');
            const $form = $('#stablezact-wallets-form');

            // Validate all addresses first
            if (!this.validateAllAddresses()) {
                this.showNotice('Please fix validation errors before saving.', 'error');
                return false;
            }

            // Collect wallet data
            const walletsData = {};
            $('.stablezact-wallet-input').each(function () {
                const $input = $(this);
                const network = $input.attr('id').replace('wallet_', '');
                const address = $input.val().trim();

                if (address) {
                    walletsData[network] = address;
                }
            });

            if (Object.keys(walletsData).length === 0) {
                this.showNotice('Please configure at least one wallet address.', 'warning');
                return false;
            }

            // Disable button and show loading
            $button.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Saving...');

            // Send to server
            $.ajax({
                url: stablezactWalletSettings.ajax_url,
                type: 'POST',
                data: {
                    action: 'stablezact_save_wallets',
                    nonce: stablezactWalletSettings.nonce,
                    wallets: walletsData
                },
                success: function (response) {
                    if (response.success) {
                        StablezactWalletSettings.showNotice(response.data.message, 'success');

                        // Update status for all configured wallets
                        Object.keys(walletsData).forEach(function (network) {
                            const $card = $('#wallet_' + network).closest('.stablezact-wallet-card');
                            $card.find('.status-icon').html('✓');
                            $card.find('.status-text').text('Configured & Saved');
                            $card.addClass('configured saved');

                            // Add success animation
                            $card.addClass('save-animation');
                            setTimeout(function () {
                                $card.removeClass('save-animation');
                            }, 1000);
                        });
                    } else {
                        StablezactWalletSettings.showNotice(response.data.message || 'Failed to save wallet addresses.', 'error');
                    }
                },
                error: function (xhr, status, error) {
                    StablezactWalletSettings.showNotice('Network error. Please try again.', 'error');
                },
                complete: function () {
                    $button.prop('disabled', false).html('<span class="dashicons dashicons-saved"></span> Save All Wallet Addresses');
                }
            });

            return false;
        },

        /**
         * Validate all wallet addresses
         */
        validateAllAddresses: function () {
            let allValid = true;
            let hasAtLeastOne = false;

            $('.stablezact-wallet-input').each(function () {
                const $input = $(this);
                const address = $input.val().trim();

                if (address) {
                    hasAtLeastOne = true;
                    const isValid = StablezactWalletSettings.validateSingleAddress.call(this);
                    if (!isValid) {
                        allValid = false;
                    }
                }
            });

            if (!hasAtLeastOne) {
                StablezactWalletSettings.showNotice('Please configure at least one wallet address.', 'warning');
                return false;
            }

            if (allValid) {
                StablezactWalletSettings.showNotice('All wallet addresses are valid!', 'success');
            }

            return allValid;
        },

        /**
         * Validate a single wallet address
         */
        validateSingleAddress: function () {
            const $input = $(this);
            const address = $input.val().trim();
            const networkType = $input.data('network-type');
            const $message = $input.siblings('.stablezact-validation-message');
            const $card = $input.closest('.stablezact-wallet-card');

            // Clear previous validation
            $input.removeClass('valid invalid');
            $message.text('').removeClass('error success');

            if (!address) {
                return true; // Empty is OK (not required)
            }

            // Validate based on network type
            let isValid = false;
            let errorMessage = '';

            if (networkType === 'evm') {
                // EVM address validation
                const evmRegex = /^0x[a-fA-F0-9]{40}$/;
                isValid = evmRegex.test(address);
                errorMessage = 'Invalid EVM address format. Must start with 0x followed by 40 hexadecimal characters.';
            } else {
                // Generic validation for non-EVM chains
                isValid = address.length >= 26 && address.length <= 128;
                errorMessage = 'Invalid address format.';
            }

            if (isValid) {
                $input.addClass('valid');
                $message.text('✓ Valid address').addClass('success');
                $card.addClass('validated');
            } else {
                $input.addClass('invalid');
                $message.text('✗ ' + errorMessage).addClass('error');
                $card.removeClass('validated');
            }

            return isValid;
        },

        /**
         * Clear validation on input
         */
        clearValidation: function () {
            const $input = $(this);
            const $message = $input.siblings('.stablezact-validation-message');
            const $card = $input.closest('.stablezact-wallet-card');

            $input.removeClass('valid invalid');
            $message.text('').removeClass('error success');
            $card.removeClass('validated');
        },

        /**
         * Show admin notice
         */
        showNotice: function (message, type) {
            type = type || 'info'; // info, success, warning, error

            const $notice = $('.stablezact-settings-notice');
            const iconMap = {
                'success': '✓',
                'error': '✗',
                'warning': '⚠',
                'info': 'ℹ'
            };

            $notice
                .removeClass('notice-info notice-success notice-warning notice-error')
                .addClass('notice notice-' + type)
                .html('<p><strong>' + iconMap[type] + '</strong> ' + message + '</p>')
                .show();

            // Auto-hide after 5 seconds for success/info
            if (type === 'success' || type === 'info') {
                setTimeout(function () {
                    $notice.fadeOut();
                }, 5000);
            }

            // Scroll to notice
            $('html, body').animate({
                scrollTop: $notice.offset().top - 100
            }, 300);
        }
    };

    // Initialize on document ready
    $(document).ready(function () {
        // Only init on settings page
        if ($('#stablezact-wallets-form').length) {
            StablezactWalletSettings.init();
        }
    });

})(jQuery);
