/**
 * Site Context Management functionality for ClearPost Simple AI Auto Post
 */
jQuery(document).ready(function($) {
    // Initialize SAIAP UI utilities if they don't exist
    window.SAIAP = window.SAIAP || {};
    window.SAIAP.ui = window.SAIAP.ui || {
        // Create skeleton loader for UI elements
        createSkeletonLoader: function(rows) {
            let html = '<div class="saiap-skeleton-loader">';
            for (let i = 0; i < rows; i++) {
                html += '<div class="skeleton-line"></div>';
            }
            html += '</div>';
            return html;
        },
        
        // Show loading state on a button
        showButtonLoading: function($button, isLoading) {
            if (isLoading) {
                $button.prop('disabled', true).addClass('button-loading');
            } else {
                $button.prop('disabled', false).removeClass('button-loading');
            }
        },
        
        // Apply animations to elements
        animateElements: function() {
            $('.saiap-context-section').addClass('animated');
        }
    };
    
    // Site Context Drawer Toggle functionality
    $('#saiap-toggle-context').on('click', function(e) {
        e.preventDefault();
        const $drawer = $('#saiap-context-display');
        const $toggleText = $('.saiap-toggle-text');
        const $toggleIcon = $('.saiap-toggle-icon');
        
        if ($drawer.is(':visible')) {
            // Close drawer
            $drawer.slideUp(300);
            $toggleText.text('View Details');
            $toggleIcon.text('▼');
        } else {
            // Open drawer
            $drawer.slideDown(300);
            $toggleText.text('Hide Details');
            $toggleIcon.text('▲');
            
            // Load context data if not already loaded and we're on the context tab
            if ($drawer.is(':empty') && window.location.search.includes('tab=site-context')) {
                loadSiteContext();
            }
        }
    });
    
    // Ensure drawer is open and load context on initial page load when on the site-context tab
    if ($('#saiap-context-display').length > 0 && window.location.search.includes('tab=site-context')) {
        const $drawer = $('#saiap-context-display');
        const $toggleText = $('.saiap-toggle-text');
        const $toggleIcon = $('.saiap-toggle-icon');

        // Open drawer immediately and show skeleton loader while fetching
        $drawer.show();
        if ($drawer.is(':empty')) {
            $drawer.html(SAIAP.ui.createSkeletonLoader(5));
        }
        $toggleText.text('Hide Details');
        $toggleIcon.text('▲');

        loadSiteContext();
        loadPostTypes();
    }
    
    /*
        Site Context Functions
    */
   
    // Update context button click handler
    $('#saiap-update-context').on('click', function(e) {
        e.preventDefault();
        const $button = $(this);
        $button.prop('disabled', true);
        
        // Show skeleton loader in context display
        $('#saiap-context-display').html(SAIAP.ui.createSkeletonLoader(5));
        
        // Make AJAX request with extended timeout for long-running updates
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            timeout: 300000, // 5 minutes - should match or exceed PHP timeout
            data: {
                action: 'saiap_update_context',
                nonce: saiapAdmin.contextNonce
            },
            beforeSend: function() {
            },
            success: function(response) {
                SAIAP.ui.showButtonLoading($button, false);
                
                if (response.success) {
                    // Update the last updated timestamp if available
                    if (response.data && response.data.last_updated) {
                        $('.saiap-last-updated-time').text(response.data.last_updated);
                    }
                    
                    // Update the context display
                    $('#saiap-context-display').html('');
                    loadSiteContext();
                    
                    // Show success message with post count information
                    let postsMessage = '';
                    if (response.data && response.data.syncResult) {
                        const { totalProcessed, successCount } = response.data.syncResult;
                        postsMessage = totalProcessed > 0 ? 
                            `<p>Processed ${totalProcessed} posts (${successCount} successfully).</p>` : 
                            '<p>No posts were processed. Make sure your site has published content.</p>';
                    }
                    
                    const successMessage = `
                        <div class="notice notice-success is-dismissible">
                            <p class="body-text">${saiapAdmin.i18n.contextUpdated || 'Site context updated successfully.'}</p>
                            ${postsMessage}
                        </div>
                    `;
                    $('#saiap-context-display').before(successMessage);

                    if (window.saiapTriggerStepCompletion && saiapAdmin && saiapAdmin.licenseKey) {
                        window.saiapTriggerStepCompletion(1);
                    }

                    // Apply animations
                    setTimeout(SAIAP.ui.animateElements, 100);
                            } else {
                // Handle error with new error handling function
                const errorMessage = getErrorMessage(response.data);
                
                // Check if this is a license-related error for free users
                if (errorMessage.includes('Missing required fields') || 
                    errorMessage.includes('license key') || 
                    errorMessage.includes('License key not found')) {
                    showFreeUserMessage();
                } else {
                    // Show regular error message
                    const errorNotice = `
                        <div class="notice notice-error is-dismissible">
                            <p class="body-text">${errorMessage || saiapAdmin.i18n.contextError || 'Error updating site context.'}</p>
                        </div>
                    `;
                    $('#saiap-context-display').before(errorNotice);
                }
            }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error occurred:', { xhr, status, error, responseText: xhr.responseText });
                SAIAP.ui.showButtonLoading($button, false);
                
                // Build detailed error message for debugging
                let errorDetail = '';
                if (xhr.status === 0) {
                    errorDetail = 'Connection error - the request may have timed out or been blocked.';
                } else if (xhr.status === 500) {
                    errorDetail = 'Server error (500). Check PHP error logs for details.';
                } else if (xhr.status === 502 || xhr.status === 504) {
                    errorDetail = `Gateway timeout (${xhr.status}). The update is taking too long.`;
                } else if (xhr.status === 503) {
                    errorDetail = 'Service unavailable (503). The server may be overloaded.';
                } else if (status === 'timeout') {
                    errorDetail = 'Request timed out. The update may still be processing.';
                } else if (status === 'parsererror') {
                    errorDetail = 'Invalid response from server. Check for PHP errors or output.';
                } else {
                    errorDetail = `Error: ${status} - ${error || 'Unknown error'} (HTTP ${xhr.status || 'N/A'})`;
                }
                
                // Show error message with details
                const errorMessage = `
                    <div class="notice notice-error is-dismissible">
                        <p class="body-text">${saiapAdmin.i18n.contextError || 'Error updating site context.'}</p>
                        <p class="body-text" style="font-size: 12px; color: #666;">${errorDetail}</p>
                    </div>
                `;
                $('#saiap-context-display').before(errorMessage);
            }
        });
    });

    // Refresh context button click handler - clears cache and fetches fresh data without regenerating
    $('#saiap-refresh-context').on('click', function(e) {
        e.preventDefault();
        const $button = $(this);
        const originalText = $button.text();
        $button.prop('disabled', true).text('Refreshing...');

        // Show skeleton loader in context display
        $('#saiap-context-display').html(SAIAP.ui.createSkeletonLoader(3));

        // First clear the cache, then fetch fresh data
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'saiap_clear_context_cache',
                nonce: saiapAdmin.contextNonce
            },
            success: function() {
                // Cache cleared, now fetch fresh data from server
                loadSiteContext();
                $button.prop('disabled', false).text(originalText);

                // Show success message
                const successMessage = `
                    <div class="notice notice-success is-dismissible">
                        <p class="body-text">Context refreshed from server.</p>
                    </div>
                `;
                $('#saiap-context-display').before(successMessage);
            },
            error: function() {
                $button.prop('disabled', false).text(originalText);
                const errorMessage = `
                    <div class="notice notice-error is-dismissible">
                        <p class="body-text">Failed to refresh context. Please try again.</p>
                    </div>
                `;
                $('#saiap-context-display').before(errorMessage);
            }
        });
    });

    // Function to load site context data asynchronously
    function getErrorMessage(errorData) {
        // Handle both string error messages (from wp_send_json_error) and object errors
        if (typeof errorData === 'string') {
            return errorData;
        } else if (errorData && errorData.error) {
            return errorData.error;
        } else if (errorData && errorData.message) {
            return errorData.message;
        } else {
            return 'Unknown error';
        }
    }

    function handleContextError(errorData) {
        const errorMessage = getErrorMessage(errorData);

        // Check if this is a license-related error for free users
        if (errorMessage.includes('Missing required fields') || 
            errorMessage.includes('license key') || 
            errorMessage.includes('License key not found')) {
            showFreeUserMessage();
        } else {
            // Show regular error message
            $('#saiap-context-error').show();
        }
    }

    function showFreeUserMessage() {
        // Show an admin notice above the site context interface
        const noticeHtml = `
            <div class="notice notice-info saiap-site-context-premium-notice">
                <p><strong>The Secret to Posts that Rank (and Sound Like You)</strong></p>
                <p>This AI agent analyzes your existing content to understand your style, your audience, and your goals. It creates a custom context architecture that ensures your new posts naturally rank and sound like you.</p>
                <p>
                    <button class="button-primary premium-upgrade-btn">Grow organic traffic on autopilot</button>
                    <button class="button-secondary notice-dismiss-btn" style="margin-left: 10px;">Dismiss</button>
                </p>
            </div>
        `;
        
        // Add notice before the site context interface if it doesn't already exist
        if (!$('.saiap-site-context-premium-notice').length) {
            $('#saiap-context-display').before(noticeHtml);
        }

        // Handle upgrade button click
        $('.premium-upgrade-btn').on('click', function(e) {
            e.preventDefault();
            window.open('https://clearpostplugin.com/', '_blank');
        });

        // Handle dismiss button
        $('.notice-dismiss-btn').on('click', function(e) {
            e.preventDefault();
            $(this).closest('.notice').fadeOut();
        });
    }

    function loadSiteContext() {
        // Do not hide the drawer; keep it visible and update contents
        $('#saiap-context-error').hide();
        
        // Make AJAX request to fetch context data  
        $.ajax({
            url: saiapAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'saiap_fetch_context',
                nonce: saiapAdmin.contextNonce
            },
            success: function(response) {
                
                if (response.success && response.data) {
                    // First-time experience: no context exists yet
                    if (response.data.no_context_yet) {
                        const firstTimeHtml = `
                            <div class="notice notice-info is-dismissible">
                                <p class="body-text"><strong>No site context yet</strong></p>
                                <p class="body-text">Click “Update Context Now” to generate your site summary, topics, style guide, and taxonomy rules. This helps the AI produce content that matches your site.</p>
                            </div>
                        `;
                        $('#saiap-context-display').html(firstTimeHtml);
                        return;
                    }
                    // Update the last updated timestamp if available
                    if (response.data.last_updated) {
                        $('.saiap-last-updated-time').text(response.data.last_updated);
                    }
                    
                    if (response.data.context) {
                        // If we don't already have the context display rendered (no cache)
                        if ($('#saiap-context-display .saiap-context-display').length === 0) {
                            // Render the context data
                            renderContextData(response.data.context);
                        }
                        
                        // Only show the context display if the drawer toggle indicates it should be visible
                        const $toggleText = $('.saiap-toggle-text');
                        if ($toggleText.text() === 'Hide Details') {
                            $('#saiap-context-display').show();
                        }
                    }
                } else {
                    // Handle error with new error handling function
                    handleContextError(response.data);
                }
            },
            error: function(xhr, status, error) {
                console.error('Context fetch AJAX error:', { xhr, status, error });
                $('#saiap-context-error').show();
            }
        });
    }
    
    // Function to render context data
    function renderContextData(context) {
        // Default to expanded (matching existing drawer behavior)
        const detailsDisplay = 'block';
        const toggleIcon = '▼';
        const toggleText = 'Collapse';
        
        // Create the context display HTML
        const html = `
            <div class="saiap-context-display">
                ${renderBusinessInfoCard()}

                <!-- Edit mode controls (hidden by default) -->
                <div id="saiap-edit-controls" style="display: none; margin-bottom: 20px;">
                    <button id="saiap-save-context" class="primary-button">
                        ${saiapAdmin.i18n.saveChanges || 'Save Changes'}
                    </button>
                    <button id="saiap-cancel-edit" class="secondary-button spacing-16">
                        ${saiapAdmin.i18n.cancel || 'Cancel'}
                    </button>
                    <div id="saiap-edit-loader" class="spinner" style="display: inline-block; margin-left: 10px; visibility: hidden;"></div>
                </div>
                
                <!-- SEO Strategy section - always visible -->
                <div class="saiap-context-section saiap-strategy-section">
                    <h4>🎯 ${saiapAdmin.i18n.seoStrategy || 'Your SEO Strategy'}</h4>
                    <div class="saiap-context-content">
                        <!-- View mode -->
                        <div class="saiap-view-mode saiap-summary-view">
                            ${renderMarkdown(context.summary)}
                        </div>
                        <!-- Edit mode (hidden by default) -->
                        <div class="saiap-edit-mode saiap-summary-edit" style="display: none;">
                            <textarea id="saiap-summary-field" class="widefat" rows="12">${escapeHtml(context.summary)}</textarea>
                            <p class="small-text">${saiapAdmin.i18n.markdownSupported}</p>
                        </div>
                        <div class="spacing-16">
                            <button class="saiap-edit-context secondary-button">
                                ${saiapAdmin.i18n.edit || 'Edit'}
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Context Details toggle button -->
                <div class="spacing-16" style="border-top: 1px solid #ddd; padding-top: 16px; margin-top: 16px;">
                    <button id="saiap-toggle-details" class="secondary-button" style="display: flex; align-items: center; gap: 8px;">
                        <span class="saiap-details-toggle-icon">${toggleIcon}</span>
                        <span class="saiap-details-toggle-text">${toggleText} Context Details</span>
                    </button>
                </div>
                
                <!-- Collapsible Context Details sections -->
                <div id="saiap-context-details" style="display: ${detailsDisplay};">
                
                <div class="saiap-context-section">
                    <h4>${saiapAdmin.i18n.keyTopics || 'Seed Topics'}</h4>
                    <div class="saiap-context-content">
                        <div class="saiap-view-mode saiap-topics-view">
                            ${context.topics ? renderTopicsList(context.topics) : '<p>No seed topics found.</p>'}
                        </div>
                        <!-- Edit mode (hidden by default) -->
                        <div class="saiap-edit-mode saiap-topics-edit" style="display: none;">
                            <textarea id="saiap-topics-field" class="widefat" rows="6">${context.topics && Array.isArray(context.topics) ? context.topics.join('\n') : ''}</textarea>
                            <p class="small-text">${saiapAdmin.i18n.oneTopicPerLine || 'Enter one topic per line.'}</p>
                        </div>
                        <div class="spacing-16">
                            <button class="saiap-edit-context secondary-button">
                                ${saiapAdmin.i18n.edit || 'Edit'}
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="saiap-context-section">
                    <h4>${saiapAdmin.i18n.writingStyleGuide || 'Writing Style Guide'}</h4>
                    <div class="saiap-context-content">
                        <!-- View mode -->
                        <div class="saiap-view-mode saiap-style-guide-view">
                            ${context.style_guide ? renderMarkdown(context.style_guide) : '<p>No style guide found.</p>'}
                        </div>
                        <!-- Edit mode (hidden by default) -->
                        <div class="saiap-edit-mode saiap-style-guide-edit" style="display: none;">
                            <textarea id="saiap-style-guide-field" class="widefat" rows="6">${escapeHtml(context.style_guide || '')}</textarea>
                        </div>
                        <div class="spacing-16">
                            <button class="saiap-edit-context secondary-button">
                                ${saiapAdmin.i18n.edit || 'Edit'}
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="saiap-context-section">
                    <h4>${saiapAdmin.i18n.customContext || 'Custom Context'}</h4>
                    <div class="saiap-context-content">
                        <div class="saiap-context-field" data-field="custom_context">
                            <!-- View mode -->
                            <div class="saiap-view-mode saiap-custom-context-view">
                                ${context.custom_context && context.custom_context.content ? wpautop(escapeHtml(context.custom_context.content)) : '<p>No custom context added yet. Click "Edit" to add your own context information.</p>'}
                            </div>
                            <!-- Edit mode (hidden by default) -->
                            <div class="saiap-edit-mode saiap-custom-context-edit" style="display: none;">
                                <textarea id="saiap-custom-context-field" class="widefat" rows="6">${context.custom_context && context.custom_context.content ? escapeHtml(context.custom_context.content) : ''}</textarea>
                                <p class="small-text">${saiapAdmin.i18n.customContextHelp || 'Add any additional context that will help the AI understand your site better.'}</p>
                            </div>
                            <div class="spacing-16">
                                <button class="saiap-edit-context secondary-button">
                                    ${saiapAdmin.i18n.edit || 'Edit'}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="saiap-context-section">
                    <h4>${saiapAdmin.i18n.taxonomySettings || 'Tag and Category Settings'}</h4>
                    <div class="saiap-context-content">
                        <div class="saiap-context-field" data-field="taxonomy_settings">
                            <!-- View mode -->
                            <div class="saiap-view-mode saiap-taxonomy-settings-view">
                                ${context.taxonomy_settings ? wpautop(escapeHtml(context.taxonomy_settings)) : '<p>No taxonomy rules defined yet. Click "Edit" to add rules for automatic categorization and tagging.</p>'}
                            </div>
                            <!-- Edit mode (hidden by default) -->
                            <div class="saiap-edit-mode saiap-taxonomy-settings-edit" style="display: none;">
                                <textarea id="saiap-taxonomy-settings-field" class="widefat" rows="8">${escapeHtml(context.taxonomy_settings || '')}</textarea>
                                <p class="small-text">${saiapAdmin.i18n.taxonomySettingsHelp || 'Define rules for automatic categorization and tagging. Example: "Technology posts should be in Tech category" or "Posts about AI should have artificial-intelligence tag".'}</p>
                                <div class="taxonomy-examples" style="margin-top: 10px; padding: 10px; background: #f5f5f5; border-radius: 4px;">
                                    <strong>Examples:</strong><br>
                                    • Technology posts should be in "Tech" category<br>
                                    • Posts about cooking should have "recipes" and "food" tags<br>
                                    • Business content should be in "Business" category with "entrepreneurship" tag<br>
                                    • How-to posts should have "tutorial" and "guide" tags
                                </div>
                            </div>
                            <div class="spacing-16">
                                <button class="saiap-edit-context secondary-button">
                                    ${saiapAdmin.i18n.edit || 'Edit'}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                </div><!-- End #saiap-context-details -->
            </div>
        `;
        
        // Add the HTML to the page
        $('#saiap-context-display').html(html);
        
        // Ensure Post Types row is present after re-render and load its data
        const row = ensurePostTypesShell();
        if (row && row.length) {
            loadPostTypes();
        }
        
        // Attach event handlers for edit buttons
        attachEditEventHandlers();
        
        // Attach event handler for context details toggle
        attachDetailsToggleHandler();
    }
    
    // Helper function to render topics list
    function renderTopicsList(topics) {
        if (!topics || !Array.isArray(topics) || topics.length === 0) {
            return `<p>${saiapAdmin.i18n.noTopicsFound || 'No seed topics found.'}</p>`;
        }

        return `<ul>${topics.map(topic => `<li>${escapeHtml(topic)}</li>`).join('')}</ul>`;
    }

    // Helper function to render Business Information card
    function renderBusinessInfoCard() {
        const wizardData = saiapAdmin.wizardData || {};

        // Only show for premium users who have wizard data
        if (!saiapAdmin.licenseKey || !wizardData.site_name) {
            return '';
        }

        const seedTopics = wizardData.seed_topics || [];
        const locations = wizardData.locations || [];
        const competitorUrls = wizardData.competitor_urls || [];

        return `
            <div class="saiap-context-section saiap-business-info-section">
                <div class="saiap-business-info-header">
                    <h4>📋 ${saiapAdmin.i18n.businessInfo || 'Site Overview'}</h4>
                    <button id="saiap-edit-business-info" class="secondary-button">
                        ${saiapAdmin.i18n.edit || 'Edit'}
                    </button>
                </div>
                <div class="saiap-context-content saiap-business-info-grid">
                    <div class="saiap-business-info-row">
                        <span class="saiap-business-info-label">${saiapAdmin.i18n.siteName || 'Site Name'}:</span>
                        <span class="saiap-business-info-value">${escapeHtml(wizardData.site_name || '')}</span>
                    </div>
                    <div class="saiap-business-info-row">
                        <span class="saiap-business-info-label">${saiapAdmin.i18n.niche || 'Niche'}:</span>
                        <span class="saiap-business-info-value">${escapeHtml(wizardData.niche || '')}</span>
                    </div>
                    <div class="saiap-business-info-row">
                        <span class="saiap-business-info-label">${saiapAdmin.i18n.description || 'Description'}:</span>
                        <span class="saiap-business-info-value">${escapeHtml(wizardData.site_description || '')}</span>
                    </div>
                    <div class="saiap-business-info-row">
                        <span class="saiap-business-info-label">${saiapAdmin.i18n.targetAudience || 'Target Audience'}:</span>
                        <span class="saiap-business-info-value">${escapeHtml(wizardData.target_audience || '')}</span>
                    </div>
                    <div class="saiap-business-info-row">
                        <span class="saiap-business-info-label">${saiapAdmin.i18n.seedTopics || 'Seed Topics'}:</span>
                        <span class="saiap-business-info-value">${seedTopics.length > 0 ? escapeHtml(seedTopics.join(', ')) : '<em>None</em>'}</span>
                    </div>
                    ${locations.length > 0 ? `
                    <div class="saiap-business-info-row">
                        <span class="saiap-business-info-label">${saiapAdmin.i18n.locations || 'Locations'}:</span>
                        <span class="saiap-business-info-value">${escapeHtml(locations.join(', '))}</span>
                    </div>
                    ` : ''}
                    ${competitorUrls.length > 0 ? `
                    <div class="saiap-business-info-row">
                        <span class="saiap-business-info-label">${saiapAdmin.i18n.competitorUrls || 'Competitor URLs'}:</span>
                        <span class="saiap-business-info-value">${escapeHtml(competitorUrls.join(', '))}</span>
                    </div>
                    ` : ''}
                </div>
            </div>
        `;
    }
    
    // Helper function to escape HTML
    function escapeHtml(text) {
        if (!text) return '';
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
    
    // Helper function to convert newlines to paragraphs (like WordPress wpautop)
    function wpautop(text) {
        if (!text) return '';
        return '<p>' + text.replace(/\n\n/g, '</p><p>').replace(/\n/g, '<br>') + '</p>';
    }
    
    // Helper function to preprocess content for markdown rendering
    function preprocessMarkdown(text) {
        if (!text) return '';
        
        // Decode HTML entities that wp_kses_post may have encoded
        let processed = text
            .replace(/&amp;/g, '&')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&quot;/g, '"')
            .replace(/&#039;/g, "'");
        
        // Convert unicode bullets with tabs to standard markdown list format
        // Handles: \t•\t, \t•, •\t, or just • at line start
        processed = processed.replace(/^[\t ]*[•●○◦▪▸►]\s*/gm, '- ');
        
        // Convert numbered lists with tabs (e.g., "\t1.\t" or "1.\t")
        processed = processed.replace(/^[\t ]*(\d+)\.\s*/gm, '$1. ');
        
        // Remove leading tabs that would create unwanted code blocks
        // (but preserve indentation for nested lists by converting tabs to spaces)
        processed = processed.replace(/^\t+/gm, (match) => '    '.repeat(match.length));
        
        return processed;
    }
    
    // Helper function to render markdown to HTML
    function renderMarkdown(text) {
        if (!text) return '';
        
        // Preprocess to handle HTML entities and non-standard list formats
        const processed = preprocessMarkdown(text);
        
        // Check if marked library is available
        if (typeof marked !== 'undefined' && typeof marked.parse === 'function') {
            try {
                // Configure marked for better line break handling
                marked.setOptions({
                    breaks: true,  // Convert single newlines to <br>
                    gfm: true      // Enable GitHub Flavored Markdown
                });
                return marked.parse(processed);
            } catch (e) {
                console.error('Error parsing markdown:', e);
                // Fallback to wpautop if markdown parsing fails
                return wpautop(processed);
            }
        }
        // Fallback to wpautop if marked is not available
        return wpautop(processed);
    }
    
    // Function to attach event handler for context details toggle
    function attachDetailsToggleHandler() {
        $('#saiap-toggle-details').off('click').on('click', function(e) {
            e.preventDefault();
            const $details = $('#saiap-context-details');
            const $icon = $('.saiap-details-toggle-icon');
            const $text = $('.saiap-details-toggle-text');
            
            if ($details.is(':visible')) {
                // Collapse details
                $details.slideUp(300);
                $icon.text('▶');
                $text.text('Expand Context Details');
            } else {
                // Expand details
                $details.slideDown(300);
                $icon.text('▼');
                $text.text('Collapse Context Details');
            }
        });
    }
    
    // Function to attach event handlers for edit buttons
    function attachEditEventHandlers() {
        // Handle Edit Business Info button click - opens wizard modal in edit mode
        $('#saiap-edit-business-info').off('click').on('click', function(e) {
            e.preventDefault();

            // Get current wizard data and add editMode flag
            const wizardData = Object.assign({}, saiapAdmin.wizardData || {}, { editMode: true });

            // Open the wizard modal with current data pre-populated
            if (typeof window.saiapShowOnboardingWizard === 'function') {
                window.saiapShowOnboardingWizard(wizardData);
            } else {
                console.error('Onboarding wizard not available');
            }
        });

        // Handle Edit Context button click
        $('.saiap-edit-context').off('click').on('click', function(e) {
            e.preventDefault();
            
            // Show edit mode, hide view mode
            $('.saiap-edit-mode').show();
            $('.saiap-view-mode').hide();
            
            // Show edit controls, hide regular controls
            $('#saiap-edit-controls').show();
            $('#saiap-update-context, .saiap-edit-context').hide();
        });
        
        // Handle Cancel button click
        $('#saiap-cancel-edit').off('click').on('click', function(e) {
            e.preventDefault();
            
            // Hide edit mode, show view mode
            $('.saiap-edit-mode').hide();
            $('.saiap-view-mode').show();
            
            // Hide edit controls, show regular controls
            $('#saiap-edit-controls').hide();
            $('#saiap-update-context, .saiap-edit-context').show();
        });

        // Handle Save button click
        $('#saiap-save-context').off('click').on('click', function(e) {
            e.preventDefault();
            const $button = $(this);
            
            // Show loading state
            $('#saiap-edit-loader').css('visibility', 'visible');
            $button.prop('disabled', true);
            
            // Collect data from form
            const summary = $('#saiap-summary-field').val() || '';
            
            // Handle topics - convert from textarea to array
            const topicsText = $('#saiap-topics-field').val() || '';
            const topics = topicsText.split('\n')
                .map(line => line.trim())
                .filter(line => line.length > 0);
            
            // Handle style guide
            const styleGuide = $('#saiap-style-guide-field').val() || '';
            
            // Handle custom context
            const customContextContent = $('#saiap-custom-context-field').val() || '';
            
            // Handle taxonomy settings
            const taxonomySettings = $('#saiap-taxonomy-settings-field').val() || '';
            
            // Create data object
            const contextFields = {
                summary: summary,
                topics: topics,
                style_guide: styleGuide,
                custom_context: {
                    content: customContextContent
                },
                taxonomy_settings: taxonomySettings
            };
            
            // Send AJAX request to update context fields
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'saiap_update_context_fields',
                    nonce: saiapAdmin.contextNonce,
                    context_fields: contextFields
                },
                success: function(response) {
                    // Hide loading state
                    $('#saiap-edit-loader').css('visibility', 'hidden');
                    $button.prop('disabled', false);
                    
                    if (response.success) {
                        // Update the view mode with new values
                        $('.saiap-summary-view').html(renderMarkdown(summary));
                        $('.saiap-topics-view').html(renderTopicsList(topics));
                        $('.saiap-style-guide-view').html(renderMarkdown(styleGuide));
                        $('.saiap-custom-context-view').html(
                            customContextContent ? wpautop(escapeHtml(customContextContent)) : 
                            '<p>No custom context added yet. Click "Edit" to add your own context information.</p>'
                        );
                        $('.saiap-taxonomy-settings-view').html(
                            taxonomySettings ? wpautop(escapeHtml(taxonomySettings)) : 
                            '<p>No taxonomy rules defined yet. Click "Edit" to add rules for automatic categorization and tagging.</p>'
                        );
                        
                        // Hide edit mode, show view mode
                        $('.saiap-edit-mode').hide();
                        $('.saiap-view-mode').show();
                        
                        // Hide edit controls, show regular controls
                        $('#saiap-edit-controls').hide();
                        $('#saiap-update-context, .saiap-edit-context').show();
                        
                        // Show success message
                        const successMessage = `
                            <div class="notice notice-success is-dismissible">
                                <p class="body-text">${saiapAdmin.i18n.contextUpdated || 'Site context fields updated successfully!'}</p>
                            </div>
                        `;
                        $('#saiap-context-display').before(successMessage);
                        
                        // Apply animations
                        setTimeout(SAIAP.ui.animateElements, 100);
                    } else {
                        // Handle error with new error handling function
                        const errorMessage = getErrorMessage(response.data);
                        
                        // Check if this is a license-related error for free users
                        if (errorMessage.includes('Missing required fields') || 
                            errorMessage.includes('license key') || 
                            errorMessage.includes('License key not found')) {
                            showFreeUserMessage();
                        } else {
                            // Show regular error message
                            const errorNotice = `
                                <div class="notice notice-error is-dismissible">
                                    <p class="body-text">${errorMessage || saiapAdmin.i18n.contextUpdateError || 'Failed to update context fields. Please try again.'}</p>
                                </div>
                            `;
                            $('#saiap-context-display').before(errorNotice);
                        }
                    }
                },
                error: function(xhr, status, error) {
                    // Hide loading state
                    $('#saiap-edit-loader').css('visibility', 'hidden');
                    $button.prop('disabled', false);
                    
                    // Show error message
                    const errorMessage = `
                        <div class="notice notice-error is-dismissible">
                            <p class="body-text">${saiapAdmin.i18n.contextUpdateError || 'Failed to update context fields. Please try again.'}</p>
                        </div>
                    `;
                    $('#saiap-context-display').before(errorMessage);
                }
            });
        });
    }

    // Post Types UI
    function ensurePostTypesShell() {
        // Try to append to context details first, fallback to main host
        let $host = $('#saiap-context-details');
        if (!$host.length) {
            $host = $('#saiap-context-display');
        }
        if (!$host.length) return null;
        if (!$('#saiap-post-types-section').length) {
            const shell = `
                <div id="saiap-post-types-section" class="saiap-context-section spacing-24" style="margin-top: 24px;">
                  <h4>${saiapAdmin.i18n.postTypesTitle || 'Post Types'}</h4>
                  <div class="saiap-context-content">
                    <div class="saiap-section-header" style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;">
                      <button id="saiap-add-post-type" class="secondary-button">${saiapAdmin.i18n.addPostType || 'Add Post Type'}</button>
                    </div>
                    <div class="saiap-horizontal-scroll" style="display:flex;gap:12px;overflow-x:auto;scroll-snap-type:x mandatory;padding-bottom:8px;"></div>
                    <div class="saiap-scroll-buttons" style="display:flex;gap:8px;margin-top:8px;">
                      <button class="secondary-button" id="saiap-pt-scroll-left" aria-label="Scroll left">◀</button>
                      <button class="secondary-button" id="saiap-pt-scroll-right" aria-label="Scroll right">▶</button>
                    </div>
                  </div>
                </div>`;
            $host.append($(shell));
        }
        if (!$('#saiap-modal-overlay').length) {
            $('body').append(`<div id="saiap-modal-overlay" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.4);z-index:1000;"></div>`);
        }
        if (!$('#saiap-add-post-type-modal').length) {
            $('body').append(`
              <div id="saiap-add-post-type-modal" style="display:none;position:fixed;left:50%;top:20%;transform:translateX(-50%);background:#fff;padding:16px;border-radius:6px;min-width:360px;z-index:1001;">
                <h4 style="margin-top:0;">${saiapAdmin.i18n.addPostTypeTitle || 'Add Post Type from URL'}</h4>
                <label for="saiap-exemplar-url">${saiapAdmin.i18n.exemplarUrl || 'Exemplar URL'}</label>
                <input type="url" id="saiap-exemplar-url" class="widefat" placeholder="https://example.com/post" />
                <p class="small-text" style="margin:8px 0 0;">
                  <a href="#" id="saiap-add-post-type-manual">${saiapAdmin.i18n.createManually || 'Or create it manually instead'}</a>
                </p>
                <div style="margin-top:12px;display:flex;gap:8px;justify-content:flex-end;">
                  <button id="saiap-add-post-type-cancel" class="secondary-button">${saiapAdmin.i18n.cancel || 'Cancel'}</button>
                  <button id="saiap-add-post-type-submit" class="primary-button">${saiapAdmin.i18n.create || 'Create'}</button>
                </div>
              </div>`);
        }
        if (!$('#saiap-edit-post-type-modal').length) {
            $('body').append(`
              <div id="saiap-edit-post-type-modal" style="display:none;position:fixed;left:50%;top:10%;transform:translateX(-50%);background:#fff;padding:16px;border-radius:6px;min-width:520px;max-width:90vw;max-height:80vh;overflow:auto;z-index:1001;">
                <h4 style="margin-top:0;">${saiapAdmin.i18n.editPostTypeTitle || 'Edit Post Type'}</h4>
                <input type="hidden" id="saiap-pt-type-key" />
                <div class="spacing-8-row">
                  <label for="saiap-pt-name">${saiapAdmin.i18n.name || 'Name'}</label>
                  <input type="text" id="saiap-pt-name" class="widefat" />
                </div>
                <div class="spacing-8-row">
                  <label for="saiap-pt-key">${saiapAdmin.i18n.typeKey || 'Type Key'}</label>
                  <input type="text" id="saiap-pt-key" class="widefat" readonly />
                </div>
                <div class="spacing-8-row">
                  <label for="saiap-pt-map">${saiapAdmin.i18n.postMap || 'Post Map (Markdown)'}</label>
                  <textarea id="saiap-pt-map" class="widefat" rows="6"></textarea>
                </div>
                <div class="spacing-8-row">
                  <label for="saiap-pt-style">${saiapAdmin.i18n.styleNotes || 'Style Notes'}</label>
                  <textarea id="saiap-pt-style" class="widefat" rows="4"></textarea>
                </div>
                <div class="spacing-8-row">
                  <label>${saiapAdmin.i18n.exemplarsLabel || 'Exemplars (URLs only, up to 4)'}</label>
                  <div id="saiap-pt-exemplars" style="display:flex;flex-wrap:wrap;gap:8px;"></div>
                  <div style="display:flex;gap:8px;margin-top:8px;">
                    <input type="url" id="saiap-pt-ex-url" class="widefat" placeholder="https://example.com/post" />
                    <button id="saiap-pt-ex-add" class="secondary-button">${saiapAdmin.i18n.add || 'Add'}</button>
                  </div>
                  <p class="small-text">${saiapAdmin.i18n.exemplarHelp || 'Give up to 4 examples of this type of post.'}</p>
                </div>
                <div style="margin-top:12px;display:flex;gap:8px;justify-content:flex-end;">
                  <button id="saiap-edit-post-type-cancel" class="secondary-button">${saiapAdmin.i18n.cancel || 'Cancel'}</button>
                  <button id="saiap-edit-post-type-save" class="primary-button">${saiapAdmin.i18n.save || 'Save'}</button>
                </div>
              </div>`);
        }
        return $('#saiap-post-types-section .saiap-horizontal-scroll');
    }

    function loadPostTypes() {
        const $row = ensurePostTypesShell();
        if (!$row || !$row.length) return;
        $row.html(SAIAP.ui.createSkeletonLoader(2));
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: { action: 'saiap_post_types_list', nonce: saiapAdmin.contextNonce },
            success: function(resp) {
                if (!resp || !resp.success) {
                    $row.html('<p>Failed to load post types.</p>');
                    updatePostMapCtaVisibility([]);
                    return;
                }
                const items = resp.data && Array.isArray(resp.data.items) ? resp.data.items : [];
                renderPostTypeCards(items);
                updatePostMapCtaVisibility(items);
            },
            error: function() { 
                $row.html('<p>Failed to load post types.</p>'); 
                updatePostMapCtaVisibility([]);
            }
        });
    }

    function renderPostTypeCards(types) {
        const $row = $('#saiap-post-types-section .saiap-horizontal-scroll');
        if (!$row.length) return;
        if (!Array.isArray(types) || types.length === 0) {
            $row.html('<p>No post types yet. Click “Add Post Type” to create one.</p>');
            return;
        }
        $row.empty();
        types.forEach(t => {
            const name = escapeHtml(t.name || '');
            const key = escapeHtml(t.type_key || '');
            const updated = t.updated_at ? new Date(t.updated_at).toLocaleString() : '';
            const exemplars = Array.isArray(t.exemplars) ? t.exemplars : [];
            const chips = exemplars.slice(0,4).map(ex => {
                const label = escapeHtml(ex.title || (ex.url ? new URL(ex.url).hostname : 'Exemplar'));
                const href = ex.url ? ` href="${escapeHtml(ex.url)}" target="_blank" rel="noopener noreferrer"` : '';
                return `<a class="saiap-chip" ${href} style="display:inline-block;padding:4px 8px;border:1px solid #ddd;border-radius:12px;text-decoration:none;">${label}</a>`;
            }).join(' ');
            const card = `
                <div class="saiap-card" data-type-key="${key}" style="min-width:280px;max-width:320px;border:1px solid #ddd;border-radius:6px;padding:12px;scroll-snap-align:start;">
                    <div class="saiap-card-header" style="margin-bottom:8px;">
                        <div style="font-weight:600;">${name}</div>
                        <div title="${key}" style="font-family:monospace;color:#666;display:block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${key}</div>
                        <div style="font-size:12px;color:#888;">${updated}</div>
                    </div>
                    <div class="saiap-card-body" style="display:flex;gap:6px;flex-wrap:wrap;">${chips}</div>
                    <div class="saiap-card-footer" style="margin-top:10px;display:flex;gap:8px;">
                        <button class="secondary-button saiap-pt-edit">Edit</button>
                        <button class="secondary-button saiap-pt-delete">Delete</button>
                    </div>
                </div>
            `;
            $row.append(card);
        });
        bindPostTypeCardActions();
        bindHorizontalScroll();
    }

    function bindHorizontalScroll() {
        const $row = $('#saiap-post-types-section .saiap-horizontal-scroll');
        $('#saiap-pt-scroll-left').off('click').on('click', function() { $row.animate({ scrollLeft: $row.scrollLeft() - 320 }, 200); });
        $('#saiap-pt-scroll-right').off('click').on('click', function() { $row.animate({ scrollLeft: $row.scrollLeft() + 320 }, 200); });
    }

    // Delegate to handle dynamically injected buttons
    $(document).on('click', '#saiap-add-post-type', function(e){ e.preventDefault(); openAddModal(); });

    // Job card helpers for async "from URL" analysis
    function addJobCard(jobId, initial) {
        const $row = $('#saiap-post-types-section .saiap-horizontal-scroll');
        if (!$row.length) return null;
        const card = $(`
          <div class="saiap-card" id="saiap-job-${jobId}" style="min-width:280px;max-width:320px;border:1px solid #ddd;border-radius:6px;padding:12px;scroll-snap-align:start;opacity:0.9;">
            <div class="saiap-card-header" style="margin-bottom:8px;">
              <div style="font-weight:600;">Analyzing exemplar…</div>
              <div style="font-family:monospace;color:#666;">job:${jobId.substring(0,8)}</div>
              <div style="font-size:12px;color:#888;"><span class="saiap-job-ts">${new Date().toLocaleString()}</span></div>
            </div>
            <div class="saiap-card-body" style="display:flex;align-items:center;gap:8px;">
              <div class="spinner" style="visibility: visible;"></div>
              <div class="saiap-job-status" style="color:#555;">${initial || 'starting…'}</div>
            </div>
            <div class="saiap-card-footer" style="margin-top:10px;display:flex;gap:8px;">
              <button class="secondary-button saiap-job-retry" style="display:none;">Retry</button>
              <button class="secondary-button saiap-job-dismiss" style="display:none;">Dismiss</button>
            </div>
          </div>
        `);
        $row.prepend(card);
        return card;
    }
    function updateJobCard(jobId, text) {
        $(`#saiap-job-${jobId} .saiap-job-status`).text(text || 'working…');
    }
    function markJobError(jobId, text) {
        updateJobCard(jobId, text || 'stream disconnected; you can retry or dismiss');
        $(`#saiap-job-${jobId} .saiap-job-retry, #saiap-job-${jobId} .saiap-job-dismiss`).show();
    }
    function removeJobCard(jobId) { $(`#saiap-job-${jobId}`).remove(); }

    function openAddModal() {
        $('#saiap-exemplar-url').val('');
        showModal('#saiap-add-post-type-modal');
        $('#saiap-add-post-type-cancel').off('click').on('click', function() { hideModal('#saiap-add-post-type-modal'); });
        $('#saiap-add-post-type-manual').off('click').on('click', function(e) {
            e.preventDefault();
            hideModal('#saiap-add-post-type-modal');
            // Open empty editor form
            openEditModal({ type_key: '', name: '', post_map_md: '', style_notes: '', exemplars: [] });
        });
        $('#saiap-add-post-type-submit').off('click').on('click', function() {
            const url = $('#saiap-exemplar-url').val();
            if (!url) return;
            const $btn = $('#saiap-add-post-type-submit');
            SAIAP.ui.showButtonLoading($btn, true);
            // Use async job start; then attach SSE to stream status until done (job card, non-blocking)
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: { action: 'saiap_post_types_from_url_async', nonce: saiapAdmin.contextNonce, url },
                success: function(resp) {
                    hideModal('#saiap-add-post-type-modal');
                    SAIAP.ui.showButtonLoading($btn, false);
                    if (resp && resp.success && resp.data && resp.data.stream_url && resp.data.job_id) {
                        const jobId = resp.data.job_id;
                        addJobCard(jobId, 'queued');
                        try {
                            let es = new EventSource(resp.data.stream_url);
                            es.addEventListener('status', function(e) {
                                try {
                                    const data = JSON.parse(e.data || '{}');
                                    updateJobCard(jobId, data && data.state ? String(data.state) : 'working');
                                } catch (_) {}
                            });
                            es.addEventListener('done', function(e) {
                                try {
                                    const data = JSON.parse(e.data || '{}');
                                    removeJobCard(jobId);
                                    if (data && data.type) {
                                        loadPostTypes();
                                        openEditModal(data.type);
                                    } else {
                                        loadPostTypes();
                                    }
                                } catch (_) {
                                    removeJobCard(jobId);
                                    loadPostTypes();
                                } finally {
                                    es.close();
                                }
                            });
                            es.addEventListener('error', function(e) {
                                // Handle both server-sent errors (with e.data) and connection errors
                                es.close();
                                let msg = 'connection lost; retry?';
                                if (e && e.data) {
                                    try {
                                        const d = JSON.parse(e.data);
                                        msg = d.message || 'Error';
                                    } catch (_) {
                                        msg = String(e.data);
                                    }
                                }
                                markJobError(jobId, msg);
                                $(`#saiap-job-${jobId} .saiap-job-retry`).off('click').on('click', function() {
                                    $(this).hide();
                                    try {
                                        es = new EventSource(resp.data.stream_url);
                                    } catch {
                                        markJobError(jobId, 'retry failed');
                                    }
                                });
                                $(`#saiap-job-${jobId} .saiap-job-dismiss`).off('click').on('click', function() {
                                    removeJobCard(jobId);
                                });
                            });
                        } catch (err) {
                            markJobError(jobId, 'failed to attach stream');
                        }
                    } else {
                        alert('Failed to start analysis');
                    }
                },
                error: function() {
                    hideModal('#saiap-add-post-type-modal');
                    SAIAP.ui.showButtonLoading($btn, false);
                    alert('Failed to start analysis');
                }
            });
        });
    }

    function bindPostTypeCardActions() {
        $('.saiap-pt-edit').off('click').on('click', function() {
            const key = $(this).closest('.saiap-card').data('type-key');
            // Fetch full record so post_map_md/style_notes populate correctly
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: { action: 'saiap_post_types_get', nonce: saiapAdmin.contextNonce, type_key: key },
                success: function(resp) {
                    if (resp && resp.success && resp.data && resp.data.type) {
                        openEditModal(resp.data.type);
                    } else {
                        // Fallback: open with key and empty fields
                        openEditModal({ type_key: key, name: '' });
                    }
                },
                error: function() {
                    openEditModal({ type_key: key, name: '' });
                }
            });
        });
        $('.saiap-pt-delete').off('click').on('click', function() {
            const key = $(this).closest('.saiap-card').data('type-key');
            if (!confirm('Delete this post type?')) return;
            $.ajax({
                url: ajaxurl, type: 'POST',
                data: { action: 'saiap_post_types_delete', nonce: saiapAdmin.contextNonce, type_key: key },
                success: function(resp) {
                    if (resp && resp.success) loadPostTypes(); else alert('Delete failed');
                },
                error: function() { alert('Delete failed'); }
            });
        });
    }

    function openEditModal(type) {
        $('#saiap-pt-type-key').val(type.type_key || '');
        $('#saiap-pt-name').val(type.name || '');
        $('#saiap-pt-key').val(type.type_key || '');
        $('#saiap-pt-map').val(type.post_map_md || '');
        $('#saiap-pt-style').val(type.style_notes || '');
        const exemplars = Array.isArray(type.exemplars) ? type.exemplars : [];
        renderExemplarChips(exemplars);
        showModal('#saiap-edit-post-type-modal');
        $('#saiap-edit-post-type-cancel').off('click').on('click', function() { hideModal('#saiap-edit-post-type-modal'); });
        $('#saiap-pt-ex-add').off('click').on('click', function(e) {
            e.preventDefault();
            const url = $('#saiap-pt-ex-url').val();
            if (!url) return;
            const current = collectExemplars();
            if (current.length >= 4) return;
            current.push({ type: 'external_url', url, title: '' });
            renderExemplarChips(current);
            $('#saiap-pt-ex-url').val('');
        });
        $('#saiap-edit-post-type-save').off('click').on('click', function() {
            const payload = {
                type_key: $('#saiap-pt-type-key').val() || $('#saiap-pt-key').val(),
                name: $('#saiap-pt-name').val() || '',
                post_map_md: $('#saiap-pt-map').val() || '',
                style_notes: $('#saiap-pt-style').val() || '',
                exemplars: collectExemplars()
            };
            $.ajax({
                url: ajaxurl, type: 'POST',
                data: { action: 'saiap_post_types_upsert', nonce: saiapAdmin.contextNonce, type: JSON.stringify(payload) },
                success: function(resp) {
                    hideModal('#saiap-edit-post-type-modal');
                    if (resp && resp.success) loadPostTypes(); else alert('Save failed');
                },
                error: function() { hideModal('#saiap-edit-post-type-modal'); alert('Save failed'); }
            });
        });
    }

    function renderExemplarChips(exemplars) {
        const $wrap = $('#saiap-pt-exemplars'); $wrap.empty();
        exemplars.slice(0,4).forEach((ex, idx) => {
            const label = escapeHtml(ex.title || (ex.url || '').toString());
            const link = ex.url ? ` href="${escapeHtml(ex.url)}" target="_blank" rel="noopener noreferrer"` : '';
            const chip = $(`
                <span class="saiap-chip" style="display:inline-flex;align-items:center;gap:6px;padding:4px 8px;border:1px solid #ddd;border-radius:12px;">
                    <a ${link} style="text-decoration:none;">${label}</a>
                    <button class="secondary-button saiap-chip-remove" data-idx="${idx}" aria-label="Remove">✕</button>
                </span>
            `);
            $wrap.append(chip);
        });
        $('.saiap-chip-remove').off('click').on('click', function() {
            const idx = parseInt($(this).data('idx'), 10);
            const current = collectExemplars();
            current.splice(idx, 1);
            renderExemplarChips(current);
        });
    }

    function collectExemplars() {
        const chips = $('#saiap-pt-exemplars .saiap-chip');
        const result = [];
        chips.each(function() {
            const a = $(this).find('a');
            const url = a.attr('href') || '';
            const title = a.text() || '';
            result.push({ type: 'external_url', url, title });
        });
        return result;
    }

    function showModal(sel) { $('#saiap-modal-overlay').show(); $(sel).show(); }
    function hideModal(sel) { $('#saiap-modal-overlay').hide(); $(sel).hide(); }

    /**
     * Show/hide the post map CTA banner based on whether post types exist.
     * Also binds the CTA button to open the add modal.
     * @param {Array} types - The list of post types from the API
     */
    function updatePostMapCtaVisibility(types) {
        const $cta = $('#saiap-post-map-cta');
        if (!$cta.length) return;
        
        // Show CTA if no post types exist, hide if they do
        if (!types || !Array.isArray(types) || types.length === 0) {
            $cta.show();
        } else {
            $cta.hide();
        }
    }

    // Bind post map CTA button to open add modal
    $(document).on('click', '#saiap-post-map-cta-add', function(e) {
        e.preventDefault();
        openAddModal();
    });

    // Expose public functions
    window.SAIAP = window.SAIAP || {};
    window.SAIAP.context = {
        load: loadSiteContext,
        render: renderContextData
    };
}); 