/**
 * Blog Generation Core Functions
 * Handles the main blog generation workflow
 */

class BlogGenerator {
    constructor() {
        this.form = null;
        this.generateBtn = null;
        this.progressDiv = null;
        this.currentBlogData = null;
        this.currentGeneratedImage = null;
        
        this.init();
    }
    
    init() {
        try {
            // Wait for DOM to be ready
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', () => this.setupElements());
            } else {
                this.setupElements();
            }
        } catch (error) {
            console.error('BlogGenerator: Error in init:', error);
        }
    }
    
    setupElements() {
        this.form = document.getElementById('blogGenerationForm');
        this.generateBtn = document.getElementById('generateBlogBtn');
        this.progressDiv = document.getElementById('generationProgress');
        
        if (!this.form || !this.generateBtn) {
            console.error('BlogGenerator: Required elements not found');
            return;
        }
        
        this.bindEvents();
        this.setupFormValidation();
    }
    
    bindEvents() {
        // Form submission
        this.form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.generateBlog();
        });
        
        // Modal close events
        const modalClose = document.querySelector('.blog82ai-modal-close');
        if (modalClose) {
            modalClose.addEventListener('click', () => this.closePreviewModal());
        }
        
        // Close modal when clicking outside
        if (this.previewModal) {
            this.previewModal.addEventListener('click', (e) => {
                if (e.target === this.previewModal) {
                    this.closePreviewModal();
                }
            });
        }
        
        // Post status change handler
        const postStatusSelect = document.getElementById('blog82ai_post_status');
        const scheduleOptions = document.querySelector('.blog82ai-schedule-options');
        if (postStatusSelect && scheduleOptions) {
            postStatusSelect.addEventListener('change', function() {
                scheduleOptions.style.display = (this.value === 'schedule') ? 'block' : 'none';
            });
        }
    }
    
    setupFormValidation() {
        // Character counters
        const metaTitleInput = document.getElementById('blog82ai_meta_title');
        const metaDescInput = document.getElementById('blog82ai_meta_description');
        
        if (metaTitleInput) {
            metaTitleInput.addEventListener('input', function() {
                const counter = document.getElementById('metaTitleCount');
                if (counter) counter.textContent = this.value.length;
            });
        }
        
        if (metaDescInput) {
            metaDescInput.addEventListener('input', function() {
                const counter = document.getElementById('metaDescCount');
                if (counter) counter.textContent = this.value.length;
            });
        }
    }
    
    generateBlog() {
        // Add visual feedback
        this.generateBtn.style.transform = 'scale(0.95)';
        setTimeout(() => {
            this.generateBtn.style.transform = 'scale(1)';
        }, 150);
        
        // Scroll to progress section
        setTimeout(() => {
            if (this.progressDiv) {
                this.progressDiv.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        }, 200);
        
        const formData = new FormData(this.form);
        formData.append('action', 'blogibot_generate_blog');
        
        // Show progress
        this.showProgress();
        
        // Disable form
        this.generateBtn.disabled = true;
        const buttonText = this.generateBtn.querySelector('.blog82ai-button-text');
        const buttonSpinner = this.generateBtn.querySelector('.button-spinner');
        
        if (buttonText) buttonText.textContent = 'Generating...';
        if (buttonSpinner) buttonSpinner.style.display = 'inline';

        fetch(blogibotAjax.ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => {
            return response.json();
        })
        .then(data => {
            
            if (data.success) {
                this.currentBlogData = data;
                this.showBlogResult(data);
            } else {
                this.hideProgress();
                this.showError(data.message || 'Failed to generate blog. Please try again.');
            }
        })
        .catch(error => {
            this.hideProgress();
            console.error('BlogGenerator Error:', error);
            this.showError('An error occurred while generating the blog. Please try again.');
        })
        .finally(() => {
            // Re-enable form
            this.generateBtn.disabled = false;
            if (buttonText) buttonText.textContent = 'Generate Blog';
            if (buttonSpinner) buttonSpinner.style.display = 'none';
        });
    }
    
    showProgress() {
        if (!this.progressDiv) return;
        
        this.progressDiv.style.display = 'block';
        
        // Check if featured image is selected
        const featuredImageCheckbox = document.getElementById('blog82ai_featured_image');
        const isFeaturedImageSelected = featuredImageCheckbox && featuredImageCheckbox.checked;
        
        // Show/hide image generation step and note based on selection
        const imageStep = document.getElementById('imageGenerationStep');
        const imageNote = document.getElementById('progressNoteImage');
        
        if (isFeaturedImageSelected) {
            if (imageStep) imageStep.style.display = 'block';
            if (imageNote) imageNote.style.display = 'block';
        } else {
            if (imageStep) imageStep.style.display = 'none';
            if (imageNote) imageNote.style.display = 'none';
        }
        
        // Reset all steps and progress
        document.querySelectorAll('.progress-step').forEach((step) => {
            step.classList.remove('active', 'completed');
        });
        
        // Start with first step active
        const steps = document.querySelectorAll('.progress-step:not([style*="display: none"])');
        const progressFill = document.querySelector('.progress-fill');
        
        let currentStep = 0;
        let progress = 0;
        
        // Smooth progress animation
        const progressInterval = setInterval(() => {
            progress += 1;
            if (progressFill) progressFill.style.width = progress + '%';
            
            if (progress >= 100) {
                clearInterval(progressInterval);
            }
        }, 100);
        
        // Step progression with realistic timing
        const baseStepTimings = [1000, 2000, 2500, 2000, 1500];
        const stepTimings = isFeaturedImageSelected ? 
            [...baseStepTimings, 2500] : // Add extra time for image generation
            baseStepTimings;
        
        const progressSteps = () => {
            if (currentStep < steps.length) {
                // Mark current step as active
                steps[currentStep].classList.add('active');
                
                // Mark previous step as completed
                if (currentStep > 0) {
                    steps[currentStep - 1].classList.remove('active');
                    steps[currentStep - 1].classList.add('completed');
                }
                
                currentStep++;
                
                if (currentStep < steps.length) {
                    setTimeout(progressSteps, stepTimings[currentStep - 1]);
                } else {
                    // Mark last step as completed after a delay
                    setTimeout(() => {
                        steps[steps.length - 1].classList.remove('active');
                        steps[steps.length - 1].classList.add('completed');
                    }, 1000);
                }
            }
        };
        
        // Start step progression
        progressSteps();
    }
    
    hideProgress() {
        if (!this.progressDiv) return;
        
        this.progressDiv.style.display = 'none';
        
        // Reset progress
        const progressFill = document.querySelector('.progress-fill');
        if (progressFill) progressFill.style.width = '0%';
        
        // Reset all steps
        document.querySelectorAll('.progress-step').forEach((step) => {
            step.classList.remove('active', 'completed');
        });
    }
    
    showBlogResult(blogData) {
        // Store blog data globally
        this.currentBlogData = blogData;
        window.currentBlogData = blogData; // For global access
        
        // Check if featured image generation was requested
        const featuredImageRequested = document.getElementById('blog82ai_featured_image')?.checked;
        
        if (featuredImageRequested) {
            this.showToast('Blog generated! Now generating featured image...', 'info');
            
            // Show the image generation step
            this.showImageGenerationStep();
            
            // Generate featured image first, then show results when complete
            this.generateFeaturedImageForBlog(blogData, (success, imageData) => {
                if (success) {
                    this.displayCompleteResult(blogData, imageData);
                } else {
                    console.error('Featured image generation failed:', imageData);
                    this.displayCompleteResult(blogData, null);
                }
            });
        } else {
            // No image requested, show result immediately
            this.displayCompleteResult(blogData, null);
        }
    }
    
    showImageGenerationStep() {
        // Show the image generation step and make it active
        const imageStep = document.getElementById('imageGenerationStep');
        if (imageStep) {
            imageStep.style.display = 'block';
            
            // Find all visible steps and make the image step active
            const allSteps = document.querySelectorAll('.progress-step:not([style*="display: none"])');
            
            // Remove active class from all steps and add completed to non-image steps
            allSteps.forEach((step, index) => {
                if (step.id === 'imageGenerationStep') {
                    step.classList.add('active');
                    step.classList.remove('completed');
                } else {
                    step.classList.remove('active');
                    step.classList.add('completed');
                }
            });
        } else {
            console.warn('BlogGenerator: Image generation step element not found');
        }
    }
    
    displayCompleteResult(blogData, imageData) {
        // Hide progress and form
        this.hideProgress();
        if (this.form) this.form.style.display = 'none';
        
        // Show result section
        const resultDiv = document.getElementById('blogResult');
        if (resultDiv) resultDiv.style.display = 'block';
        
        // Populate result data
        this.populateResultData(blogData, imageData);
        
        // Scroll to result section
        setTimeout(() => {
            if (resultDiv) {
                resultDiv.scrollIntoView({ 
                    behavior: 'smooth',
                    block: 'start'
                });
            }
            
            const message = imageData ? 
                '🎉 Your blog post and featured image have been generated successfully!' : 
                '🎉 Your blog post has been generated successfully!';
                
            this.showToast(message, 'success');
        }, 500);
    }
    
    populateResultData(blogData, imageData) {
        // Safely extract values from blogData
        const safeGet = (obj, path, defaultValue = '') => {
            const keys = path.split('.');
            let value = obj;
            for (const key of keys) {
                value = value?.[key];
                if (value === undefined) return defaultValue;
            }
            return value || defaultValue;
        };
        
        // Populate basic stats
        const wordCountEl = document.getElementById('resultWordCount');
        const readingTimeEl = document.getElementById('resultReadingTime');
        const seoScoreEl = document.getElementById('resultSeoScore');
        
        if (wordCountEl) wordCountEl.textContent = safeGet(blogData, 'word_count', 0);
        if (readingTimeEl) readingTimeEl.textContent = safeGet(blogData, 'reading_time', '0 min');
        if (seoScoreEl) seoScoreEl.textContent = safeGet(blogData, 'seo_score', 0);
        
        // Populate content
        const title = safeGet(blogData, 'data.title') || safeGet(blogData, 'title', 'Untitled');
        const content = safeGet(blogData, 'data.content') || safeGet(blogData, 'content', '');
        const metaTitle = safeGet(blogData, 'data.meta_title') || safeGet(blogData, 'meta_title', title);
        const metaDescription = safeGet(blogData, 'data.meta_description') || safeGet(blogData, 'meta_description', '');
        const keyphrase = safeGet(blogData, 'data.keyphrase') || safeGet(blogData, 'keyphrase', '');
        
        const titleEl = document.getElementById('resultTitle');
        const contentEl = document.getElementById('resultContent');
        const metaTitleEl = document.getElementById('resultMetaTitle');
        const metaDescEl = document.getElementById('resultMetaDescription');
        const keyphraseEl = document.getElementById('resultKeyphrase');
        
        if (titleEl) titleEl.textContent = title;
        if (contentEl) contentEl.innerHTML = content;
        if (metaTitleEl) metaTitleEl.value = metaTitle;
        if (metaDescEl) metaDescEl.value = metaDescription;
        if (keyphraseEl) keyphraseEl.value = keyphrase;
        
        // Handle featured image if present
        if (imageData) {
            this.updateBlogDataWithImage(imageData);
            this.updateResultWithFeaturedImage(imageData);
        }
    }
    
    updateBlogDataWithImage(imageData) {
        if (!this.currentBlogData || !imageData) return;
        
        const imageInfo = {
            featured_image_id: imageData.attachment_id,
            featured_image_url: imageData.wordpress_url,
            featured_image_filename: imageData.filename,
            featured_image_size: imageData.file_size || imageData.size || 0
        };
        
        // Handle different blog data structures
        if (this.currentBlogData.data) {
            Object.assign(this.currentBlogData.data, imageInfo);
        } else {
            Object.assign(this.currentBlogData, imageInfo);
        }
        
        // Also update global references
        window.currentBlogData = this.currentBlogData;
        window.currentGeneratedImage = imageData;
    }
    
    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);
        }
    }
    
    showError(message) {
        this.showToast(message, 'error');
    }
    
    // Placeholder methods for image functionality
    generateFeaturedImageForBlog(blogData, callback) {
        // Use the image handler to generate featured image
        if (window.blogImageHandler && window.blogImageHandler.generateFeaturedImage) {
            window.blogImageHandler.generateFeaturedImage(blogData, callback);
        } else {
            console.error('BlogGenerator: Image handler not available');
            this.showToast('Image handler not available', 'error');
            callback(false, null);
        }
    }
    
    updateResultWithFeaturedImage(imageData) {
        // Update the result section with featured image
        if (window.blogImageHandler && window.blogImageHandler.updateResultFeaturedImage) {
            window.blogImageHandler.updateResultFeaturedImage(imageData);
        } else {
            // Fallback: update directly
            this.updateResultFeaturedImageDirect(imageData);
        }
    }
    
    updateResultFeaturedImageDirect(imageData) {
        const resultImageSection = document.getElementById('resultFeaturedImageSection');
        const resultImageSrc = document.getElementById('resultFeaturedImageSrc');
        
        if (!resultImageSection || !resultImageSrc || !imageData) return;
        
        if (imageData.wordpress_url) {
            resultImageSrc.src = imageData.wordpress_url;
            resultImageSection.style.display = 'block';
            
            // Update image meta info
            const fileName = document.getElementById('resultImageFileName');
            const fileSize = document.getElementById('resultImageSize');
            
            if (fileName && imageData.filename) {
                fileName.textContent = imageData.filename;
            }
            
            if (fileSize && imageData.file_size) {
                fileSize.textContent = this.formatFileSize(imageData.file_size);
            }
        } else {
            resultImageSection.style.display = 'none';
        }
    }
    
    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];
    }
    
    updatePreviewWithFeaturedImage(imageData) {
        // This will be implemented in the image handler for result section
    }
}

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

// Auto-initialize if on the right page
try {
    if (document.getElementById('blogGenerationForm')) {
        window.blogGenerator = new BlogGenerator();
    }
} catch (error) {
    console.error('BlogGenerator: Initialization error:', error);
}

// ===== Modal and Helper Functions =====

/**
 * Show the blog preview modal
 */
function showPreviewModal() {
    const modal = document.getElementById('previewModal');
    if (!modal) {
        console.error('Preview modal not found');
        return;
    }
    
    // Get current blog data
    const currentBlogData = window.currentBlogData;
    if (!currentBlogData) {
        console.error('No blog data available for preview');
        return;
    }
    
    // Populate preview content
    populatePreviewModal(currentBlogData);
    
    // Show modal
    modal.style.display = 'block';
    document.body.style.overflow = 'hidden'; // Prevent background scroll
}

/**
 * Close the preview modal
 */
function closePreviewModal() {
    const modal = document.getElementById('previewModal');
    if (modal) {
        modal.style.display = 'none';
        document.body.style.overflow = 'auto'; // Restore scroll
    }
}

/**
 * Populate the preview modal with blog data
 */
function populatePreviewModal(blogData) {
    // Safely extract values from blogData
    const safeGet = (obj, path, defaultValue = '') => {
        const keys = path.split('.');
        let value = obj;
        for (const key of keys) {
            value = value?.[key];
            if (value === undefined) return defaultValue;
        }
        return value || defaultValue;
    };
    
    // Populate content
    const title = safeGet(blogData, 'data.title') || safeGet(blogData, 'title', 'Untitled');
    const content = safeGet(blogData, 'data.content') || safeGet(blogData, 'content', '');
    const metaTitle = safeGet(blogData, 'data.meta_title') || safeGet(blogData, 'meta_title', title);
    const metaDescription = safeGet(blogData, 'data.meta_description') || safeGet(blogData, 'meta_description', '');
    const keyphrase = safeGet(blogData, 'data.keyphrase') || safeGet(blogData, 'keyphrase', '');
    
    // Update preview elements
    const previewTitle = document.getElementById('previewTitle');
    const previewContent = document.getElementById('previewContent');
    const previewMetaTitle = document.getElementById('previewMetaTitle');
    const previewMetaDescription = document.getElementById('previewMetaDescription');
    const previewKeyphrase = document.getElementById('previewKeyphrase');
    
    if (previewTitle) previewTitle.textContent = title;
    if (previewContent) previewContent.innerHTML = content;
    if (previewMetaTitle) previewMetaTitle.textContent = metaTitle;
    if (previewMetaDescription) previewMetaDescription.textContent = metaDescription;
    if (previewKeyphrase) previewKeyphrase.textContent = keyphrase;
    
    // Handle featured image if present
    const featuredImageUrl = safeGet(blogData, 'data.featured_image_url') || safeGet(blogData, 'featured_image_url');
    const previewImageSection = document.getElementById('previewFeaturedImageSection');
    const previewImageSrc = document.getElementById('previewFeaturedImageSrc');
    
    if (featuredImageUrl && previewImageSrc && previewImageSection) {
        previewImageSrc.src = featuredImageUrl;
        previewImageSection.style.display = 'block';
        
        // Update image meta info
        const fileName = document.getElementById('previewImageFileName');
        const fileSize = document.getElementById('previewImageSize');
        
        if (fileName) {
            const imageFileName = safeGet(blogData, 'data.featured_image_filename') || 'featured-image.jpg';
            fileName.textContent = imageFileName;
        }
        
        if (fileSize) {
            const imageSize = safeGet(blogData, 'data.featured_image_size', 0);
            fileSize.textContent = formatFileSize(imageSize);
        }
    } else {
        if (previewImageSection) {
            previewImageSection.style.display = 'none';
        }
    }
}

/**
 * Format file size in human readable format
 */
function 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];
}

/**
 * Edit the blog - show the form again
 */
function editBlog() {
    const form = document.getElementById('blogGenerationForm');
    const result = document.getElementById('blogResult');
    
    if (form && result) {
        result.style.display = 'none';
        form.style.display = 'block';
        
        // Scroll to form
        form.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
}

// Note: saveDraft() and publishPost() functions are implemented in blog-actions.js
// and should not be redefined here to avoid overriding the real implementation.

// Close modal when clicking outside
document.addEventListener('click', function(event) {
    const modal = document.getElementById('previewModal');
    if (event.target === modal) {
        closePreviewModal();
    }
});

// Make functions globally available
window.showPreviewModal = showPreviewModal;
window.closePreviewModal = closePreviewModal;
window.editBlog = editBlog;
// saveDraft and publishPost are made available by blog-actions.js
