/**
 * CloudXM NFe Settings JavaScript
 * Handles tabs, test connection, and form interactions
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        // ============================================================
        // TAB NAVIGATION
        // ============================================================

        // Tab switching functionality
        $('.woo-nav-tab-wrapper .nav-tab').on('click', function(e) {
            e.preventDefault();

            var $tab = $(this);
            var targetId = $tab.attr('href');

            // Update active tab styling
            $('.woo-nav-tab-wrapper .nav-tab').removeClass('nav-tab-active');
            $tab.addClass('nav-tab-active');

            // Show/hide tab content
            $('.tab-content').hide();
            $(targetId).show();

            // Store active tab in localStorage for persistence
            if (typeof(Storage) !== "undefined") {
                localStorage.setItem('cloudxm_nfe_active_tab', targetId);
            }
        });

        // Restore active tab from localStorage on page load
        if (typeof(Storage) !== "undefined") {
            var activeTab = localStorage.getItem('cloudxm_nfe_active_tab');
            if (activeTab) {
                var $tabLink = $('.woo-nav-tab-wrapper .nav-tab[href="' + activeTab + '"]');
                if ($tabLink.length) {
                    $tabLink.trigger('click');
                }
            }
        }

        // ============================================================
        // TEST CONNECTION
        // ============================================================

        $('#cloudxm-nfe-test-connection').on('click', function() {
            var $button = $(this);
            var $status = $('#cloudxm-nfe-connection-status');

            // Prevent multiple clicks
            if ($button.prop('disabled')) {
                return;
            }

            // Show loading state
            $button.prop('disabled', true);
            $status.attr('data-status', 'testing');
            $status.html('<span class="spinner is-active" style="float: left; margin: 5px 0 0;"></span>' +
                        '<span class="testing">' + cloudxm_nfe_settings.i18n.testing + '</span>');

            // Make AJAX request
            $.ajax({
                url: cloudxm_nfe_settings.ajax_url,
                type: 'POST',
                data: {
                    action: 'cloudxm_nfe_test_connection',
                    nonce: cloudxm_nfe_settings.nonce
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        // Show success message
                        $status.attr('data-status', 'success');
                        $status.html('<span style="color: #46b450;">✓ ' + response.data.message + '</span>');

                        // Show tenant details if available
                        if (response.data.municipality_code) {
                            $status.append('<br><small>' +
                                cloudxm_nfe_settings.i18n.municipality_code + ': ' +
                                response.data.municipality_code +
                                '</small>');
                        }
                        if (response.data.municipal_service_code) {
                            $status.append('<br><small>' +
                                cloudxm_nfe_settings.i18n.municipal_service_code + ': ' +
                                response.data.municipal_service_code +
                                '</small>');
                        }
                        if (response.data.national_service_code) {
                            $status.append('<br><small>' +
                                cloudxm_nfe_settings.i18n.national_service_code + ': ' +
                                response.data.national_service_code +
                                '</small>');
                        }
                    } else {
                        // Show error message
                        $status.attr('data-status', 'error');
                        $status.html('<span style="color: #dc3232;">✗ ' + response.data.message + '</span>');
                        if (response.data.error_detail) {
                            $status.append('<br><small class="error-detail">' +
                                cloudxm_nfe_settings.i18n.error_detail + ' ' +
                                response.data.error_detail +
                                '</small>');
                        }
                    }
                },
                error: function(xhr, status, error) {
                    // Show error message
                    $status.attr('data-status', 'error');
                    $status.html('<span style="color: #dc3232;">✗ ' +
                        cloudxm_nfe_settings.i18n.error + '</span>');
                    console.error('Test connection error:', error);
                },
                complete: function() {
                    // Reset button state
                    $button.prop('disabled', false);
                    setTimeout(function() {
                        $status.find('.spinner').remove();
                    }, 500);
                }
            });
        });

        // ============================================================
        // ENVIRONMENT CHANGE
        // ============================================================

        $('#cloudxm_nfe_environment').on('change', function() {
            var isCustom = $(this).val() === 'custom';
            $('#custom-url-row').toggle(isCustom);
            $('#custom-token-row').toggle(isCustom);

            if (!isCustom) {
                $('#cloudxm_nfe_api_base_url').val('');
            }
        });

        // ============================================================
        // GENERATE WEBHOOK SECRET
        // ============================================================

        $(document).on('click', '#cloudxm-nfe-generate-secret', function() {
            var arr = new Uint8Array(32);
            window.crypto.getRandomValues(arr);
            var hex = Array.from(arr).map(function(b) {
                return b.toString(16).padStart(2, '0');
            }).join('');
            $('#cloudxm_nfe_webhook_secret').val(hex);
        });
    });

})(jQuery);
