/**
 * Onboarding Checklist JavaScript
 * 
 * Handles interactive behaviors for the onboarding checklist including
 * dismissal functionality and animations.
 */

(function($) {
    'use strict';

    /**
     * Initialize onboarding functionality when DOM is ready
     */
    $(document).ready(function() {
        initOnboardingAnimations();
        initProgressUpdates();
    });

    /**
     * Initialize animations for the onboarding checklist
     */
    function initOnboardingAnimations() {
        const $onboardingChecklist = $('#saiap-onboarding-checklist');
        
        if ($onboardingChecklist.length) {
            // Fade in the onboarding checklist
            $onboardingChecklist.hide().fadeIn(300);
            
            // Animate steps with staggered delay
            const $steps = $('.saiap-step');
            $steps.each(function(index) {
                const $step = $(this);
                $step.css('opacity', '0').delay(index * 100).animate({
                    opacity: 1
                }, 300);
            });
            
            // Animate progress bar fill
            const $progressFill = $('.saiap-progress-fill');
            if ($progressFill.length) {
                const targetWidth = $progressFill.css('width');
                $progressFill.css('width', '0').animate({
                    width: targetWidth
                }, 800, 'easeOutCubic');
            }
        }
    }

    /**
     * Initialize progress update functionality
     */
    function initProgressUpdates() {
        // Listen for changes that affect progress
        $(document).on('saiap:step_completed', function(event, stepNumber) {
            updateStepVisual(stepNumber);
            updateProgressBar();
        });
    }

    /**
     * Update visual state of a completed step
     */
    function updateStepVisual(stepNumber) {
        const $step = $(`.saiap-step:nth-child(${stepNumber})`);
        
        if ($step.length && !$step.hasClass('completed')) {
            // Add completed class with animation
            $step.removeClass('incomplete').addClass('completed');
            
            // Update step indicator
            const $indicator = $step.find('.saiap-step-indicator');
            $indicator.html('<span class="dashicons dashicons-yes-alt"></span>');
            
            // Hide step link if present
            $step.find('.saiap-step-link').fadeOut(200);
            
            // Trigger completion animation
            $step.addClass('step-completing');
            setTimeout(function() {
                $step.removeClass('step-completing');
            }, 500);
        }
    }

    /**
     * Update progress bar based on completed steps
     */
    function updateProgressBar() {
        const $completedSteps = $('.saiap-step.completed');
        const totalSteps = $('.saiap-step').length;
        const completedCount = $completedSteps.length;
        const progressPercentage = (completedCount / totalSteps) * 100;
        
        // Update progress bar
        $('.saiap-progress-fill').animate({
            width: progressPercentage + '%'
        }, 300);
        
        // Update progress text
        $('.saiap-progress-text').text(completedCount + '/' + totalSteps + ' steps completed');
        
        // Check if all steps are completed
        if (completedCount === totalSteps) {
            setTimeout(function() {
                showCompletionMessage();
            }, 500);
        }
    }

    /**
     * Show completion message and auto-dismiss
     */
    function showCompletionMessage() {
        const $onboardingChecklist = $('#saiap-onboarding-checklist');
        
        // Replace content with completion message
        const completionHTML = `
            <div class="saiap-onboarding-container">
                <div class="saiap-onboarding-header">
                    <h3>🎉 Setup Complete!</h3>
                    <p>Keep creating great content!</p>
                </div>
                <div style="text-align: center; padding: 20px 0;">
                    <button type="button" class="primary-button" onclick="saiapDismissOnboarding()">
                        Get Started
                    </button>
                </div>
            </div>
        `;
        
        $onboardingChecklist.html(completionHTML);
        
        // Auto-dismiss after 5 seconds
        setTimeout(function() {
            if ($onboardingChecklist.is(':visible')) {
                saiapDismissOnboarding();
            }
        }, 5000);
    }

    /**
     * Add smooth easing function
     */
    $.easing.easeOutCubic = function(x, t, b, c, d) {
        return c * ((t = t / d - 1) * t * t + 1) + b;
    };

})(jQuery);

/**
 * Global function to dismiss onboarding checklist
 * Called by the dismiss button onclick handler
 */
function saiapDismissOnboarding() {
    const $ = jQuery;
    const $onboardingChecklist = $('#saiap-onboarding-checklist');
    
    // Show loading state
    $onboardingChecklist.addClass('dismissing');
    
    // Make AJAX request to dismiss onboarding
    $.ajax({
        url: saiapOnboarding.ajaxurl,
        type: 'POST',
        data: {
            action: 'saiap_dismiss_onboarding',
            nonce: saiapOnboarding.nonce
        },
        success: function(response) {
            if (response.success) {
                // Fade out and remove the onboarding checklist
                $onboardingChecklist.fadeOut(300, function() {
                    $(this).remove();
                });
                
                // Show success message briefly
                showNotice(saiapOnboarding.i18n.dismissSuccess, 'success');
            } else {
                // Show error message
                showNotice(saiapOnboarding.i18n.dismissError, 'error');
                $onboardingChecklist.removeClass('dismissing');
            }
        },
        error: function() {
            // Show error message
            showNotice(saiapOnboarding.i18n.dismissError, 'error');
            $onboardingChecklist.removeClass('dismissing');
        }
    });
}

/**
 * Show a temporary notice message
 */
function showNotice(message, type) {
    const $ = jQuery;
    const noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
    
    const $notice = $(`
        <div class="notice ${noticeClass} is-dismissible" style="display: none;">
            <p>${message}</p>
        </div>
    `);
    
    // Insert after the onboarding checklist or at the top of the page
    const $target = $('#saiap-onboarding-checklist');
    if ($target.length) {
        $target.after($notice);
    } else {
        $('.wrap').prepend($notice);
    }
    
    // Show the notice
    $notice.fadeIn(200);
    
    // Auto-remove after 3 seconds
    setTimeout(function() {
        $notice.fadeOut(200, function() {
            $(this).remove();
        });
    }, 3000);
}

/**
 * Utility function to trigger step completion events
 * Can be called from other parts of the plugin when steps are completed
 */
window.saiapTriggerStepCompletion = function(stepNumber) {
    jQuery(document).trigger('saiap:step_completed', [stepNumber]);
};