/**
 * CloudXM NFe Order Meta Box JavaScript
 *
 * @package CloudXM_NFe
 */

function cloudxmNfeAjaxError(xhr, fallbackMsg) {
    var detail = '';
    if (xhr.status) {
        detail += 'HTTP ' + xhr.status + '. ';
    }
    try {
        var body = JSON.parse(xhr.responseText);
        if (body.data && body.data.message) {
            detail += body.data.message;
        } else if (body.message) {
            detail += body.message;
        } else if (typeof body.data === 'string') {
            detail += body.data;
        }
    } catch(e) {
        if (xhr.responseText) {
            detail += xhr.responseText.substring(0, 200);
        }
    }
    return detail ? fallbackMsg + '\n\n' + detail : fallbackMsg;
}

function cloudxmExtractResponseMessage(response, fallback) {
    if (response && response.data) {
        if (typeof response.data === 'string') {
            return response.data;
        }
        if (response.data.message) {
            return response.data.message;
        }
    }
    if (response && response.message) {
        return response.message;
    }
    return fallback || '';
}

function cloudxmShowInlineError(message) {
    var $errorDiv = $('#cloudxm-nfe-error-display');
    if ($errorDiv.length) {
        $errorDiv.text(message).show();
        setTimeout(function() {
            $errorDiv.fadeOut(3000);
        }, 8000);
    }
    console.error('CloudXM NFe Error:', message);
}

(function($) {
    'use strict';

    $(document).ready(function() {
        console.log('CloudXM NFe Meta Box loaded - v' + new Date().getTime());

        // Ensure environment notice stays visible - prevent WordPress/other plugins from hiding it
        (function keepEnvNoticeVisible() {
            var $metaBox = $('.cloudxm-nfe-meta-box');

            function ensureNoticeVisible() {
                var $notice = $metaBox.find('.cloudxm-nfe-env-notice');

                // Build notice content with actual environment from server
                var envLabel = cloudxm_nfe_admin.i18n.environment_label || 'Unknown';
                var noticeContent = '<div class="notice notice-warning cloudxm-nfe-env-notice" style="padding: 8px 12px; margin: 0 0 12px 0;"><p style="margin: 0;"><strong>NFe Environment: ' + envLabel + '</strong> — Invoices will be issued to the <strong>' + envLabel + '</strong> environment.</p></div>';

                // If notice exists and is visible, don't recreate it (preserves PHP template)
                if ($notice.length > 0 && !$notice.is(':hidden')) {
                    return;
                }

                // If notice doesn't exist or was removed, recreate it
                if ($notice.length === 0) {
                    $metaBox.prepend(noticeContent);
                    console.log('CloudXM NFe: Environment notice recreated with: ' + envLabel);
                } else if ($notice.is(':hidden')) {
                    $notice.show();
                    $notice.css('display', 'block');
                    console.log('CloudXM NFe: Environment notice re-shown (was hidden)');
                }
            }

            // Check immediately
            setTimeout(ensureNoticeVisible, 50);

            // Check periodically
            setInterval(ensureNoticeVisible, 500);
        })();

        // Create loading modal
        createLoadingModal();

        // Initialize line/column counter on page load
        $('#cloudxm_nfe_description').trigger('input');

        // Create cancellation, force unlock, and schedule modals
        createCancellationModal();
        createForceUnlockModal();
        createScheduleModal();

        // Issue NFe - use off() to prevent duplicate event handlers
        $(document).on('click', '.cloudxm-nfe-issue', function() {
            var $button = $(this);
            var orderId = $button.data('order-id');
            var ajaxUrl = cloudxm_nfe_admin.ajax_url;
            var originalText = $button.text();

            // Check if button is disabled - don't allow issue
            if ($button.prop('disabled')) {
                return;
            }

            // Auto-save description before issuing (if field exists and is editable)
            var $textarea = $('#cloudxm_nfe_description');
            if ($textarea.length && !$textarea.prop('readonly')) {
                // Save description first, then issue
                saveDescriptionBeforeIssue(orderId, ajaxUrl, $button);
            } else {
                // No description to save, proceed with issue
                performIssue(orderId, ajaxUrl, $button);
            }
        });

        // Cancel NFe
        $(document).on('click', '.cloudxm-nfe-cancel', function() {
            var $button = $(this);
            var orderId = $button.data('order-id');
            var ajaxUrl = cloudxm_nfe_admin.ajax_url;
            var originalText = $button.text();

            // Check if button is disabled - don't allow cancel
            if ($button.prop('disabled')) {
                return;
            }

            // Open cancellation modal
            openCancellationModal(orderId, ajaxUrl, $button, originalText);
        });

        // Query SEFIN Status
        $(document).on('click', '.cloudxm-nfe-query-status', function() {
            var $button = $(this);
            var accessKey = $button.data('access-key');
            var orderId = $button.data('order-id');
            var ajaxUrl = cloudxm_nfe_admin.ajax_url;
            var originalText = $button.text();

            // Check if button is disabled - don't allow query
            if ($button.prop('disabled')) {
                return;
            }

            $button.prop('disabled', true).text(cloudxm_nfe_admin.i18n.querying);

            $.ajax({
                url: ajaxUrl,
                method: 'POST',
                data: {
                    action: 'cloudxm_nfe_query_status',
                    access_key: accessKey,
                    order_id: orderId,
                    nonce: cloudxm_nfe_admin.nonces.query_status
                },
                success: function(response) {
                    if (response.success) {
                        alert(cloudxmExtractResponseMessage(response, cloudxm_nfe_admin.i18n.success_query));
                        location.reload();
                    } else {
                        cloudxmShowInlineError(cloudxmExtractResponseMessage(response, cloudxm_nfe_admin.i18n.error_query));
                        $button.prop('disabled', false).text(originalText);
                    }
                },
                error: function(xhr) {
                    cloudxmShowInlineError(cloudxmNfeAjaxError(xhr, cloudxm_nfe_admin.i18n.error_query));
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });

        // Force Unlock NFe
        $(document).on('click', '.cloudxm-nfe-force-unlock', function() {
            console.log('CloudXM NFe: Force Unlock button clicked');

            var $button = $(this);
            var orderId = $button.data('order-id');
            var ajaxUrl = cloudxm_nfe_admin.ajax_url;
            var originalText = $button.text();

            console.log('CloudXM NFe: Order ID:', orderId);
            console.log('CloudXM NFe: Nonce:', cloudxm_nfe_admin.nonces.force_unlock);

            // Open force unlock modal
            openForceUnlockModal(orderId, ajaxUrl, $button, originalText);
        });

        // Recover NFSe by DPS
        $(document).on('click', '.cloudxm-nfe-recover-dps', function() {
            var $button = $(this);
            var orderId = $button.data('order-id');
            var ajaxUrl = cloudxm_nfe_admin.ajax_url;
            createDpsRecoveryModal();
            openDpsRecoveryModal(orderId, ajaxUrl, $button);
        });

        // Schedule NFe
        $(document).on('click', '.cloudxm-nfe-schedule', function() {
            var $button = $(this);
            var orderId = $button.data('order-id');
            var ajaxUrl = cloudxm_nfe_admin.ajax_url;
            var hasCancelledHistory = $button.data('has-cancelled-history') === '1';

            // Always open modal for cancelled invoices to let user pick a new date
            if (hasCancelledHistory) {
                openScheduleModal(orderId, ajaxUrl, false, true);
                return;
            }

            // Check if schedule date is already set
            var $scheduleInput = $('#cloudxm_nfe_schedule_date');
            var scheduleDate = $scheduleInput.length > 0 ? $scheduleInput.val() : '';

            if (scheduleDate !== '') {
                // Date is set, schedule directly without modal
                performDirectSchedule(orderId, ajaxUrl, scheduleDate, false);
            } else {
                // No date set, open modal to choose
                openScheduleModal(orderId, ajaxUrl, false, false);
            }
        });

        // Issue Now (immediate issuance)
        $(document).on('click', '.cloudxm-nfe-issue-now', function() {
            var $button = $(this);
            var orderId = $button.data('order-id');
            var ajaxUrl = cloudxm_nfe_admin.ajax_url;
            var originalText = $button.text();

            // Auto-save description before issuing (if field exists and is editable)
            var $textarea = $('#cloudxm_nfe_description');
            if ($textarea.length && !$textarea.prop('readonly')) {
                // Save description first, then issue
                saveDescriptionBeforeIssue(orderId, ajaxUrl, $button);
            } else {
                // No description to save, proceed with issue
                performIssue(orderId, ajaxUrl, $button);
            }
        });

        // Cancel Schedule
        $(document).on('click', '.cloudxm-nfe-cancel-schedule', function() {
            var $button = $(this);
            var orderId = $button.data('order-id');
            var ajaxUrl = cloudxm_nfe_admin.ajax_url;

            // Confirm before canceling schedule
            if (!confirm(cloudxm_nfe_admin.i18n.confirm_cancel_schedule)) {
                return;
            }

            $button.prop('disabled', true).text(cloudxm_nfe_admin.i18n.cancelling_schedule);

            $.ajax({
                url: ajaxUrl,
                method: 'POST',
                data: {
                    action: 'cloudxm_nfe_cancel_schedule',
                    order_id: orderId,
                    nonce: cloudxm_nfe_admin.nonces.cancel_schedule
                },
                success: function(response) {
                    if (response.success) {
                        alert(cloudxm_nfe_admin.i18n.success_cancel_schedule);
                        location.reload();
                    } else {
                        cloudxmShowInlineError(cloudxmExtractResponseMessage(response, cloudxm_nfe_admin.i18n.error_cancel_schedule));
                        $button.prop('disabled', false).text(cloudxm_nfe_admin.i18n.cancel_schedule_button);
                    }
                },
                error: function(xhr) {
                    cloudxmShowInlineError(cloudxmNfeAjaxError(xhr, cloudxm_nfe_admin.i18n.error_cancel_schedule));
                    $button.prop('disabled', false).text(cloudxm_nfe_admin.i18n.cancel_schedule_button);
                }
            });
        });

        // Reschedule NFe
        $(document).on('click', '.cloudxm-nfe-reschedule', function(e) {
            e.preventDefault();
            var $button = $(this);

            // Prevent duplicate clicks
            if ($button.prop('disabled') || $button.data('processing')) {
                return;
            }

            var orderId = $button.data('order-id');
            var ajaxUrl = cloudxm_nfe_admin.ajax_url;
            var originalText = $button.text();

            // Mark as processing
            $button.data('processing', true).prop('disabled', true);

            // Check if schedule date is already set
            var $scheduleInput = $('#cloudxm_nfe_schedule_date');
            var scheduleDate = $scheduleInput.length > 0 ? $scheduleInput.val() : '';

            if (scheduleDate !== '') {
                // Date is set, save it first, then reschedule
                saveScheduleDateThenReschedule(orderId, ajaxUrl, scheduleDate, $button, originalText);
            } else {
                // No date set, open modal to choose
                $button.data('processing', false).prop('disabled', false);
                openScheduleModal(orderId, ajaxUrl, true, false);
            }
        });

        // Download PDF
        $(document).on('click', '.cloudxm-nfe-download-pdf', function(e) {
            e.preventDefault();
            var url = $(this).attr('href');
            if (url) {
                window.open(url, '_blank');
            }
        });

        // ---- Per-order flag actions (CLO-11) ----

        // Set Ready Now flag
        $(document).on('click', '.cloudxm-nfe-set-ready-now', function() {
            var $button = $(this);
            var orderId = $button.data('order-id');
            var ajaxUrl = cloudxm_nfe_admin.ajax_url;
            var originalText = $button.text();

            if (!confirm('' + cloudxm_nfe_admin.i18n.confirm_issue)) {
                return;
            }

            $button.prop('disabled', true).text(cloudxm_nfe_admin.i18n.issuing);

            $.ajax({
                url: ajaxUrl,
                method: 'POST',
                data: {
                    action: 'cloudxm_nfe_set_ready_now',
                    order_id: orderId,
                    nonce: cloudxm_nfe_admin.nonces.set_ready_now
                },
                success: function(response) {
                    if (response.success) {
                        alert(cloudxm_nfe_admin.i18n.success_issue);
                        location.reload();
                    } else {
                        cloudxmShowInlineError(cloudxmExtractResponseMessage(response, cloudxm_nfe_admin.i18n.error_issue));
                        $button.prop('disabled', false).text(originalText);
                    }
                },
                error: function(xhr) {
                    cloudxmShowInlineError(cloudxmNfeAjaxError(xhr, cloudxm_nfe_admin.i18n.error_issue));
                    $button.prop('disabled', false).text(originalText);
                }
            });
        });

        // Download XML
        $(document).on('click', '.cloudxm-nfe-download-xml', function(e) {
            e.preventDefault();
            var url = $(this).attr('href');
            if (url) {
                window.open(url, '_blank');
            }
        });
    });

    /**
     * Create cancellation modal
     */
    function createCancellationModal() {
        var modal = $('#cloudxm-nfe-cancel-modal');

        // If modal already exists, don't recreate
        if (modal.length > 0) {
            return;
        }

        // Create modal HTML
        $('body').append(
            '<div id="cloudxm-nfe-cancel-modal" class="cloudxm-nfe-modal-overlay" style="display:none;">' +
                '<div class="cloudxm-nfe-modal">' +
                    '<h2>' + cloudxm_nfe_admin.i18n.prompt_cancel + '</h2>' +
                    '<div class="cloudxm-nfe-modal-content">' +
                        '<label for="cancel-reason">' + cloudxm_nfe_admin.i18n.cancellation_reason + ' <span class="required">*</span></label>' +
                        '<textarea id="cancel-reason" class="cloudxm-nfe-textarea" rows="5" maxlength="255" placeholder="' + cloudxm_nfe_admin.i18n.prompt_cancel_placeholder + '"></textarea>' +
                        '<div class="cloudxm-nfe-character-count"><span id="char-count">0</span> / 255 ' + cloudxm_nfe_admin.i18n.characters + '</div>' +
                    '</div>' +
                    '<div class="cloudxm-nfe-modal-footer">' +
                        '<button type="button" class="button button-secondary" id="cancel-modal-cancel">' + cloudxm_nfe_admin.i18n.cancel + '</button>' +
                        '<button type="button" class="button button-primary button-small-danger" id="cancel-modal-confirm">' + cloudxm_nfe_admin.i18n.cancel_button + '</button>' +
                    '</div>' +
                '</div>' +
            '</div>'
        );

        // Add event listeners
        $('#cancel-modal-cancel').on('click', closeCancellationModal);
        $('#cancel-modal-confirm').on('click', function() {
            performCancellation();
        });

        // Character counter
        $('#cancel-reason').on('input', function() {
            var length = $(this).val().length;
            $('#char-count').text(length);

            // Enable/disable confirm button
            if (length === 0) {
                $('#cancel-modal-confirm').prop('disabled', true);
            } else {
                $('#cancel-modal-confirm').prop('disabled', false);
            }
        });

        // Close on overlay click
        $('.cloudxm-nfe-modal-overlay').on('click', function(e) {
            if (e.target === this) {
                closeCancellationModal();
            }
        });

        // Close on ESC key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                closeCancellationModal();
            }
        });
    }

    /**
     * Create force unlock modal
     */
    function createForceUnlockModal() {
        var modal = $('#cloudxm-nfe-force-unlock-modal');

        // If modal already exists, don't recreate
        if (modal.length > 0) {
            return;
        }

        // Create modal HTML
        $('body').append(
            '<div id="cloudxm-nfe-force-unlock-modal" class="cloudxm-nfe-modal-overlay" style="display:none;">' +
                '<div class="cloudxm-nfe-modal">' +
                    '<h2>' + cloudxm_nfe_admin.i18n.prompt_force_unlock + '</h2>' +
                    '<div class="cloudxm-nfe-modal-content">' +
                        '<label for="unlock-reason">' + cloudxm_nfe_admin.i18n.force_unlock_reason + ' <span class="required">*</span></label>' +
                        '<textarea id="unlock-reason" class="cloudxm-nfe-textarea" rows="5" maxlength="255" placeholder="' + cloudxm_nfe_admin.i18n.prompt_force_unlock_placeholder + '"></textarea>' +
                        '<div class="cloudxm-nfe-character-count"><span id="unlock-char-count">0</span> / 255 ' + cloudxm_nfe_admin.i18n.characters + '</div>' +
                    '</div>' +
                    '<div class="cloudxm-nfe-modal-footer">' +
                        '<button type="button" class="button button-secondary" id="unlock-modal-cancel">' + cloudxm_nfe_admin.i18n.cancel + '</button>' +
                        '<button type="button" class="button button-primary button-small-danger" id="unlock-modal-confirm">' + cloudxm_nfe_admin.i18n.force_unlock_button + '</button>' +
                    '</div>' +
                '</div>' +
            '</div>'
        );

        // Add event listeners
        $('#unlock-modal-cancel').on('click', closeForceUnlockModal);
        $('#unlock-modal-confirm').on('click', function() {
            performForceUnlock();
        });

        // Character counter
        $('#unlock-reason').on('input', function() {
            var length = $(this).val().length;
            $('#unlock-char-count').text(length);

            // Enable/disable confirm button
            if (length === 0) {
                $('#unlock-modal-confirm').prop('disabled', true);
            } else {
                $('#unlock-modal-confirm').prop('disabled', false);
            }
        });

        // Close on overlay click
        $('.cloudxm-nfe-modal-overlay').on('click', function(e) {
            if (e.target === this) {
                closeForceUnlockModal();
            }
        });

        // Close on ESC key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                closeForceUnlockModal();
            }
        });
    }

    function createDpsRecoveryModal() {
        var modal = $('#cloudxm-nfe-dps-recovery-modal');

        if (modal.length > 0) {
            return;
        }

        $('body').append(
            '<div id="cloudxm-nfe-dps-recovery-modal" class="cloudxm-nfe-modal-overlay" style="display:none;">' +
                '<div class="cloudxm-nfe-modal">' +
                    '<h2>' + cloudxm_nfe_admin.i18n.recover_dps_title + '</h2>' +
                    '<div class="cloudxm-nfe-modal-content">' +
                        '<div>' +
                            '<label for="dps-recovery-series">' + cloudxm_nfe_admin.i18n.recover_dps_series + ' <span class="required">*</span></label>' +
                            '<input type="text" id="dps-recovery-series" class="regular-text" maxlength="10" placeholder="' + cloudxm_nfe_admin.i18n.recover_dps_series_placeholder + '">' +
                        '</div>' +
                        '<div>' +
                            '<label for="dps-recovery-number">' + cloudxm_nfe_admin.i18n.recover_dps_number + ' <span class="required">*</span></label>' +
                            '<input type="text" id="dps-recovery-number" class="regular-text" maxlength="15" placeholder="' + cloudxm_nfe_admin.i18n.recover_dps_number_placeholder + '">' +
                        '</div>' +
                    '</div>' +
                    '<div class="cloudxm-nfe-modal-footer">' +
                        '<button type="button" class="button button-secondary" id="dps-recovery-cancel">' + cloudxm_nfe_admin.i18n.cancel + '</button>' +
                        '<button type="button" class="button button-primary" id="dps-recovery-confirm" disabled>' + cloudxm_nfe_admin.i18n.recover_dps_title + '</button>' +
                    '</div>' +
                '</div>' +
            '</div>'
        );

        $('#dps-recovery-cancel').on('click', closeDpsRecoveryModal);

        $('#dps-recovery-confirm').on('click', function() {
            performDpsRecovery();
        });

        $('#dps-recovery-series, #dps-recovery-number').on('input', function() {
            var series = $('#dps-recovery-series').val().trim();
            var number = $('#dps-recovery-number').val().trim();
            $('#dps-recovery-confirm').prop('disabled', series === '' || number === '');
        });

        $('.cloudxm-nfe-modal-overlay').on('click', function(e) {
            if (e.target === this) {
                closeDpsRecoveryModal();
            }
        });

        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                closeDpsRecoveryModal();
            }
        });
    }

    function openDpsRecoveryModal(orderId, ajaxUrl, $button) {
        var originalText = $button.text();
        $('#cloudxm-nfe-dps-recovery-modal').data({
            orderId: orderId,
            ajaxUrl: ajaxUrl,
            button: $button,
            originalText: originalText
        });

        $('#dps-recovery-series').val('');
        $('#dps-recovery-number').val('');
        $('#dps-recovery-confirm').prop('disabled', true);

        $('#cloudxm-nfe-dps-recovery-modal').fadeIn(200);

        setTimeout(function() {
            $('#dps-recovery-series').focus();
        }, 250);
    }

    function closeDpsRecoveryModal() {
        $('#cloudxm-nfe-dps-recovery-modal').fadeOut(200);
    }

    function performDpsRecovery() {
        var modal = $('#cloudxm-nfe-dps-recovery-modal');
        var orderId = modal.data('orderId');
        var ajaxUrl = modal.data('ajaxUrl');
        var $button = modal.data('button');
        var originalText = modal.data('originalText');

        var series = $('#dps-recovery-series').val().trim();
        var number = $('#dps-recovery-number').val().trim();

        if (series === '' || number === '' || !/^\d+$/.test(series) || !/^\d+$/.test(number)) {
            alert(cloudxm_nfe_admin.i18n.recover_dps_invalid);
            return;
        }

        closeDpsRecoveryModal();

        createLoadingModal();
        showLoadingModal('recover', orderId);

        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            timeout: 60000,
            data: {
                action: 'cloudxm_nfe_recover_invoice',
                nonce: cloudxm_nfe_admin.nonces.recover_invoice,
                order_id: orderId,
                series: series,
                dps_number: parseInt(number, 10)
            },
            success: function(response) {
                if (response.success) {
                    updateLoadingComplete('recovered');
                    setTimeout(function() {
                        closeLoadingModal();
                        location.reload();
                    }, 1500);
                } else {
                    showLoadingError((response.data && response.data.message) || cloudxm_nfe_admin.i18n.error_recover_dps);
                    $button.prop('disabled', false).text(originalText);
                }
            },
            error: function(xhr) {
                showLoadingError(cloudxmNfeAjaxError(xhr, cloudxm_nfe_admin.i18n.error_recover_dps));
                $button.prop('disabled', false).text(originalText);
            }
        });
    }

    /**
     * Open cancellation modal
     */
    function openCancellationModal(orderId, ajaxUrl, $button, originalText) {
        // Store current context
        $('#cloudxm-nfe-cancel-modal').data({
            orderId: orderId,
            ajaxUrl: ajaxUrl,
            button: $button,
            originalText: originalText
        });

        // Clear previous input
        $('#cancel-reason').val('');
        $('#char-count').text('0');
        $('#cancel-modal-confirm').prop('disabled', true);

        // Show modal
        $('#cloudxm-nfe-cancel-modal').fadeIn(200);

        // Focus textarea
        setTimeout(function() {
            $('#cancel-reason').focus();
        }, 100);
    }

    /**
     * Close cancellation modal
     */
    function closeCancellationModal() {
        $('#cloudxm-nfe-cancel-modal').fadeOut(200);
    }

    /**
     * Perform cancellation
     */
    function performCancellation() {
        var reason = $('#cancel-reason').val().trim();

        if (!reason) {
            return;
        }

        var modal = $('#cloudxm-nfe-cancel-modal');
        var orderId = modal.data('orderId');
        var ajaxUrl = modal.data('ajaxUrl');

        // Close modal
        closeCancellationModal();

        // Show loading modal
        showLoadingModal('cancel', orderId);

        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: {
                action: 'cloudxm_nfe_cancel_order',
                order_id: orderId,
                reason: reason,
                nonce: cloudxm_nfe_admin.nonces.cancel_order
            },
            success: function(response) {
                console.log('CloudXM NFe: Cancel response:', response);
                if (response.success) {
                    updateLoadingComplete('cancelled');
                    setTimeout(function() {
                        closeLoadingModal();
                        location.reload();
                    }, 1500);
                } else {
                    showLoadingError(response.data.message || cloudxm_nfe_admin.i18n.error_cancel);
                }
            },
            error: function(xhr, status, error) {
                console.error('CloudXM NFe: Cancel AJAX error:', status, error);
                console.error('CloudXM NFe: Response:', xhr.responseText);
                showLoadingError(cloudxm_nfe_admin.i18n.error_cancel);
            }
        });
    }

    /**
     * Open force unlock modal
     */
    function openForceUnlockModal(orderId, ajaxUrl, $button, originalText) {
        // Store current context
        $('#cloudxm-nfe-force-unlock-modal').data({
            orderId: orderId,
            ajaxUrl: ajaxUrl,
            button: $button,
            originalText: originalText
        });

        // Clear previous input
        $('#unlock-reason').val('');
        $('#unlock-char-count').text('0');
        $('#unlock-modal-confirm').prop('disabled', true);

        // Show modal
        $('#cloudxm-nfe-force-unlock-modal').fadeIn(200);

        // Focus textarea
        setTimeout(function() {
            $('#unlock-reason').focus();
        }, 100);
    }

    /**
     * Close force unlock modal
     */
    function closeForceUnlockModal() {
        $('#cloudxm-nfe-force-unlock-modal').fadeOut(200);
    }

    /**
     * Perform force unlock
     */
    function performForceUnlock() {
        var reason = $('#unlock-reason').val().trim();

        if (!reason) {
            return;
        }

        var modal = $('#cloudxm-nfe-force-unlock-modal');
        var orderId = modal.data('orderId');
        var ajaxUrl = modal.data('ajaxUrl');
        var $button = modal.data('button');
        var originalText = modal.data('originalText');

        // Close modal
        closeForceUnlockModal();

        // Disable button
        $button.prop('disabled', true).text(cloudxm_nfe_admin.i18n.force_unlocking);

        console.log('CloudXM NFe: Reason provided:', reason);

        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: {
                action: 'cloudxm_nfe_force_unlock',
                order_id: orderId,
                reason: reason,
                nonce: cloudxm_nfe_admin.nonces.force_unlock
            },
            beforeSend: function() {
                console.log('CloudXM NFe: Force unlock AJAX request sending...');
            },
            success: function(response) {
                console.log('CloudXM NFe: Force unlock response:', response);
                if (response.success) {
                    alert(cloudxm_nfe_admin.i18n.success_force_unlock);
                    location.reload();
                } else {
                    cloudxmShowInlineError(cloudxmExtractResponseMessage(response, cloudxm_nfe_admin.i18n.error_force_unlock));
                    $button.prop('disabled', false).text(originalText);
                }
            },
            error: function(xhr, status, error) {
                console.error('CloudXM NFe: Force unlock AJAX error:', status, error);
                console.error('CloudXM NFe: Response:', xhr.responseText);
                cloudxmShowInlineError(cloudxmNfeAjaxError(xhr, cloudxm_nfe_admin.i18n.error_force_unlock));
                $button.prop('disabled', false).text(originalText);
            }
        });
    }

    /**
     * Auto-save schedule date if the field exists and has a value
     */
    function autoSaveScheduleDateIfNeeded(orderId, ajaxUrl, callback) {
        var $scheduleInput = $('#cloudxm_nfe_schedule_date');
        if ($scheduleInput.length === 0) {
            // No schedule date field, just call callback
            callback();
            return;
        }

        var scheduleDate = $scheduleInput.val();
        if (scheduleDate === '') {
            // Empty date, just call callback
            callback();
            return;
        }

        // Save the schedule date via AJAX
        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: {
                action: 'cloudxm_nfe_save_schedule_date',
                nonce: cloudxm_nfe_admin.nonces.save_schedule_date || '',
                order_id: orderId,
                schedule_date: scheduleDate
            },
            success: function(response) {
                if (response.success) {
                    // Date saved, call callback
                    callback();
                } else {
                    // Show error but still proceed (user can retry)
                    console.error('Error saving schedule date:', response.data && response.data.message);
                    callback();
                }
            },
            error: function() {
                // Show error but still proceed
                console.error('Error saving schedule date');
                callback();
            }
        });
    }

    /**
     * Create schedule modal
     */
    function createScheduleModal() {
        var modal = $('#cloudxm-nfe-schedule-modal');

        // If modal already exists, don't recreate
        if (modal.length > 0) {
            return;
        }

        // Create modal HTML
        $('body').append(
            '<div id="cloudxm-nfe-schedule-modal" class="cloudxm-nfe-modal-overlay" style="display:none;">' +
                '<div class="cloudxm-nfe-modal">' +
                    '<h2 id="schedule-modal-title">' + cloudxm_nfe_admin.i18n.prompt_schedule_date + '</h2>' +
                    '<div class="cloudxm-nfe-modal-content">' +
                        '<div id="schedule-custom-date" style="margin-top:12px;">' +
                            '<label for="schedule-date-time" style="display:block;margin-bottom:4px;">' +
                                '<input type="datetime-local" id="schedule-date-time" class="regular-text">' +
                            '</label>' +
                            '<p class="description" id="schedule-date-error" style="color:#dc3232;display:none;"></p>' +
                        '</div>' +
                    '</div>' +
                    '<div class="cloudxm-nfe-modal-footer">' +
                        '<button type="button" class="button button-secondary" id="schedule-modal-cancel">' + cloudxm_nfe_admin.i18n.cancel + '</button>' +
                        '<button type="button" class="button button-primary" id="schedule-modal-confirm">' + cloudxm_nfe_admin.i18n.schedule_button + '</button>' +
                    '</div>' +
                '</div>' +
            '</div>'
        );

        // Add event listeners
        $('#schedule-modal-cancel').on('click', closeScheduleModal);
        $('#schedule-modal-confirm').on('click', function() {
            performSchedule();
        });

        // Validate custom date
        $('#schedule-date-time').on('change', function() {
            validateScheduleDate($(this).val());
        });

        // Close on overlay click
        $('#cloudxm-nfe-schedule-modal').on('click', function(e) {
            if (e.target === this) {
                closeScheduleModal();
            }
        });

        // Close on ESC key
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                closeScheduleModal();
            }
        });
    }

    /**
     * Open schedule modal
     */
    function openScheduleModal(orderId, ajaxUrl, isReschedule, isCancelledInvoice) {
        // Store current context
        $('#cloudxm-nfe-schedule-modal').data({
            orderId: orderId,
            ajaxUrl: ajaxUrl,
            isReschedule: isReschedule,
            isCancelledInvoice: isCancelledInvoice || false
        });

        // Set title
        var title = isReschedule ? cloudxm_nfe_admin.i18n.prompt_reschedule_date : cloudxm_nfe_admin.i18n.prompt_schedule_date;
        if (isCancelledInvoice) {
            title = cloudxm_nfe_admin.i18n.prompt_schedule_cancelled;
        }
        $('#schedule-modal-title').text(title);

        // Set button text
        var buttonText = isReschedule ? cloudxm_nfe_admin.i18n.reschedule_button : cloudxm_nfe_admin.i18n.schedule_button;
        if (isCancelledInvoice) {
            buttonText = cloudxm_nfe_admin.i18n.schedule_button;
        }
        $('#schedule-modal-confirm').text(buttonText);

        // Clear date input and show it
        $('#schedule-date-time').val('');
        $('#schedule-date-error').hide();

        // Show modal
        $('#cloudxm-nfe-schedule-modal').fadeIn(200);

        // Focus on date input
        setTimeout(function() {
            $('#schedule-date-time').focus();
        }, 100);
    }

    /**
     * Close schedule modal
     */
    function closeScheduleModal() {
        $('#cloudxm-nfe-schedule-modal').fadeOut(200);
    }

    /**
     * Validate schedule date
     */
    function validateScheduleDate(dateStr) {
        var $errorDiv = $('#schedule-date-error');
        $errorDiv.hide();

        if (!dateStr) {
            return false;
        }

        // datetime-local input sends "2026-04-23T09:00" (no timezone).
        // Append WP timezone offset so it's interpreted as São Paulo time.
        if (dateStr.indexOf('T') === -1) {
            dateStr = dateStr.replace(' ', 'T');
        }
        var selectedDate = new Date(dateStr + cloudxm_nfe_admin.timezone_offset);

        if (isNaN(selectedDate.getTime())) {
            $errorDiv.text(cloudxm_nfe_admin.i18n.error_invalid_date).show();
            return false;
        }

        if (selectedDate <= new Date()) {
            $errorDiv.text(cloudxm_nfe_admin.i18n.error_past_date).show();
            return false;
        }

        return true;
    }

    /**
     * Perform direct scheduling without modal (when date is already set)
     */
    function performDirectSchedule(orderId, ajaxUrl, customDate, isCancelledInvoice) {
        // Validate the date is not in the past
        if (!validateScheduleDate(customDate)) {
            alert(cloudxm_nfe_admin.i18n.error_past_date);
            return;
        }

        var loadingMsg = cloudxm_nfe_admin.i18n.scheduling;
        var $metaBox = $('.cloudxm-nfe-meta-box');
        $metaBox.css('position', 'relative').append(
            '<div class="cloudxm-nfe-loading-overlay" style="position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(255,255,255,0.8);display:flex;align-items:center;justify-content:center;z-index:10;">' +
                '<div style="text-align:center;">' +
                    '<span class="spinner is-active" style="float:none;margin:0;"></span>' +
                    '<p style="margin-top:10px;">' + loadingMsg + '</p>' +
                '</div>' +
            '</div>'
        );

        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: {
                action: 'cloudxm_nfe_schedule_order',
                order_id: orderId,
                nonce: cloudxm_nfe_admin.nonces.schedule_order,
                custom_schedule_date: customDate,
                is_cancelled_invoice: isCancelledInvoice ? '1' : '0'
            },
            success: function(response) {
                $('.cloudxm-nfe-loading-overlay').remove();
                if (response.success) {
                    alert(cloudxm_nfe_admin.i18n.success_schedule);
                    location.reload();
                } else {
                    cloudxmShowInlineError(cloudxmExtractResponseMessage(response, cloudxm_nfe_admin.i18n.error_schedule));
                }
            },
            error: function(xhr) {
                $('.cloudxm-nfe-loading-overlay').remove();
                cloudxmShowInlineError(cloudxmNfeAjaxError(xhr, cloudxm_nfe_admin.i18n.error_schedule));
            }
        });
    }

    /**
     * Save schedule date then reschedule
     */
    function saveScheduleDateThenReschedule(orderId, ajaxUrl, customDate, $button, originalText) {
        // First save the date to the external field
        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: {
                action: 'cloudxm_nfe_save_schedule_date',
                nonce: cloudxm_nfe_admin.nonces.save_schedule_date || '',
                order_id: orderId,
                schedule_date: customDate
            },
            success: function(response) {
                if (response.success) {
                    // Date saved, now reschedule
                    performDirectReschedule(orderId, ajaxUrl, customDate, $button, originalText);
                } else {
                    cloudxmShowInlineError(cloudxmExtractResponseMessage(response, 'Error saving schedule date.'));
                    if ($button) {
                        $button.data('processing', false).prop('disabled', false).text(originalText);
                    }
                }
            },
            error: function() {
                // Continue with reschedule anyway (use the value from input)
                performDirectReschedule(orderId, ajaxUrl, customDate, $button, originalText);
            }
        });
    }

    /**
     * Perform direct reschedule without modal (when date is already set)
     */
    function performDirectReschedule(orderId, ajaxUrl, customDate, $button, originalText) {
        // Validate the date is not in the past
        if (!validateScheduleDate(customDate)) {
            if ($button) {
                $button.data('processing', false).prop('disabled', false).text(originalText);
            }
            return;
        }

        var loadingMsg = cloudxm_nfe_admin.i18n.rescheduling;
        var $metaBox = $('.cloudxm-nfe-meta-box');
        $metaBox.css('position', 'relative').append(
            '<div class="cloudxm-nfe-loading-overlay" style="position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(255,255,255,0.8);display:flex;align-items:center;justify-content:center;z-index:10;">' +
                '<div style="text-align:center;">' +
                    '<span class="spinner is-active" style="float:none;margin:0;"></span>' +
                    '<p style="margin-top:10px;">' + loadingMsg + '</p>' +
                '</div>' +
            '</div>'
        );

        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: {
                action: 'cloudxm_nfe_reschedule',
                order_id: orderId,
                nonce: cloudxm_nfe_admin.nonces.reschedule,
                custom_schedule_date: customDate
            },
            success: function(response) {
                $('.cloudxm-nfe-loading-overlay').remove();
                if (response.success) {
                    alert(cloudxm_nfe_admin.i18n.success_reschedule);
                    location.reload();
                } else {
                    cloudxmShowInlineError(cloudxmExtractResponseMessage(response, cloudxm_nfe_admin.i18n.error_reschedule));
                    if ($button) {
                        $button.data('processing', false).prop('disabled', false).text(originalText);
                    }
                }
            },
            error: function(xhr) {
                $('.cloudxm-nfe-loading-overlay').remove();
                cloudxmShowInlineError(cloudxmNfeAjaxError(xhr, cloudxm_nfe_admin.i18n.error_reschedule));
                if ($button) {
                    $button.data('processing', false).prop('disabled', false).text(originalText);
                }
            }
        });
    }

    /**
     * Perform schedule
     */
    function performSchedule() {
        var modal = $('#cloudxm-nfe-schedule-modal');
        var orderId = modal.data('orderId');
        var ajaxUrl = modal.data('ajaxUrl');
        var isReschedule = modal.data('isReschedule');
        var isCancelledInvoice = modal.data('isCancelledInvoice') || false;
        var customDate = $('#schedule-date-time').val();

        // Validate date
        if (!customDate || !validateScheduleDate(customDate)) {
            return;
        }

        // Close modal
        closeScheduleModal();

        // Show loading state with a message
        var loadingMsg = isReschedule ? cloudxm_nfe_admin.i18n.rescheduling : cloudxm_nfe_admin.i18n.scheduling;
        var $metaBox = $('.cloudxm-nfe-meta-box');
        $metaBox.css('position', 'relative').append(
            '<div class="cloudxm-nfe-loading-overlay" style="position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(255,255,255,0.8);display:flex;align-items:center;justify-content:center;z-index:10;">' +
                '<div style="text-align:center;">' +
                    '<span class="spinner is-active" style="float:none;margin:0;"></span>' +
                    '<p style="margin-top:10px;">' + loadingMsg + '</p>' +
                '</div>' +
            '</div>'
        );

        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: {
                action: isReschedule ? 'cloudxm_nfe_reschedule' : 'cloudxm_nfe_schedule_order',
                order_id: orderId,
                nonce: isReschedule ? cloudxm_nfe_admin.nonces.reschedule : cloudxm_nfe_admin.nonces.schedule_order,
                custom_schedule_date: customDate,
                is_cancelled_invoice: isCancelledInvoice ? '1' : '0'
            },
            success: function(response) {
                $('.cloudxm-nfe-loading-overlay').remove();
                if (response.success) {
                    var successMsg = isReschedule ? cloudxm_nfe_admin.i18n.success_reschedule : cloudxm_nfe_admin.i18n.success_schedule;
                    alert(successMsg);
                    location.reload();
                } else {
                    cloudxmShowInlineError(cloudxmExtractResponseMessage(response, isReschedule ? cloudxm_nfe_admin.i18n.error_reschedule : cloudxm_nfe_admin.i18n.error_schedule));
                }
            },
            error: function(xhr) {
                $('.cloudxm-nfe-loading-overlay').remove();
                cloudxmShowInlineError(cloudxmNfeAjaxError(xhr, isReschedule ? cloudxm_nfe_admin.i18n.error_reschedule : cloudxm_nfe_admin.i18n.error_schedule));
            }
        });
    }

    /**
     * Create loading modal for NFe operations
     */
    function createLoadingModal() {
        var modal = $('#cloudxm-nfe-loading-modal');
        
        // If modal already exists, don't recreate
        if (modal.length > 0) {
            return;
        }

        // Create modal HTML
        $('body').append(
            '<div id="cloudxm-nfe-loading-modal" class="cloudxm-nfe-modal-overlay" style="display:none;">' +
                '<div class="cloudxm-nfe-modal">' +
                    '<div class="cloudxm-nfe-modal-header">' +
                        '<h2 id="loading-title">' + cloudxm_nfe_admin.i18n.processing_nfe + '</h2>' +
                        '<button type="button" class="cloudxm-nfe-modal-title-close" id="loading-close">&times;</button>' +
                    '</div>' +
                    '<div class="cloudxm-nfe-modal-content">' +
                        '<div class="cloudxm-nfe-spinner"></div>' +
                        '<p id="loading-message">' + cloudxm_nfe_admin.i18n.processing_issue + '</p>' +
                    '</div>' +
                '</div>' +
            '</div>'
        );

        // Add event listeners
        $('#loading-close').on('click', closeLoadingModal);
        $('.cloudxm-nfe-modal-overlay').on('click', function(e) {
            if (e.target === this) {
                closeLoadingModal();
            }
        });
    }

    /**
     * Show loading modal with operation type
     */
    function showLoadingModal(operationType, orderId) {
        var $modal = $('#cloudxm-nfe-loading-modal');
        var titles = {
            'issue': cloudxm_nfe_admin.i18n.issuing_nfe,
            'cancel': cloudxm_nfe_admin.i18n.cancelling_nfe,
            'reissue': cloudxm_nfe_admin.i18n.reissuing_nfe,
            'recover': cloudxm_nfe_admin.i18n.recovering_dps
        };
        var messages = {
            'issue': cloudxm_nfe_admin.i18n.processing_issue,
            'cancel': cloudxm_nfe_admin.i18n.processing_cancel,
            'reissue': cloudxm_nfe_admin.i18n.processing_reissue,
            'recover': cloudxm_nfe_admin.i18n.recover_dps_loading
        };

        var $spinner = $('.cloudxm-nfe-spinner');
        $spinner.removeClass('error').empty().show();
        $('#loading-title').text(titles[operationType]);
        $('#loading-message').text(messages[operationType]);
        $('#loading-close').html('&times;').prop('disabled', true).css('opacity', '0.5');
        $modal.fadeIn(200);
    }

    /**
     * Close loading modal
     */
    function closeLoadingModal() {
        var $modal = $('#cloudxm-nfe-loading-modal');
        $modal.fadeOut(200);
    }

    /**
     * Update loading modal with completion status
     */
    function updateLoadingComplete(status) {
        var $modal = $('#cloudxm-nfe-loading-modal');
        var $spinner = $('.cloudxm-nfe-spinner');
        
        var messages = {
            'issued': cloudxm_nfe_admin.i18n.nfe_issued_success,
            'cancelled': cloudxm_nfe_admin.i18n.nfe_cancelled_success,
            'recovered': cloudxm_nfe_admin.i18n.success_recover_dps,
            'unknown': cloudxm_nfe_admin.i18n.operation_completed
        };

        var message = messages[status] || messages['unknown'];
        
        $('#loading-title').text(cloudxm_nfe_admin.i18n.success);
        $('#loading-message').text(message);
        $('#loading-close').prop('disabled', false).css('opacity', '1');
    }

    /**
     * Show loading error
     */
    function showLoadingError(errorMessage) {
        var $modal = $('#cloudxm-nfe-loading-modal');
        var $spinner = $('.cloudxm-nfe-spinner');

        console.error('CloudXM NFe Operation Error:', errorMessage);

        var errorIcon = '<svg style="display:inline;vertical-align:middle;margin-right:8px;" viewBox="0 0 24 24" fill="none" stroke="#dc3232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="22" height="22"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>';

        $('#loading-title').html(errorIcon + cloudxm_nfe_admin.i18n.error);
        $spinner.hide();

        $('#loading-message').html(
            '<strong>' + cloudxm_nfe_admin.i18n.error + '</strong>' +
            '<div style="margin-top:10px;padding:10px;background:#fff3f3;border-left:3px solid #dc3232;word-wrap:break-word;max-height:200px;overflow-y:auto;font-size:13px;">' +
            $('<span>').text(errorMessage).html() +
            '</div>'
        );
        $('#loading-close').prop('disabled', false).css('opacity', '1');
    }

    // Description save handler
    $(document).on('click', '.cloudxm-nfe-save-description', function () {
        var $btn = $(this);
        var orderId = $btn.data('order-id');
        var description = $('#cloudxm_nfe_description').val();

        $btn.prop('disabled', true).text('...');

        $.ajax({
            url: cloudxm_nfe_admin.ajax_url,
            type: 'POST',
            data: {
                action: 'cloudxm_nfe_save_description',
                nonce: cloudxm_nfe_admin.nonces.save_description,
                order_id: orderId,
                description: description
            },
            success: function (response) {
                $btn.prop('disabled', false).text(cloudxm_nfe_admin.i18n.save_button || 'Save');
                if (response.success) {
                    $btn.text('✓');
                    setTimeout(function () {
                        $btn.text(cloudxm_nfe_admin.i18n.save_button || 'Save');
                    }, 2000);
                } else {
                    cloudxmShowInlineError(cloudxmExtractResponseMessage(response, 'Error saving description.'));
                }
            },
            error: function (xhr) {
                $btn.prop('disabled', false).text(cloudxm_nfe_admin.i18n.save_button || 'Save');
                cloudxmShowInlineError(cloudxmNfeAjaxError(xhr, 'Request failed.'));
            }
        });
    });

    // Schedule date save handler
    $(document).on('click', '.cloudxm-nfe-save-schedule-date', function () {
        var $btn = $(this);
        var orderId = $btn.data('order-id');
        var scheduleDate = $('#cloudxm_nfe_schedule_date').val();

        $btn.prop('disabled', true).text('...');

        $.ajax({
            url: cloudxm_nfe_admin.ajax_url,
            type: 'POST',
            data: {
                action: 'cloudxm_nfe_save_schedule_date',
                nonce: cloudxm_nfe_admin.nonces.save_schedule_date || '',
                order_id: orderId,
                schedule_date: scheduleDate
            },
            success: function (response) {
                $btn.prop('disabled', false).text(cloudxm_nfe_admin.i18n.save_button || 'Save');
                if (response.success) {
                    $btn.text('✓');
                    setTimeout(function () {
                        $btn.text(cloudxm_nfe_admin.i18n.save_button || 'Save');
                    }, 2000);
                    // Reload page to show updated state
                    location.reload();
                } else {
                    cloudxmShowInlineError(cloudxmExtractResponseMessage(response, 'Error saving schedule date.'));
                }
            },
            error: function (xhr) {
                $btn.prop('disabled', false).text(cloudxm_nfe_admin.i18n.save_button || 'Save');
                cloudxmShowInlineError(cloudxmNfeAjaxError(xhr, 'Request failed.'));
            }
        });
    });

    // Character counter for description textarea with line/column validation
    $(document).on('input', '#cloudxm_nfe_description', function () {
        var $textarea = $(this);
        var text = $textarea.val();
        var len = text.length;

        // Update character count
        $('#cloudxm-nfe-desc-char-count').text(len);

        // Get limits
        var maxColumns = parseInt($textarea.data('max-columns') || 165, 10);
        var maxLines = parseInt($textarea.data('max-lines') || 9, 10);

        // Count lines and check each line's length
        var lines = text.split('\n');
        var lineCount = lines.length;
        var maxLineLength = 0;
        var invalidLine = -1;

        for (var i = 0; i < lines.length; i++) {
            if (lines[i].length > maxLineLength) {
                maxLineLength = lines[i].length;
            }
            if (lines[i].length > maxColumns) {
                invalidLine = i + 1;
                break;
            }
        }

        // Update line and column counts
        $('#cloudxm-nfe-desc-line-count').text(lineCount);
        $('#cloudxm-nfe-desc-col-count').text(maxLineLength);

        // Show/hide validation warning
        var $warningDiv = $('#cloudxm-nfe-desc-validation-error');
        if (invalidLine > -1 || lineCount > maxLines) {
            var warningMsg = '';
            if (invalidLine > -1) {
                warningMsg = 'Linha ' + invalidLine + ' tem ' + lines[invalidLine - 1].length + ' caracteres (máximo: ' + maxColumns + ').';
            } else if (lineCount > maxLines) {
                warningMsg = 'Descrição tem ' + lineCount + ' linhas (máximo: ' + maxLines + ').';
            }
            $warningDiv.removeClass('notice-error').addClass('notice-warning');
            $warningDiv.find('p').text(warningMsg);
            $warningDiv.show();
        } else {
            $warningDiv.hide();
        }
    });

    /**
     * Save description before issuing NFe
     */
    function saveDescriptionBeforeIssue(orderId, ajaxUrl, $button) {
        var description = $('#cloudxm_nfe_description').val();

        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: {
                action: 'cloudxm_nfe_save_description',
                nonce: cloudxm_nfe_admin.nonces.save_description,
                order_id: orderId,
                description: description
            },
            success: function(response) {
                if (response.success) {
                    performIssue(orderId, ajaxUrl, $button);
                } else {
                    cloudxmShowInlineError(cloudxmExtractResponseMessage(response, 'Error saving description. NFe was not issued.'));
                }
            },
            error: function(xhr) {
                cloudxmShowInlineError(cloudxmNfeAjaxError(xhr, 'Failed to save description. Please try again.'));
            }
        });
    }

    /**
     * Perform NFe issue after description is saved
     */
    function performIssue(orderId, ajaxUrl, $button) {
        // Show loading modal
        showLoadingModal('issue', orderId);

        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: {
                action: 'cloudxm_nfe_issue_order',
                order_id: orderId,
                nonce: cloudxm_nfe_admin.nonces.issue_order
            },
            success: function(response) {
                console.log('CloudXM NFe: Issue response:', response);

                if (response.success) {
                    updateLoadingComplete('issued');
                    setTimeout(function() {
                        closeLoadingModal();
                        location.reload();
                    }, 1500);
                } else {
                    console.error('CloudXM NFe: Error response:', response);
                    showLoadingError(response.data.message || cloudxm_nfe_admin.i18n.error_issue);
                }
            },
            error: function(xhr, status, error) {
                console.error('CloudXM NFe: AJAX error:', status, error);
                console.error('CloudXM NFe: Response:', xhr.responseText);
                showLoadingError(cloudxm_nfe_admin.i18n.error_issue);
            }
        });
    }

})(jQuery);
