/**
 * Virtual Files Admin JavaScript
 */

jQuery(document).ready(function($) {
    'use strict';

    // Initialize functionality on virtual file post type pages
    if ($('#post_type_idep_virtual_file').length || $('body.post-type-idep_virtual_file').length) {
        initVirtualFileAdmin();
    }

    // Initialize functionality on settings page
    if ($('#virtual-files-settings').length) {
        initSettingsPage();
    }

    /**
     * Initialize Virtual File admin functionality
     */
    function initVirtualFileAdmin() {
        // Debug logging
        if (typeof intentdeepVfData !== 'undefined' && intentdeepVfData.debug) {
            // console.log('Virtual Files: Initializing admin functionality');
            // console.log('Virtual Files: Data object:', intentdeepVfData);
        }

        // Check if we have the new layout (separate filename and extension)
        if ($('#vf_extension').length) {
            initNewFilenameLayout();
        } else {
            // Legacy layout handling
            initLegacyFilenameLayout();
        }

        // Show/hide pro features
        toggleProFeatures();

        // Initialize CodeMirror if available
        initCodeMirror();

        // Initialize AI Generator
        initAiGenerator();

        // Handle limit banner "Later" button click
        $('#vf-dismiss-banner').on('click', function() {
            dismissLimitBanner();
        });

        // Handle publish/update validation and CodeMirror sync
        $('#post').on('submit', function(e) {
            // Sync CodeMirror content back to textarea before submission
            if (typeof window.virtualFilesCodeMirror !== 'undefined') {
                window.virtualFilesCodeMirror.save();
                // console.log('CodeMirror synced. Content:', $('#vf_content').val());
            } else {
                // console.log('No CodeMirror. Content:', $('#vf_content').val());
            }
            return validateVirtualFileForm();
        });
    }

    /**
     * Initialize new filename layout (separate filename + extension dropdown)
     */
    function initNewFilenameLayout() {
        const $filename = $('#vf_filename');
        const $extension = $('#vf_extension');

        // Update MIME type when inputs change
        function updateMimeType() {
            const extension = $extension.val();
            const selectedOption = $extension.find('option:selected');

            // Update MIME type display
            const mimeType = selectedOption.data('mime') || 'text/plain; charset=utf-8';
            $('.vf-mime-value').text(mimeType);

            // Update CodeMirror mode if available
            if (typeof updateCodeMirrorMode === 'function') {
                updateCodeMirrorMode(extension);
            }
        }

        // Event listeners
        $extension.on('change', updateMimeType);

        // Initial MIME type update
        updateMimeType();

        // Validate filename on blur
        $filename.on('blur', function() {
            validateNewFilename($(this), $extension);
        });

        // Handle Pro feature upsell when selecting Pro extension
        $extension.on('change', function() {
            const selectedOption = $(this).find('option:selected');
            const isPro = typeof intentdeepVfData !== 'undefined' && intentdeepVfData.isPro;

            // Only show upsell if extension is Pro AND user doesn't have Pro
            if (selectedOption.data('pro') === true && !isPro) {
                showProUpsell(selectedOption.text());
                // Reset to first available option
                $(this).val('txt');
                updateMimeType();
            }
        });
    }

    /**
     * Initialize legacy filename layout (single filename input)
     */
    function initLegacyFilenameLayout() {
        // Auto-detect MIME type when filename changes
        $('#vf_filename').on('input', function() {
            const filename = $(this).val();
            const mimeType = detectMimeType(filename);

            // Update MIME type display if it exists
            if ($('.vf-mime-value').length) {
                $('.vf-mime-value').text(mimeType);
            } else {
                $('#vf_mime_type').val(mimeType);
            }
        });

        // Validate filename on blur
        $('#vf_filename').on('blur', function() {
            validateFilename($(this));
        });
    }

    /**
     * Initialize Settings page functionality
     */
    function initSettingsPage() {
        // Handle settings form submission
        $('#virtual-files-settings-form').on('submit', function(e) {
            e.preventDefault();
            saveSettings();
        });

        // Handle flush rewrite rules button
        $('#vf-flush-rewrite').on('click', function(e) {
            e.preventDefault();
            flushRewriteRules($(this));
        });

        // Handle export/import buttons if they exist
        $('#vf-export-files').on('click', function(e) {
            e.preventDefault();
            exportVirtualFiles();
        });

        $('#vf-import-files').on('change', function(e) {
            importVirtualFiles(e.target.files[0]);
        });

        // Show/hide advanced settings
        $('.vf-advanced-toggle').on('click', function() {
            $('.vf-advanced-settings').slideToggle();
            $(this).text($(this).text().includes('Show') ? 'Hide Advanced Settings' : 'Show Advanced Settings');
        });
    }

    /**
     * Detect MIME type based on filename extension
     */
    function detectMimeType(filename) {
        if (!filename) return 'text/plain; charset=utf-8';

        const extension = filename.split('.').pop().toLowerCase();
        const mimeTypes = {
            'txt': 'text/plain; charset=utf-8',
            'md': 'text/markdown; charset=utf-8',
            'json': 'application/json; charset=utf-8',
            'xml': 'application/xml; charset=utf-8',
            'rss': 'application/rss+xml; charset=utf-8',
            'csv': 'text/csv; charset=utf-8',
            'yml': 'text/yaml; charset=utf-8',
            'yaml': 'text/yaml; charset=utf-8',
            'log': 'text/plain; charset=utf-8'
        };

        return mimeTypes[extension] || 'text/plain; charset=utf-8';
    }

    /**
     * Validate filename input (legacy - full filename)
     */
    function validateFilename($input) {
        const filename = $input.val();

        if (!filename) {
            showFilenameError($input, 'Filename is required');
            return false;
        }

        // Check for invalid characters
        if (/[<>:"|?*]/.test(filename)) {
            showFilenameError($input, 'Filename contains invalid characters');
            return false;
        }

        // Check for extension
        const extension = filename.split('.').pop().toLowerCase();
        const allowedExtensions = ['txt', 'md', 'json', 'xml', 'rss', 'csv', 'yml', 'yaml', 'log'];

        if (!allowedExtensions.includes(extension)) {
            showFilenameError($input, `File extension .${extension} is not allowed`);
            return false;
        }

        hideFilenameError($input);
        return true;
    }

    /**
     * Validate new filename format (separate filename + extension)
     */
    function validateNewFilename($filenameInput, $extensionSelect) {
        const filename = $filenameInput.val();
        const extension = $extensionSelect.val();

        if (!filename) {
            showFilenameError($filenameInput, 'File name is required');
            return false;
        }

        // Check for invalid characters
        if (/[<>:"|?*]/.test(filename)) {
            showFilenameError($filenameInput, 'Path contains invalid characters');
            return false;
        }

        // Normalize path for validation (remove leading/trailing slashes)
        const normalizedPath = filename.replace(/^\/+|\/+$/g, '').toLowerCase();

        // Check for restricted WordPress paths
        const restrictedPrefixes = [
            'wp-admin/',
            'wp-includes/',
            'wp-content/plugins/',
            'wp-content/themes/',
            'wp-json/'
        ];

        for (const prefix of restrictedPrefixes) {
            if (normalizedPath.startsWith(prefix)) {
                showFilenameError($filenameInput, 'Cannot use WordPress reserved path "' + normalizedPath.split('/')[0] + '/". Please choose a different path.');
                return false;
            }
        }

        // Check for restricted WordPress slugs (first path segment)
        const restrictedSlugs = ['feed', 'embed', 'trackback'];
        const firstSegment = normalizedPath.split('/')[0];

        if (restrictedSlugs.includes(firstSegment)) {
            showFilenameError($filenameInput, 'Cannot use WordPress reserved path "' + firstSegment + '". Please choose a different path.');
            return false;
        }

        // Check for .htaccess files (server restriction warning)
        if (normalizedPath.startsWith('.htaccess') || normalizedPath.includes('/.htaccess')) {
            showFilenameError($filenameInput, 'Warning: .htaccess files are blocked by most web servers and will not be accessible.');
            return false;
        }

        // Check if filename has an extension (avoid false positives with dots in folder names like .well-known)
        // Only check the actual filename part (after last slash)
        const parts = filename.split('/');
        const filenamePart = parts[parts.length - 1];

        // Check if filename part has a file extension (dot + 2-6 letters at the end)
        // Exclude hidden files that start with a dot (like .htaccess)
        const hasExtension = /\.[a-z]{2,6}$/i.test(filenamePart) && !filenamePart.startsWith('.');

        if (hasExtension) {
            showFilenameError($filenameInput, 'Path should not include file extension. Select the extension from the dropdown.');
            return false;
        }

        hideFilenameError($filenameInput);
        return true;
    }

    /**
     * Show filename error message
     */
    function showFilenameError($input, message) {
        let $errorDiv = $input.siblings('.vf-filename-error');
        if (!$errorDiv.length) {
            $errorDiv = $('<div class="vf-filename-error vf-filename-error-compact"></div>');
            $input.parent().css('position', 'relative').append($errorDiv);
        }
        $errorDiv.text(message).show();
        $input.removeClass('success').addClass('error');

        // Remove success class if exists
        $input.removeClass('success');
    }

    /**
     * Hide filename error message
     */
    function hideFilenameError($input) {
        $input.siblings('.vf-filename-error').hide();
        $input.removeClass('error');

        // Add success class briefly for feedback
        $input.addClass('success');
        setTimeout(() => {
            $input.removeClass('success');
        }, 2000);
    }

    /**
     * Show Pro upsell dialog
     */
    function showProUpsell(featureName) {
        const message = `The ${featureName} file type is a Pro feature. Upgrade to Pro to unlock advanced file types including XML, RSS, CSV, and YAML formats.`;

        if (confirm(message + '\n\nWould you like to upgrade to Pro now?')) {
            // Redirect to upgrade page
            if (typeof FS !== 'undefined' && typeof FS.upgrade === 'function') {
                FS.upgrade(true);
            } else {
                // Fallback: show a message with instructions
                alert('To upgrade, please go to the Virtual Files settings page and click on "Upgrade to Pro".');
            }
        }
    }

    /**
     * Toggle pro features visibility
     */
    function toggleProFeatures() {
        // This would be handled server-side, but we can enhance the UI
        if (typeof intentdeepVfData !== 'undefined' && intentdeepVfData.isPro) {
            $('.vf-pro-only').show();
            $('.vf-free-upsell').hide();
        } else {
            $('.vf-pro-only').hide();
            $('.vf-free-upsell').show();
        }
    }

    /**
     * Initialize CodeMirror if available (Pro feature)
     */
    function initCodeMirror() {
        // Debug logging
        if (typeof intentdeepVfData !== 'undefined' && intentdeepVfData.debug) {
            // console.log('Virtual Files: CodeMirror init check');
            // console.log('- intentdeepVfData exists:', typeof intentdeepVfData !== 'undefined');
            // console.log('- isPro:', intentdeepVfData.isPro);
            // console.log('- wp.codeEditor available:', typeof wp !== 'undefined' && typeof wp.codeEditor !== 'undefined');
            // console.log('- vf_content exists:', $('#vf_content').length);
            // console.log('- codeEditorSettings:', intentdeepVfData.codeEditorSettings);
        }

        // Initialize for pro users with WordPress code editor
        if (typeof intentdeepVfData !== 'undefined' &&
            intentdeepVfData.isPro &&
            intentdeepVfData.codeEditorSettings &&
            typeof wp !== 'undefined' &&
            typeof wp.codeEditor !== 'undefined' &&
            $('#vf_content').length) {

            // Show loading state only if loading element exists
            if ($('.vf-editor-loading').length) {
                $('.vf-editor-loading').show();
                $('#vf_content').hide();
            }

            // Get mode based on file extension
            let mode = 'text/plain';
            if ($('#vf_extension').length) {
                const extension = $('#vf_extension').val();
                mode = getCodeMirrorModeForWP(extension);
            } else {
                mode = detectCodeMirrorModeForWP($('#vf_filename').val());
            }

            // Customize settings with our mode
            const editorSettings = $.extend(true, {}, intentdeepVfData.codeEditorSettings, {
                codemirror: {
                    mode: mode,
                    lineNumbers: true,
                    lineWrapping: true,
                    indentUnit: 2,
                    tabSize: 2,
                }
            });

            // Initialize editor with small delay
            setTimeout(function() {
                // Initialize WordPress code editor
                const editorInstance = wp.codeEditor.initialize('vf_content', editorSettings);

                if (editorInstance) {
                    // Store editor reference for external access
                    window.virtualFilesCodeMirror = editorInstance.codemirror;

                    // Hide loading and show editor
                    if ($('.vf-editor-loading').length) {
                        $('.vf-editor-loading').fadeOut(200);
                    }
                    $('.CodeMirror').show();

                    // Update mode when inputs change
                    updateCodeMirrorModeOnChange();

                    // Add status bar with file info
                    addEditorStatusBar();

                    if (typeof intentdeepVfData !== 'undefined' && intentdeepVfData.debug) {
                        // console.log('WordPress Code Editor initialized with mode:', mode);
                    }
                } else {
                    console.error('Failed to initialize WordPress code editor');
                    if ($('.vf-editor-loading').length) {
                        $('.vf-editor-loading').hide();
                    }
                    $('#vf_content').show();
                }
            }, 300);
        }
    }

    /**
     * Safely try to set CodeMirror mode with fallback
     */
    function trySetCodeMirrorMode(mode) {
        if (typeof window.virtualFilesCodeMirror === 'undefined') return;

        try {
            // Test if the mode is available by trying to set it
            window.virtualFilesCodeMirror.setOption('mode', mode);

            if (typeof intentdeepVfData !== 'undefined' && intentdeepVfData.debug) {
                // console.log('Virtual Files: Successfully set mode to', mode);
            }
        } catch (error) {
            console.warn('Virtual Files: Failed to set mode', mode, 'falling back to plain text', error);
            // Fallback to plain text mode
            window.virtualFilesCodeMirror.setOption('mode', 'text/plain');
        }
    }

    /**
     * Update CodeMirror mode from extension (for external calls)
     */
    function updateCodeMirrorMode(extension) {
        if (typeof window.virtualFilesCodeMirror !== 'undefined') {
            const mode = getCodeMirrorModeForWP(extension);
            trySetCodeMirrorMode(mode);
        }
    }

    /**
     * Get CodeMirror mode from file extension (for WordPress code editor)
     */
    function getCodeMirrorModeForWP(extension) {
        // Map extensions to WordPress-compatible CodeMirror modes
        const modes = {
            'txt': 'text/plain',
            'md': 'text/x-gfm',
            'markdown': 'text/x-gfm',
            'json': 'application/json',
            'xml': 'application/xml',
            'rss': 'application/xml',
            'csv': 'text/plain',
            'yml': 'text/x-yaml',
            'yaml': 'text/x-yaml',
            'log': 'text/plain',
            'js': 'javascript',
            'javascript': 'javascript',
            'css': 'css',
            'html': 'htmlmixed',
            'htm': 'htmlmixed',
            'php': 'application/x-httpd-php',
            'py': 'python',
            'python': 'python',
            'sql': 'text/x-sql',
            'sh': 'text/x-sh',
            'bash': 'text/x-sh'
        };

        const mode = modes[extension] || 'text/plain';

        // Debug logging for mode detection
        if (typeof intentdeepVfData !== 'undefined' && intentdeepVfData.debug) {
            // console.log('Virtual Files: Extension "' + extension + '" mapped to mode "' + mode + '"');
        }

        return mode;
    }

    /**
     * Detect CodeMirror mode based on filename (for WordPress code editor)
     */
    function detectCodeMirrorModeForWP(filename) {
        if (!filename) return 'text/plain';

        const extension = filename.split('.').pop().toLowerCase();
        return getCodeMirrorModeForWP(extension);
    }

    /**
     * Get CodeMirror mode from file extension (legacy - kept for backward compatibility)
     */
    function getCodeMirrorModeFromExtension(extension) {
        return getCodeMirrorModeForWP(extension);
    }

    /**
     * Detect CodeMirror mode based on filename (legacy - kept for backward compatibility)
     */
    function detectCodeMirrorMode(filename) {
        return detectCodeMirrorModeForWP(filename);
    }

    /**
     * Validate virtual file form before submission
     */
    function validateVirtualFileForm() {
        const $filename = $('#vf_filename');
        const $content = $('#vf_content');

        let isFilenameValid = false;

        // Check which layout we're using and validate accordingly
        if ($('#vf_extension').length) {
            // New layout
            isFilenameValid = validateNewFilename($filename, $('#vf_extension'));
        } else {
            // Legacy layout
            isFilenameValid = validateFilename($filename);
        }

        // Validate filename
        if (!isFilenameValid) {
            $filename.focus();
            return false;
        }

        // Validate content
        if (!$content.val().trim()) {
            alert('File content cannot be empty');
            $content.focus();
            return false;
        }

        return true;
    }

    /**
     * Save settings via AJAX
     */
    function saveSettings() {
        const $form = $('#virtual-files-settings-form');
        const $button = $form.find('button[type="submit"]');
        const originalText = $button.text();

        // Show loading state
        $button.prop('disabled', true).html('<span class="vf-loading"></span>Saving...');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'intentdeep_vf_save_options',
                nonce: $('#vf-settings-nonce').val(),
                settings: $form.serialize()
            },
            success: function(response) {
                if (response.success) {
                    showNotice('Settings saved successfully!', 'success');
                } else {
                    showNotice(response.data.message || 'Error saving settings', 'error');
                }
            },
            error: function() {
                showNotice('An error occurred while saving settings', 'error');
            },
            complete: function() {
                $button.prop('disabled', false).text(originalText);
            }
        });
    }

    /**
     * Flush rewrite rules via AJAX
     */
    function flushRewriteRules($button) {
        const originalText = $button.text();

        // Show loading state
        $button.prop('disabled', true).html('<span class="vf-loading"></span>Flushing...');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'intentdeep_vf_flush_rewrite',
                nonce: $('#vf-settings-nonce').val()
            },
            success: function(response) {
                if (response.success) {
                    showNotice('Rewrite rules flushed successfully!', 'success');
                } else {
                    showNotice(response.data.message || 'Error flushing rewrite rules', 'error');
                }
            },
            error: function() {
                showNotice('An error occurred while flushing rewrite rules', 'error');
            },
            complete: function() {
                $button.prop('disabled', false).text(originalText);
            }
        });
    }

    /**
     * Export virtual files (Pro feature)
     */
    function exportVirtualFiles() {
        if (typeof intentdeepVfData !== 'undefined' && !intentdeepVfData.isPro) {
            if (confirm('Export is a Pro feature. Would you like to upgrade?')) {
                // Redirect to upgrade page
                if (typeof FS !== 'undefined') {
                    FS.upgrade(true);
                }
            }
            return;
        }

        window.location.href = ajaxurl + '?action=intentdeep_vf_export&nonce=' + $('#vf-settings-nonce').val();
    }

    /**
     * Import virtual files (Pro feature)
     */
    function importVirtualFiles(file) {
        if (!file) return;

        if (typeof intentdeepVfData !== 'undefined' && !intentdeepVfData.isPro) {
            alert('Import is a Pro feature. Please upgrade to Pro to use this feature.');
            return;
        }

        const formData = new FormData();
        formData.append('action', 'intentdeep_vf_import');
        formData.append('nonce', $('#vf-settings-nonce').val());
        formData.append('import_file', file);

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    showNotice('Files imported successfully!', 'success');
                    // Reload the page to show imported files
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showNotice(response.data.message || 'Error importing files', 'error');
                }
            },
            error: function() {
                showNotice('An error occurred while importing files', 'error');
            }
        });
    }

    /**
     * Show admin notice
     */
    function showNotice(message, type) {
        const $notice = $('<div class="notice notice-' + type + ' is-dismissible"><p>' + message + '</p></div>');

        $('h1').after($notice);

        // Auto-hide after 5 seconds for success notices
        if (type === 'success') {
            setTimeout(() => {
                $notice.fadeOut(() => $notice.remove());
            }, 5000);
        }

        // Make dismissible
        $notice.on('click', '.notice-dismiss', function() {
            $notice.fadeOut(() => $notice.remove());
        });
    }

    /**
     * Confirm delete action for virtual files
     */
    $(document).on('click', '.submitdelete', function(e) {
        if (!confirm('Are you sure you want to delete this virtual file? This action cannot be undone.')) {
            e.preventDefault();
            return false;
        }
    });

    /**
     * Handle File Details metabox enhanced functionality
     */
    // Copy URL functionality
    $(document).on('click', '.vf-copy-btn', function(e) {
        e.preventDefault();
        const targetId = $(this).data('target');
        const $target = $('#' + targetId);
        const url = $target.val();

        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(() => {
                // Show feedback
                const $feedback = $('.vf-url-copy-feedback');
                $feedback.show();
                setTimeout(() => {
                    $feedback.fadeOut();
                }, 2000);
            }).catch(err => {
                console.error('Failed to copy URL:', err);
                // Fallback for older browsers
                $target.select();
                document.execCommand('copy');
            });
        } else {
            // Fallback for older browsers
            $target.select();
            document.execCommand('copy');
            const $feedback = $('.vf-url-copy-feedback');
            $feedback.show();
            setTimeout(() => {
                $feedback.fadeOut();
            }, 2000);
        }
    });

    // Visit file button
    $(document).on('click', '.vf-visit-file', function(e) {
        e.preventDefault();
        const url = $(this).data('url');
        if (url) {
            window.open(url, '_blank');
        }
    });

    // Copy URL button (for file link metabox)
    $(document).on('click', '.vf-copy-url-btn', function(e) {
        e.preventDefault();
        const url = $(this).data('url');

        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(() => {
                alert('URL copied to clipboard!');
            }).catch(err => {
                console.error('Failed to copy URL:', err);
                // Fallback for older browsers
                fallbackCopyToClipboard(url);
            });
        } else {
            // Fallback for older browsers
            fallbackCopyToClipboard(url);
        }
    });

    // Fallback copy to clipboard function
    function fallbackCopyToClipboard(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        try {
            document.execCommand('copy');
            alert('URL copied to clipboard!');
        } catch (err) {
            alert('Failed to copy URL');
        }
        document.body.removeChild(textArea);
    }

    // Copy edit link
    $(document).on('click', '.vf-copy-edit-link', function(e) {
        e.preventDefault();
        const url = $(this).data('edit-url');
        if (url && navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(() => {
                alert('Edit link copied to clipboard!');
            }).catch(err => {
                console.error('Failed to copy edit link:', err);
            });
        }
    });

    // Upgrade prompt
    $(document).on('click', '.vf-upgrade-prompt', function(e) {
        e.preventDefault();
        const url = $(this).data('upgrade-url');
        if (url) {
            window.location.href = url;
        }
    });

    /**
     * Sync status dropdowns between main metabox and sidebar
     */
    function syncStatusDropdowns() {
        // Sync from main to sidebar
        $(document).on('change', '#vf_status', function() {
            const value = $(this).val();
            $('#vf_status_sidebar').val(value);
        });

        // Sync from sidebar to main
        $(document).on('change', '#vf_status_sidebar', function() {
            const value = $(this).val();
            $('#vf_status').val(value);
        });
    }

    // Initialize status sync
    syncStatusDropdowns();

    /**
     * Handle bulk actions
     */
    $('#doaction, #doaction2').on('click', function(e) {
        const action = $(this).prev('select').val();

        if (action === 'delete') {
            const count = $('#bulk-action-selector-top').length ?
                $('#bulk-action-selector-top').val() :
                $('#bulk-action-selector-bottom').val();

            if ($('input[name="post[]"]:checked').length === 0) {
                alert('Please select at least one virtual file to delete.');
                e.preventDefault();
                return false;
            }

            if (!confirm('Are you sure you want to delete the selected virtual files? This action cannot be undone.')) {
                e.preventDefault();
                return false;
            }
        }
    });

    /**
     * Handle media uploader for file import (if needed)
     */
    function initMediaUploader() {
        let file_frame;

        $(document).on('click', '.vf-upload-file', function(e) {
            e.preventDefault();

            // If the media frame already exists, reopen it.
            if (file_frame) {
                file_frame.open();
                return;
            }

            // Create the media frame.
            file_frame = wp.media.frames.file_frame = wp.media({
                title: 'Select File to Import',
                button: {
                    text: 'Import File',
                },
                multiple: false
            });

            // When a file is selected, run a callback.
            file_frame.on('select', function() {
                const attachment = file_frame.state().get('selection').first().toJSON();
                // Handle the selected file
                // console.log('Selected file:', attachment);
            });

            // Open the modal
            file_frame.open();
        });
    }

    /**
     * Check if dark mode is preferred by user
     */
    function isDarkModePreferred() {
        return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    }

    /**
     * Update CodeMirror mode when file inputs change
     */
    function updateCodeMirrorModeOnChange() {
        if (typeof window.virtualFilesCodeMirror === 'undefined') return;

        if ($('#vf_extension').length) {
            // New layout: update mode when extension changes
            $('#vf_extension').on('change', function() {
                const extension = $(this).val();
                const mode = getCodeMirrorModeForWP(extension);
                trySetCodeMirrorMode(mode);
                updateStatusBar(extension, mode);
            });
        } else {
            // Legacy layout: update mode when filename changes
            $('#vf_filename').on('input', function() {
                const filename = $(this).val();
                const mode = detectCodeMirrorModeForWP(filename);
                const extension = filename.split('.').pop().toLowerCase();
                trySetCodeMirrorMode(mode);
                updateStatusBar(extension, mode);
            });
        }
    }

    /**
     * Add status bar with file information
     */
    function addEditorStatusBar() {
        if (typeof window.virtualFilesCodeMirror === 'undefined') return;

        const $statusBar = $('<div id="vf-editor-status" style="margin-top: 5px; font-size: 12px; color: #666; border-top: 1px solid #ddd; padding-top: 5px;">' +
            '<span id="vf-mode-info">Mode: text/plain</span> | ' +
            '<span id="vf-lines-info">Lines: 1</span>' +
            '</div>');

        // Insert after the editor
        $('.CodeMirror').after($statusBar);

        // Update status when content changes
        const editor = window.virtualFilesCodeMirror;
        editor.on('change', function() {
            const lineCount = editor.lineCount();
            $('#vf-lines-info').text('Lines: ' + lineCount);
        });

        // Initial status update - update line count immediately after content is loaded
        const extension = $('#vf_extension').length ? $('#vf_extension').val() : $('#vf_filename').val().split('.').pop().toLowerCase();
        const mode = getCodeMirrorModeForWP(extension);
        const initialLineCount = editor.lineCount();

        // Update all status bar items including the initial line count
        updateStatusBar(extension, mode, null, initialLineCount);
    }

    /**
     * Update status bar information
     */
    function updateStatusBar(extension, mode, theme, lineCount = null) {
        if ($('#vf-mode-info').length) {
            $('#vf-mode-info').text('Mode: ' + mode + ' (.' + extension + ')');
        }
        if ($('#vf-lines-info').length && lineCount !== null) {
            $('#vf-lines-info').text('Lines: ' + lineCount);
        }
    }

    /**
     * Dismiss limit banner via AJAX
     */
    function dismissLimitBanner() {
        $.ajax({
            url: typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl ? intentdeepVfData.ajaxUrl : ajaxurl,
            type: "POST",
            data: {
                action: "intentdeep_vf_dismiss_limit_banner",
                nonce: typeof intentdeepVfData !== "undefined" && intentdeepVfData.dismissBannerNonce ? intentdeepVfData.dismissBannerNonce : ""
            },
            success: function(response) {
                if (response.success) {
                    // Hide the banner with fade out
                    $(".vf-limit-banner").fadeOut(300, function() {
                        $(this).remove();
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error("Failed to dismiss banner:", error);
            }
        });
    }

    /**
     * Initialize AI Generator functionality
     */
    function initAiGenerator() {
        const $generateBtn = $('#vf-ai-generate-btn');
        const $improveBtn = $('#vf-ai-improve-btn');
        const $analyzeBtn = $('#vf-ai-analyze-btn');
        const $quickPrompts = $('#vf-ai-quick-prompts');
        const $modal = $('#vf-ai-modal');
        const $close = $('.vf-modal-close, .vf-modal-cancel');
        const $submit = $('#vf-ai-submit');
        const $prompt = $('#vf-ai-prompt');
        const $error = $('#vf-ai-error');
        const $loading = $('.vf-ai-loading');
        const $streamContainer = $('#vf-ai-stream-container');
        const $streamOutput = $('#vf-ai-stream-output');
        const $initialFooter = $('#vf-ai-initial-footer');
        const $optionsFooter = $('#vf-ai-options-footer');
        const $analyzeFooter = $('#vf-ai-analyze-footer');

        // Context Elements
        const $contextSearch = $('#vf-context-search');
        const $contextResults = $('#vf-context-results');
        const $attachedItems = $('#vf-attached-items');

        let currentAction = 'generate';
        let currentPrompt = '';
        let generatedContentBuffer = '';
        let attachedPosts = []; // Stores IDs of attached posts

        if (!$generateBtn.length || !$modal.length) return;

        // Open Modal Handler
        function openModal(action) {
            currentAction = action;
            $modal.fadeIn(200);

            // Reset state
            $prompt.val('').focus();
            $error.hide();
            $streamContainer.hide();
            $streamOutput.text('');
            $initialFooter.show();
            $optionsFooter.hide();
            if ($analyzeFooter.length) $analyzeFooter.hide();
            $submit.prop('disabled', false);
            $loading.hide();
            generatedContentBuffer = '';
            currentPrompt = '';

            // Reset Context
            attachedPosts = [];
            renderAttachedItems();
            $contextSearch.val('');
            $contextResults.hide();

            // Update UI based on action
            if (action === 'improve') {
                $modal.find('.vf-modal-header h3').html('<span class="dashicons dashicons-stars-filled" style="margin-right: 8px;"></span> Improve Content with AI');
                $modal.find('.description').text('Describe how you want to improve or fix the current content.');
                $prompt.attr('placeholder', 'E.g., Fix syntax errors, optimize for SEO, or add comments.');
                $submit.text('Improve');
                $quickPrompts.hide();
            } else if (action === 'analyze') {
                $modal.find('.vf-modal-header h3').html('<span class="dashicons dashicons-search" style="margin-right: 8px;"></span> Analyze / Explain Content');
                $modal.find('.description').text('The AI will analyze your current content and provide an explanation or suggestions.');
                $prompt.val('Analyze the current content, explain what it does, and identify any potential errors or improvements.');
                $submit.text('Analyze');
                $quickPrompts.hide();
            } else {
                $modal.find('.vf-modal-header h3').html('<span class="dashicons dashicons-superhero" style="margin-right: 8px;"></span> Generate Content with AI');
                $modal.find('.description').text('Describe what you want to generate. The AI will use your file extension to determine the format.');
                $prompt.attr('placeholder', 'E.g., Create a robots.txt that allows all bots but blocks the /private directory.');
                $submit.text('Generate');
                $quickPrompts.show();
            }
        }

        // Button Listeners
        $generateBtn.on('click', function(e) {
            e.preventDefault();
            openModal('generate');
        });

        $improveBtn.on('click', function(e) {
            e.preventDefault();
            openModal('improve');
        });

        $analyzeBtn.on('click', function(e) {
            e.preventDefault();
            openModal('analyze');
        });

        // Auto-fill filename, title, and extension based on prompt keywords
        function autoFillFromPrompt(promptText) {
            if (!promptText) return;

            const $filenameInput = $('#vf_filename');
            const $titleInput = $('#title');
            const $extensionSelect = $('#vf_extension');

            // Only auto-fill if fields are empty
            const filenameEmpty = !$filenameInput.val() || $filenameInput.val().trim() === '';
            const titleEmpty = !$titleInput.val() || $titleInput.val().trim() === '';

            if (!filenameEmpty && !titleEmpty) return;

            // Detection patterns for common files (with extension)
            const patterns = [
                { regex: /robots\.txt/i, filename: 'robots', title: 'Robots.txt', extension: 'txt' },
                { regex: /security\.txt/i, filename: '.well-known/security', title: 'Security.txt - RFC 9116', extension: 'txt' },
                { regex: /ads\.txt/i, filename: 'ads', title: 'Ads.txt', extension: 'txt' },
                { regex: /app-ads\.txt/i, filename: 'app-ads', title: 'App-Ads.txt', extension: 'txt' },
                { regex: /llms\.txt/i, filename: 'llms', title: 'LLMs.txt - AI Crawler Instructions', extension: 'txt' },
                { regex: /humans\.txt/i, filename: 'humans', title: 'Humans.txt', extension: 'txt' },
                { regex: /json-ld|structured\s+data|schema\.org/i, filename: 'schema', title: 'JSON-LD Structured Data', extension: 'json' },
                { regex: /manifest\.json/i, filename: 'manifest', title: 'Web App Manifest', extension: 'json' },
                { regex: /sitemap.*\.xml/i, filename: 'sitemap', title: 'Sitemap XML', extension: 'xml' },
                { regex: /feed\.xml|rss\.xml/i, filename: 'feed', title: 'RSS Feed', extension: 'rss' },
                { regex: /(\.well-known\/)?apple-app-site-association/i, filename: '.well-known/apple-app-site-association', title: 'Apple App Site Association', extension: 'json' },
                { regex: /assetlinks\.json/i, filename: '.well-known/assetlinks', title: 'Android Asset Links', extension: 'json' }
            ];

            for (const pattern of patterns) {
                if (pattern.regex.test(promptText)) {
                    if (filenameEmpty) {
                        $filenameInput.val(pattern.filename).trigger('change');
                        // Add visual feedback
                        $filenameInput.css('background-color', '#f0fdf4');
                        setTimeout(() => $filenameInput.css('background-color', ''), 1500);
                    }
                    if (titleEmpty) {
                        $titleInput.val(pattern.title).trigger('change');
                        // Add visual feedback
                        $titleInput.css('background-color', '#f0fdf4');
                        setTimeout(() => $titleInput.css('background-color', ''), 1500);
                    }
                    // Auto-select extension if pattern has one
                    if (pattern.extension) {
                        $extensionSelect.val(pattern.extension).trigger('change');
                    }
                    break; // Only match first pattern
                }
            }
        }

        // Quick Prompts Handler
        $quickPrompts.on('change', function() {
            const prompt = $(this).val();
            if (prompt) {
                $prompt.val(prompt);
                // Auto-fill filename and title
                autoFillFromPrompt(prompt);
            }
        });

        // Close Modal
        $close.on('click', function(e) {
            e.preventDefault();
            $modal.fadeOut(200);
        });

        // Handle Escape key
        $(document).on('keydown', function(e) {
            if (e.key === "Escape" && $modal.is(':visible')) {
                $modal.fadeOut(200);
            }
        });

        function escapeHtml(text) {
            if (!text) return text;
            return text
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }

        // Context Search Logic
        let searchTimeout;
        $contextSearch.on('input', function() {
            const query = $(this).val().trim();

            clearTimeout(searchTimeout);

            if (query.length < 3) {
                $contextResults.hide();
                return;
            }

            searchTimeout = setTimeout(() => {
                const nonce = typeof intentdeepVfData !== "undefined" && intentdeepVfData.aiNonce
                    ? intentdeepVfData.aiNonce
                    : '';

                $.ajax({
                    url: typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl ? intentdeepVfData.ajaxUrl : ajaxurl,
                    type: 'GET',
                    data: {
                        action: 'intentdeep_vf_search_posts',
                        search: query,
                        nonce: nonce
                    },
                    success: function(response) {
                        if (response.success && response.data.length > 0) {
                            let html = '';
                            response.data.forEach(item => {
                                // Don't show already attached items
                                if (!attachedPosts.includes(item.id)) {
                                    const title = escapeHtml(item.title);
                                    const type = escapeHtml(item.type);
                                    html += `<div class="vf-search-result-item" data-id="${item.id}" data-title="${title}">
                                        <span class="dashicons dashicons-admin-post" style="font-size: 14px; width: 14px; margin-right: 5px;"></span>
                                        ${title} <span style="font-size: 10px; color: #888;">(${type})</span>
                                    </div>`;
                                }
                            });

                            if (html) {
                                $contextResults.html(html).show();
                            } else {
                                $contextResults.hide();
                            }
                        } else {
                            $contextResults.hide();
                        }
                    }
                });
            }, 500);
        });

        // Handle Search Result Selection
        $(document).on('click', '.vf-search-result-item', function() {
            const id = $(this).data('id');
            const title = $(this).data('title'); // Already escaped in data attribute? No, jQuery .data() might auto-type it but string is safe if we use it carefully.
            // Wait, if we set data-title="${title}" where title is escaped, $(this).data('title') returns the escaped string.
            // But we want to store the original title if possible, OR just display the escaped one.
            // Let's decode it for storage? No, let's keep it simple.
            // Actually, best to pass ID only and re-fetch, but here we pass title.
            // If I escape it in the HTML, .data('title') will get the escaped version.
            // That's fine for display in chips.

            if (attachedPosts.length >= 3) {
                alert('You can only attach up to 3 items.');
                return;
            }

            attachedPosts.push(id);
            renderAttachedItems();

            $contextSearch.val('');
            $contextResults.hide();
        });

        // Render Attached Items Chips
        function renderAttachedItems() {
            $attachedItems.empty();

            if (attachedPosts.length === 0) return;
        }

        // Re-implementing correctly:
        // Use attachedPostsObjects for state
        let attachedPostsObjects = [];

        // Correct Search Result Selection with State
        $(document).off('click', '.vf-search-result-item').on('click', '.vf-search-result-item', function() {
            const id = $(this).data('id');
            const title = $(this).data('title'); // This will be the escaped title from the HTML data attribute

            if (attachedPostsObjects.length >= 3) {
                alert('You can only attach up to 3 items.');
                return;
            }

            // Check duplicates
            if (attachedPostsObjects.some(p => p.id === id)) return;

            attachedPostsObjects.push({id, title});
            updateAttachedChips();

            $contextSearch.val('');
            $contextResults.hide();
        });

        // Remove Attached Item
        $(document).on('click', '.vf-remove-attachment', function() {
            const id = $(this).data('id');
            attachedPostsObjects = attachedPostsObjects.filter(p => p.id !== id);
            updateAttachedChips();
        });

        function updateAttachedChips() {
            $attachedItems.empty();
            attachedPostsObjects.forEach(post => {
                const safeTitle = escapeHtml(post.title);
                $attachedItems.append(`
                    <span class="vf-chip">
                        ${safeTitle}
                        <span class="dashicons dashicons-dismiss vf-remove-attachment" data-id="${post.id}"></span>
                    </span>
                `);
            });
        }

        // Close search results when clicking outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.vf-context-search-wrapper').length) {
                $contextResults.hide();
            }
        });

        // Submit Generation Request
        $submit.on('click', function(e) {
            e.preventDefault();

            const prompt = $prompt.val().trim();
            if (!prompt) {
                $error.find('p').text('Please enter a prompt.').parent().show();
                $prompt.focus();
                return;
            }

            // Store current prompt
            currentPrompt = prompt;

            // Get extension and content
            let extension = 'txt';
            if ($('#vf_extension').length) {
                extension = $('#vf_extension').val();
            } else if ($('#vf_filename').length) {
                const parts = $('#vf_filename').val().split('.');
                if (parts.length > 1) extension = parts.pop().toLowerCase();
            }

            let currentContent = '';
            if (typeof window.virtualFilesCodeMirror !== 'undefined') {
                currentContent = window.virtualFilesCodeMirror.getValue();
            } else {
                currentContent = $('#vf_content').val();
            }

            // UI Loading State
            $submit.prop('disabled', true);
            $loading.show();
            $error.hide();
            $streamContainer.show();
            $streamOutput.text(''); // Clear previous output
            generatedContentBuffer = ''; // Reset buffer

            // Prepare Data
            const nonce = typeof intentdeepVfData !== "undefined" && intentdeepVfData.aiNonce
                ? intentdeepVfData.aiNonce
                : (typeof intentdeepVfData !== "undefined" ? intentdeepVfData.nonce : '');

            const ajaxUrl = typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl ? intentdeepVfData.ajaxUrl : ajaxurl;

            // Use fetch for streaming support
            const formData = new FormData();
            formData.append('action', 'intentdeep_vf_generate_ai_content');
            formData.append('nonce', nonce);
            formData.append('prompt', prompt);
            formData.append('extension', extension);
            formData.append('action_type', currentAction);
            formData.append('stream', 'true');
            if (currentAction === 'improve' || currentAction === 'analyze') {
                formData.append('current_content', currentContent);
            }

            // Append attached posts
            attachedPostsObjects.forEach(post => {
                formData.append('attached_posts[]', post.id);
            });

            fetch(ajaxUrl, {
                method: 'POST',
                body: formData
            }).then(response => {
                // Check if response is successful and is a stream
                const contentType = response.headers.get('Content-Type');
                if (!response.ok || !contentType || !contentType.includes('text/event-stream')) {
                    return response.json().then(data => {
                        // Extract error message from WP response format or standard JSON
                        const msg = data.data && data.data.message ? data.data.message : (data.message || 'Unknown error occurred');
                        throw new Error(msg);
                    }).catch(e => {
                        // If json parsing fails (e.g. 500 HTML error), use text or status text
                        if (e.message !== 'Unexpected end of JSON input') {
                            throw e;
                        }
                        throw new Error(response.statusText || 'Network response was not ok');
                    });
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';

                function readStream() {
                    return reader.read().then(({ done, value }) => {
                        if (done) {
                            // Process any remaining buffer
                            if (buffer.trim()) {
                                processLine(buffer);
                            }

                            // Stream finished
                            $loading.hide();
                            $initialFooter.hide();

                            // Show appropriate footer based on action type
                            if (currentAction === 'analyze') {
                                if ($analyzeFooter.length) $analyzeFooter.fadeIn();
                            } else {
                                $optionsFooter.fadeIn();
                            }

                            // Save generation to post meta
                            saveGenerationToMeta();
                            return;
                        }

                        const chunk = decoder.decode(value, {stream: true});
                        buffer += chunk;

                        const lines = buffer.split('\n');
                        // Keep the last line in the buffer as it might be incomplete
                        buffer = lines.pop();

                        lines.forEach(line => processLine(line));

                        return readStream();
                    });
                }

                function processLine(line) {
                    line = line.trim();
                    if (!line) return;

                    if (line.startsWith('data: ')) {
                        try {
                            const jsonStr = line.substring(6);
                            if (jsonStr === '[DONE]') return;

                            const data = JSON.parse(jsonStr);
                            if (data.content && typeof data.content === 'string') {
                                generatedContentBuffer += data.content;
                                $streamOutput.text(generatedContentBuffer);
                                // Auto-scroll to bottom
                                $streamOutput.scrollTop($streamOutput[0].scrollHeight);
                            }
                        } catch (e) {
                            // Ignore parse errors for broken/incomplete lines
                        }
                    } else if (line.includes('"message":')) {
                        // Handle JSON error response (non-stream)
                        try {
                            const data = JSON.parse(line);
                            if (data.message) {
                                // If it's an error message
                                // console.error('AI API Error:', data.message);
                            } else if (data.data && data.data.message) {
                                // console.error('AI API Error:', data.data.message);
                            }
                        } catch (e) {}
                    }
                }

                return readStream();
            }).catch(err => {
                // console.error('AI Generation Error:', err);
                $error.find('p').text(err.message || 'Error connecting to AI service.').parent().show();
                $submit.prop('disabled', false);
                $loading.hide();
                $streamContainer.hide();
            });
        });

        // Handle Post-Generation Actions (use delegation for dynamically shown buttons)
        $(document).on('click', '.vf-ai-action-btn', function(e) {
            e.preventDefault();
            const action = $(this).data('action');
            const $button = $(this);

            // Handle copy action separately (works even without generatedContentBuffer check)
            if (action === 'copy') {
                if (!generatedContentBuffer) {
                    alert('No content to copy. Please generate content first.');
                    return;
                }

                // Copy to clipboard with error handling
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(generatedContentBuffer).then(() => {
                        const originalText = $button.text();
                        $button.text('Copied!');
                        setTimeout(() => {
                            $button.text(originalText);
                        }, 2000);
                    }).catch((err) => {
                        // console.error('Failed to copy:', err);
                        alert('Failed to copy to clipboard. Please try again.');
                    });
                } else {
                    // Fallback for older browsers
                    const $temp = $('<textarea>');
                    $('body').append($temp);
                    $temp.val(generatedContentBuffer).select();
                    try {
                        document.execCommand('copy');
                        const originalText = $button.text();
                        $button.text('Copied!');
                        setTimeout(() => {
                            $button.text(originalText);
                        }, 2000);
                    } catch (err) {
                        // console.error('Fallback copy failed:', err);
                        alert('Failed to copy to clipboard.');
                    }
                    $temp.remove();
                }
                return; // Don't close modal on copy
            }

            // For other actions, check if content exists
            if (!generatedContentBuffer) return;

            const editor = typeof window.virtualFilesCodeMirror !== 'undefined' ? window.virtualFilesCodeMirror : null;
            const $textarea = $('#vf_content');

            if (action === 'replace') {
                if (editor) editor.setValue(generatedContentBuffer);
                else $textarea.val(generatedContentBuffer);
            } else if (action === 'insert') {
                if (editor) editor.replaceSelection(generatedContentBuffer);
                else {
                    // Insert at cursor for textarea
                    const el = $textarea[0];
                    const start = el.selectionStart;
                    const end = el.selectionEnd;
                    const val = $textarea.val();
                    $textarea.val(val.substring(0, start) + generatedContentBuffer + val.substring(end));
                }
            } else if (action === 'append') {
                if (editor) {
                    const lastLine = editor.lineCount();
                    editor.replaceRange('\n' + generatedContentBuffer, {line: lastLine});
                } else {
                    $textarea.val($textarea.val() + '\n' + generatedContentBuffer);
                }
            } else if (action === 'download') {
                // Handle download for analyze mode
                const blob = new Blob([generatedContentBuffer], { type: 'text/markdown' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'analysis-' + Date.now() + '.md';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                return; // Don't close modal on download
            }

            // Auto-fill filename and title for generate action (not improve/analyze)
            if (currentAction === 'generate' && currentPrompt) {
                autoFillFromPrompt(currentPrompt);
            }

            // Close modal after action (except copy and download)
            $modal.fadeOut(200);
        });

        // Save Generation to Post Meta
        function saveGenerationToMeta() {
            const postId = $('#post_ID').val();
            if (!postId || !generatedContentBuffer) return;

            const nonce = typeof intentdeepVfData !== "undefined" && intentdeepVfData.aiNonce
                ? intentdeepVfData.aiNonce
                : '';

            $.ajax({
                url: typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl ? intentdeepVfData.ajaxUrl : ajaxurl,
                type: 'POST',
                data: {
                    action: 'intentdeep_vf_save_ai_generation',
                    nonce: nonce,
                    post_id: postId,
                    action_type: currentAction,
                    prompt: currentPrompt,
                    content: generatedContentBuffer
                },
                success: function(response) {
                    if (response.success) {
                        // Reload history sidebar
                        loadAiHistory();
                    }
                }
            });
        }

        // Load AI History
        function loadAiHistory() {
            const postId = $('#post_ID').val();
            if (!postId) return;

            const nonce = typeof intentdeepVfData !== "undefined" && intentdeepVfData.aiNonce
                ? intentdeepVfData.aiNonce
                : '';

            $.ajax({
                url: typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl ? intentdeepVfData.ajaxUrl : ajaxurl,
                type: 'GET',
                data: {
                    action: 'intentdeep_vf_get_ai_history',
                    nonce: nonce,
                    post_id: postId
                },
                success: function(response) {
                    if (response.success && response.data) {
                        renderAiHistory(response.data);
                    }
                }
            });
        }

        // Render AI History in Sidebar
        function renderAiHistory(history) {
            const $historyContainer = $('#vf-ai-history-list');
            if (!$historyContainer.length) return;

            if (!history || history.length === 0) {
                $historyContainer.html('<p style="text-align: center; color: #64748b; font-size: 12px; padding: 20px;">No AI generations yet</p>');
                return;
            }

            let html = '';
            history.forEach((item, index) => {
                const actionLabel = item.action_type === 'generate' ? 'Generated' : (item.action_type === 'improve' ? 'Improved' : 'Analyzed');
                const actionIcon = item.action_type === 'generate' ? 'superhero' : (item.action_type === 'improve' ? 'star-filled' : 'search');
                const safeContent = escapeHtml(item.content);
                const preview = safeContent.substring(0, 80) + (safeContent.length > 80 ? '...' : '');

                html += `
                    <div class="vf-history-item" data-index="${index}" data-id="${item.id}">
                        <div class="vf-history-header">
                            <span class="dashicons dashicons-${actionIcon} vf-history-icon"></span>
                            <span class="vf-history-label">${actionLabel}</span>
                            <span class="vf-history-time">${item.time_ago}</span>
                            <button type="button" class="vf-history-delete" data-id="${item.id}" title="Delete">
                                <span class="dashicons dashicons-no-alt"></span>
                            </button>
                        </div>
                        <div class="vf-history-preview">${preview}</div>
                    </div>
                `;
            });

            $historyContainer.html(html);
        }

        // Handle History Item Click
        $(document).on('click', '.vf-history-item', function(e) {
            // Don't open if clicking delete button
            if ($(e.target).closest('.vf-history-delete').length) return;

            const index = $(this).data('index');
            const postId = $('#post_ID').val();
            const nonce = typeof intentdeepVfData !== "undefined" && intentdeepVfData.aiNonce
                ? intentdeepVfData.aiNonce
                : '';

            $.ajax({
                url: typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl ? intentdeepVfData.ajaxUrl : ajaxurl,
                type: 'GET',
                data: {
                    action: 'intentdeep_vf_get_ai_history',
                    nonce: nonce,
                    post_id: postId
                },
                success: function(response) {
                    if (response.success && response.data && response.data[index]) {
                        const item = response.data[index];

                        // Open modal with this content
                        generatedContentBuffer = item.content;
                        currentAction = item.action_type;
                        currentPrompt = item.prompt;

                        // Open modal
                        $modal.fadeIn(200);
                        $prompt.val(item.prompt);
                        $streamContainer.show();
                        $streamOutput.text(item.content);
                        $initialFooter.hide();

                        // Show appropriate footer
                        if (item.action_type === 'analyze') {
                            if ($analyzeFooter.length) $analyzeFooter.show();
                        } else {
                            $optionsFooter.show();
                        }

                        // Update modal title
                        if (item.action_type === 'improve') {
                            $modal.find('.vf-modal-header h3').html('<span class="dashicons dashicons-stars-filled" style="margin-right: 8px;"></span> Improve Content with AI');
                        } else if (item.action_type === 'analyze') {
                            $modal.find('.vf-modal-header h3').html('<span class="dashicons dashicons-search" style="margin-right: 8px;"></span> Analyze / Explain Content');
                        } else {
                            $modal.find('.vf-modal-header h3').html('<span class="dashicons dashicons-superhero" style="margin-right: 8px;"></span> Generate Content with AI');
                        }
                    }
                }
            });
        });

        // Handle History Delete
        $(document).on('click', '.vf-history-delete', function(e) {
            e.stopPropagation();

            if (!confirm('Are you sure you want to delete this AI generation?')) {
                return;
            }

            const itemId = $(this).data('id');
            const postId = $('#post_ID').val();
            const nonce = typeof intentdeepVfData !== "undefined" && intentdeepVfData.aiNonce
                ? intentdeepVfData.aiNonce
                : '';

            $.ajax({
                url: typeof intentdeepVfData !== "undefined" && intentdeepVfData.ajaxUrl ? intentdeepVfData.ajaxUrl : ajaxurl,
                type: 'POST',
                data: {
                    action: 'intentdeep_vf_delete_ai_generation',
                    nonce: nonce,
                    post_id: postId,
                    item_id: itemId
                },
                success: function(response) {
                    if (response.success) {
                        loadAiHistory();
                    }
                }
            });
        });

        // Load history on page load
        if ($('#vf-ai-history-list').length) {
            loadAiHistory();
        }
    }
});

// Global variables that may be passed from server
if (typeof intentdeepVfData === 'undefined') {
    window.intentdeepVfData = {
        isPro: false,
        nonce: '',
        ajaxUrl: ajaxurl
    };
}