/**
 * Blog Actions Handler
 * Handles save draft, publish, and other blog actions
 */

class BlogActions {
    constructor() {
        this.init();
    }
    
    init() {
        // Make functions globally accessible for onclick handlers
        window.saveDraft = this.saveDraft.bind(this);
        window.publishPost = this.publishPost.bind(this);
        window.editBlog = this.editBlog.bind(this);
        window.regenerateBlog = this.regenerateBlog.bind(this);
        window.copyHtmlContent = this.copyHtmlContent.bind(this);
    }
    
    saveDraft() {
        const currentBlogData = window.currentBlogData;
        
        if (!currentBlogData) {
            console.error('No blog data available for saving');
            this.showToast('No blog data available. Please generate a blog first.', 'error');
            return;
        }
        
        // Disable all action buttons
        this.disableActionButtons();
        
        const formData = this.buildFormData('blogibot_save_draft', currentBlogData);
        
        // Show toast notification
        this.showToast('Saving draft...', 'info');

        fetch(blogibotAjax.ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.showToast(data.message, 'success');
                
                // Redirect after a short delay
                setTimeout(() => {
                    const redirectUrl = data.redirect_url || this.getRedirectUrl();
                    window.location.href = redirectUrl;
                }, 1500);
            } else {
                this.showToast(data.message || 'Failed to save draft.', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            this.showToast('An error occurred while saving the draft.', 'error');
        })
        .finally(() => {
            this.enableActionButtons();
        });
    }
    
    publishPost() {
        const currentBlogData = window.currentBlogData;
        
        if (!currentBlogData) {
            console.error('No blog data available for publishing');
            this.showToast('No blog data available. Please generate a blog first.', 'error');
            return;
        }
        
        // Disable all action buttons
        this.disableActionButtons();
        
        const formData = this.buildFormData('blogibot_publish_post', currentBlogData);
        
        // Add publishing-specific fields
        const postStatus = document.getElementById('blog82ai_post_status')?.value || 'publish';
        const scheduleDate = document.getElementById('blog82ai_schedule_date')?.value || '';
        
        formData.append('post_status', postStatus);
        formData.append('schedule_date', scheduleDate);

        // Show toast notification
        this.showToast('Publishing post...', 'info');

        fetch(blogibotAjax.ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.showToast(data.message, 'success');
                
                // Redirect after a short delay
                setTimeout(() => {
                    const redirectUrl = data.redirect_url || this.getRedirectUrl();
                    window.location.href = redirectUrl;
                }, 1500);
            } else {
                this.showToast(data.message || 'Failed to publish post.', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            this.showToast('An error occurred while publishing the post.', 'error');
        })
        .finally(() => {
            this.enableActionButtons();
        });
    }
    
    editBlog() {
        // Hide result and show form again
        const blogResult = document.getElementById('blogResult');
        const blogForm = document.getElementById('blogGenerationForm');
        
        if (blogResult) blogResult.style.display = 'none';
        if (blogForm) blogForm.style.display = 'block';
        
        // Scroll back to form
        if (blogForm) {
            blogForm.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
            
            // Focus on form
            setTimeout(() => {
                blogForm.focus();
            }, 500);
        }
    }
    
    regenerateBlog() {
        // Find the generate blog function and call it
        const generateBtn = document.getElementById('generateBlogBtn');
        if (generateBtn) {
            generateBtn.click();
        }
    }
    
    copyHtmlContent() {
        const htmlTextarea = document.getElementById('htmlContent');
        if (htmlTextarea) {
            htmlTextarea.select();
            document.execCommand('copy');
            this.showToast('HTML content copied to clipboard!', 'success');
        }
    }
    
    buildFormData(action, blogData) {
        const formData = new FormData();
        
        // Add action and nonce
        formData.append('action', action);
        
        // Add appropriate nonce based on action
        if (action === 'blogibot_save_draft') {
            formData.append('nonce', blogibotAjax.nonces.save_draft);
        } else if (action === 'blogibot_publish_post') {
            formData.append('nonce', blogibotAjax.nonces.publish_post);
        }
        
        // Helper function to safely get blog data values
        const getBlogDataValue = (key, defaultValue = '') => {
            if (!blogData) return defaultValue;
            
            // Try nested structure first
            if (blogData.data && blogData.data[key] !== undefined) {
                return blogData.data[key];
            }
            
            // Try direct structure
            if (blogData[key] !== undefined) {
                return blogData[key];
            }
            
            return defaultValue;
        };
        
        // Add form fields
        const metaTitleEl = document.getElementById('resultMetaTitle');
        const metaDescEl = document.getElementById('resultMetaDescription');
        const keyphraseEl = document.getElementById('resultKeyphrase');
        const authorEl = document.getElementById('blog82ai_author');
        
        formData.append('title', metaTitleEl?.value || getBlogDataValue('title'));
        formData.append('content', getBlogDataValue('content'));
        formData.append('meta_title', metaTitleEl?.value || '');
        formData.append('meta_description', metaDescEl?.value || '');
        formData.append('keyphrase', keyphraseEl?.value || getBlogDataValue('keyphrase'));
        formData.append('category_id', getBlogDataValue('category_id'));
        formData.append('featured_image', getBlogDataValue('featured_image'));
        formData.append('featured_image_id', getBlogDataValue('featured_image_id'));
        formData.append('author_id', authorEl?.value || '');
        
        return formData;
    }
    
    disableActionButtons() {
        const buttons = document.querySelectorAll('.blog-actions button, .blog82ai-modal-actions button');
        buttons.forEach(btn => {
            btn.disabled = true;
            btn.style.opacity = '0.6';
        });
    }
    
    enableActionButtons() {
        const buttons = document.querySelectorAll('.blog-actions button, .blog82ai-modal-actions button');
        buttons.forEach(btn => {
            btn.disabled = false;
            btn.style.opacity = '1';
        });
    }
    
    getRedirectUrl() {
        return window.location.pathname + '?page=blogibot&tab=ai_blog&subtab=generate_new_blog&action=new';
    }
    
    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.BlogActions = BlogActions;

// Auto-initialize
window.blogActions = new BlogActions();
