/**
 * Blog Image Handler
 * Handles featured image generation and management
 */

class BlogImageHandler {
    constructor() {
        this.init();
    }
    
    init() {
        // Make functions globally accessible for onclick handlers
        window.showResultImageRegenerateForm = this.showResultImageRegenerateForm.bind(this);
        window.hideResultImageRegenerateForm = this.hideResultImageRegenerateForm.bind(this);
        window.regenerateResultImage = this.regenerateResultImage.bind(this);
        window.showImageRegenerateForm = this.showImageRegenerateForm.bind(this);
        window.hidePreviewImageRegenerateForm = this.hidePreviewImageRegenerateForm.bind(this);
        window.regeneratePreviewFeaturedImage = this.regeneratePreviewFeaturedImage.bind(this);
        
        // Make main methods available
        window.generateFeaturedImageForBlog = this.generateFeaturedImage.bind(this);
        window.updateResultWithFeaturedImage = this.updateResultFeaturedImage.bind(this);
    }
    
    showResultImageRegenerateForm() {
        const form = document.getElementById('resultImageRegenerateForm');
        if (form) {
            form.style.display = 'block';
            
            // Auto-fill with current blog title for context
            const currentBlogData = window.currentBlogData;
            const title = currentBlogData?.data?.title || currentBlogData?.title || '';
            const promptField = document.getElementById('resultCustomImagePrompt');
            if (promptField && title) {
                promptField.placeholder = `e.g., "A professional image related to '${title}'"`;
            }
        } else {
            console.error('Result image regenerate form not found');
        }
    }
    
    hideResultImageRegenerateForm() {
        const form = document.getElementById('resultImageRegenerateForm');
        if (form) {
            form.style.display = 'none';
        }
    }
    
    regenerateResultImage() {
        const customPromptEl = document.getElementById('resultCustomImagePrompt');
        const styleEl = document.getElementById('resultImageStyle');
        
        if (!customPromptEl || !styleEl) {
            this.showToast('Image regeneration form not found', 'error');
            return;
        }
        
        const customPrompt = customPromptEl.value.trim();
        const style = styleEl.value || '';
        
        if (!customPrompt) {
            this.showToast('Please enter a description for the new image.', 'error');
            return;
        }

        // Hide the form
        this.hideResultImageRegenerateForm();
        
        // Show progress indicator
        this.showImageProgress();
        
        // Show toast notification
        this.showToast('Generating new featured image...', 'info');

        // Create form data
        const formData = new FormData();
        formData.append('action', 'blogibot_generate_image');
        formData.append('image_description', customPrompt);
        // Only add style if it's not empty
        if (style) {
            formData.append('style', style);
        }
        formData.append('quality', 'high quality');
        formData.append('aspect_ratio', '16:9');
        formData.append('filename', 'blog_featured_image_regenerated_' + Date.now());
        
        // Add nonce for security
        if (blogibotAjax.nonces && blogibotAjax.nonces.generate_image) {
            formData.append('nonce', blogibotAjax.nonces.generate_image);
        }

        // Make the request
        fetch(blogibotAjax.ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            this.hideImageProgress();
            
            if (data.success) {
                // Update the current blog data with new image
                this.updateBlogDataWithNewImage(data.data);
                
                // Update the displayed image
                this.updateResultImageDisplay(data.data);
                
                // Update preview modal if it's open
                this.updatePreviewImageDisplay(data.data);
                
                this.showToast('New featured image generated successfully!', 'success');
                
                // Clear the prompt field
                if (customPromptEl) {
                    customPromptEl.value = '';
                }
                
            } else {
                console.error('Image regeneration failed:', data.message);
                this.showToast('Failed to regenerate image: ' + (data.message || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            this.hideImageProgress();
            console.error('Image regeneration error:', error);
            this.showToast('Error regenerating image. Please try again.', 'error');
        });
    }
    
    showImageRegenerateForm() {
        const form = document.getElementById('previewImageRegenerateForm');
        if (form) {
            form.style.display = 'block';
            
            // Auto-fill with current blog title for context
            const currentBlogData = window.currentBlogData;
            const title = currentBlogData?.data?.title || currentBlogData?.title || '';
            const promptField = document.getElementById('previewCustomImagePrompt');
            if (promptField && title) {
                promptField.placeholder = `e.g., "A professional image related to '${title}'"`;
            }
        } else {
            console.warn('BlogImageHandler: Preview image regenerate form not found');
        }
    }
    
    hidePreviewImageRegenerateForm() {
        const form = document.getElementById('previewImageRegenerateForm');
        if (form) {
            form.style.display = 'none';
        }
    }
    
    regeneratePreviewFeaturedImage() {
        const customPromptEl = document.getElementById('previewCustomImagePrompt');
        const styleEl = document.getElementById('previewImageStyle');
        
        if (!customPromptEl || !styleEl) {
            this.showToast('Image regeneration form not found', 'error');
            return;
        }
        
        const customPrompt = customPromptEl.value.trim();
        const style = styleEl.value || '';
        
        if (!customPrompt) {
            this.showToast('Please enter a description for the new image.', 'error');
            return;
        }

        // Hide the form
        this.hidePreviewImageRegenerateForm();
        
        // Show progress indicator
        this.showPreviewImageProgress();
        
        // Show toast notification
        this.showToast('Generating new featured image...', 'info');

        // Create form data
        const formData = new FormData();
        formData.append('action', 'blogibot_generate_image');
        formData.append('image_description', customPrompt);
        // Only add style if it's not empty
        if (style) {
            formData.append('style', style);
        }
        formData.append('quality', 'high quality');
        formData.append('aspect_ratio', '16:9');
        formData.append('filename', 'blog_featured_image_preview_' + Date.now());
        
        // Add nonce for security
        if (blogibotAjax.nonces && blogibotAjax.nonces.generate_image) {
            formData.append('nonce', blogibotAjax.nonces.generate_image);
        }

        // Make the request
        fetch(blogibotAjax.ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            this.hidePreviewImageProgress();
            
            if (data.success) {
                // Update the current blog data with new image
                this.updateBlogDataWithNewImage(data.data);
                
                // Update the displayed image in preview
                this.updatePreviewImageDisplay(data.data);
                
                // Update result section if visible
                this.updateResultImageDisplay(data.data);
                
                this.showToast('New featured image generated successfully!', 'success');
                
                // Clear the prompt field
                if (customPromptEl) {
                    customPromptEl.value = '';
                }
                
            } else {
                console.error('Preview image regeneration failed:', data.message);
                this.showToast('Failed to regenerate image: ' + (data.message || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            this.hidePreviewImageProgress();
            console.error('Preview image regeneration error:', error);
            this.showToast('Error regenerating image. Please try again.', 'error');
        });
    }
    
    showImageProgress() {
        const imageContainer = document.querySelector('.blog82ai-result-image-container');
        if (imageContainer) {
            this.createProgressIndicator(imageContainer, 'image-regeneration-loading');
        }
    }
    
    hideImageProgress() {
        const loadingDiv = document.querySelector('.image-regeneration-loading');
        if (loadingDiv) {
            loadingDiv.remove();
        }
    }
    
    showPreviewImageProgress() {
        const progressDiv = document.getElementById('previewRegenerationProgress');
        if (progressDiv) {
            progressDiv.style.display = 'block';
        }
    }
    
    hidePreviewImageProgress() {
        const progressDiv = document.getElementById('previewRegenerationProgress');
        if (progressDiv) {
            progressDiv.style.display = 'none';
        }
    }
    
    createProgressIndicator(container, className) {
        const progressDiv = document.createElement('div');
        progressDiv.className = className;
        progressDiv.innerHTML = `
            <div style="text-align: center; padding: 20px; background: #f0f0f0; border-radius: 5px;">
                <div style="margin-bottom: 10px;">🎨 Generating new image...</div>
                <div style="width: 100%; background: #ddd; border-radius: 10px; height: 6px;">
                    <div style="width: 0%; background: #0073aa; height: 100%; border-radius: 10px; animation: progress 3s ease-in-out infinite;"></div>
                </div>
            </div>
            <style>
            @keyframes progress {
                0% { width: 0%; }
                50% { width: 70%; }
                100% { width: 100%; }
            }
            </style>
        `;
        container.appendChild(progressDiv);
    }
    
    updateBlogDataWithNewImage(imageData) {
        const currentBlogData = window.currentBlogData;
        if (!currentBlogData || !imageData) return;
        
        const imageInfo = {
            featured_image_id: imageData.attachment_id,
            featured_image_url: imageData.wordpress_url
        };
        
        // Handle different blog data structures
        if (currentBlogData.data) {
            Object.assign(currentBlogData.data, imageInfo);
        } else {
            Object.assign(currentBlogData, imageInfo);
        }
        
        // Update global image reference
        window.currentGeneratedImage = imageData;
    }
    
    updateResultImageDisplay(imageData) {
        // Update any existing image in result container
        const resultImageContainer = document.querySelector('.blog82ai-result-image-container');
        if (resultImageContainer) {
            const existingImg = resultImageContainer.querySelector('img');
            if (existingImg && imageData.wordpress_url) {
                // Add cache busting parameter to force refresh
                const newUrl = imageData.wordpress_url + '?v=' + Date.now();
                existingImg.src = newUrl;
                existingImg.alt = 'Regenerated featured image';
            }
        }
        
        // Show the featured image section if hidden and update the main image
        const resultFeaturedImageSection = document.getElementById('resultFeaturedImageSection');
        if (resultFeaturedImageSection && imageData.wordpress_url) {
            resultFeaturedImageSection.style.display = 'block';
            
            const resultImageSrc = document.getElementById('resultFeaturedImageSrc');
            if (resultImageSrc) {
                // Add cache busting parameter to force refresh
                const newUrl = imageData.wordpress_url + '?v=' + Date.now();
                
                // Show a brief loading state
                resultImageSrc.style.opacity = '0.5';
                resultImageSrc.style.transition = 'opacity 0.3s';
                
                // Update the image
                resultImageSrc.src = newUrl;
                resultImageSrc.alt = 'Regenerated featured image';
                
                // When image loads, restore opacity
                resultImageSrc.onload = function() {
                    this.style.opacity = '1';
                };
            }
            
            // Update image metadata
            const fileName = document.getElementById('resultImageFileName');
            const fileSize = document.getElementById('resultImageSize');
            
            if (fileName && imageData.filename) {
                fileName.textContent = imageData.filename;
            }
            
            if (fileSize) {
                const size = imageData.file_size || imageData.size || 0;
                fileSize.textContent = this.formatFileSize(size);
            }
        }
    }
    
    updatePreviewImageDisplay(imageData) {
        const previewImage = document.getElementById('previewFeaturedImageSrc');
        if (previewImage && imageData.wordpress_url) {
            // Add cache busting parameter to force refresh
            const newUrl = imageData.wordpress_url + '?v=' + Date.now();
            previewImage.src = newUrl;
        }
        
        // Show the featured image section if hidden
        const previewFeaturedImageSection = document.getElementById('previewFeaturedImageSection');
        if (previewFeaturedImageSection && imageData.wordpress_url) {
            previewFeaturedImageSection.style.display = 'block';
            
            // Update image meta information
            const fileName = document.getElementById('previewImageFileName');
            const fileSize = document.getElementById('previewImageSize');
            
            if (fileName) {
                fileName.textContent = imageData.filename || 'featured-image.jpg';
            }
            
            if (fileSize) {
                const size = imageData.file_size || 0;
                fileSize.textContent = this.formatFileSize(size);
            }
        }
    }
    
    /**
     * Generate featured image for blog post
     * @param {Object} blogData - The blog data object
     * @param {Function} callback - Callback function (success, imageData)
     */
    generateFeaturedImage(blogData, callback) {
        if (!blogData) {
            console.error('BlogImageHandler: No blog data provided');
            callback(false, null);
            return;
        }
        
        // Extract title and content for image prompt
        const title = blogData?.data?.title || blogData?.title || 'Blog Post';
        const content = blogData?.data?.content || blogData?.content || '';
        
        // Create automatic prompt based on blog content
        let imagePrompt = `Professional featured image for a blog post titled "${title}"`;
        
        // Try to extract key topics from content (simple approach)
        if (content) {
            const contentText = content.replace(/<[^>]*>/g, ''); // Strip HTML
            const words = contentText.split(' ').slice(0, 20).join(' '); // First 20 words
            imagePrompt = `Professional, high-quality image related to "${title}" and ${words}`;
        }
        
        // Default style for featured images - use a simple, widely accepted style
        const style = 'realistic';
        
        // Prepare form data for image generation
        const formData = new FormData();
        formData.append('action', 'blogibot_generate_image');
        formData.append('image_description', imagePrompt); // PHP expects 'image_description'
        // Note: Temporarily removing style parameter due to API validation issues
        // formData.append('style', style);
        formData.append('quality', 'high quality');
        formData.append('aspect_ratio', '16:9');
        formData.append('filename', 'featured_image_' + Date.now());
        formData.append('type', 'featured_image');
        
        // Add nonce for security
        if (blogibotAjax && blogibotAjax.nonces && blogibotAjax.nonces.generate_image) {
            formData.append('nonce', blogibotAjax.nonces.generate_image);
        } else {
            console.error('BlogImageHandler: No nonce available for image generation!');
            this.showToast('Security nonce not available. Please refresh the page.', 'error');
            callback(false, null);
            return;
        }
        
        // Check if AJAX URL is available
        if (!blogibotAjax || !blogibotAjax.ajaxurl) {
            console.error('BlogImageHandler: AJAX URL not available!');
            this.showToast('AJAX URL not available. Please refresh the page.', 'error');
            callback(false, null);
            return;
        }
        
        // Show progress indicator
        this.showToast('Generating featured image...', 'info');
        
        // Make the request
        fetch(blogibotAjax.ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            return response.json();
        })
        .then(data => {
            if (data.success && data.data) {
                this.showToast('Featured image generated successfully!', 'success');
                callback(true, data.data);
            } else {
                const errorMessage = data.message || data.data || 'Unknown error occurred';
                console.error('BlogImageHandler: Failed to generate image:', errorMessage);
                console.error('BlogImageHandler: Full error response:', data);
                this.showToast('Failed to generate featured image: ' + errorMessage, 'error');
                callback(false, null);
            }
        })
        .catch(error => {
            console.error('BlogImageHandler: Image generation error:', error);
            console.error('BlogImageHandler: Error stack:', error.stack);
            this.showToast('Error generating featured image: ' + error.message, 'error');
            callback(false, null);
        });
    }
    
    /**
     * Update result section with featured image
     * @param {Object} imageData - The generated image data
     */
    updateResultFeaturedImage(imageData) {
        const resultImageSection = document.getElementById('resultFeaturedImageSection');
        const resultImageSrc = document.getElementById('resultFeaturedImageSrc');
        
        if (!resultImageSection || !resultImageSrc) {
            console.warn('BlogImageHandler: Result image elements not found');
            return;
        }
        
        if (imageData && imageData.wordpress_url) {
            // Add cache busting parameter to ensure fresh image load
            const newUrl = imageData.wordpress_url + '?v=' + Date.now();
            resultImageSrc.src = newUrl;
            resultImageSrc.alt = 'Generated Featured Image';
            resultImageSection.style.display = 'block';
            
            // Update image meta information
            const fileName = document.getElementById('resultImageFileName');
            const fileSize = document.getElementById('resultImageSize');
            
            if (fileName) {
                fileName.textContent = imageData.filename || 'featured-image.jpg';
            }
            
            if (fileSize) {
                const size = imageData.file_size || 0;
                fileSize.textContent = this.formatFileSize(size);
            }
        } else {
            resultImageSection.style.display = 'none';
            console.warn('BlogImageHandler: No valid image URL provided');
        }
    }
    
    /**
     * Format file size in human readable format
     */
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    showToast(message, type = 'info') {
        // Use the new Toastr utility if available
        if (window.BlogiToastr) {
            window.BlogiToastr.show(message, type);
        } else if (window.BlogToast) {
            window.BlogToast.show(message, type);
        }
    }
}

// Initialize when DOM is ready
window.BlogImageHandler = BlogImageHandler;

// Auto-initialize
window.blogImageHandler = new BlogImageHandler();
