jQuery(document).ready(function($) {
    const $loader = $('#saiap-loader');
    
    // Hide loader initially
    $loader.hide().removeClass('is-active');
    
    // Function to show loader
    window.showLoader = function() {
        // Show and activate loader with animation
        $loader
            .css('display', 'flex')  // Set display flex before showing
            .hide()                  // Hide it again
            .fadeIn(300)             // Fade it in
            .addClass('is-active');   // Add active class
        
        // Scroll to loader
        $('html, body').animate({
            scrollTop: $loader.offset().top - 100
        }, 500);
    };
    
    // Function to hide loader
    window.hideLoader = function() {
        $loader.fadeOut(300).removeClass('is-active');
    };
    
    // Add loading state to buttons when clicked
    $('.primary-button, .secondary-button').not('#saiap-generate-button, #saiap-toggle-context').on('click', function() {
        const $button = $(this);
        const originalText = $button.text();
        
        // Don't add loading state to buttons with specific actions
        if ($button.is('#saiap-modal-close') || $button.hasClass('notice-dismiss')) {
            return;
        }
        
        // Store original text and add loading indicator
        const cleanText = originalText.replace(/\.+$/, ''); // Remove any trailing dots
        $button.data('original-text', cleanText);
        $button.prop('disabled', true).text(cleanText + '...');
        
        // Reset after 5 seconds if not reset by the action
        setTimeout(function() {
            if ($button.prop('disabled') && $button.text() === cleanText + '...') {
                $button.prop('disabled', false).text(cleanText);
            }
        }, 5000);
    });
});