jQuery(document).ready(function($) {
    // Initialize SAIAP global namespace
    window.SAIAP = window.SAIAP || {};
    
    // UI functions namespace
    SAIAP.ui = {
        // Function to add animation classes to elements
        animateElements: function() {
            // Add fade-in animation to cards
            $('.card').addClass('fade-in');
            
            // Add slide-in animation for prompt items
            $('.saiap-all-prompts-list .saiap-prompt-item').addClass('slide-in');
            
            // Add staggered animations to lists
            $('.saiap-prompt-buttons button').each(function(index) {
                $(this).css('animation-delay', (index * 0.1) + 's');
                $(this).addClass('fade-in');
            });
        },

        // Function to create skeleton loaders
        createSkeletonLoader: function(lines = 3, container) {
            let html = '<div class="skeleton-loader" style="height: auto; padding: 16px;">';
            
            // Add a heading skeleton
            html += '<div class="skeleton-line short" style="height: 24px; margin-bottom: 16px;"></div>';
            
            // Add paragraph skeletons
            for (let i = 0; i < lines; i++) {
                const width = i === lines - 1 ? 'medium' : 'long';
                html += `<div class="skeleton-line ${width}"></div>`;
            }
            
            html += '</div>';
            
            if (container) {
                $(container).html(html);
            }
            
            return html;
        },

        // Function to show loading state on buttons
        showButtonLoading: function(button, isLoading) {
            const $button = $(button);
            
            if (isLoading) {
                const originalText = $button.text();
                $button.data('original-text', originalText);
                $button.addClass('button-loading');
                $button.prop('disabled', true);
            } else {
                const originalText = $button.data('original-text');
                $button.removeClass('button-loading');
                $button.prop('disabled', false);
                
                if (originalText) {
                    $button.text(originalText);
                }
            }
        },
        
        // Initialize tooltips
        initTooltips: function() {
            $('.tooltip').each(function() {
                const tooltipText = $(this).data('tooltip');
                if (tooltipText) {
                    $(this).append(`<span class="tooltip-text">${tooltipText}</span>`);
                }
            });
        }
    };
    
    // Initialize animations
    SAIAP.ui.animateElements();
    
    // Initialize tooltips
    SAIAP.ui.initTooltips();
    
    // Add tooltip class to elements with title attribute
    $('[title]').each(function() {
        const title = $(this).attr('title');
        $(this).addClass('tooltip');
        $(this).data('tooltip', title);
        $(this).removeAttr('title');
    });

    // Handle license key clearing
    $('#saiap-clear-license').on('click', function(e) {
        e.preventDefault();
        
        if (!confirm('Are you sure you want to clear your license key? This will deactivate the premium features.')) {
            return;
        }
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                'action': 'saiap_save_license',
                'saiap_license_key': '',
                'saiap_license_form_nonce': $('#saiap_license_form_nonce').val()
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Failed to clear license key. Please try again.');
                }
            }
        });
    });

    // Handle license form submission (manual license key entry)
    $('#saiap-activate-license').on('click', function(e) {
        e.preventDefault();
        
        const licenseKey = $('#saiap-license-key').val().trim();
        const $submitButton = $(this);
        const originalText = $submitButton.text();
        
        if (!licenseKey) {
            alert('Please enter a license key.');
            return;
        }
        
        // Show loading state
        $submitButton.prop('disabled', true).text('Validating...');
        
        // Save and validate the license key
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                'action': 'saiap_save_license',
                'saiap_license_key': licenseKey,
                'saiap_license_form_nonce': $('#saiap_license_form_nonce').val()
            },
            success: function(response) {
                if (response.success) {
                    // License key saved - show validation result
                    if (response.data && response.data.validation) {
                        if (response.data.validation.isValid) {
                            alert('License key saved and validated successfully!');
                            location.reload();
                        } else {
                            alert('License key saved but validation failed: ' + (response.data.validation.error || 'Unknown error'));
                            $submitButton.prop('disabled', false).text(originalText);
                        }
                    } else {
                        alert('License key saved successfully!');
                        location.reload();
                    }
                } else {
                    alert('Failed to save license key. Please try again.');
                    $submitButton.prop('disabled', false).text(originalText);
                }
            },
            error: function() {
                alert('Error saving license key. Please try again.');
                $submitButton.prop('disabled', false).text(originalText);
            }
        });
    });

    // API Settings save function
    window.saveApiKeys = function() {
        var form = document.getElementById('saiap-api-settings-form');
        var btn = document.getElementById('saiap-save-api-keys');
        
        if (btn) {
            btn.disabled = true;
            btn.textContent = 'Saving...';
        }
        
        var formData = new FormData(form);
        formData.append('action', 'saiap_save_api_keys');
        
        var nonceField = document.querySelector('input[name="saiap_api_keys_nonce"]');
        if (nonceField) {
            formData.append('saiap_api_keys_nonce', nonceField.value);
        }
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (btn) {
                    btn.disabled = false;
                    btn.textContent = 'Save API Settings';
                }
                
                var messageType = response.success ? 'success' : 'error';
                var message = response.success 
                    ? (response.data?.message || 'API keys saved successfully.') 
                    : (response.data || 'Error saving API keys.');
                
                showApiMessage(messageType, message);
                
                // Show tracking consent prompt if this is first API key save
                if (response.success && response.data?.show_tracking_consent) {
                    showTrackingConsentPrompt();
                }
            },
            error: function() {
                if (btn) {
                    btn.disabled = false;
                    btn.textContent = 'Save API Settings';
                }
                showApiMessage('error', 'Server error occurred. Please try again later.');
            }
        });
    };
    
    function showApiMessage(type, message) {
        var msgElem = document.getElementById('api-settings-message');
        if (msgElem) {
            msgElem.innerHTML = '<div class="notice notice-' + type + ' inline"><p>' + message + '</p></div>';
            msgElem.style.display = 'block';
            
            setTimeout(function() {
                msgElem.style.display = 'none';
            }, 5000);
        }
    }
    
    /**
     * Show tracking consent prompt after first API key save.
     * Injects the prompt HTML and adds a "Now try the Generate tab" guidance after consent.
     */
    function showTrackingConsentPrompt() {
        // Don't show if prompt already exists
        if ($('#saiap-tracking-consent-prompt').length) {
            return;
        }
        
        var promptHtml = '<div class="notice notice-info saiap-tracking-consent-prompt is-dismissible" id="saiap-tracking-consent-prompt">' +
            '<div class="saiap-tracking-consent-prompt__content">' +
            '<span class="dashicons dashicons-chart-bar saiap-tracking-consent-prompt__icon"></span>' +
            '<div class="saiap-tracking-consent-prompt__text">' +
            '<strong>Help improve ClearPost?</strong> ' +
            '<span>Share anonymous usage data to help us make the plugin better. No personal information collected.</span>' +
            '</div>' +
            '<div class="saiap-tracking-consent-prompt__actions">' +
            '<button type="button" class="button button-primary" id="saiap-tracking-prompt-allow">Yes, I\'ll help</button> ' +
            '<button type="button" class="button button-secondary" id="saiap-tracking-prompt-deny">No thanks</button>' +
            '</div>' +
            '</div>' +
            '</div>';
        
        // Insert at the top of the settings container
        var $container = $('.saiap-ai-settings, .wrap').first();
        if ($container.length) {
            $container.prepend(promptHtml);
            
            // Scroll to top so user sees the prompt
            $('html, body').animate({ scrollTop: 0 }, 300);
        }
    }

    // Privacy Settings save function
    window.savePrivacySettings = function() {
        var form = document.getElementById('saiap-privacy-settings-form');
        var btn = document.getElementById('saiap-save-privacy');
        
        if (btn) {
            btn.disabled = true;
            btn.textContent = 'Saving...';
        }
        
        var formData = new FormData(form);
        formData.append('action', 'saiap_save_privacy_settings');
        
        var nonceField = document.querySelector('input[name="saiap_privacy_nonce"]');
        if (nonceField) {
            formData.append('saiap_privacy_nonce', nonceField.value);
        }
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (btn) {
                    btn.disabled = false;
                    btn.textContent = 'Save Privacy Settings';
                }
                
                var messageType = response.success ? 'success' : 'error';
                var message = response.success 
                    ? (response.data?.message || 'Privacy settings saved successfully.') 
                    : (response.data || 'Error saving privacy settings.');
                
                showPrivacyMessage(messageType, message);
            },
            error: function() {
                if (btn) {
                    btn.disabled = false;
                    btn.textContent = 'Save Privacy Settings';
                }
                showPrivacyMessage('error', 'Server error occurred. Please try again later.');
            }
        });
    };
    
    function showPrivacyMessage(type, message) {
        var msgElem = document.getElementById('privacy-settings-message');
        if (msgElem) {
            msgElem.innerHTML = '<div class="notice notice-' + type + ' inline"><p>' + message + '</p></div>';
            msgElem.style.display = 'block';
            
            setTimeout(function() {
                msgElem.style.display = 'none';
            }, 5000);
        }
    }

    // Notification Settings save function
    window.saveNotificationSettings = function() {
        var form = document.getElementById('saiap-notifications-form');
        var btn = document.getElementById('saiap-save-notifications');

        if (btn) {
            btn.disabled = true;
            btn.textContent = 'Saving...';
        }

        var formData = new FormData(form);
        formData.append('action', 'saiap_save_notifications');

        var nonceField = document.querySelector('input[name="saiap_notifications_nonce"]');
        if (nonceField) {
            formData.append('saiap_notifications_nonce', nonceField.value);
        }

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (btn) {
                    btn.disabled = false;
                    btn.textContent = 'Save Notification Settings';
                }

                var messageType = response.success ? 'success' : 'error';
                var message = response.success 
                    ? (response.data?.message || 'Notification settings saved successfully.') 
                    : (response.data || 'Error saving notification settings.');

                showNotificationsMessage(messageType, message);
            },
            error: function() {
                if (btn) {
                    btn.disabled = false;
                    btn.textContent = 'Save Notification Settings';
                }
                showNotificationsMessage('error', 'Server error occurred. Please try again later.');
            }
        });
    };

    function showNotificationsMessage(type, message) {
        var msgElem = document.getElementById('notifications-settings-message');
        if (msgElem) {
            msgElem.innerHTML = '<div class="notice notice-' + type + ' inline"><p>' + message + '</p></div>';
            msgElem.style.display = 'block';

            setTimeout(function() {
                msgElem.style.display = 'none';
            }, 5000);
        }
    }

    window.saveTaxonomySettings = function() {
        var form = document.getElementById('saiap-taxonomy-settings-form');
        var btn = document.getElementById('saiap-save-taxonomy-settings');

        if (btn) {
            btn.disabled = true;
            btn.textContent = 'Saving...';
        }

        var formData = new FormData(form);
        formData.append('action', 'saiap_save_taxonomy_settings');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (btn) {
                    btn.disabled = false;
                    btn.textContent = 'Save Settings';
                }
                var messageType = response.success ? 'success' : 'error';
                var message = response.success
                    ? (response.data?.message || 'Settings saved.')
                    : (response.data || 'Error saving settings.');
                showTaxonomyMessage(messageType, message);
            },
            error: function() {
                if (btn) {
                    btn.disabled = false;
                    btn.textContent = 'Save Settings';
                }
                showTaxonomyMessage('error', 'Server error occurred. Please try again later.');
            }
        });
    };

    function showTaxonomyMessage(type, message) {
        var msgElem = document.getElementById('taxonomy-settings-message');
        if (msgElem) {
            msgElem.innerHTML = '<div class="notice notice-' + type + ' inline"><p>' + message + '</p></div>';
            msgElem.style.display = 'block';
            setTimeout(function() {
                msgElem.style.display = 'none';
            }, 5000);
        }
    }

    // Tracking consent notice handlers
    $('#saiap-tracking-allow').on('click', function() {
        $.post(ajaxurl, {
            action: 'saiap_set_tracking_preference',
            preference: 'allow',
            nonce: saiapAdmin.trackingNonce || ''
        }, function() {
            $('#saiap-tracking-notice').fadeOut();
        });
    });
    
    $('#saiap-tracking-deny').on('click', function() {
        $.post(ajaxurl, {
            action: 'saiap_set_tracking_preference',
            preference: 'deny',
            nonce: saiapAdmin.trackingNonce || ''
        }, function() {
            $('#saiap-tracking-notice').fadeOut();
        });
    });

    // Unified onboarding tracking consent prompt handlers (using event delegation for dynamically injected prompts)
    $(document).on('click', '#saiap-tracking-prompt-allow', function() {
        var $prompt = $('#saiap-tracking-consent-prompt');
        $.post(ajaxurl, {
            action: 'saiap_tracking_consent_prompt',
            consent: 'allow',
            nonce: saiapAdmin.nonce || ''
        }, function() {
            handleTrackingConsentComplete($prompt);
        });
    });

    $(document).on('click', '#saiap-tracking-prompt-deny', function() {
        var $prompt = $('#saiap-tracking-consent-prompt');
        $.post(ajaxurl, {
            action: 'saiap_tracking_consent_prompt',
            consent: 'deny',
            nonce: saiapAdmin.nonce || ''
        }, function() {
            handleTrackingConsentComplete($prompt);
        });
    });
    
    /**
     * Handle post-consent actions: fade out prompt and show guidance on AI Settings page.
     */
    function handleTrackingConsentComplete($prompt) {
        // Check if we're on the AI Settings tab (API keys path)
        var isApiKeysPath = window.location.search.indexOf('tab=ai-settings') !== -1;
        
        if (isApiKeysPath) {
            // Replace prompt with guidance to Generate tab
            var guidanceHtml = '<div class="notice notice-success saiap-next-step-guidance" id="saiap-next-step-guidance">' +
                '<p><strong>You\'re all set!</strong> ' +
                '<a href="' + window.location.pathname + '?page=saiap&tab=generate">Now try the Generate tab →</a></p>' +
                '</div>';
            $prompt.replaceWith(guidanceHtml);
        } else {
            $prompt.fadeOut(300);
        }
    }

    // Generate tab CTA show/dismiss logic using sessionStorage
    (function initGenerateCta() {
        try {
            var dismissed = sessionStorage.getItem('saiap_generate_cta_dismissed') === '1';
            var $cta = $('#saiap-generate-cta');
            if ($cta.length) {
                if (!dismissed) {
                    $cta.show();
                }
                $('#saiap-generate-cta-dismiss').on('click', function(e) {
                    e.preventDefault();
                    sessionStorage.setItem('saiap_generate_cta_dismissed', '1');
                    $cta.fadeOut(150);
                });
            }
        } catch (e) {
            // no-op if sessionStorage is unavailable
        }
    })();

    // Trial start button handler (works on plugin page and anywhere the button appears)
    $(document).on('click', '.saiap-start-trial-btn', function(e) {
        e.preventDefault();
        e.stopPropagation(); // Prevent event bubbling
        
        console.log('Trial button clicked'); // Debug log

        var $btn = $(this);
        var originalText = $btn.text();

        // Check if saiapAdmin is available
        if (typeof saiapAdmin === 'undefined') {
            console.error('saiapAdmin is not defined. Make sure admin.js is properly loaded and localized.');
            var configError = 'Error: Configuration not loaded. Please refresh the page and try again.';
            try {
                alert(configError);
            } catch (e) {
                console.error(configError);
            }
            return;
        }
        
        // Check if nonce is available
        if (!saiapAdmin.trialNonce) {
            console.error('Trial nonce is missing. The page may need to be refreshed.');
            var nonceError = 'Security token missing. Please refresh the page and try again.';
            try {
                alert(nonceError);
            } catch (e) {
                console.error(nonceError);
            }
            return;
        }

        // Disable button and show loading state
        $btn.prop('disabled', true).text('Starting trial...');

        $.ajax({
            url: saiapAdmin.ajaxurl || ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'saiap_start_trial',
                nonce: saiapAdmin.trialNonce || '',
                email: '' // Email is optional
            },
            success: function(response) {
                console.log('Trial start response:', response); // Debug log

                // Handle case where response might be a string (nonce failure returns -1)
                if (typeof response === 'string' && response === '-1') {
                    console.error('Nonce verification failed');
                    alert('Security check failed. Please refresh the page and try again.');
                    $btn.prop('disabled', false).text(originalText);
                    return;
                }

                if (response && response.success) {
                    // Check if wizard should be shown (always true for plugin-first trials now)
                    if (response.data && response.data.show_wizard) {
                        // Show the onboarding wizard with prefill data
                        $btn.prop('disabled', false).text(originalText);
                        if (typeof window.saiapShowOnboardingWizard === 'function') {
                            // Pass prefill data to wizard
                            var prefillData = response.data.prefill_data || null;
                            window.saiapShowOnboardingWizard(prefillData);
                        } else {
                            console.error('Onboarding wizard not available');
                            alert('Please refresh the page and try again.');
                        }
                        return;
                    }

                    // Success! Redirect to Dashboard with trial_started flag for tracking consent
                    window.location.href = 'admin.php?page=saiap&tab=dashboard&trial_started=1';
                } else {
                    // Show error message
                    var message = 'Failed to start trial. Please try again.';
                    
                    if (response && response.data) {
                        if (response.data.message) {
                            message = response.data.message;
                        } else if (typeof response.data === 'string') {
                            message = response.data;
                        }
                    } else if (typeof response === 'string') {
                        message = response;
                    }
                    
                    console.error('Trial start failed:', response);
                    
                    // Show error message - try alert first, then fallback to on-page notice
                    try {
                        alert(message);
                    } catch (e) {
                        console.error('Alert blocked, showing on-page error');
                        // Create a notice element near the button
                        var $errorNotice = $('<div class="notice notice-error is-dismissible" style="margin: 10px 0;"><p>' + message + '</p></div>');
                        $btn.closest('.saiap-trial-welcome-hero__actions, .saiap-dashboard').prepend($errorNotice);
                        
                        // Auto-dismiss after 10 seconds
                        setTimeout(function() {
                            $errorNotice.fadeOut(function() {
                                $(this).remove();
                            });
                        }, 10000);
                    }
                    
                    $btn.prop('disabled', false).text(originalText);
                }
            },
            error: function(xhr, status, error) {
                console.error('Trial start AJAX error:', {
                    status: status,
                    error: error,
                    xhr: xhr,
                    responseText: xhr.responseText,
                    statusCode: xhr.status
                });
                
                var errorMessage = 'Network error. Please check your connection and try again.';
                
                // Try to parse error response if available
                if (xhr.responseText) {
                    // Check if it's a nonce failure (-1)
                    if (xhr.responseText.trim() === '-1') {
                        errorMessage = 'Security check failed. Please refresh the page and try again.';
                    } else {
                        try {
                            var errorResponse = JSON.parse(xhr.responseText);
                            if (errorResponse && errorResponse.data) {
                                if (errorResponse.data.message) {
                                    errorMessage = errorResponse.data.message;
                                } else if (typeof errorResponse.data === 'string') {
                                    errorMessage = errorResponse.data;
                                }
                            } else if (errorResponse && errorResponse.message) {
                                errorMessage = errorResponse.message;
                            }
                        } catch (e) {
                            // If parsing fails, check if responseText contains useful info
                            if (xhr.responseText.length < 200) {
                                errorMessage = 'Error: ' + xhr.responseText.substring(0, 100);
                            }
                        }
                    }
                }
                
                // Show error message - try alert first, then fallback to on-page notice
                try {
                    alert(errorMessage);
                } catch (e) {
                    console.error('Alert blocked, showing on-page error');
                    // Create a notice element near the button
                    var $errorNotice = $('<div class="notice notice-error is-dismissible" style="margin: 10px 0;"><p>' + errorMessage + '</p></div>');
                    $btn.closest('.saiap-trial-welcome-hero__actions, .saiap-dashboard').prepend($errorNotice);
                    
                    // Auto-dismiss after 10 seconds
                    setTimeout(function() {
                        $errorNotice.fadeOut(function() {
                            $(this).remove();
                        });
                    }, 10000);
                }
                
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });
});