<?php
/**
 * Email Delivery Settings View - Setup Wizard
 *
 * @package Freelance_Studio
 * @since 8.6.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$status          = FS_Email_Delivery::get_status();
$provider        = $status['provider'];
$has_api_key     = $status['has_api_key'];
$setup_complete  = $status['setup_complete'];
$provider_label  = $status['provider_label'];
$business_email  = get_option( 'fs_business_email', get_option( 'admin_email' ) );
$nonce           = wp_create_nonce( 'fs_email_delivery' );
?>

<div class="fs-settings-section">
    <h2><?php esc_html_e( 'Email Delivery', 'freelance-studio' ); ?></h2>
    <p class="description mb-15"><?php esc_html_e( 'Set up reliable email delivery so your invoices, proposals, contracts, and booking confirmations always reach your clients.', 'freelance-studio' ); ?></p>

    <?php if ( $setup_complete ): ?>
    <!-- ===== CONFIGURED STATE ===== -->
    <div class="fs-email-delivery-status fs-email-delivery-status--active">
        <div class="fs-email-delivery-status-icon">
            <span class="dashicons dashicons-yes-alt"></span>
        </div>
        <div class="fs-email-delivery-status-info">
            <h3><?php esc_html_e( 'Email delivery is active', 'freelance-studio' ); ?></h3>
            <p>
                <?php
                printf(
                    /* translators: %s: provider name */
                    esc_html__( 'Emails are being sent through %s.', 'freelance-studio' ),
                    '<strong>' . esc_html( $provider_label ) . '</strong>'
                );
                ?>
                <?php if ( $status['last_test'] ): ?>
                    <span class="fs-email-delivery-last-test">
                        <?php
                        printf(
                            /* translators: %s: date */
                            esc_html__( 'Last test: %s', 'freelance-studio' ),
                            esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $status['last_test'] ) ) )
                        );
                        ?>
                    </span>
                <?php endif; ?>
            </p>
        </div>
        <div class="fs-email-delivery-status-actions">
            <button type="button" class="fs-btn fs-btn-secondary fs-btn-small" id="fs-email-delivery-send-test"><?php esc_html_e( 'Send Test Email', 'freelance-studio' ); ?></button>
            <button type="button" class="fs-btn fs-btn-secondary fs-btn-small" id="fs-email-delivery-reconfigure"><?php esc_html_e( 'Reconfigure', 'freelance-studio' ); ?></button>
        </div>
    </div>
    <div id="fs-email-delivery-test-result" style="display:none;"></div>
    <?php endif; ?>

    <!-- ===== WIZARD ===== -->
    <div id="fs-email-delivery-wizard" class="fs-email-delivery-wizard" <?php if ( $setup_complete ) echo 'style="display:none;"'; ?>>

        <!-- Step Indicators -->
        <div class="fs-wizard-steps">
            <div class="fs-wizard-step active" data-step="1">
                <span class="fs-wizard-step-number">1</span>
                <span class="fs-wizard-step-label"><?php esc_html_e( 'Choose Provider', 'freelance-studio' ); ?></span>
            </div>
            <div class="fs-wizard-step-line"></div>
            <div class="fs-wizard-step" data-step="2">
                <span class="fs-wizard-step-number">2</span>
                <span class="fs-wizard-step-label"><?php esc_html_e( 'Create Account', 'freelance-studio' ); ?></span>
            </div>
            <div class="fs-wizard-step-line"></div>
            <div class="fs-wizard-step" data-step="3">
                <span class="fs-wizard-step-number">3</span>
                <span class="fs-wizard-step-label"><?php esc_html_e( 'Connect', 'freelance-studio' ); ?></span>
            </div>
            <div class="fs-wizard-step-line"></div>
            <div class="fs-wizard-step" data-step="4">
                <span class="fs-wizard-step-number">4</span>
                <span class="fs-wizard-step-label"><?php esc_html_e( 'Test', 'freelance-studio' ); ?></span>
            </div>
        </div>

        <!-- ===== STEP 1: Choose Provider ===== -->
        <div class="fs-wizard-panel active" data-step="1">
            <h3><?php esc_html_e( 'How would you like to send emails?', 'freelance-studio' ); ?></h3>
            <p class="description"><?php esc_html_e( "Choose a delivery service to ensure your emails land in your clients' inboxes, not spam.", 'freelance-studio' ); ?></p>

            <div class="fs-provider-cards">
                <label class="fs-provider-card" data-provider="brevo">
                    <input type="radio" name="fs_email_provider" value="brevo" <?php checked( $provider, 'brevo' ); ?>>
                    <div class="fs-provider-card-inner">
                        <div class="fs-provider-card-header">
                            <span class="fs-provider-logo fs-provider-logo--brevo">B</span>
                            <div>
                                <strong>Brevo</strong>
                                <span class="fs-provider-badge fs-provider-badge--recommended"><?php esc_html_e( 'Recommended', 'freelance-studio' ); ?></span>
                            </div>
                        </div>
                        <p class="fs-provider-card-desc"><?php esc_html_e( 'Free plan includes 300 emails/day — more than enough for most freelancers. Quick setup, no credit card required.', 'freelance-studio' ); ?></p>
                        <div class="fs-provider-card-meta">
                            <span class="fs-provider-card-price"><?php esc_html_e( 'Free', 'freelance-studio' ); ?></span>
                            <span class="fs-provider-card-limit"><?php esc_html_e( '300 emails/day', 'freelance-studio' ); ?></span>
                        </div>
                    </div>
                </label>

                <label class="fs-provider-card" data-provider="postmark">
                    <input type="radio" name="fs_email_provider" value="postmark" <?php checked( $provider, 'postmark' ); ?>>
                    <div class="fs-provider-card-inner">
                        <div class="fs-provider-card-header">
                            <span class="fs-provider-logo fs-provider-logo--postmark">P</span>
                            <div>
                                <strong>Postmark</strong>
                                <span class="fs-provider-badge fs-provider-badge--fast"><?php esc_html_e( 'Fastest', 'freelance-studio' ); ?></span>
                            </div>
                        </div>
                        <p class="fs-provider-card-desc"><?php esc_html_e( 'Industry-leading delivery speed (~3 seconds). Best deliverability rates. Account approval required.', 'freelance-studio' ); ?></p>
                        <div class="fs-provider-card-meta">
                            <span class="fs-provider-card-price"><?php esc_html_e( '100 free/mo', 'freelance-studio' ); ?></span>
                            <span class="fs-provider-card-limit"><?php esc_html_e( 'then pay-as-you-go', 'freelance-studio' ); ?></span>
                        </div>
                    </div>
                </label>

                <label class="fs-provider-card" data-provider="smtp_plugin">
                    <input type="radio" name="fs_email_provider" value="smtp_plugin" <?php checked( $provider, 'smtp_plugin' ); ?>>
                    <div class="fs-provider-card-inner">
                        <div class="fs-provider-card-header">
                            <span class="fs-provider-logo fs-provider-logo--smtp"><span class="dashicons dashicons-admin-plugins"></span></span>
                            <div>
                                <strong><?php esc_html_e( 'I already use an SMTP plugin', 'freelance-studio' ); ?></strong>
                            </div>
                        </div>
                        <p class="fs-provider-card-desc"><?php esc_html_e( "If you already have WP Mail SMTP, Post SMTP, or another email plugin configured, you're all set.", 'freelance-studio' ); ?></p>
                        <div class="fs-provider-card-meta">
                            <span class="fs-provider-card-price">&nbsp;</span>
                            <span class="fs-provider-card-limit"><?php esc_html_e( 'No extra setup needed', 'freelance-studio' ); ?></span>
                        </div>
                    </div>
                </label>
            </div>

            <div class="fs-wizard-actions">
                <button type="button" class="fs-btn fs-btn-primary" id="fs-wizard-step1-next" disabled><?php esc_html_e( 'Continue', 'freelance-studio' ); ?></button>
            </div>
        </div>

        <!-- ===== STEP 2: Create Account ===== -->
        <div class="fs-wizard-panel" data-step="2">
            
            <!-- Brevo instructions -->
            <div class="fs-provider-instructions" data-provider="brevo" style="display:none;">
                <h3><?php esc_html_e( 'Set up your Brevo account', 'freelance-studio' ); ?></h3>
                <div class="fs-setup-steps">
                    <div class="fs-setup-step">
                        <span class="fs-setup-step-number">1</span>
                        <div class="fs-setup-step-content">
                            <strong><?php esc_html_e( 'Create a free account', 'freelance-studio' ); ?></strong>
                            <p><?php esc_html_e( 'Sign up at Brevo — no credit card required.', 'freelance-studio' ); ?></p>
                            <a href="https://app.brevo.com/account/register" target="_blank" rel="noopener" class="fs-btn fs-btn-secondary fs-btn-small"><?php esc_html_e( 'Open Brevo Signup', 'freelance-studio' ); ?> <span class="dashicons dashicons-external" style="font-size:14px; line-height:1.6;"></span></a>
                        </div>
                    </div>
                    <div class="fs-setup-step">
                        <span class="fs-setup-step-number">2</span>
                        <div class="fs-setup-step-content">
                            <strong><?php esc_html_e( 'Verify your domain', 'freelance-studio' ); ?></strong>
                            <p><?php esc_html_e( 'In your Brevo dashboard, go to Senders, Domains & Dedicated IPs → Domains. Add your website domain and follow the steps to add the DNS records. This ensures your emails pass authentication.', 'freelance-studio' ); ?></p>
                        </div>
                    </div>
                    <div class="fs-setup-step">
                        <span class="fs-setup-step-number">3</span>
                        <div class="fs-setup-step-content">
                            <strong><?php esc_html_e( 'Get your API key', 'freelance-studio' ); ?></strong>
                            <p><?php esc_html_e( 'Go to SMTP & API → API Keys → Generate a new API key. Copy the key — you\'ll paste it in the next step.', 'freelance-studio' ); ?></p>
                            <a href="https://app.brevo.com/settings/keys/api" target="_blank" rel="noopener" class="fs-btn fs-btn-secondary fs-btn-small"><?php esc_html_e( 'Open Brevo API Keys', 'freelance-studio' ); ?> <span class="dashicons dashicons-external" style="font-size:14px; line-height:1.6;"></span></a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Postmark instructions -->
            <div class="fs-provider-instructions" data-provider="postmark" style="display:none;">
                <h3><?php esc_html_e( 'Set up your Postmark account', 'freelance-studio' ); ?></h3>
                <div class="fs-setup-steps">
                    <div class="fs-setup-step">
                        <span class="fs-setup-step-number">1</span>
                        <div class="fs-setup-step-content">
                            <strong><?php esc_html_e( 'Create an account', 'freelance-studio' ); ?></strong>
                            <p><?php esc_html_e( 'Sign up at Postmark. Note: Postmark reviews new accounts to keep spam off their network, so approval may take a few hours.', 'freelance-studio' ); ?></p>
                            <a href="https://account.postmarkapp.com/sign_up" target="_blank" rel="noopener" class="fs-btn fs-btn-secondary fs-btn-small"><?php esc_html_e( 'Open Postmark Signup', 'freelance-studio' ); ?> <span class="dashicons dashicons-external" style="font-size:14px; line-height:1.6;"></span></a>
                        </div>
                    </div>
                    <div class="fs-setup-step">
                        <span class="fs-setup-step-number">2</span>
                        <div class="fs-setup-step-content">
                            <strong><?php esc_html_e( 'Verify your sending domain', 'freelance-studio' ); ?></strong>
                            <p><?php esc_html_e( 'In your Postmark dashboard, go to Sender Signatures and add your domain. Follow the DNS verification steps.', 'freelance-studio' ); ?></p>
                        </div>
                    </div>
                    <div class="fs-setup-step">
                        <span class="fs-setup-step-number">3</span>
                        <div class="fs-setup-step-content">
                            <strong><?php esc_html_e( 'Get your Server API Token', 'freelance-studio' ); ?></strong>
                            <p><?php esc_html_e( 'Go to your Server → API Tokens. Copy the Server API Token (not the Account API Token).', 'freelance-studio' ); ?></p>
                            <a href="https://account.postmarkapp.com/servers" target="_blank" rel="noopener" class="fs-btn fs-btn-secondary fs-btn-small"><?php esc_html_e( 'Open Postmark Servers', 'freelance-studio' ); ?> <span class="dashicons dashicons-external" style="font-size:14px; line-height:1.6;"></span></a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- SMTP plugin instructions -->
            <div class="fs-provider-instructions" data-provider="smtp_plugin" style="display:none;">
                <h3><?php esc_html_e( 'Using an existing SMTP plugin', 'freelance-studio' ); ?></h3>
                <div class="fs-setup-steps">
                    <div class="fs-setup-step">
                        <span class="fs-setup-step-number"><span class="dashicons dashicons-yes"></span></span>
                        <div class="fs-setup-step-content">
                            <strong><?php esc_html_e( "You're all set!", 'freelance-studio' ); ?></strong>
                            <p><?php esc_html_e( 'Freelance Studio uses WordPress\'s standard wp_mail() function, so any SMTP plugin you have configured will automatically handle delivery of all emails — invoices, contracts, proposals, booking confirmations, and more.', 'freelance-studio' ); ?></p>
                            <p class="description"><?php esc_html_e( 'We recommend sending a test email below to make sure everything is working correctly.', 'freelance-studio' ); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="fs-wizard-actions">
                <button type="button" class="fs-btn fs-btn-secondary" id="fs-wizard-step2-back"><?php esc_html_e( 'Back', 'freelance-studio' ); ?></button>
                <button type="button" class="fs-btn fs-btn-primary" id="fs-wizard-step2-next"><?php esc_html_e( 'Continue', 'freelance-studio' ); ?></button>
            </div>
        </div>

        <!-- ===== STEP 3: Connect (API Key) ===== -->
        <div class="fs-wizard-panel" data-step="3">
            
            <!-- API key input for Brevo/Postmark -->
            <div class="fs-api-key-section" data-provider="brevo" style="display:none;">
                <h3><?php esc_html_e( 'Enter your Brevo API key', 'freelance-studio' ); ?></h3>
                <p class="description"><?php esc_html_e( 'Paste the API key you generated in the previous step.', 'freelance-studio' ); ?></p>
                <div class="fs-api-key-input-wrap">
                    <input type="text" id="fs-brevo-api-key" class="regular-text fs-api-key-input" placeholder="xkeysib-xxxxxxxx..." autocomplete="off" spellcheck="false" value="<?php echo $provider === 'brevo' && $has_api_key ? '••••••••••••••••••••' : ''; ?>">
                    <button type="button" class="fs-btn fs-btn-primary fs-btn-small fs-verify-key-btn" data-provider="brevo"><?php esc_html_e( 'Verify Connection', 'freelance-studio' ); ?></button>
                </div>
                <div class="fs-api-key-result" id="fs-brevo-key-result"></div>
            </div>

            <div class="fs-api-key-section" data-provider="postmark" style="display:none;">
                <h3><?php esc_html_e( 'Enter your Postmark Server API Token', 'freelance-studio' ); ?></h3>
                <p class="description"><?php esc_html_e( 'Paste the Server API Token from your Postmark server settings.', 'freelance-studio' ); ?></p>
                <div class="fs-api-key-input-wrap">
                    <input type="text" id="fs-postmark-api-key" class="regular-text fs-api-key-input" placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" autocomplete="off" spellcheck="false" value="<?php echo $provider === 'postmark' && $has_api_key ? '••••••••••••••••••••' : ''; ?>">
                    <button type="button" class="fs-btn fs-btn-primary fs-btn-small fs-verify-key-btn" data-provider="postmark"><?php esc_html_e( 'Verify Connection', 'freelance-studio' ); ?></button>
                </div>
                <div class="fs-api-key-result" id="fs-postmark-key-result"></div>
            </div>

            <!-- SMTP plugin skip message -->
            <div class="fs-api-key-section" data-provider="smtp_plugin" style="display:none;">
                <h3><?php esc_html_e( 'No API key needed', 'freelance-studio' ); ?></h3>
                <p><?php esc_html_e( "Your SMTP plugin handles the connection. Let's skip ahead and send a test email to verify it's working.", 'freelance-studio' ); ?></p>
            </div>

            <div class="fs-wizard-actions">
                <button type="button" class="fs-btn fs-btn-secondary" id="fs-wizard-step3-back"><?php esc_html_e( 'Back', 'freelance-studio' ); ?></button>
                <button type="button" class="fs-btn fs-btn-primary" id="fs-wizard-step3-next" disabled><?php esc_html_e( 'Continue', 'freelance-studio' ); ?></button>
            </div>
        </div>

        <!-- ===== STEP 4: Test ===== -->
        <div class="fs-wizard-panel" data-step="4">
            <h3><?php esc_html_e( "Let's make sure it works!", 'freelance-studio' ); ?></h3>
            <p class="description">
                <?php
                printf(
                    /* translators: %s: business email */
                    esc_html__( 'We\'ll send a test email to %s to confirm everything is configured correctly.', 'freelance-studio' ),
                    '<strong>' . esc_html( $business_email ) . '</strong>'
                );
                ?>
            </p>

            <div class="fs-test-email-section">
                <button type="button" class="fs-btn fs-btn-accent" id="fs-wizard-send-test">
                    <span class="dashicons dashicons-email-alt" style="font-size:18px; line-height:1.3; margin-right:4px;"></span>
                    <?php esc_html_e( 'Send Test Email', 'freelance-studio' ); ?>
                </button>
                <div id="fs-wizard-test-result" class="fs-wizard-test-result"></div>
            </div>

            <div class="fs-wizard-actions">
                <button type="button" class="fs-btn fs-btn-secondary" id="fs-wizard-step4-back"><?php esc_html_e( 'Back', 'freelance-studio' ); ?></button>
                <button type="button" class="fs-btn fs-btn-primary" id="fs-wizard-finish"><?php esc_html_e( 'Complete Setup', 'freelance-studio' ); ?></button>
            </div>
        </div>

    </div><!-- /.fs-email-delivery-wizard -->
</div>

<script>
jQuery(function($) {
    var selectedProvider = '<?php echo esc_js( $provider ); ?>';
    var nonce = '<?php echo esc_js( $nonce ); ?>';
    var keyVerified = false;
    var currentStep = 1;

    // Provider selection
    $('input[name="fs_email_provider"]').on('change', function() {
        selectedProvider = $(this).val();
        $('.fs-provider-card').removeClass('selected');
        $(this).closest('.fs-provider-card').addClass('selected');
        $('#fs-wizard-step1-next').prop('disabled', false);
    });

    // Pre-select if already configured
    if (selectedProvider) {
        $('input[name="fs_email_provider"][value="' + selectedProvider + '"]').trigger('change');
    }

    // Clicking the card also selects it
    $('.fs-provider-card').on('click', function() {
        $(this).find('input[type="radio"]').prop('checked', true).trigger('change');
    });

    function goToStep(step) {
        currentStep = step;
        
        // Update step indicators
        $('.fs-wizard-step').each(function() {
            var s = $(this).data('step');
            $(this).toggleClass('active', s === step).toggleClass('completed', s < step);
        });

        // Show/hide panels
        $('.fs-wizard-panel').removeClass('active');
        $('.fs-wizard-panel[data-step="' + step + '"]').addClass('active');

        // Show provider-specific content
        if (step >= 2) {
            $('.fs-provider-instructions, .fs-api-key-section').hide();
            $('.fs-provider-instructions[data-provider="' + selectedProvider + '"]').show();
            $('.fs-api-key-section[data-provider="' + selectedProvider + '"]').show();
        }

        // Step 3: enable Continue for smtp_plugin (no key needed)
        if (step === 3 && selectedProvider === 'smtp_plugin') {
            $('#fs-wizard-step3-next').prop('disabled', false);
        }
    }

    // Navigation
    $('#fs-wizard-step1-next').on('click', function() {
        if (!selectedProvider) return;
        // If SMTP plugin, skip step 2 instructions (still show the note)
        goToStep(2);
    });

    $('#fs-wizard-step2-back').on('click', function() { goToStep(1); });
    $('#fs-wizard-step2-next').on('click', function() {
        if (selectedProvider === 'smtp_plugin') {
            // Skip API key step, go straight to test
            goToStep(4);
        } else {
            goToStep(3);
        }
    });

    $('#fs-wizard-step3-back').on('click', function() { goToStep(2); });
    $('#fs-wizard-step3-next').on('click', function() {
        if (keyVerified || selectedProvider === 'smtp_plugin') {
            goToStep(4);
        }
    });

    $('#fs-wizard-step4-back').on('click', function() {
        if (selectedProvider === 'smtp_plugin') {
            goToStep(2);
        } else {
            goToStep(3);
        }
    });

    // Verify API key
    $('.fs-verify-key-btn').on('click', function() {
        var $btn = $(this);
        var provider = $btn.data('provider');
        var $input = $btn.closest('.fs-api-key-input-wrap').find('.fs-api-key-input');
        var apiKey = $input.val().trim();
        var $result = $('#fs-' + provider + '-key-result');

        if (!apiKey || apiKey.indexOf('•') !== -1) {
            $result.html('<div class="fs-key-result-error"><span class="dashicons dashicons-warning"></span> ' + '<?php echo esc_js( __( 'Please enter your API key.', 'freelance-studio' ) ); ?>' + '</div>');
            return;
        }

        $btn.prop('disabled', true).text('<?php echo esc_js( __( 'Verifying...', 'freelance-studio' ) ); ?>');
        $result.html('');

        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'fs_email_delivery_verify_key',
                nonce: nonce,
                provider: provider,
                api_key: apiKey
            },
            success: function(response) {
                if (response.success) {
                    $result.html('<div class="fs-key-result-success"><span class="dashicons dashicons-yes-alt"></span> ' + response.data.message + '</div>');
                    keyVerified = true;
                    $('#fs-wizard-step3-next').prop('disabled', false);
                } else {
                    $result.html('<div class="fs-key-result-error"><span class="dashicons dashicons-warning"></span> ' + response.data.message + '</div>');
                    keyVerified = false;
                    $('#fs-wizard-step3-next').prop('disabled', true);
                }
            },
            error: function() {
                $result.html('<div class="fs-key-result-error"><span class="dashicons dashicons-warning"></span> ' + '<?php echo esc_js( __( 'Connection error. Please try again.', 'freelance-studio' ) ); ?>' + '</div>');
            },
            complete: function() {
                $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Verify Connection', 'freelance-studio' ) ); ?>');
            }
        });
    });

    // Send test email (wizard)
    $('#fs-wizard-send-test').on('click', function() {
        var $btn = $(this);
        var $result = $('#fs-wizard-test-result');

        $btn.prop('disabled', true);
        $btn.html('<span class="dashicons dashicons-update spin" style="font-size:18px; line-height:1.3; margin-right:4px;"></span> <?php echo esc_js( __( 'Sending...', 'freelance-studio' ) ); ?>');
        $result.html('');

        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'fs_email_delivery_send_test',
                nonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    $result.html('<div class="fs-test-result-success"><span class="dashicons dashicons-yes-alt"></span> ' + response.data.message + '</div>');
                } else {
                    $result.html('<div class="fs-test-result-error"><span class="dashicons dashicons-warning"></span> ' + response.data.message + '</div>');
                }
            },
            error: function() {
                $result.html('<div class="fs-test-result-error"><span class="dashicons dashicons-warning"></span> <?php echo esc_js( __( 'Connection error. Please try again.', 'freelance-studio' ) ); ?></div>');
            },
            complete: function() {
                $btn.prop('disabled', false);
                $btn.html('<span class="dashicons dashicons-email-alt" style="font-size:18px; line-height:1.3; margin-right:4px;"></span> <?php echo esc_js( __( 'Send Test Email', 'freelance-studio' ) ); ?>');
            }
        });
    });

    // Complete setup
    $('#fs-wizard-finish').on('click', function() {
        var $btn = $(this);
        $btn.prop('disabled', true).text('<?php echo esc_js( __( 'Saving...', 'freelance-studio' ) ); ?>');

        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'fs_email_delivery_complete_setup',
                nonce: nonce,
                provider: selectedProvider
            },
            success: function(response) {
                if (response.success) {
                    // Reload to show the configured state
                    window.location.href = '<?php echo esc_js( admin_url( 'admin.php?page=fs-settings&tab=email_delivery&message=saved' ) ); ?>';
                } else {
                    $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Complete Setup', 'freelance-studio' ) ); ?>');
                }
            }
        });
    });

    // Send test from configured state
    $('#fs-email-delivery-send-test').on('click', function() {
        var $btn = $(this);
        var $result = $('#fs-email-delivery-test-result');

        $btn.prop('disabled', true).text('<?php echo esc_js( __( 'Sending...', 'freelance-studio' ) ); ?>');
        $result.show().html('<p style="color: var(--fs-gray-600);"><span class="dashicons dashicons-update spin" style="font-size:16px;"></span> <?php echo esc_js( __( 'Sending test email...', 'freelance-studio' ) ); ?></p>');

        $.ajax({
            url: fs_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'fs_email_delivery_send_test',
                nonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    $result.html('<div class="fs-test-result-success" style="margin-top:12px;"><span class="dashicons dashicons-yes-alt"></span> ' + response.data.message + '</div>');
                } else {
                    $result.html('<div class="fs-test-result-error" style="margin-top:12px;"><span class="dashicons dashicons-warning"></span> ' + response.data.message + '</div>');
                }
            },
            complete: function() {
                $btn.prop('disabled', false).text('<?php echo esc_js( __( 'Send Test Email', 'freelance-studio' ) ); ?>');
            }
        });
    });

    // Reconfigure button
    $('#fs-email-delivery-reconfigure').on('click', function() {
        $('.fs-email-delivery-status').hide();
        $('#fs-email-delivery-test-result').hide();
        $('#fs-email-delivery-wizard').show();
        keyVerified = false;
        goToStep(1);
    });
});
</script>
