// Dropdown menu functionality
(function($) {
    'use strict';

    // Canonical API routing shim.
    (function initAysaApiRoutingShim() {
        const prodBase = 'https://api.aysa.ai';
        const apiBase = prodBase;

        window.AYSA_API_BASE = apiBase;

        function rewriteUrl(url) {
            if (typeof url !== 'string') {
                return url;
            }
            if (url.indexOf(prodBase) !== 0) {
                return url;
            }
            return apiBase + url.slice(prodBase.length);
        }

        if (typeof window.fetch === 'function' && !window.__aysaFetchRewriterInstalled) {
            const nativeFetch = window.fetch.bind(window);
            window.fetch = function(resource, init) {
                try {
                    if (typeof resource === 'string') {
                        return nativeFetch(rewriteUrl(resource), init);
                    }
                    if (resource && typeof resource.url === 'string' && typeof Request === 'function' && resource instanceof Request) {
                        const rewritten = rewriteUrl(resource.url);
                        if (rewritten !== resource.url) {
                            return nativeFetch(new Request(rewritten, resource), init);
                        }
                    }
                } catch (e) {
                    // fall through to native fetch
                }
                return nativeFetch(resource, init);
            };
            window.__aysaFetchRewriterInstalled = true;
        }

        if (typeof window.XMLHttpRequest === 'function' && !window.__aysaXhrRewriterInstalled) {
            const originalOpen = window.XMLHttpRequest.prototype.open;
            window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
                const nextUrl = rewriteUrl(url);
                return originalOpen.call(this, method, nextUrl, async, user, password);
            };
            window.__aysaXhrRewriterInstalled = true;
        }
    })();

    // Track active dropdowns
    let activeDropdown = null;
    let activeSubmenu = null;

    /**
     * Initialize dropdown functionality
     */
    function initDropdowns() {
        // Close dropdowns when clicking outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.aysa-dropdown-menu, .action-buttons button').length) {
                closeAllDropdowns();
            }
        });

        // Handle ESC key to close dropdowns
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                closeAllDropdowns();
            }
        });
    }

    /**
     * Close all open dropdowns
     */
    function closeAllDropdowns() {
        $('.aysa-dropdown-menu').remove();
        activeDropdown = null;
        activeSubmenu = null;
    }

    /**
     * Refresh the keywords table by loading data from localStorage
     */
    function refreshKeywordsTable() {
        const storedResults = localStorage.getItem('aysa_keyword_suggestions');
        if (storedResults) {
            try {
                const results = JSON.parse(storedResults);
                // If we have a displayKeywordResults function in the page, use it
                if (typeof window.displayKeywordResults === 'function') {
                    window.displayKeywordResults(results);
                } else {
                    // Basic table refresh if no display function exists
                    const $tbody = $('.aysa-keywords-table tbody');
                    if ($tbody.length) {
                        $tbody.empty();
                        
                        results.forEach(function(result) {
                            $tbody.append(`
                                <tr>
                                    <td>${result.keyword || ''}</td>
                                    <td>${result.intent || 'N/A'}</td>
                                    <td>${result.searchVolume || '0'}</td>
                                    <td>${result.difficulty || '0'}%</td>
                                    <td><button class="aysa-action-btn">Action</button></td>
                                </tr>
                            `);
                        });
                    }
                }
                
                // Show notification
                showNotification('success', 'Keywords table refreshed successfully');
            } catch (e) {
                console.error('Failed to parse stored keyword suggestions:', e);
                showNotification('error', 'Failed to refresh keywords table');
            }
        } else {
            showNotification('error', 'No keyword data found in storage');
        }
    }

    /**
     * Show dropdown menu
     * 
     * @param {HTMLElement} triggerElement - The element that triggered the dropdown
     * @param {Array} items - Array of items to display in the dropdown
     * @param {Object} options - Additional options for the dropdown
     */
    function showDropdownMenu(triggerElement, items, options = {}) {
        // Close any open dropdowns first
        closeAllDropdowns();

        const $trigger = $(triggerElement);
        const triggerOffset = $trigger.offset();
        const triggerHeight = $trigger.outerHeight();
        
        // Generate unique ID for this dropdown
        const dropdownId = 'dropdown-' + Math.random().toString(36).substr(2, 9);
        
        // Create dropdown container
        const $dropdown = $('<div>', {
            'class': 'aysa-dropdown-menu',
            'id': dropdownId,
            'data-dropdown-for': options.targetId || ''
        }).css({
            'position': 'absolute',
            'top': triggerOffset.top + triggerHeight + 5,
            'left': triggerOffset.left
        });

        // Add items to dropdown
        const $itemsList = $('<ul>', {'class': 'dropdown-items'});
        items.forEach(item => {
            const $item = $('<li>', {'class': 'dropdown-item'});
            
            if (item.type === 'submenu') {
                // Create submenu toggle
                const $submenuToggle = $('<button>', {
                    'class': 'dropdown-submenu-toggle',
                    'data-submenu-id': item.id,
                    'data-action': item.action || ''
                }).html(`
                    <span>${item.label}</span>
                    <span class="dashicons dashicons-arrow-right-alt2"></span>
                `);
                
                const $submenu = $('<div>', {
                    'class': 'dropdown-submenu',
                });
                
                $item.append($submenuToggle);
                $item.data('submenuData', item.data || {});
                
                // Add click handler for submenu toggle
                $submenuToggle.on('click', function() {
                    const submenuId = $(this).data('submenu-id');
                    const action = $(this).data('action');
                    const submenuData = $item.data('submenuData');
                    
                    activeSubmenu = submenuId;
                    showSubmenu($dropdown, submenuId, action, submenuData);
                });
            } else {
                // Create regular action button
                const $button = $('<button>', {
                    'data-action': item.action || '',
                    'data-id': item.id || ''
                }).text(item.label);
                
                // Add click handler for action
                $button.on('click', function() {
                    const action = $(this).data('action');
                    const id = $(this).data('id');
                    
                    if (typeof options.onAction === 'function') {
                        options.onAction(action, id, item.data || {});
                    }
                    
                    closeAllDropdowns();
                });
                
                $item.append($button);
            }
            
            $itemsList.append($item);
        });
        
        $dropdown.append($itemsList);
        $('body').append($dropdown);
        
        // Store active dropdown reference
        activeDropdown = dropdownId;
        
        // Position check to ensure dropdown is fully visible
        positionDropdown($dropdown, triggerOffset);
        
        return $dropdown;
    }

    /**
     * Show submenu within a dropdown
     * 
     * @param {jQuery} $dropdown - The dropdown container
     * @param {string} submenuId - ID of the submenu to show
     * @param {string} action - Action associated with the submenu
     * @param {Object} data - Additional data for the submenu
     */
    function showSubmenu($dropdown, submenuId, action, data = {}) {
        // Hide the main dropdown items
        $dropdown.find('.dropdown-items').hide();
        
        // Create submenu container if it doesn't exist
        let $submenuContainer = $dropdown.find('.dropdown-submenu-container');
        if (!$submenuContainer.length) {
            $submenuContainer = $('<div>', {'class': 'dropdown-submenu-container'});
            $dropdown.append($submenuContainer);
        } else {
            $submenuContainer.empty();
        }
        
        // Create submenu header with back button
        const $header = $('<div>', {'class': 'dropdown-submenu-header'});
        const $backBtn = $('<button>', {'class': 'dropdown-back-button'}).html(`
            <span class="dashicons dashicons-arrow-left-alt2"></span>
        `);
        
        $backBtn.on('click', function() {
            hideSubmenu($dropdown);
        });
        
        $header.append($backBtn);
        $header.append($('<h4>').text(data.title || 'Select an option'));
        $submenuContainer.append($header);
        
        // Create submenu items container
        const $submenuItems = $('<ul>', {'class': 'dropdown-submenu-items'});
        $submenuContainer.append($submenuItems);
        
        // Show loading state
        $submenuItems.html('<div class="dropdown-loading">Loading...</div>');
        
        // Load submenu items based on the action
        if (action === 'loadCategories') {
            loadCategories(data.keywordId, $submenuItems, function(categories) {
                if (categories.length === 0) {
                    $submenuItems.html('<div class="dropdown-no-items">No categories found</div>');
                    return;
                }
                
                $submenuItems.empty();
                categories.forEach(category => {
                    const $item = $('<li>', {'class': 'dropdown-item'});
                    const $button = $('<button>', {
                        'class': 'dropdown-category-button',
                        'data-action': 'assignCategory',
                        'data-category-id': category.id,
                        'data-keyword-id': data.keywordId
                    }).text(category.name);
                    
                    $button.on('click', function() {
                        const categoryId = $(this).data('category-id');
                        const keywordId = $(this).data('keyword-id');
                        
                        associateKeywordWithCategory(keywordId, categoryId);
                        closeAllDropdowns();
                    });
                    
                    $item.append($button);
                    $submenuItems.append($item);
                });
            });
        }
    }

    /**
     * Hide submenu and show main dropdown items
     * 
     * @param {jQuery} $dropdown - The dropdown container
     */
    function hideSubmenu($dropdown) {
        $dropdown.find('.dropdown-submenu-container').remove();
        $dropdown.find('.dropdown-items').show();
        activeSubmenu = null;
    }

    /**
     * Load categories via AJAX
     * 
     * @param {number} keywordId - ID of the keyword
     * @param {jQuery} $container - Container to update with error messages
     * @param {Function} callback - Function to call with loaded categories
     */
    function loadCategories(keywordId, $container, callback) {
        $.ajax({
            url: aysa_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_get_categories',
                nonce: aysa_ajax.nonce,
                keyword_id: keywordId
            },
            success: function(response) {
                if (response.success) {
                    callback(response.data.categories || []);
                } else {
                    $container.html('<div class="dropdown-error">' + (response.data.message || 'Error loading categories') + '</div>');
                }
            },
            error: function() {
                $container.html('<div class="dropdown-error">Network error. Please try again.</div>');
            }
        });
    }

    /**
     * Associate a keyword with a category via AJAX
     * 
     * @param {number} keywordId - ID of the keyword
     * @param {number} categoryId - ID of the category
     */
    function associateKeywordWithCategory(keywordId, categoryId) {
        $.ajax({
            url: aysa_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'aysa_assign_category',
                nonce: aysa_ajax.nonce,
                keyword_id: keywordId,
                category_id: categoryId
            },
            success: function(response) {
                if (response.success) {
                    showNotification('success', response.data.message || 'Category assigned successfully');
                    // Refresh the keywords table if needed
                    if (typeof refreshKeywordsTable === 'function') {
                        refreshKeywordsTable();
                    }
                } else {
                    showNotification('error', response.data.message || 'Error assigning category');
                }
            },
            error: function() {
                showNotification('error', 'Network error. Please try again.');
            }
        });
    }

    /**
     * Position dropdown to ensure it's visible in viewport
     * 
     * @param {jQuery} $dropdown - The dropdown to position
     * @param {Object} triggerOffset - Offset position of the trigger element
     */
    function positionDropdown($dropdown, triggerOffset) {
        const dropdownWidth = $dropdown.outerWidth();
        const windowWidth = $(window).width();
        
        // Check if dropdown extends beyond right edge of screen
        if (triggerOffset.left + dropdownWidth > windowWidth - 20) {
            // Reposition to align with right edge of trigger
            $dropdown.css({
                'left': 'auto',
                'right': (windowWidth - (triggerOffset.left + triggerOffset.width))
            });
        }
    }

    /**
     * Initialize Social Media Content Generator functionality
     */
    function initSocialContentGenerator() {
        const platformLimits = {
            'facebook': 63206,
            'linkedin': 3000,
            'x': 280,
            'instagram': 2200,
            'youtube': 5000,
            'pinterest': 500
        };
        
        let selectedPlatform = '';
        
        window.showCustomModal = function(modalId) {
            console.log('🔄 [AYSA DEBUG] Opening custom modal:', modalId);
            const modal = document.getElementById(modalId);
            console.log('🔍 [AYSA DEBUG] Modal element in showCustomModal:', modal);
            console.log('🔍 [AYSA DEBUG] Modal current display:', modal ? modal.style.display : 'N/A');
            
            if (modal) {
                console.log('🔄 [AYSA DEBUG] Setting modal display to flex...');
                modal.style.display = 'flex';
                console.log('🔄 [AYSA DEBUG] Adding modal-open class to body...');
                document.body.classList.add('modal-open');
                console.log('✅ [AYSA DEBUG] Custom modal opened successfully');
                console.log('🔍 [AYSA DEBUG] Final modal display:', modal.style.display);
                console.log('🔍 [AYSA DEBUG] Body classes:', document.body.className);
            } else {
                console.error('❌ [AYSA DEBUG] Modal element not found in showCustomModal function');
            }
        };
        
        window.hideCustomModal = function(modalId) {
            console.log('🔄 [AYSA DEBUG] Closing custom modal:', modalId);
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.style.display = 'none';
                document.body.classList.remove('modal-open');
                console.log('✅ [AYSA DEBUG] Custom modal closed');
            }
        };
        
        $(document).on('click', '.custom-modal', function(e) {
            if (e.target === this) {
                hideCustomModal(this.id);
            }
        });
        
        $(document).on('click', '.custom-modal-close', function() {
            const modal = $(this).closest('.custom-modal');
            if (modal.length) {
                hideCustomModal(modal.attr('id'));
            }
        });
        
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                $('.custom-modal:visible').each(function() {
                    hideCustomModal(this.id);
                });
            }
        });

        $(document).on('click', '#open-social-content-generator', function() {
            console.log('🎯 [AYSA DEBUG] Generate Content button clicked!');
            console.log('🔍 [AYSA DEBUG] Current page URL:', window.location.href);
            console.log('🔍 [AYSA DEBUG] jQuery version:', $.fn.jquery);
            console.log('🔍 [AYSA DEBUG] Document ready state:', document.readyState);
            
            const modalElement = document.getElementById('social-content-generator-modal');
            console.log('🔍 [AYSA DEBUG] Modal element found:', modalElement);
            console.log('🔍 [AYSA DEBUG] Modal element display style:', modalElement ? modalElement.style.display : 'N/A');
            console.log('🔍 [AYSA DEBUG] Modal element computed display:', modalElement ? window.getComputedStyle(modalElement).display : 'N/A');
            
            if (!modalElement) {
                console.error('❌ [AYSA DEBUG] Modal element not found in DOM!');
                console.log('🔍 [AYSA DEBUG] Available elements with "modal" in ID:', 
                    Array.from(document.querySelectorAll('[id*="modal"]')).map(el => el.id));
                alert('Modal element not found. Please check if the modal HTML is present.');
                return;
            }
            
            try {
                console.log('🔄 [AYSA DEBUG] Attempting to show custom modal...');
                console.log('🔍 [AYSA DEBUG] showCustomModal function available:', typeof showCustomModal);
                showCustomModal('social-content-generator-modal');
                console.log('✅ [AYSA DEBUG] Custom modal shown successfully');
                
                setTimeout(() => {
                    const modalAfter = document.getElementById('social-content-generator-modal');
                    console.log('🔍 [AYSA DEBUG] Modal display after show:', modalAfter ? modalAfter.style.display : 'N/A');
                    console.log('🔍 [AYSA DEBUG] Body has modal-open class:', document.body.classList.contains('modal-open'));
                }, 100);
            } catch (error) {
                console.error('❌ [AYSA DEBUG] Error showing custom modal:', error);
                console.error('❌ [AYSA DEBUG] Error stack:', error.stack);
                alert('Error opening modal: ' + error.message);
            }
        });

        $(document).on('click', '#social-content-generator-modal .platform-card', function() {
            console.log('🎯 [AYSA DEBUG] Modal platform card clicked:', $(this).data('platform'));
            
            $('#social-content-generator-modal .platform-card').removeClass('selected');
            $(this).addClass('selected');
            
            selectedPlatform = $(this).data('platform');
            const limit = $(this).data('limit');
            
            console.log('✅ [AYSA DEBUG] Modal platform selected:', {
                platform: selectedPlatform,
                limit: limit
            });
            
            $('#character-limit').text(limit);
            updateCharacterCount();
            
            $('#social-content').val('');
            $('#copy-content-btn').hide();
        });

        $(document).on('input', '#social-content', function() {
            updateCharacterCount();
        });

        // Generate content
        $(document).on('click', '#generate-content-btn', function() {
            console.log('🎯 [AYSA DEBUG] Generate content button clicked');
            console.log('🔍 [AYSA DEBUG] Selected platform:', selectedPlatform);
            
            if (!selectedPlatform) {
                console.warn('⚠️ [AYSA DEBUG] No platform selected');
                showNotification('error', 'Please select a platform first.');
                return;
            }

            const button = $(this);
            const originalText = button.html();
            
            console.log('🔄 [AYSA DEBUG] Starting content generation for platform:', selectedPlatform);
            button.html('<i class="fas fa-spinner fa-spin me-2"></i>Generating...').prop('disabled', true);

            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_generate_social_content',
                    platform: selectedPlatform,
                    nonce: typeof aysaTaskNonce !== 'undefined' ? aysaTaskNonce : (typeof aysa_ajax !== 'undefined' ? aysa_ajax.nonce : '')
                },
                success: function(response) {
                    if (response.success) {
                        $('#social-content').val(response.data.content);
                        updateCharacterCount();
                        $('#copy-content-btn').show();
                        
                        showNotification('success', 'Content generated successfully!');
                    } else {
                        showNotification('error', response.data.message || 'Failed to generate content. Please try again.');
                    }
                },
                error: function() {
                    showNotification('error', 'A server error occurred. Please try again.');
                },
                complete: function() {
                    button.html(originalText).prop('disabled', false);
                }
            });
        });

        // Copy to clipboard
        $(document).on('click', '#copy-content-btn', function() {
            const content = $('#social-content').val();
            
            if (navigator.clipboard) {
                navigator.clipboard.writeText(content).then(function() {
                    showNotification('success', 'Content copied to clipboard!');
                }).catch(function() {
                    fallbackCopyToClipboard(content);
                });
            } else {
                fallbackCopyToClipboard(content);
            }
        });

        function updateCharacterCount() {
            const content = $('#social-content').val();
            const count = content.length;
            const limit = selectedPlatform ? platformLimits[selectedPlatform] : 0;
            
            $('#character-count').text(count);
            
            if (limit > 0) {
                const percentage = (count / limit) * 100;
                const countElement = $('#character-count');
                
                countElement.removeClass('warning danger');
                $('#character-status').text('');
                
                if (count > limit) {
                    countElement.addClass('danger');
                    $('#character-status').text('Over limit').addClass('text-danger');
                } else if (percentage > 90) {
                    countElement.addClass('warning');
                    $('#character-status').text('Near limit').addClass('text-warning');
                } else if (percentage > 75) {
                    countElement.addClass('warning');
                    $('#character-status').text('Getting close').addClass('text-warning');
                }
            }
        }

        function fallbackCopyToClipboard(text) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            
            try {
                document.execCommand('copy');
                showNotification('success', 'Content copied to clipboard!');
            } catch (err) {
                showNotification('error', 'Failed to copy content. Please copy manually.');
            }
            
            document.body.removeChild(textArea);
        }
    }

    /**
     * Show a notification message
     * 
     * @param {string} type - Type of notification (success, error, loading)
     * @param {string} message - Message to display
     * @param {number} duration - Duration in ms (0 for no auto-hide)
     */
    function showNotification(type, message, duration = 3000) {
        // Remove existing notifications
        $('.aysa-notification').remove();
        
        let icon = 'info';
        if (type === 'success') {
            icon = 'yes';
        } else if (type === 'error') {
            icon = 'no';
        } else if (type === 'loading') {
            icon = 'update spinning';
            // Don't auto-hide loading notifications
            duration = 0;
        }
        
        const $notification = $('<div>', {
            'class': 'aysa-notification aysa-notification-' + type
        }).html(`
            <span class="dashicons dashicons-${icon}"></span>
            <span class="notification-message">${message}</span>
            <button class="close-notification">&times;</button>
        `);
        
        // Add close button handler
        $notification.find('.close-notification').on('click', function() {
            $notification.fadeOut(200, function() {
                $(this).remove();
            });
        });
        
        // Add to page
        $('body').append($notification);
        
        // Position in top right corner
        $notification.css({
            'position': 'fixed',
            'top': '20px',
            'right': '20px',
            'z-index': 9999
        });
        
        // Auto-hide after duration (if not 0)
        if (duration > 0) {
            setTimeout(function() {
                $notification.fadeOut(200, function() {
                    $(this).remove();
                });
            }, duration);
        }
        
        return $notification;
    }

    // Initialize on document ready
    $(document).ready(function() {
        console.log('📄 [AYSA DEBUG] DOM ready, initializing Aysa Admin...');
        console.log('🔍 [AYSA DEBUG] jQuery version:', $.fn.jquery);
        console.log('🔍 [AYSA DEBUG] Document ready state:', document.readyState);
        console.log('🔍 [AYSA DEBUG] Bootstrap available on DOM ready:', typeof bootstrap !== 'undefined');
        console.log('🔍 [AYSA DEBUG] Current page URL:', window.location.href);
        console.log('🔍 [AYSA DEBUG] Page contains off-page-optimization:', window.location.href.includes('off-page-optimization'));
        
        initDropdowns();
        
        // Social Media Content Generator Modal functionality
        console.log('🔄 [AYSA DEBUG] Initializing Social Content Generator...');
        initSocialContentGenerator();
        
        // Check if modal elements exist
        const modalElement = document.getElementById('social-content-generator-modal');
        const buttonElement = document.getElementById('open-social-content-generator');
        console.log('🔍 [AYSA DEBUG] Modal elements check:', {
            modalExists: !!modalElement,
            buttonExists: !!buttonElement,
            modalHTML: modalElement ? modalElement.outerHTML.substring(0, 200) + '...' : 'N/A',
            buttonHTML: buttonElement ? buttonElement.outerHTML : 'N/A'
        });
        
        console.log('🔍 [AYSA DEBUG] All elements with "social" in ID:', 
            Array.from(document.querySelectorAll('[id*="social"]')).map(el => el.id));
        console.log('🔍 [AYSA DEBUG] All elements with "generator" in ID:', 
            Array.from(document.querySelectorAll('[id*="generator"]')).map(el => el.id));
        console.log('🔍 [AYSA DEBUG] All elements with "modal" in ID:', 
            Array.from(document.querySelectorAll('[id*="modal"]')).map(el => el.id));
        
        // Expose functions to global scope for use in other files
        window.aysaDropdown = {
            showDropdownMenu: showDropdownMenu,
            closeAllDropdowns: closeAllDropdowns,
            showNotification: showNotification
        };
        
        console.log('✅ [AYSA DEBUG] Aysa Admin initialization complete');
        
        setTimeout(() => {
            console.log('🧪 [AYSA DEBUG] Testing modal availability after initialization...');
            const testModal = document.getElementById('social-content-generator-modal');
            const testButton = document.getElementById('open-social-content-generator');
            console.log('🧪 [AYSA DEBUG] Post-init modal check:', {
                modalExists: !!testModal,
                buttonExists: !!testButton,
                showCustomModalAvailable: typeof showCustomModal === 'function'
            });
        }, 1000);
        
        // Initialize page-based social content generator if on the dedicated page
        if (window.location.href.includes('social-content-generator')) {
            console.log('🔄 [AYSA DEBUG] Initializing page-based social content generator...');
            initPageSocialContentGenerator();
        }

        // Handle update links for active Aysa plugin
        $('tr[data-plugin="aysaaiseo/aysa.php"] .update-now').on('click', function(e) {
            var $row = $(this).closest('tr');
            var $updateCell = $row.find('.plugin-update-tr .update-message');
            
            // Check if this is the Aysa plugin and it's active
            if ($row.hasClass('active')) {
                e.preventDefault();
                e.stopPropagation();
                
                // Show custom message instead of updating
                $updateCell.html(
                    '<p><strong>Cannot update active plugin.</strong> ' +
                    '<a href="#" class="aysa-deactivate-first">Deactivate plugin first</a>, then try updating again.</p>'
                );
                
                return false;
            }
        });
        
        // Handle deactivate first link
        $(document).on('click', '.aysa-deactivate-first', function(e) {
            e.preventDefault();
            
            var deactivateUrl = $('tr[data-plugin="aysaaiseo/aysa.php"] .deactivate a').attr('href');
            if (deactivateUrl) {
                if (confirm('Deactivate Aysa.ai plugin to allow safe updating?')) {
                    window.location.href = deactivateUrl;
                }
            }
        });
        
        // Override the default update behavior for Aysa plugin
        if (window.wp && window.wp.updates) {
            var originalUpdatePlugin = window.wp.updates.updatePlugin;
            
            window.wp.updates.updatePlugin = function(args) {
                // Check if this is the Aysa plugin
                if (args.plugin === 'aysaaiseo/aysa.php') {
                    // Check if plugin is active by looking at the table row
                    var $row = $('tr[data-plugin="' + args.plugin + '"]');
                    if ($row.hasClass('active')) {
                        // Show error message instead of updating
                        var $updateRow = $row.next('.plugin-update-tr');
                        $updateRow.find('.update-message').html(
                            '<p class="update-message notice inline notice-error notice-alt">' +
                            '<strong>Update blocked:</strong> Please deactivate the plugin first. ' +
                            '<a href="' + $row.find('.deactivate a').attr('href') + '">Deactivate Now</a>' +
                            '</p>'
                        );
                        return;
                    }
                }
                
                // Call original function for other plugins or inactive Aysa plugin
                return originalUpdatePlugin.call(this, args);
            };
        }
    });

    // Page-based Social Content Generator functionality
    function initPageSocialContentGenerator() {
        console.log('📄 [AYSA DEBUG] Initializing page-based social content generator...');
        
        let selectedPlatforms = [];
        let generatedContent = [];
        
        // Platform selection functionality
        $(document).on('click', '#platform-selection-page .platform-card', function() {
            const platform = $(this).data('platform');
            const limit = $(this).data('limit');
            
            if ($(this).hasClass('selected')) {
                $(this).removeClass('selected');
                selectedPlatforms = selectedPlatforms.filter(p => p.platform !== platform);
                console.log('🔄 [AYSA DEBUG] Platform deselected:', platform);
                
                // Remove dummy content for deselected platform
                generatedContent = generatedContent.filter(item => item.platform !== platform);
            } else {
                $(this).addClass('selected');
                selectedPlatforms.push({ platform, limit });
                console.log('🔄 [AYSA DEBUG] Platform selected:', platform, 'limit:', limit);
                
                // Generate dummy content immediately for selected platform
                generateDummyContentForPlatform(platform, limit);
            }
            
            updateSelectedPlatformsDisplay();
            updateGenerateButtonState();
            updateContentDisplay();
        });
        
        // Generate content for all selected platforms
        $(document).on('click', '#generate-all-content', function() {
            const topic = $('#content-topic').val().trim();
            const tone = $('#content-tone').val();
            
            if (!topic) {
                alert('Please enter a topic or keywords before generating content.');
                return;
            }
            
            if (selectedPlatforms.length === 0) {
                alert('Please select at least one platform before generating content.');
                return;
            }
            
            console.log('🎯 [AYSA DEBUG] Generating content for platforms:', selectedPlatforms);
            generateContentForPlatforms(topic, tone, selectedPlatforms);
        });
        

        
        $(document).on('click', '#copy-all-content', function() {
            copyAllContent();
        });
        
        $(document).on('click', '#export-all-content', function() {
            exportAllContent();
        });
        
        $(document).on('click', '#clear-all-content', function() {
            clearAllContent();
        });
        
        $(document).on('click', '.copy-content-btn', function() {
            const contentId = $(this).data('content-id');
            copyIndividualContent(contentId);
        });
        
        $(document).on('click', '.delete-content-btn', function() {
            const contentId = $(this).data('content-id');
            deleteIndividualContent(contentId);
        });
        
        function updateSelectedPlatformsDisplay() {
            const count = selectedPlatforms.length;
            const platformNames = selectedPlatforms.map(p => capitalizeFirst(p.platform)).join(', ');
            
            const generateBtn = $('#generate-all-content');
            if (count > 0) {
                generateBtn.html(`<i class="fas fa-magic"></i> Generate for ${count} Selected Platform${count > 1 ? 's' : ''}`);
            } else {
                generateBtn.html('<i class="fas fa-magic"></i> Generate for Selected Platforms');
            }
            
            console.log('📊 [AYSA DEBUG] Selected platforms updated:', count, 'platforms:', platformNames);
        }
        
        function updateGenerateButtonState() {
            const generateBtn = $('#generate-all-content');
            const topic = $('#content-topic').val().trim();
            
            if (selectedPlatforms.length > 0 && topic) {
                generateBtn.prop('disabled', false);
            } else {
                generateBtn.prop('disabled', true);
            }
        }
        
        function generateContentForPlatforms(topic, tone, platforms) {
            console.log('🎯 [AYSA DEBUG] Starting content generation for:', platforms.length, 'platforms');
            
            const button = $('#generate-all-content');
            const originalText = button.html();
            button.html('<i class="fas fa-spinner fa-spin me-2"></i>Generating...').prop('disabled', true);
            
            const platformNames = platforms.map(p => p.platform);
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'aysa_generate_social_content',
                    platforms: platformNames,
                    appname: 'aysa-plugin', // For future API integration
                    nonce: typeof aysaTaskNonce !== 'undefined' ? aysaTaskNonce : (typeof aysa_ajax !== 'undefined' ? aysa_ajax.nonce : '')
                },
                success: function(response) {
                    if (response.success && response.data.results) {
                        response.data.results.forEach(result => {
                            const contentItem = {
                                id: Date.now() + Math.random(),
                                platform: result.platform,
                                content: result.content,
                                topic: topic,
                                tone: tone,
                                characterCount: result.character_count,
                                characterLimit: result.character_limit,
                                timestamp: new Date().toLocaleString()
                            };
                            
                            generatedContent.push(contentItem);
                            addContentToDisplay(contentItem);
                        });
                        
                        updateBulkActionButtons();
                        showNotification('success', `Content generated for ${response.data.results.length} platforms!`);
                    } else {
                        showNotification('error', response.data.message || 'Failed to generate content. Please try again.');
                    }
                },
                error: function() {
                    showNotification('error', 'A server error occurred. Please try again.');
                },
                complete: function() {
                    button.html(originalText).prop('disabled', false);
                }
            });
        }
        
        function generateContentForSinglePlatform(topic, tone, platformData) {
            const { platform, limit } = platformData;
            
            console.log('📝 [AYSA DEBUG] Generating content for platform:', platform, 'with limit:', limit);
            
            // Generate lorem ipsum content for now (as requested by user)
            const content = generateLoremIpsumContent(platform, limit, topic, tone);
            
            const contentItem = {
                id: Date.now() + Math.random(),
                platform: platform,
                content: content,
                topic: topic,
                tone: tone,
                characterCount: content.length,
                characterLimit: limit,
                timestamp: new Date().toLocaleString()
            };
            
            generatedContent.push(contentItem);
            addContentToDisplay(contentItem);
            updateBulkActionButtons();
            
            console.log('✅ [AYSA DEBUG] Content generated for', platform, ':', content.substring(0, 50) + '...');
        }
        
        function generateLoremIpsumContent(platform, limit, topic, tone) {
            // Generate professional placeholder content instead of Lorem Ipsum
            const professionalTexts = [
                "Professional content generation in progress. Please wait while we create optimized content for your platform.",
                "AI-powered content optimization is currently being processed. This ensures the highest quality output.",
                "Content generation system is analyzing your requirements to deliver personalized marketing content.",
                "Smart content creation in progress. Our system is crafting content that matches your brand voice.",
                "Advanced content optimization engine is preparing tailored content for maximum engagement."
            ];
            
            let content = `${topic ? '[' + topic + '] ' : ''}${professionalTexts[Math.floor(Math.random() * professionalTexts.length)]}`;
            
            // Add tone-specific modifications
            switch(tone) {
                case 'professional':
                    content += ' #Professional #Business';
                    break;
                case 'casual':
                    content += ' 😊 #Casual #Fun';
                    break;
                case 'friendly':
                    content += ' 👋 #Friendly #Community';
                    break;
                case 'authoritative':
                    content += ' #Expert #Authority';
                    break;
                case 'creative':
                    content += ' ✨ #Creative #Innovation';
                    break;
            }
            
            if (content.length > limit) {
                content = content.substring(0, limit - 3) + '...';
            }
            
            return content;
        }
        
        function generateDummyContentForPlatform(platform, limit) {
            const topic = $('#content-topic').val().trim() || 'Content Topic';
            const tone = $('#content-tone').val() || 'professional';
            
            const content = generateLoremIpsumContent(platform, limit, topic, tone);
            
            const contentItem = {
                id: Date.now() + Math.random(),
                platform: platform,
                content: content,
                topic: topic,
                tone: tone,
                characterCount: content.length,
                characterLimit: limit,
                timestamp: new Date().toLocaleString()
            };
            
            generatedContent.push(contentItem);
            console.log('✅ [AYSA DEBUG] Dummy content generated for', platform, ':', content.substring(0, 50) + '...');
        }
        
        function addContentToDisplay(contentItem) {
            updateContentDisplay();
        }
        
        function updateContentDisplay() {
            const contentTable = $('#content-table');
            const contentTableBody = $('#content-table-body');
            const emptyState = $('#empty-state');
            
            if (generatedContent.length === 0) {
                contentTable.hide();
                emptyState.show();
                return;
            }
            
            contentTableBody.empty();
            
            generatedContent.forEach(contentItem => {
                const rowHtml = `
                    <tr class="content-row" data-content-id="${contentItem.id}" data-platform="${contentItem.platform}">
                        <td class="content-platform">
                            <strong>${capitalizeFirst(contentItem.platform)}</strong>
                        </td>
                        <td class="content-text">
                            <div class="content-preview">${contentItem.content}</div>
                            <div class="content-meta">
                                ${contentItem.tone} tone | Generated: ${contentItem.timestamp}
                            </div>
                        </td>
                        <td class="content-count">
                            <span class="character-count">${contentItem.characterCount}/${contentItem.characterLimit}</span>
                        </td>
                        <td class="content-actions">
                            <button class="btn btn-outline-primary copy-content-btn" data-content-id="${contentItem.id}">
                                <i class="fas fa-copy"></i> Copy
                            </button>
                            <button class="btn btn-outline-danger delete-content-btn" data-content-id="${contentItem.id}">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </td>
                    </tr>
                `;
                contentTableBody.append(rowHtml);
            });
            
            emptyState.hide();
            contentTable.show();
        }
        
        function updateBulkActionButtons() {
            const hasContent = generatedContent.length > 0;
            $('#copy-all-content, #export-all-content, #clear-all-content').prop('disabled', !hasContent);
        }
        
        function copyAllContent() {
            if (generatedContent.length === 0) return;
            
            const allContent = generatedContent.map(item => 
                `${capitalizeFirst(item.platform)}:\n${item.content}\n`
            ).join('\n---\n\n');
            
            copyToClipboard(allContent);
            console.log('📋 [AYSA DEBUG] All content copied to clipboard');
        }
        
        function exportAllContent() {
            if (generatedContent.length === 0) return;
            
            const exportData = {
                exportDate: new Date().toISOString(),
                totalItems: generatedContent.length,
                content: generatedContent
            };
            
            const dataStr = JSON.stringify(exportData, null, 2);
            const dataBlob = new Blob([dataStr], {type: 'application/json'});
            const url = URL.createObjectURL(dataBlob);
            
            const link = document.createElement('a');
            link.href = url;
            link.download = `social-content-export-${new Date().toISOString().split('T')[0]}.json`;
            link.click();
            
            URL.revokeObjectURL(url);
            console.log('💾 [AYSA DEBUG] Content exported to file');
        }
        
        function clearAllContent() {
            if (generatedContent.length === 0) return;
            
            if (confirm('Are you sure you want to clear all generated content? This action cannot be undone.')) {
                generatedContent = [];
                updateContentDisplay();
                updateBulkActionButtons();
                console.log('🗑️ [AYSA DEBUG] All content cleared');
            }
        }
        
        function copyIndividualContent(contentId) {
            const content = generatedContent.find(item => item.id == contentId);
            if (content) {
                copyToClipboard(content.content);
                console.log('📋 [AYSA DEBUG] Individual content copied:', content.platform);
            }
        }
        
        function deleteIndividualContent(contentId) {
            generatedContent = generatedContent.filter(item => item.id != contentId);
            updateContentDisplay();
            updateBulkActionButtons();
            console.log('🗑️ [AYSA DEBUG] Individual content deleted:', contentId);
        }
        
        function copyToClipboard(text) {
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text).then(() => {
                    showNotification('Content copied to clipboard!', 'success');
                }).catch(() => {
                    fallbackCopyToClipboard(text);
                });
            } else {
                fallbackCopyToClipboard(text);
            }
        }
        
        function capitalizeFirst(str) {
            return str.charAt(0).toUpperCase() + str.slice(1);
        }
        
        $(document).on('input', '#content-topic', function() {
            updateGenerateButtonState();
        });
        
        console.log('✅ [AYSA DEBUG] Page-based social content generator initialized');
    }

})(jQuery);                                                                                                                                                                                                                                                                                                                                                                        
