/**
 * StaticQ Cloudflare Worker Setup Wizard
 * 
 * Handles the modal wizard for deploying Cloudflare Workers.
 * 
 * @package suspended-cloud/staticq
 * @since 2.1.0
 */

(function($) {
    'use strict';
    
    // Wizard state
    var SQMediaCloudflareWizard = {
        currentStep: 1,
        totalSteps: 4,
        token: '',
        tokenVerified: false,
        tokenSource: '',
        accountId: '',
        accountName: '',
        zones: [],
        buckets: [],
        config: {
            zoneId: '',
            zoneName: '',
            workerName: 'staticq-media-worker',
            bucketName: '',
            useExistingBucket: false,
            routePattern: '',
            enableFallback: true,
            storageProvider: 'r2'
        }
    };
    
    /**
     * Initialize the wizard
     */
    function init() {
        // Bind launch button
        $(document).on('click', '#sqmedia-cf-launch-wizard', openWizard);
        
        // Bind modal controls
        $(document).on('click', '.sqmedia-cf-modal-close', closeWizard);
        $(document).on('click', '.sqmedia-cf-modal-overlay', function(e) {
            if ($(e.target).hasClass('sqmedia-cf-modal-overlay')) {
                closeWizard();
            }
        });
        
        // Bind step navigation
        $(document).on('click', '#sqmedia-cf-next-btn', nextStep);
        $(document).on('click', '#sqmedia-cf-back-btn', prevStep);
        $(document).on('click', '#sqmedia-cf-deploy-btn', deploy);
        
        // Bind token verification
        $(document).on('click', '#sqmedia-cf-verify-token', verifyToken);
        $(document).on('click', '#sqmedia-cf-verify-config-token', verifyConfigToken);
        
        // Bind storage method toggle
        $(document).on('change', 'input[name="sqmedia_cf_token_storage"]', toggleTokenStorageMethod);
        
        // Bind availability checks with debounce
        $(document).on('input', '#sqmedia-cf-worker-name', debounce(checkWorkerName, 500));
        $(document).on('input', '#sqmedia-cf-bucket-name', debounce(checkBucketName, 500));
        
        // Bind bucket toggle
        $(document).on('change', 'input[name="sqmedia_cf_bucket_option"]', toggleBucketOption);
        
        // Bind zone change
        $(document).on('change', '#sqmedia-cf-zone', updateRoutePattern);
        
        // Bind test button
        $(document).on('click', '#sqmedia-cf-test-btn', testDeployment);
        
        // Bind copy code button
        $(document).on('click', '#sqmedia-cf-copy-code', copyConfigCode);
        
        // Bind delete button and modal
        $(document).on('click', '#sqmedia-cf-delete-btn', showDeleteModal);
        $(document).on('click', '#sqmedia-cf-delete-cancel', hideDeleteModal);
        $(document).on('click', '#sqmedia-cf-delete-confirm', confirmDelete);
        
        // Bind clear local settings
        $(document).on('click', '#sqmedia-cf-clear-local', showClearLocalModal);
        $(document).on('click', '#sqmedia-cf-clear-local-cancel', hideClearLocalModal);
        $(document).on('click', '#sqmedia-cf-clear-local-confirm', confirmClearLocal);
        
        // Storage provider is always R2 in the free plugin.
        SQMediaCloudflareWizard.config.storageProvider = 'r2';
    }
    
    /**
     * Open the wizard modal
     */
    function openWizard() {
        // Reset to step 1
        SQMediaCloudflareWizard.currentStep = 1;

        SQMediaCloudflareWizard.config.storageProvider = 'r2';

        // Apply provider-specific visibility
        applyProviderVisibility();
        
        // Show modal
        $('#sqmedia-cf-modal').addClass('active');
        $('body').addClass('sqmedia-modal-open');
        
        // Show first step
        showStep(1);
        
        // Reset token verification state
        SQMediaCloudflareWizard.tokenVerified = false;
        SQMediaCloudflareWizard.token = '';
        SQMediaCloudflareWizard.tokenSource = '';
    }
    
    /**
     * Apply visibility based on storage provider (always R2)
     */
    function applyProviderVisibility() {
        $('.sqmedia-cf-r2-only').show();
        $('#sqmedia-cf-r2-bucket-section').show();
    }
    
    /**
     * Close the wizard modal
     */
    function closeWizard() {
        $('#sqmedia-cf-modal').removeClass('active');
        $('body').removeClass('sqmedia-modal-open');
    }
    
    /**
     * Show a specific step
     */
    function showStep(step) {
        SQMediaCloudflareWizard.currentStep = step;
        
        // Hide all steps
        $('.sqmedia-cf-step').removeClass('active');
        
        // Show current step
        $('#sqmedia-cf-step-' + step).addClass('active');
        
        // Update progress indicator
        $('.sqmedia-cf-progress-step').removeClass('active completed');
        for (var i = 1; i <= SQMediaCloudflareWizard.totalSteps; i++) {
            var $step = $('.sqmedia-cf-progress-step[data-step="' + i + '"]');
            if (i < step) {
                $step.addClass('completed');
            } else if (i === step) {
                $step.addClass('active');
            }
        }
        
        // Update navigation buttons
        updateNavButtons();
    }
    
    /**
     * Update navigation buttons based on current step
     */
    function updateNavButtons() {
        var step = SQMediaCloudflareWizard.currentStep;
        
        // Back button
        if (step === 1) {
            $('#sqmedia-cf-back-btn').hide();
        } else {
            $('#sqmedia-cf-back-btn').show();
        }
        
        // Next/Deploy button
        if (step === 4) {
            $('#sqmedia-cf-next-btn').hide();
            $('#sqmedia-cf-deploy-btn').show();
        } else {
            $('#sqmedia-cf-next-btn').show();
            $('#sqmedia-cf-deploy-btn').hide();
        }
    }
    
    /**
     * Go to next step
     */
    function nextStep() {
        var step = SQMediaCloudflareWizard.currentStep;
        
        // Validate current step
        if (!validateStep(step)) {
            return;
        }
        
        // Load data for next step if needed
        if (step === 1) {
            // After token, load zones
            loadZones();
            
            // Only load buckets if using R2
            if (SQMediaCloudflareWizard.config.storageProvider === 'r2') {
                loadBuckets();
            }
            
            // Reapply provider visibility after step change
            setTimeout(applyProviderVisibility, 100);
        }
        
        if (step < SQMediaCloudflareWizard.totalSteps) {
            showStep(step + 1);
        }
    }
    
    /**
     * Go to previous step
     */
    function prevStep() {
        var step = SQMediaCloudflareWizard.currentStep;
        if (step > 1) {
            showStep(step - 1);
        }
    }
    
    /**
     * Validate current step
     */
    function validateStep(step) {
        switch (step) {
            case 1:
                if (!SQMediaCloudflareWizard.tokenVerified) {
                    var method = $('input[name="sqmedia_cf_token_storage"]:checked').val();
                    if (method === 'database') {
                        showStepError(1, sqmedia_cf_i18n.error_verify_token);
                    } else {
                        showStepError(1, sqmedia_cf_i18n.error_verify_config_token);
                    }
                    return false;
                }
                return true;
                
            case 2:
                var zoneId = $('#sqmedia-cf-zone').val();
                var bucketName = '';

                if (!zoneId) {
                    showStepError(2, sqmedia_cf_i18n.error_select_zone);
                    return false;
                }

                bucketName = $('#sqmedia-cf-bucket-name').val() || $('#sqmedia-cf-existing-bucket').val();
                if (!bucketName) {
                    showStepError(2, sqmedia_cf_i18n.error_bucket_name);
                    return false;
                }
                SQMediaCloudflareWizard.config.bucketName = bucketName;
                SQMediaCloudflareWizard.config.useExistingBucket = $('input[name="sqmedia_cf_bucket_option"]:checked').val() === 'existing';

                SQMediaCloudflareWizard.config.zoneId = zoneId;
                SQMediaCloudflareWizard.config.zoneName = $('#sqmedia-cf-zone option:selected').text();
                return true;
                
            case 3:
                var workerName = $('#sqmedia-cf-worker-name').val();
                var routePattern = $('#sqmedia-cf-route-pattern').val();
                
                if (!workerName) {
                    showStepError(3, sqmedia_cf_i18n.error_worker_name);
                    return false;
                }
                
                if (!routePattern) {
                    showStepError(3, sqmedia_cf_i18n.error_route_pattern);
                    return false;
                }
                
                SQMediaCloudflareWizard.config.workerName = workerName;
                SQMediaCloudflareWizard.config.routePattern = routePattern;
                SQMediaCloudflareWizard.config.enableFallback = $('#sqmedia-cf-enable-fallback').is(':checked');
                return true;
                
            case 4:
                return true;
        }
        return true;
    }
    
    /**
     * Show error message for a step
     */
    function showStepError(step, message) {
        var $error = $('#sqmedia-cf-step-' + step + ' .sqmedia-cf-step-error');
        $error.text(message).show();
        setTimeout(function() {
            $error.fadeOut();
        }, 5000);
    }
    
    /**
     * Clear error message for a step
     */
    function clearStepError(step) {
        var $error = $('#sqmedia-cf-step-' + step + ' .sqmedia-cf-step-error');
        $error.hide().empty();
    }
    
    /**
     * Check for existing token
     */
    /**
     * Toggle token storage method sections
     */
    function toggleTokenStorageMethod() {
        var method = $('input[name="sqmedia_cf_token_storage"]:checked').val();
        
        if (method === 'database') {
            $('#sqmedia-cf-database-token-section').show();
            $('#sqmedia-cf-config-token-section').hide();
        } else {
            $('#sqmedia-cf-database-token-section').hide();
            $('#sqmedia-cf-config-token-section').show();
        }
        
        // Reset verification status when switching
        SQMediaCloudflareWizard.tokenVerified = false;
        SQMediaCloudflareWizard.token = '';
        SQMediaCloudflareWizard.tokenSource = '';
        $('#sqmedia-cf-token-status').empty();
        $('#sqmedia-cf-config-token-status').empty();
    }
    
    /**
     * Verify and save token (database storage method)
     */
    function verifyToken() {
        var token = $('#sqmedia-cf-token').val();
        
        if (!token) {
            showStepError(1, sqmedia_cf_i18n.error_enter_token);
            return;
        }
        
        var $btn = $('#sqmedia-cf-verify-token');
        var $status = $('#sqmedia-cf-token-status');
        
        $btn.prop('disabled', true).text(sqmedia_cf_i18n.verifying);
        $status.html('<span class="spinner is-active"></span>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_verify_and_save_token',
                nonce: sqmedia_cf_nonce,
                token: token
            },
            success: function(response) {
                $btn.prop('disabled', false).text(sqmedia_cf_i18n.verify_and_save);
                
                if (response.success) {
                    SQMediaCloudflareWizard.token = token;
                    SQMediaCloudflareWizard.tokenVerified = true;
                    SQMediaCloudflareWizard.tokenSource = 'database';
                    SQMediaCloudflareWizard.accountId = response.data.account_id;
                    SQMediaCloudflareWizard.accountName = response.data.account_name;
                    
                    $status.html(
                        '<span class="sqmedia-cf-success">✓ ' + sqmedia_cf_i18n.token_verified_saved + '</span><br>' +
                        '<small>' + sqmedia_cf_i18n.account + ': ' + response.data.account_name + '</small>'
                    );
                    clearStepError(1);
                } else {
                    SQMediaCloudflareWizard.tokenVerified = false;
                    $status.html('<span class="sqmedia-cf-error">✗ ' + response.data.message + '</span>');
                }
            },
            error: function() {
                $btn.prop('disabled', false).text(sqmedia_cf_i18n.verify_and_save);
                $status.html('<span class="sqmedia-cf-error">✗ ' + sqmedia_cf_i18n.error_connection + '</span>');
            }
        });
    }
    
    /**
     * Verify token from wp-config.php constant
     */
    function verifyConfigToken() {
        var $btn = $('#sqmedia-cf-verify-config-token');
        var $status = $('#sqmedia-cf-config-token-status');
        
        $btn.prop('disabled', true).text(sqmedia_cf_i18n.verifying);
        $status.html('<span class="spinner is-active"></span>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_verify_config_token',
                nonce: sqmedia_cf_nonce
            },
            success: function(response) {
                $btn.prop('disabled', false).text(sqmedia_cf_i18n.verify_config_token);
                
                if (response.success) {
                    SQMediaCloudflareWizard.token = ''; // Don't store in JS - will be read from wp-config
                    SQMediaCloudflareWizard.tokenVerified = true;
                    SQMediaCloudflareWizard.tokenSource = 'config';
                    SQMediaCloudflareWizard.accountId = response.data.account_id;
                    SQMediaCloudflareWizard.accountName = response.data.account_name;
                    
                    $status.html(
                        '<span class="sqmedia-cf-success">✓ ' + sqmedia_cf_i18n.token_config_valid + '</span><br>' +
                        '<small>' + sqmedia_cf_i18n.account + ': ' + response.data.account_name + '</small>'
                    );
                    clearStepError(1);
                } else {
                    SQMediaCloudflareWizard.tokenVerified = false;
                    
                    if (response.data.code === 'not_defined') {
                        $status.html('<span class="sqmedia-cf-error">✗ ' + sqmedia_cf_i18n.token_not_in_config + '</span>');
                    } else {
                        $status.html('<span class="sqmedia-cf-error">✗ ' + response.data.message + '</span>');
                    }
                }
            },
            error: function() {
                $btn.prop('disabled', false).text(sqmedia_cf_i18n.verify_config_token);
                $status.html('<span class="sqmedia-cf-error">✗ ' + sqmedia_cf_i18n.error_connection + '</span>');
            }
        });
    }
    
    /**
     * Save token to database (legacy - kept for compatibility)
     */
    function saveToken(token, method) {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_save_token',
                nonce: sqmedia_cf_nonce,
                token: token,
                storage_method: method
            }
        });
    }
    
    /**
     * Copy config code to clipboard
     */
    function copyConfigCode() {
        var code = $('#sqmedia-cf-config-code').text();
        var $btn = $('#sqmedia-cf-copy-code');
        
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(code).then(function() {
                $btn.text('✓ ' + sqmedia_cf_i18n.copied);
                setTimeout(function() {
                    $btn.text('ðŸ“‹ ' + sqmedia_cf_i18n.copy);
                }, 2000);
            });
        } else {
            // Fallback for older browsers
            var $temp = $('<textarea>');
            $('body').append($temp);
            $temp.val(code).select();
            document.execCommand('copy');
            $temp.remove();
            
            $btn.text('✓ ' + sqmedia_cf_i18n.copied);
            setTimeout(function() {
                $btn.text('ðŸ“‹ ' + sqmedia_cf_i18n.copy);
            }, 2000);
        }
    }
    
    /**
     * Load zones from Cloudflare
     */
    function loadZones() {
        var $select = $('#sqmedia-cf-zone');
        $select.html('<option value="">' + sqmedia_cf_i18n.loading + '</option>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_get_zones',
                nonce: sqmedia_cf_nonce,
                token: SQMediaCloudflareWizard.token
            },
            success: function(response) {
                if (response.success) {
                    SQMediaCloudflareWizard.zones = response.data.zones;
                    
                    var html = '<option value="">' + sqmedia_cf_i18n.select_zone + '</option>';
                    $.each(response.data.zones, function(i, zone) {
                        html += '<option value="' + zone.id + '">' + zone.name + '</option>';
                    });
                    $select.html(html);
                } else {
                    $select.html('<option value="">' + sqmedia_cf_i18n.error_loading_zones + '</option>');
                }
            }
        });
    }
    
    /**
     * Load existing R2 buckets
     */
    function loadBuckets() {
        var $select = $('#sqmedia-cf-existing-bucket');
        $select.html('<option value="">' + sqmedia_cf_i18n.loading + '</option>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_get_buckets',
                nonce: sqmedia_cf_nonce,
                token: SQMediaCloudflareWizard.token
            },
            success: function(response) {
                if (response.success) {
                    SQMediaCloudflareWizard.buckets = response.data.buckets;
                    
                    if (response.data.buckets.length === 0) {
                        $select.html('<option value="">' + sqmedia_cf_i18n.no_buckets + '</option>');
                        $select.prop('disabled', true);
                        $('input[value="existing"]').prop('disabled', true);
                    } else {
                        var html = '<option value="">' + sqmedia_cf_i18n.select_bucket + '</option>';
                        $.each(response.data.buckets, function(i, bucket) {
                            html += '<option value="' + bucket.name + '">' + bucket.name + '</option>';
                        });
                        $select.html(html);
                    }
                }
            }
        });
    }
    
    /**
     * Toggle between new/existing bucket
     */
    function toggleBucketOption() {
        var option = $(this).val();
        
        if (option === 'new') {
            $('#sqmedia-cf-new-bucket-row').show();
            $('#sqmedia-cf-existing-bucket-row').hide();
        } else {
            $('#sqmedia-cf-new-bucket-row').hide();
            $('#sqmedia-cf-existing-bucket-row').show();
        }
    }
    
    /**
     * Check worker name availability
     */
    function checkWorkerName() {
        var name = $('#sqmedia-cf-worker-name').val();
        var $status = $('#sqmedia-cf-worker-status');
        
        if (!name) {
            $status.html('');
            return;
        }
        
        $status.html('<span class="spinner is-active" style="float:none;"></span>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_check_availability',
                nonce: sqmedia_cf_nonce,
                token: SQMediaCloudflareWizard.token,
                check_type: 'worker',
                value: name
            },
            success: function(response) {
                if (response.success) {
                    if (response.data.available) {
                        $status.html('<span class="sqmedia-cf-success">✓ ' + response.data.message + '</span>');
                    } else {
                        $status.html('<span class="sqmedia-cf-warning">26A0 ' + response.data.message + '</span>');
                    }
                } else {
                    $status.html('<span class="sqmedia-cf-error">✗ ' + response.data.message + '</span>');
                }
            }
        });
    }
    
    /**
     * Check bucket name availability
     */
    function checkBucketName() {
        var name = $('#sqmedia-cf-bucket-name').val();
        var $status = $('#sqmedia-cf-bucket-status');
        
        if (!name || $('input[name="sqmedia_cf_bucket_option"]:checked').val() === 'existing') {
            $status.html('');
            return;
        }
        
        $status.html('<span class="spinner is-active" style="float:none;"></span>');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_check_availability',
                nonce: sqmedia_cf_nonce,
                token: SQMediaCloudflareWizard.token,
                check_type: 'bucket',
                value: name
            },
            success: function(response) {
                if (response.success) {
                    if (response.data.available) {
                        $status.html('<span class="sqmedia-cf-success">✓ ' + response.data.message + '</span>');
                    } else {
                        $status.html('<span class="sqmedia-cf-error">✗ ' + response.data.message + '</span>');
                    }
                } else {
                    $status.html('<span class="sqmedia-cf-error">✗ ' + response.data.message + '</span>');
                }
            }
        });
    }
    
    /**
     * Update route pattern based on zone
     */
    function updateRoutePattern() {
        var zoneName = $('#sqmedia-cf-zone option:selected').text();
        if (zoneName && zoneName !== sqmedia_cf_i18n.select_zone) {
            // Use wildcard prefix to match both www and non-www
            var pattern = '*' + zoneName + '/wp-content/uploads/*';
            $('#sqmedia-cf-route-pattern').val(pattern);
            SQMediaCloudflareWizard.config.routePattern = pattern;
        }
    }
    
    /**
     * Deploy the worker
     */
    function deploy() {
        var $btn = $('#sqmedia-cf-deploy-btn');
        var $progress = $('#sqmedia-cf-deploy-progress');

        $btn.prop('disabled', true);
        $progress.show();

        // Update config with final values from input field
        SQMediaCloudflareWizard.config.routePattern = $('#sqmedia-cf-route-pattern').val();

        // Reset step status
        $('.sqmedia-cf-deploy-step').removeClass('complete error running').addClass('pending');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_deploy',
                nonce: sqmedia_cf_nonce,
                token: SQMediaCloudflareWizard.token, // Empty if using wp-config
                token_source: SQMediaCloudflareWizard.tokenSource, // 'database' or 'config'
                zone_id: SQMediaCloudflareWizard.config.zoneId,
                zone_name: SQMediaCloudflareWizard.config.zoneName,
                worker_name: SQMediaCloudflareWizard.config.workerName,
                bucket_name: SQMediaCloudflareWizard.config.bucketName,
                use_existing_bucket: SQMediaCloudflareWizard.config.useExistingBucket ? 1 : 0,
                route_pattern: SQMediaCloudflareWizard.config.routePattern,
                storage_provider: 'r2',
                enable_fallback: SQMediaCloudflareWizard.config.enableFallback ? 1 : 0,
                uploads_prefix: '/wp-content/uploads/',
                bucket_prefix: $('input[name="sqmedia_r2_prefix"]').val() || 'wp-content/uploads/'
            },
            success: function(response) {
                $btn.prop('disabled', false);
                
                // Update step indicators
                if (response.data && response.data.steps) {
                    $.each(response.data.steps, function(step, data) {
                        var $step = $('.sqmedia-cf-deploy-step[data-step="' + step + '"]');
                        $step.removeClass('pending running');
                        
                        if (data.status === 'complete') {
                            $step.addClass('complete');
                            $step.find('.sqmedia-cf-step-status').text('✓');
                        } else if (data.status === 'error') {
                            $step.addClass('error');
                            $step.find('.sqmedia-cf-step-status').text('✗');
                            $step.find('.sqmedia-cf-step-message').text(data.message);
                        } else if (data.status === 'warning') {
                            $step.addClass('complete');
                            $step.find('.sqmedia-cf-step-status').text('\u26A0');
                            $step.find('.sqmedia-cf-step-message').text(data.message);
                        }
                    });
                }
                
                if (response.success) {
                    // Show success state
                    $('#sqmedia-cf-deploy-success').show();
                    
                    // Refresh the status box on the settings page
                    setTimeout(function() {
                        location.reload();
                    }, 2000);
                } else {
                    // Show error
                    $('#sqmedia-cf-deploy-error').show();
                    $('#sqmedia-cf-deploy-error-message').text(response.data.error || sqmedia_cf_i18n.error_deploy);
                }
            },
            error: function() {
                $btn.prop('disabled', false);
                $('#sqmedia-cf-deploy-error').show();
                $('#sqmedia-cf-deploy-error-message').text(sqmedia_cf_i18n.error_connection);
            }
        });
    }
    
    /**
     * Test the deployment
     */
    function testDeployment() {
        var $btn = $('#sqmedia-cf-test-btn');
        var $status = $('#sqmedia-cf-test-status');
        
        $btn.prop('disabled', true);
        $status.html('<span class="spinner is-active"></span> ' + sqmedia_cf_i18n.testing);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_test',
                nonce: sqmedia_cf_nonce
            },
            success: function(response) {
                $btn.prop('disabled', false);
                
                if (response.success) {
                    $status.html(
                        '<span class="sqmedia-cf-success">✓ ' + sqmedia_cf_i18n.test_success + '</span><br>' +
                        '<small>' + sqmedia_cf_i18n.response_time + ': ' + response.data.response_time + 'ms, ' +
                        sqmedia_cf_i18n.source + ': ' + response.data.source + '</small>'
                    );
                } else {
                    $status.html('<span class="sqmedia-cf-warning">26A0 ' + (response.data.error || sqmedia_cf_i18n.test_warning) + '</span>');
                }
            },
            error: function() {
                $btn.prop('disabled', false);
                $status.html('<span class="sqmedia-cf-error">✗ ' + sqmedia_cf_i18n.error_connection + '</span>');
            }
        });
    }
    
    /**
     * Show delete confirmation modal
     */
    function showDeleteModal() {
        $('#sqmedia-cf-delete-modal').show();
    }
    
    /**
     * Hide delete confirmation modal
     */
    function hideDeleteModal() {
        $('#sqmedia-cf-delete-modal').hide();
    }
    
    /**
     * Confirm and execute delete
     */
    function confirmDelete() {
        var $btn = $('#sqmedia-cf-delete-confirm');
        $btn.prop('disabled', true).text(sqmedia_cf_i18n.removing);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_undeploy',
                nonce: sqmedia_cf_nonce,
                delete_bucket: 0 // Never delete bucket
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    hideDeleteModal();
                    alert(sqmedia_cf_i18n.error_undeploy + ': ' + (response.data.errors?.join(', ') || response.data.message || ''));
                    $btn.prop('disabled', false).text(sqmedia_cf_i18n.confirm_delete);
                }
            },
            error: function() {
                hideDeleteModal();
                $btn.prop('disabled', false).text(sqmedia_cf_i18n.confirm_delete);
            }
        });
    }
    
    /**
     * Show clear local settings modal
     */
    function showClearLocalModal(e) {
        e.preventDefault();
        $('#sqmedia-cf-clear-local-modal').show();
    }
    
    /**
     * Hide clear local settings modal
     */
    function hideClearLocalModal() {
        $('#sqmedia-cf-clear-local-modal').hide();
    }
    
    /**
     * Confirm and clear local settings
     */
    function confirmClearLocal() {
        var $btn = $('#sqmedia-cf-clear-local-confirm');
        $btn.prop('disabled', true).text(sqmedia_cf_i18n.clearing);
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sqmedia_cf_clear_local',
                nonce: sqmedia_cf_nonce
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    hideClearLocalModal();
                    alert(sqmedia_cf_i18n.error_clear_local || 'Failed to clear settings');
                    $btn.prop('disabled', false).text(sqmedia_cf_i18n.clear_local);
                }
            },
            error: function() {
                hideClearLocalModal();
                $btn.prop('disabled', false).text(sqmedia_cf_i18n.clear_local);
            }
        });
    }
    
    /**
     * Debounce helper
     */
    function debounce(func, wait) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                func.apply(context, args);
            }, wait);
        };
    }
    
    // Initialize on document ready
    $(document).ready(init);
    
})(jQuery);