// Access createApp directly from Vue object
Vue.createApp({
    data() {
        return {
            loading: false,
            isSubmitting: false, // Added to fix Vue warning
            currentStep: 1,
            productWizardStep: 1,
            seoWizardStep: 1,
            showMainAlert: true,
            showSuccessAlert: false,
            isErrorMessage: false,
            successMessage: '',
            errors: {},
            // Separate error objects for each wizard step
            mainWizardErrors: {
                1: {},
                2: {},
                3: {}
            },
            productWizardErrors: {
                1: {},
                2: {},
                3: {},
                4: {},
                5: {}
            },
            seoWizardErrors: {
                1: {},
                2: {},
                3: {},
                4: {}
            },
            categories: window.PostomaticAutoPilotData.categories,
            authors: window.PostomaticAutoPilotData.authors,
            writers: window.PostomaticAutoPilotData.authors,
            hasProducts: window.PostomaticAutoPilotData.hasProducts,
            _initialLoadComplete: false, // Flag to track initial loading state
            // Content data fetched from the API
            contentData: {
                languages: []
            },
            // Content goal types fetched from the API
            contentGoalTypes: [],
            // Products fetched from the API
            products: [],
            isLoadingProducts: false,
            productSearch: '',
            productPagination: {total: 0, per_page: 9, current_page: 1, total_pages: 0},
            // Mapping between API type_of_autopilot keys and their display titles
            contentGoalTypeMap: {
                'content_generation': 'Content Generation',
                'content_curation': 'Content Curation',
                'seo-traffic': 'SEO Traffic',
                'brand-awareness': 'Brand Awareness',
                'educational': 'Educational Content',
                'community-engagement': 'Community Engagement',
                'news-announcements': 'News / Announcements',
                'product-promotion': 'Product Promotion',
                'affiliate-marketing': 'Affiliate Marketing',
                'traffic': 'Traffic',
                'product-comparison': 'Compare Products'
            },
            form: {
                goal: '',
                topic: '',
                contentGoalType: '',
                contentGoalDetails: '',
                productName: '',
                selectedProduct: '',
                selectedProducts: [], // Array for multiple product selection
                affiliateProductName: '',
                affiliateLink: '',
                commission: '',
                keywords: '',
                category: '',
                category_by_ai: false, // Auto-select category by AI
                language: '', // Language selection
                author: '',
                writer: '', // Who's writing field
                speaker: '', // Who is speaking field
                contentTone: 'conversational', // Content tone field
                frequency: 'weekly',
                count: 1,
                status: 'draft',
                budget: 8,
                commentStatus: 'open',
                aiFeatureImage: false,
                contentLength: 'brief'
            },
            minimumBudget: 10,
            availableCredits: 0,
            isLoadingCredits: true,
            isAnalyzing: false,
            analyzedKeywords: [],
            analysisCompleted: false,
            tasks: [],
            currentTask: null,
            showTaskModal: false,
            showDeleteModal: false,
            taskToDeleteIndex: null
        };
    },
    computed: {
        postStatus() {
            // Map form.status to form.postStatus for compatibility
            return this.form.status;
        },
        estimatedCredits() {
            // Simple estimation - in a real app, this would be more sophisticated
            return this.form.count * (this.form.budget || this.minimumBudget);
        },
        hasValidationErrors() {
            // Check if there are any errors in the current errors object
            if (Object.keys(this.errors).length > 0) {
                return true;
            }

            // Check if there are any errors in the main wizard steps
            for (const step in this.mainWizardErrors) {
                if (Object.keys(this.mainWizardErrors[step]).length > 0) {
                    return true;
                }
            }

            // Check if there are any errors in the product wizard steps
            for (const step in this.productWizardErrors) {
                if (Object.keys(this.productWizardErrors[step]).length > 0) {
                    return true;
                }
            }

            // Check if there are any errors in the SEO wizard steps
            for (const step in this.seoWizardErrors) {
                if (Object.keys(this.seoWizardErrors[step]).length > 0) {
                    return true;
                }
            }

            return false;
        },
        maxPossiblePosts() {
            // Calculate the maximum number of posts possible with available credits
            const creditsPerPost = this.form.budget || this.minimumBudget;
            return Math.floor(this.availableCredits / creditsPerPost);
        },
        activeAutopilots() {
            // Filter tasks to include only active autopilots
            return this.tasks.filter(task => task.isActive);
        },
        allAutopilots() {
            // Return all autopilots without filtering
            return this.tasks;
        },
        hasInactiveAutopilotsDueToCredits() {
            // Check if any autopilots are inactive due to insufficient credits
            return this.tasks.some(task => !task.isActive && task.inactiveReason === 'Insufficient credits');
        },
        addCreditPageUrl() {
            // Return the URL to the add credit page
            return window.PostomaticAutoPilotData.addCreditPage;
        },
        getSelectedProduct() {
            // Find the selected product in the products array
            if (!this.form.selectedProduct || this.products.length === 0) {
                return null;
            }
            return this.products.find(product => product.id === this.form.selectedProduct) || null;
        },
        isProductComparisonType() {
            // Check if the selected content goal type is "product-comparison"
            if (!this.form.contentGoalType || this.contentGoalTypes.length === 0) {
                return false;
            }
            const selectedType = this.contentGoalTypes.find(type => type.id === this.form.contentGoalType);
            return selectedType && selectedType.id === 'product-comparison';
        },
        contentLengths() {
            return [
                {value: 'brief', label: 'Brief (600+ words) – [Starter]', available: true},
                {value: 'standard', label: 'Standard (1000+ words) – [BASIC][PRO]', available: true},
                {value: 'detailed', label: 'Detailed (1500+ words) – [PRO]', available: true},
                {value: 'comprehensive', label: 'Comprehensive (2500+ words) – [PRO]', available: true},
            ];
        },
        contentTones() {
            return [
                {value: 'conversational', label: 'Conversational-[Starter]', available: true},
                {value: 'professional', label: 'Professional-[BASIC][PRO]', available: true},
                {value: 'academic', label: 'Academic-[BASIC][PRO]', available: true},
                {value: 'technical', label: 'Technical-[PRO]', available: true},
                {value: 'storytelling', label: 'Storytelling-[PRO]', available: true},
                {value: 'persuasive', label: 'Persuasive-[BASIC][PRO]', available: true},
                {value: 'humorous', label: 'Humorous-[PRO]', available: true},
            ];
        }
    },
    methods: {
        clearErrors() {
            // Clear all errors when any button is clicked
            this.errors = {};

            // Clear all errors in the main wizard steps
            for (const step in this.mainWizardErrors) {
                this.mainWizardErrors[step] = {};
            }

            // Clear all errors in the product wizard steps
            for (const step in this.productWizardErrors) {
                this.productWizardErrors[step] = {};
            }

            // Clear all errors in the SEO wizard steps
            for (const step in this.seoWizardErrors) {
                this.seoWizardErrors[step] = {};
            }
        },
        // Humanize a camelCase variable name to Title Case with spaces
        humanizeVariableName(name) {
            // Special case for contentGoalDetails
            if (name === 'contentGoalDetails') {
                return 'Goal Description';
            }

            // Replace camelCase with spaces and capitalize each word
            return name
                .replace(/([A-Z])/g, ' $1') // Insert a space before all capital letters
                .replace(/^./, function (str) {
                    return str.toUpperCase();
                }) // Capitalize the first letter
                .trim(); // Remove any leading/trailing spaces
        },

        // Search for similar titles
        searchSimilarTitles(title, category = '', keywords = '', goalDescription = '') {
            return new Promise((resolve, reject) => {
                const formData = new FormData();
                formData.append('action', 'postomatic_similar_titles_search');
                formData.append('title', title);
                formData.append('nonce', window.PostomaticAutoPilotData.nonce);

                // Add new parameters
                if (category) {
                    formData.append('category', category);
                }
                if (keywords) {
                    formData.append('keywords', keywords);
                }
                if (goalDescription) {
                    formData.append('goal_description', goalDescription);
                }

                fetch(ajaxurl, {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        resolve(data.data.similar_titles);
                    } else {
                        console.error('Similar Titles Search Error:', data.data.message);
                        resolve([]); // Return empty array on error to continue the process
                    }
                })
                .catch(error => {
                    console.error('Similar Titles Search Error:', error);
                    resolve([]); // Return empty array on error to continue the process
                });
            });
        },
        updateProductName() {
            // Update the productName field when a product is selected
            if (this.form.selectedProduct && this.getSelectedProduct) {
                this.form.productName = this.getSelectedProduct.name;
            } else {
                this.form.productName = '';
            }
        },

        // Get a product by its ID
        getProductById(productId) {
            return this.products.find(product => product.id === productId) || null;
        },

        // Handle product selection based on content goal type
        selectProduct(productId) {
            if (this.isProductComparisonType) {
                // For product comparison, handle multiple selection (up to 3)
                const index = this.form.selectedProducts.indexOf(productId);
                if (index === -1) {
                    // Add product if not already selected and less than 3 products are selected
                    if (this.form.selectedProducts.length < 3) {
                        this.form.selectedProducts.push(productId);
                    } else {
                        // Show alert if user tries to select more than 3 products
                        alert("You cannot compare more than 3 products.");
                    }
                } else {
                    // Remove product if already selected
                    this.form.selectedProducts.splice(index, 1);
                }

                // Update productName to be a comma-separated list of product names
                if (this.form.selectedProducts.length > 0) {
                    const productNames = this.form.selectedProducts.map(id => {
                        const product = this.getProductById(id);
                        return product ? product.name : '';
                    }).filter(name => name !== '');

                    this.form.productName = productNames.join(', ');
                } else {
                    this.form.productName = '';
                }
            } else {
                // For other types, only allow single selection
                this.form.selectedProduct = productId;
                this.updateProductName();
            }
        },

        // Remove a product from the comparison list
        removeProductFromComparison(productId) {
            const index = this.form.selectedProducts.indexOf(productId);
            if (index !== -1) {
                this.form.selectedProducts.splice(index, 1);

                // Update productName
                if (this.form.selectedProducts.length > 0) {
                    const productNames = this.form.selectedProducts.map(id => {
                        const product = this.getProductById(id);
                        return product ? product.name : '';
                    }).filter(name => name !== '');

                    this.form.productName = productNames.join(', ');
                } else {
                    this.form.productName = '';
                }
            }
        },

        // Search products
        searchProducts() {
            this.fetchProducts(this.productSearch, 1);
        },

        // Reset search and show all products
        resetSearch() {
            this.productSearch = '';
            this.fetchProducts('', 1);
        },

        // Handle product pagination
        changePage(page) {
            if (page < 1 || page > this.productPagination.total_pages) {
                return;
            }
            this.fetchProducts(this.productSearch, page);
        },
        fetchContentGoalTypes() {
            // Make an AJAX request to the WordPress admin-ajax.php
            const data = {
                action: 'postomatic_get_content_goal_types',
                nonce: window.PostomaticAutoPilotData.nonce
            };

            // Use the WordPress admin-ajax.php endpoint
            return fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(data)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`There is an issue connecting to server. Please try again.`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success && data.data) {
                        this.contentGoalTypes = data.data;
                    }
                    return this.contentGoalTypes;
                })
                .catch(err => {
                    console.error('Error fetching content goal types:', err);
                    // If there's an error, we'll keep using the hardcoded values
                    return [];
                });
        },

        fetchProducts(search = '', page = 1) {
            // Only fetch products if we have products
            if (!this.hasProducts) {
                return Promise.resolve({
                    products: [],
                    pagination: {total: 0, per_page: 9, current_page: 1, total_pages: 0}
                });
            }

            this.isLoadingProducts = true;

            // Make an AJAX request to the WordPress admin-ajax.php
            const data = {
                action: 'postomatic_get_products',
                nonce: window.PostomaticAutoPilotData.nonce,
                search: search,
                page: page
            };

            // Use the WordPress admin-ajax.php endpoint
            return fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(data)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`There is an issue connecting to server. Please try again.`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success && data.data) {
                        this.products = data.data.products;
                        this.productPagination = data.data.pagination;
                    }
                    return {
                        products: this.products,
                        pagination: this.productPagination
                    };
                })
                .catch(err => {
                    console.error('Error fetching products:', err);
                    return {
                        products: [],
                        pagination: {total: 0, per_page: 9, current_page: 1, total_pages: 0}
                    };
                })
                .finally(() => {
                    this.isLoadingProducts = false;
                });
        },

        fetchAvailableCredits() {
            this.isLoadingCredits = true;

            // Make an AJAX request to the WordPress admin-ajax.php
            const data = {
                action: 'postomatic_get_credits',
                nonce: window.PostomaticAutoPilotData.nonce
            };

            // Use the WordPress admin-ajax.php endpoint
            return fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(data)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`There is an issue connecting to server. Please try again.`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data) {
                        this.availableCredits = data.data.credit || 0;
                        // Only set the budget to 5 if it's not already set
                        if (!this.form.budget) {
                            this.form.budget = 5;
                        }
                    }
                    return this.availableCredits;
                })
                .catch(err => {
                    console.error('Error fetching credit data:', err);
                    this.availableCredits = 0;
                    return this.availableCredits;
                })
                .finally(() => {
                    this.isLoadingCredits = false;
                });
        },
        nextStep() {
            if (this.currentStep === 1) {
                // Validate step 1
                this.mainWizardErrors[1] = {};

                // If user tries to use product goal but no products exist, show error
                if (this.form.goal === 'product' && !this.hasProducts) {
                    this.mainWizardErrors[1].productName = 'You need to add at least one product to your website first';
                    this.errors = this.mainWizardErrors[1]; // Set current errors for UI display
                    return;
                }

                // Validate content goal type (required)
                if (!this.form.contentGoalType) {
                    this.mainWizardErrors[1].contentGoalType = 'Please select a Content Goal Type';
                }

                if (this.form.goal === 'traffic') {
                    if (!this.form.budget || this.form.budget < this.minimumBudget) {
                        this.mainWizardErrors[1].budget = `Budget must be at least ${this.minimumBudget} credits (the final credit can be less or more)`;
                    } else if (this.form.budget > this.availableCredits) {
                        this.mainWizardErrors[1].budget = 'Budget cannot exceed available credits';
                    }

                    // Validate keywords for SEO-Focused Content
                    if (!this.form.keywords || this.form.keywords.trim() === '') {
                        this.mainWizardErrors[1].keywords = 'Please enter at least one keyword or use the Analyze Blog feature';
                    }
                } else if (this.form.goal === 'product') {
                    if (!this.form.selectedProduct) {
                        this.mainWizardErrors[1].productName = 'Please select a product';
                    }

                    // Validate keywords for Product-Focused Content
                    if (!this.form.keywords || this.form.keywords.trim() === '') {
                        this.mainWizardErrors[1].keywords = 'Please enter at least one keyword or use the Analyze Blog feature';
                    }
                } else if (this.form.goal === 'affiliate') {
                    if (!this.form.affiliateProductName) {
                        this.mainWizardErrors[1].affiliateProductName = 'Affiliate product name is required';
                    }
                    if (!this.form.affiliateLink) {
                        this.mainWizardErrors[1].affiliateLink = 'Affiliate link is required';
                    }
                    if (!this.form.commission) {
                        this.mainWizardErrors[1].commission = 'Commission information is required';
                    }

                    // Validate keywords for Affiliate-Focused Content
                    if (!this.form.keywords || this.form.keywords.trim() === '') {
                        this.mainWizardErrors[1].keywords = 'Please enter at least one keyword or use the Analyze Blog feature';
                    }
                }

                // Category is optional
                // if (!this.form.category) {
                //     this.mainWizardErrors[1].category = 'Category is required';
                // }

                if (!this.form.author) {
                    this.mainWizardErrors[1].author = 'Author is required';
                }

                // Validate speaker (required)
                if (!this.form.speaker) {
                    this.mainWizardErrors[1].speaker = 'Who is speaking is required';
                }

                // Validate language (required)
                if (!this.form.language) {
                    this.mainWizardErrors[1].language = 'Language is required';
                }

                // Set current errors for UI display
                this.errors = this.mainWizardErrors[1];

                if (Object.keys(this.errors).length > 0) {
                    // Scroll to the first field with an error and highlight it
                    this.$nextTick(() => {
                        this.scrollToFirstError();
                    });
                    return;
                }
            }

            if (this.currentStep === 2) {
                // Validate step 2
                this.mainWizardErrors[2] = {};
                if (!this.form.count || this.form.count < 1) {
                    this.mainWizardErrors[2].count = 'Number of posts must be at least 1';
                }

                // Calculate total credits required and check if it exceeds available credits
                const creditsPerPost = this.minimumBudget; // Each post costs minimumBudget credits
                const totalCreditsRequired = this.form.count * creditsPerPost;

                if (totalCreditsRequired > this.availableCredits) {
                    this.mainWizardErrors[2].count = `Insufficient credits. Total required: ${totalCreditsRequired}, Available: ${this.availableCredits}. You can create a maximum of ${this.maxPossiblePosts} posts with your current credits.`;
                }

                // Validate keywords (required for all steps)
                if (!this.form.keywords || this.form.keywords.trim() === '') {
                    this.mainWizardErrors[2].keywords = 'Please enter at least one keyword or use the Analyze Blog feature';
                }

                // Set current errors for UI display
                this.errors = this.mainWizardErrors[2];

                if (Object.keys(this.errors).length > 0) {
                    // Scroll to the first field with an error and highlight it
                    this.$nextTick(() => {
                        this.scrollToFirstError();
                    });
                    return;
                }
            }

            // If moving to the review step (step 3), refresh the credits
            if (this.currentStep === 2) {
                this.fetchAvailableCredits();
            }

            this.currentStep++;
        },
        prevStep() {
            this.currentStep--;
            // Set the current errors to the errors for the current step
            this.errors = this.mainWizardErrors[this.currentStep] || {};
        },
        nextProductStep() {
            if (this.productWizardStep === 1) {
                // Validate step 1 for Product Selection
                this.productWizardErrors[1] = {};

                // If user tries to use product goal but no products exist, show error
                if (!this.hasProducts) {
                    this.productWizardErrors[1].productName = 'You need to add at least one product to your website first';
                    this.errors = this.productWizardErrors[1]; // Set current errors for UI display
                    return;
                }

                // Validate content goal type (required)
                if (!this.form.contentGoalType) {
                    this.productWizardErrors[1].contentGoalType = 'Please select a Content Goal Type';
                }

                // Validate product selection based on content goal type
                if (this.isProductComparisonType) {
                    // For product comparison, require at least 2 products
                    if (!this.form.selectedProducts || this.form.selectedProducts.length < 2) {
                        this.productWizardErrors[1].productName = 'Please select at least 2 products for comparison';
                    }
                } else {
                    // For other types, require a single product
                    if (!this.form.selectedProduct) {
                        this.productWizardErrors[1].productName = 'Please select a product';
                    }
                }

                // Set current errors for UI display
                this.errors = this.productWizardErrors[1];

                if (Object.keys(this.errors).length > 0) {
                    // Scroll to the first field with an error and highlight it
                    this.$nextTick(() => {
                        this.scrollToFirstError();
                    });
                    return;
                }
            }

            if (this.productWizardStep === 2) {
                // Validate step 2 for Content Settings
                this.productWizardErrors[2] = {};

                // Validate keywords (required)
                if (!this.form.keywords || this.form.keywords.trim() === '') {
                    this.productWizardErrors[2].keywords = 'Please enter at least one keyword or use the Analyze Blog feature';
                }

                // Validate Goal Description (required)
                if (!this.form.contentGoalDetails) {
                    this.productWizardErrors[2].contentGoalDetails = 'Goal Description is required';
                }

                // Validate author (required)
                if (!this.form.author) {
                    this.productWizardErrors[2].author = 'Author is required';
                }

                // Validate writer (required)
                if (!this.form.writer) {
                    this.productWizardErrors[2].writer = 'Who\'s Writing is required';
                }

                // Validate speaker (required)
                if (!this.form.speaker) {
                    this.productWizardErrors[2].speaker = 'Who is speaking is required';
                }

                // Validate language (required)
                if (!this.form.language) {
                    this.productWizardErrors[2].language = 'Language is required';
                }

                // Set current errors for UI display
                this.errors = this.productWizardErrors[2];

                if (Object.keys(this.errors).length > 0) {
                    // Scroll to the first field with an error and highlight it
                    this.$nextTick(() => {
                        this.scrollToFirstError();
                    });
                    return;
                }
            }

            if (this.productWizardStep === 3) {
                // Validate step 3 for Budget Settings
                this.productWizardErrors[3] = {};

                if (!this.form.budget || this.form.budget < this.minimumBudget) {
                    this.productWizardErrors[3].budget = `Budget must be at least ${this.minimumBudget} credits (the final credit can be less or more)`;
                } else if (this.form.budget > this.availableCredits) {
                    this.productWizardErrors[3].budget = 'Budget cannot exceed available credits';
                }

                // Validate keywords (required for all steps)
                if (!this.form.keywords || this.form.keywords.trim() === '') {
                    this.productWizardErrors[3].keywords = 'Please enter at least one keyword or use the Analyze Blog feature';
                }

                // Set current errors for UI display
                this.errors = this.productWizardErrors[3];

                if (Object.keys(this.errors).length > 0) {
                    // Scroll to the first field with an error and highlight it
                    this.$nextTick(() => {
                        this.scrollToFirstError();
                    });
                    return;
                }
            }

            if (this.productWizardStep === 4) {
                // Validate step 4 for Schedule
                this.productWizardErrors[4] = {};
                if (!this.form.count || this.form.count < 1) {
                    this.productWizardErrors[4].count = 'Number of posts must be at least 1';
                }

                // Calculate total credits required and check if it exceeds available credits
                const creditsPerPost = this.minimumBudget; // Each post costs minimumBudget credits
                const totalCreditsRequired = this.form.count * creditsPerPost;

                if (totalCreditsRequired > this.availableCredits) {
                    this.productWizardErrors[4].count = `Insufficient credits. Total required: ${totalCreditsRequired}, Available: ${this.availableCredits}. You can create a maximum of ${this.maxPossiblePosts} posts with your current credits.`;
                }

                // Validate keywords (required for all steps)
                if (!this.form.keywords || this.form.keywords.trim() === '') {
                    this.productWizardErrors[4].keywords = 'Please enter at least one keyword or use the Analyze Blog feature';
                }

                // Set current errors for UI display
                this.errors = this.productWizardErrors[4];

                if (Object.keys(this.errors).length > 0) {
                    // Scroll to the first field with an error and highlight it
                    this.$nextTick(() => {
                        this.scrollToFirstError();
                    });
                    return;
                }
            }

            // If moving to the review step (step 5), refresh the credits
            if (this.productWizardStep === 4) {
                this.fetchAvailableCredits();
            }

            this.productWizardStep++;
        },
        prevProductStep() {
            this.productWizardStep--;
        },
        nextSeoStep() {
            if (this.seoWizardStep === 1) {
                // Validate step 1 for SEO tab
                this.seoWizardErrors[1] = {};

                // Validate content goal type (required)
                if (!this.form.contentGoalType) {
                    this.seoWizardErrors[1].contentGoalType = 'Please select a Content Goal Type';
                }

                // Validate Goal Description (required)
                if (!this.form.contentGoalDetails) {
                    this.seoWizardErrors[1].contentGoalDetails = 'Goal Description is required';
                }

                // Validate keywords for SEO-Focused Content
                if (!this.form.keywords || this.form.keywords.trim() === '') {
                    this.seoWizardErrors[1].keywords = 'Please enter at least one keyword or use the Analyze Blog feature';
                }

                // Validate author (required)
                if (!this.form.author) {
                    this.seoWizardErrors[1].author = 'Author is required';
                }

                // Validate writer (required)
                if (!this.form.writer) {
                    this.seoWizardErrors[1].writer = 'Who\'s Writing is required';
                }

                // Validate speaker (required)
                if (!this.form.speaker) {
                    this.seoWizardErrors[1].speaker = 'Who is speaking is required';
                }

                // Validate language (required)
                if (!this.form.language) {
                    this.seoWizardErrors[1].language = 'Language is required';
                }

                // Set current errors for UI display
                this.errors = this.seoWizardErrors[1];

                if (Object.keys(this.errors).length > 0) {
                    // Scroll to the first field with an error and highlight it
                    this.$nextTick(() => {
                        this.scrollToFirstError();
                    });
                    return;
                }
            }

            if (this.seoWizardStep === 2) {
                // Validate step 2 for Budget
                this.seoWizardErrors[2] = {};

                if (!this.form.budget || this.form.budget < this.minimumBudget) {
                    this.seoWizardErrors[2].budget = `Budget must be at least ${this.minimumBudget} credits (the final credit can be less or more)`;
                } else if (this.form.budget > this.availableCredits) {
                    this.seoWizardErrors[2].budget = 'Budget cannot exceed available credits';
                }

                // Validate keywords (required for all steps)
                if (!this.form.keywords || this.form.keywords.trim() === '') {
                    this.seoWizardErrors[2].keywords = 'Please enter at least one keyword or use the Analyze Blog feature';
                }

                // Set current errors for UI display
                this.errors = this.seoWizardErrors[2];

                if (Object.keys(this.errors).length > 0) {
                    // Scroll to the first field with an error and highlight it
                    this.$nextTick(() => {
                        this.scrollToFirstError();
                    });
                    return;
                }
            }

            if (this.seoWizardStep === 3) {
                // Validate step 3 for Schedule
                this.seoWizardErrors[3] = {};
                if (!this.form.count || this.form.count < 1) {
                    this.seoWizardErrors[3].count = 'Number of posts must be at least 1';
                }

                // Calculate total credits required and check if it exceeds available credits
                const creditsPerPost = this.form.budget; // Use the budget as the credits per post
                const totalCreditsRequired = this.form.count * creditsPerPost;

                if (totalCreditsRequired > this.availableCredits) {
                    this.seoWizardErrors[3].count = `Insufficient credits. Total required: ${totalCreditsRequired}, Available: ${this.availableCredits}. You can create a maximum of ${this.maxPossiblePosts} posts with your current credits.`;
                }

                // Validate keywords (required for all steps)
                if (!this.form.keywords || this.form.keywords.trim() === '') {
                    this.seoWizardErrors[3].keywords = 'Please enter at least one keyword or use the Analyze Blog feature';
                }

                // Set current errors for UI display
                this.errors = this.seoWizardErrors[3];

                if (Object.keys(this.errors).length > 0) {
                    // Scroll to the first field with an error and highlight it
                    this.$nextTick(() => {
                        this.scrollToFirstError();
                    });
                    return;
                }
            }

            // If moving to the review step (step 4), refresh the credits
            if (this.seoWizardStep === 3) {
                this.fetchAvailableCredits();
            }

            this.seoWizardStep++;
        },
        prevSeoStep() {
            this.seoWizardStep--;
        },
        async getOneTimeCode() {
            try {
                const response = await fetch(ajaxurl, {
                    method: "POST",
                    credentials: 'same-origin',
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded",
                    },
                    body: new URLSearchParams({
                        action: "save_one_time_code",
                        nonce: window.PostomaticAutoPilotData.nonce
                    }).toString()
                });

                const data = await response.json();

                if (data.success && data.data && data.data.code) {
                    return data.data.code;
                } else {
                    //console.error('Failed to generate one-time code:', data);
                    return '';
                }
            } catch (error) {
                console.error("Request failed:", error);
                return '';
            }
        },

        async submitForm() {
            this.loading = true;
            this.isSubmitting = true;

            // Generate and save one-time code on the server
            const oneTimeCode = await this.getOneTimeCode();

            // Create a new task with separated content goal
            const contentGoal = {
                type: this.form.goal,
                goal_type: this.form.contentGoalType, // Use goal_type as expected by the API
            };

            // Add specific fields based on the goal type
            if (this.form.goal === 'product') {
                contentGoal.product_name = this.form.productName;
                contentGoal.budget = Number(this.form.budget);
                contentGoal.keywords = this.form.keywords; // Include keywords for product-focused content

                if (this.isProductComparisonType && this.form.selectedProducts && this.form.selectedProducts.length > 0) {
                    // For product comparison, use the selectedProducts array
                    contentGoal.product_ids = this.form.selectedProducts;

                    // Include the full product details for each product if available
                    const productMetas = [];
                    this.form.selectedProducts.forEach(productId => {
                        const product = this.getProductById(productId);
                        if (product && product['product-meta']) {
                            productMetas.push(product['product-meta']);
                        }
                    });

                    if (productMetas.length > 0) {
                        contentGoal.product_meta = productMetas;
                    }
                } else {
                    // For single product, use the selectedProduct field
                    contentGoal.product_id = this.form.selectedProduct;

                    // Include the full product details if available
                    if (this.getSelectedProduct && this.getSelectedProduct['product-meta']) {
                        contentGoal.product_meta = this.getSelectedProduct['product-meta'];
                    }
                }
            } else if (this.form.goal === 'traffic') {
                contentGoal.budget = Number(this.form.budget);
                contentGoal.keywords = this.form.keywords;
            }

            // Search for similar titles if we have content goal details
            let similarTitles = [];
            if (this.form.contentGoalDetails) {
                // Get category and keywords from the form
                const category = this.form.category ? this.form.category : '';
                const keywords = this.form.keywords ? this.form.keywords : '';
                const goalDescription = this.form.contentGoalDetails;

                // Search for similar titles
                try {
                    similarTitles = await this.searchSimilarTitles(goalDescription, category, keywords, goalDescription);
                } catch (error) {
                }
            }

            // Create the task object with separated content goal
            const newTask = {
                content_goal_details: this.form.contentGoalDetails,
                content_goal: contentGoal,
                category: this.form.category,
                author_id: this.form.author,
                author_name: this.getAuthorName(this.form.author),
                frequency: this.form.frequency,
                count: this.form.count,
                status: this.form.status,
                created_at: this.formatDateWithTime(new Date()),
                next_run: this.getNextRunDate(this.form.frequency),
                estimated_credits: this.estimatedCredits,
                all_categories: this.categories.map(cat => cat.name), // Send only category titles
                comment_status: this.form.commentStatus, // Allow comment
                ai_feature_image: this.form.aiFeatureImage, // AI feature image
                category_title: this.getCategoryName(this.form.category), // category in title
                content_tone: this.form.contentTone, // Content tone
                speaker: this.form.speaker, // Who is speaking
                language: this.form.language, // Language
                // similar_titles: similarTitles.length > 0 ? JSON.stringify(similarTitles.map(t => ({title: t.title, shortlink: t.shortlink}))) : '', // Similar titles with shortlinks
                blog_similar_titles: similarTitles.length > 0 ? JSON.stringify(similarTitles.map(t => ({title: t.title, shortlink: t.shortlink}))) : '', // Similar titles for blog
                one_time_code: oneTimeCode // Add one-time code to the task
            };

            // Log the task object to verify product details are included

            // Make a POST request to the WordPress admin-ajax.php
            const data = {
                action: 'postomatic_create_autopilot',
                nonce: window.PostomaticAutoPilotData.nonce,
                task: JSON.stringify(newTask)
            };

            // Use the WordPress admin-ajax.php endpoint
            fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(data)
            })
                .then(response => {
                    // Always try to parse the JSON response, even if the response is not ok
                    // This allows us to get detailed error messages from the server
                    return response.json().catch(e => {
                        // If we can't parse the JSON, then throw a generic error
                        if (!response.ok) {
                            throw new Error(`There is an issue connecting to server. Please try again.`);
                        }
                        throw e;
                    });
                })
                .then(data => {
                    // Check if the response has status: false or success: false
                    if ((data && data.status === false) || (data && data.success === false)) {
                        // Show error message at the top
                        this.showSuccessAlert = true;
                        this.isErrorMessage = true;
                        // Handle both message formats (data.message or data.data)
                        this.successMessage = data.message || (data.data ? data.data : 'Error creating AutoPilot task. Please try again.');

                        // Also set field-specific errors based on the message
                        this.errors = {};

                        // Check for common validation issues in the error message
                        const errorMsg = (data.message || (data.data ? data.data : '')).toLowerCase();

                        if (errorMsg.includes('content goal type')) {
                            this.errors.contentGoalType = 'Content Goal Type is required';
                        }
                        if (errorMsg.includes('goal description') || errorMsg.includes('content goal details')) {
                            this.errors.contentGoalDetails = 'Goal Description is required';
                        }
                        if (errorMsg.includes('product')) {
                            this.errors.productName = 'Product selection is required';
                        }
                        if (errorMsg.includes('keyword')) {
                            this.errors.keywords = 'Keywords are required';
                        }
                        if (errorMsg.includes('budget')) {
                            this.errors.budget = 'Budget is required';
                        }
                        if (errorMsg.includes('author')) {
                            this.errors.author = 'Author is required';
                        }
                        if (errorMsg.includes('speaker')) {
                            this.errors.speaker = 'Who is speaking is required';
                        }
                        if (errorMsg.includes('language')) {
                            this.errors.language = 'Language is required';
                        }
                        if (errorMsg.includes('category')) {
                            this.errors.category = 'Category is required';
                        }
                        if (errorMsg.includes('count') || errorMsg.includes('number of posts')) {
                            this.errors.count = 'Number of posts is required';
                        }

                        // If we have errors, scroll to the first error field
                        if (Object.keys(this.errors).length > 0) {
                            this.$nextTick(() => {
                                this.scrollToFirstError();
                            });
                        }

                        return;
                    }

                    // Add to tasks array
                    this.tasks.push(newTask);

                    // Show success message
                    this.showSuccessAlert = true;
                    this.isErrorMessage = false;
                    this.successMessage = 'Your AutoPilot task has been created successfully!';
                    this.showMainAlert = false;

                    // Move to task list view (main add page)
                    this.currentStep = 4;

                    // Reload tasks from the API
                    this.fetchAutopilotTasks();
                })
                .catch(err => {
                    console.error('Error creating autopilot task:', err);

                    // Function to handle error data
                    const handleErrorData = (errorData) => {
                        if (errorData && errorData.errors) {
                            // Clear previous errors
                            this.errors = {};

                            // Process validation errors
                            for (const [field, messages] of Object.entries(errorData.errors)) {
                                // Handle nested fields like contentGoal.budget
                                if (field.includes('.')) {
                                    const [parent, child] = field.split('.');
                                    if (parent === 'contentGoal') {
                                        // Map API field names to form field names
                                        if (child === 'budget') {
                                            this.errors.budget = messages[0];
                                        } else if (child === 'keywords') {
                                            this.errors.keywords = messages[0];
                                        } else if (child === 'goalType') {
                                            this.errors.contentGoalType = messages[0];
                                        }
                                    }
                                } else {
                                    // Direct field mapping
                                    this.errors[field] = messages[0];
                                }
                            }

                            // Navigate back to the appropriate step based on errors
                            if (this.errors.budget || this.errors.keywords ||
                                this.errors.productName || this.errors.category ||
                                this.errors.author) {
                                this.currentStep = 1;

                                // If the error is related to budget or keywords, ensure we're on the traffic tab
                                if (this.errors.budget || this.errors.keywords) {
                                    this.form.goal = 'traffic';
                                }
                            } else if (this.errors.count || this.errors.frequency || this.errors.status) {
                                this.currentStep = 2;
                            }

                            // Don't show success alert when there are validation errors
                            this.showSuccessAlert = false;
                            return true; // Errors were handled
                        }
                        return false; // No errors to handle
                    };

                    // Try to get the response data from the error
                    if (err.response) {
                        // For Axios-like errors
                        if (err.response.data) {
                            if (handleErrorData(err.response.data)) {
                                // Errors were handled, exit early
                                return;
                            }
                        }
                    } else if (err instanceof Response || (err.json && typeof err.json === 'function')) {
                        // For fetch Response objects
                        err.json().then(errorData => {
                            if (!handleErrorData(errorData)) {
                                // If no validation errors, show error message (not success)
                                this.showSuccessAlert = true;
                                this.isErrorMessage = true;
                                this.successMessage = errorData.message || 'Error creating AutoPilot task. Please try again.';
                            }
                        }).catch(() => {
                            // Fallback if JSON parsing fails
                            this.showSuccessAlert = true;
                            this.isErrorMessage = true;
                            this.successMessage = 'Error creating AutoPilot task: ' + err.message;
                        });
                        return; // Exit early as we're handling the error asynchronously
                    } else if (err.message && (err.message.includes('API request failed') || err.message.includes('There is an issue connecting to server'))) {
                        // This is likely from our own throw in the first then() block
                        // Try to parse the response
                        const match = err.message.match(/API request failed with status (\d+)/) || err.message.match(/status (\d+)/);
                        if (match) {
                            const statusCode = match[1];
                            // Handle 403 errors specifically
                            if (statusCode === '403') {
                                this.showSuccessAlert = true;
                                this.isErrorMessage = true;
                                this.successMessage = 'You have reached your daily limit of autopilot for your plan. Please try again tomorrow or upgrade your plan for higher limits.';
                                return;
                            } else if (statusCode === '422') {
                                // This is likely a validation error, but we don't have the details
                                // Add a generic validation error to display in the validation errors alert
                                this.errors = {form: 'Please check your form for errors and try again.'};
                                this.showSuccessAlert = false;
                                return;
                            }
                        }
                    }

                    // Generic error handling if none of the above worked
                    this.showSuccessAlert = true;
                    this.isErrorMessage = true;
                    this.successMessage = 'Error creating AutoPilot task: ' + (err.message || 'Unknown error');
                })
                .finally(() => {
                    this.loading = false;
                    this.isSubmitting = false;
                });
        },
        resetForm() {
            this.form = {
                goal: '',
                topic: '',
                productName: '',
                keywords: '',
                category: '',
                author: '',
                frequency: 'weekly',
                count: 1,
                status: 'draft',
                budget: 8,
                commentStatus: 'open',
                aiFeatureImage: false
            };
            this.minimumBudget = 8;
            this.currentStep = 1;
            this.productWizardStep = 1;
            this.seoWizardStep = 1;
            this.showMainAlert = true;
            this.showSuccessAlert = false;
            this.isErrorMessage = false;
            this.errors = {};
        },
        getNextRunDate(frequency) {
            const date = new Date();
            switch (frequency) {
                case 'daily':
                    date.setDate(date.getDate() + 1);
                    break;
                case 'weekly':
                    date.setDate(date.getDate() + 7);
                    break;
                case 'biweekly':
                    date.setDate(date.getDate() + 14);
                    break;
                case 'monthly':
                    date.setMonth(date.getMonth() + 1);
                    break;
            }
            return this.formatDateWithTime(date);
        },

        formatDateWithTime(date) {
            if (!(date instanceof Date)) {
                // Try to convert string to Date object
                date = new Date(date);
                if (isNaN(date.getTime())) {
                    return 'Invalid Date';
                }
            }

            // Format: "Jan 1, 2023 at 14:30"
            const options = { 
                year: 'numeric', 
                month: 'short', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            };
            return date.toLocaleDateString(undefined, options);
        },
        getCategoryName(categoryId) {
            if (!categoryId) {
                return null;
            }
            const category = this.categories.find(cat => cat.term_id == categoryId);
            return category ? category.name : 'None';
        },
        getAuthorName(authorId) {
            const author = this.authors.find(auth => auth.ID == authorId);
            return author ? author.display_name : 'None';
        },
        getContentGoalTypeTitle(typeId) {
            // First try to find the content goal type in the fetched array
            const contentGoalType = this.contentGoalTypes.find(type => type.id === typeId);
            if (contentGoalType) {
                return contentGoalType.title;
            }

            // If not found, fall back to the contentGoalTypeMap for backward compatibility
            return this.contentGoalTypeMap[typeId] || typeId;
        },

        getFrequencyLabel(frequency) {
            const labels = {
                daily: 'Daily',
                weekly: 'Weekly',
                biweekly: 'Bi-weekly',
                monthly: 'Monthly'
            };
            return labels[frequency] || frequency;
        },
        getFrequencyIcon(frequency) {
            // Return a simple SVG icon based on frequency
            // These are just placeholder SVG strings - you can replace with actual icon components if available
            const icons = {
                daily: 'svg-icon-daily',
                weekly: 'svg-icon-weekly',
                biweekly: 'svg-icon-biweekly',
                monthly: 'svg-icon-monthly'
            };
            return icons[frequency] || 'svg-icon-default';
        },
        updateMinimumCredit() {
            // Add or subtract 6 credits based on the checkbox state
            if (this.form.aiFeatureImage) {
                this.minimumBudget = 14; // 8 + 6 credits
                // If current budget is less than minimum, update it
                if (this.form.budget < this.minimumBudget) {
                    this.form.budget = this.minimumBudget;
                }
            } else {
                this.minimumBudget = 8; // Reset to default
            }
        },
        viewTaskDetails(task) {
            this.currentTask = task;
            this.showTaskModal = true;
        },
        confirmDeleteTask(index) {
            // Store the task ID directly instead of the index
            // Check if index is valid and allAutopilots exists
            if (this.allAutopilots && index >= 0 && index < this.allAutopilots.length) {
                const task = this.allAutopilots[index];
                if (task) {
                    // If task exists but doesn't have an ID, use the index as the ID
                    this.taskToDeleteIndex = task.identifier;
                    // Use Vue.nextTick to ensure taskToDeleteIndex is set before showing the modal
                        this.showDeleteModal = true;
                } else {
                    console.error('Task is null or undefined at index:', index);
                }
            } else {
                console.error('Invalid index or allAutopilots not initialized:', index);
            }
        },
        deleteTask() {
            if (this.taskToDeleteIndex !== null) {
                const taskId = this.taskToDeleteIndex;
                // Check if this is a generated ID (created for tasks without an ID)
                if (taskId.toString().startsWith('generated-')) {

                    // Even for generated IDs, we now call the API to finalize the delete
                    // But first store the local index so we can remove it if API fails
                    const taskIndex = this.tasks.findIndex(task => task && task.id === this.taskToDeleteIndex);

                    // Call admin-ajax.php to finalize the delete
                    const data = {
                        action: 'postomatic_delete_autopilot',
                        nonce: window.PostomaticAutoPilotData.nonce,
                        task_id: taskId
                    };

                    // Use the WordPress admin-ajax.php endpoint
                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: new URLSearchParams(data)
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`There is an issue connecting to server. Please try again.`);
                        }
                        // this.fetchAutopilotTasks()
                        return response.json();
                    })
                    .then(data => {
                        if (data && (data.success === true || data.status === true)) {
                            // Remove from local array after successful API call
                            // if (taskIndex !== -1) {
                            //     this.tasks.splice(taskIndex, 1);
                            // } else {
                            //     console.warn('Task not found in tasks array:', this.taskToDeleteIndex);
                            // }

                            this.taskToDeleteIndex = null;
                            this.showDeleteModal = false;

                            // Show success message
                            this.showSuccessAlert = true;
                            this.isErrorMessage = false;
                            // Check if data.message is a string or an object
                            if (typeof data.message === 'string') {
                                this.successMessage = data.message;
                            } else if (data.data && typeof data.data === 'string') {
                                this.successMessage = data.data;
                            } else {
                                this.successMessage = 'AutoPilot task has been deleted successfully!';
                            }

                            // Reload tasks from the API
                            this.fetchAutopilotTasks();
                        } else {
                            // Show error message from the response
                            this.showSuccessAlert = true;
                            this.isErrorMessage = true;
                            // Check if data.message is a string or an object
                            if (typeof data.message === 'string') {
                                this.successMessage = data.message;
                            } else if (data.data && typeof data.data === 'string') {
                                this.successMessage = data.data;
                            } else if (data.data && data.data.message && typeof data.data.message === 'string') {
                                this.successMessage = data.data.message;
                            } else {
                                this.successMessage = 'Failed to delete task';
                            }

                            this.taskToDeleteIndex = null;
                            this.showDeleteModal = false;

                            // Reload tasks from the API to ensure UI is in sync
                            this.fetchAutopilotTasks();
                        }
                    })
                    .catch(err => {
                        console.error('Error deleting task:', err);

                        // Show error message
                        this.showSuccessAlert = true;
                        this.isErrorMessage = true;
                        this.successMessage = `Failed to delete task: ${err.data || err.message || 'Unknown error'}`;

                        // Hide error message after 5 seconds
                        setTimeout(() => {
                            this.showSuccessAlert = false;
                        }, 5000);

                        // Close the modal
                        this.taskToDeleteIndex = null;
                        this.showDeleteModal = false;

                        // Reload tasks from the API to ensure UI is in sync
                        this.fetchAutopilotTasks();
                    });

                    return; // Exit early, API call is in progress
                }

                // For real task IDs, make request to admin-ajax.php
                const data = {
                    action: 'postomatic_delete_autopilot',
                    nonce: window.PostomaticAutoPilotData.nonce,
                    task_id: taskId
                };

                // Use the WordPress admin-ajax.php endpoint
                fetch(ajaxurl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams(data)
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`There is an issue connecting to server. Please try again.`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data && (data.success === true || data.status === true)) {
                            // Find the task in the tasks array using the task ID and remove it
                            const taskIndex = this.tasks.findIndex(task => task && task.id === this.taskToDeleteIndex);
                            if (taskIndex !== -1) {
                                this.tasks.splice(taskIndex, 1);
                            } else {
                                console.warn('Task not found in tasks array:', this.taskToDeleteIndex);
                            }
                            this.taskToDeleteIndex = null;
                            this.showDeleteModal = false;

                            // Show success message
                            this.showSuccessAlert = true;
                            this.isErrorMessage = false;
                            // Check if data.message is a string or an object
                            if (typeof data.message === 'string') {
                                this.successMessage = data.message;
                            } else if (data.data && typeof data.data === 'string') {
                                this.successMessage = data.data;
                            } else {
                                this.successMessage = 'AutoPilot task has been deleted successfully!';
                            }

                            // Reload tasks from the API
                            this.fetchAutopilotTasks();

                        } else {
                            // Show error message from the response
                            this.showSuccessAlert = true;
                            this.isErrorMessage = true;
                            // Check if data.message is a string or an object
                            if (typeof data.message === 'string') {
                                this.successMessage = data.message;
                            } else if (data.data && typeof data.data === 'string') {
                                this.successMessage = data.data;
                            } else if (data.data && data.data.message && typeof data.data.message === 'string') {
                                this.successMessage = data.data.message;
                            } else {
                                this.successMessage = 'Failed to delete task';
                            }

                            this.taskToDeleteIndex = null;
                            this.showDeleteModal = false;

                            // Reload tasks from the API to ensure UI is in sync
                            this.fetchAutopilotTasks();
                        }
                    })
                    .catch(err => {
                        console.error('Error deleting task:', err);

                        // Show error message
                        this.showSuccessAlert = true;
                        this.isErrorMessage = true;
                        this.successMessage = `Failed to delete task: ${err.message || 'Unknown error'}`;

                        // Hide error message after 5 seconds
                        setTimeout(() => {
                            this.showSuccessAlert = false;
                        }, 5000);

                        // Close the modal
                        this.taskToDeleteIndex = null;
                        this.showDeleteModal = false;

                        // Reload tasks from the API to ensure UI is in sync
                        this.fetchAutopilotTasks();
                    });
            } else {
                console.error('No task selected for deletion');
                this.showDeleteModal = false;
            }
        },
        analyzeContent() {
            // Set analyzing state to true
            this.isAnalyzing = true;
            this.loading = true; // Show loading overlay
            this.analyzedKeywords = [];
            this.analysisCompleted = false;

            // Make an AJAX request to the WordPress REST API
            const data = {
                action: 'postomatic_analyze_blog',
                nonce: window.PostomaticAutoPilotData.nonce,
                category: this.form.category
            };

            // Add author information if an author is selected
            if (this.form.author) {
                data.wordpress_author_id = this.form.author;
                // Find the author name from the authors array
                const selectedAuthor = this.authors.find(author => author.ID == this.form.author);
                if (selectedAuthor) {
                    data.wordpress_author_name = selectedAuthor.display_name;
                }
            }

            // Use the WordPress admin-ajax.php endpoint
            fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(data)
            })
                .then(response => {

                    if (!response.ok) {
                        throw new Error(`There is an issue connecting to server. Please try again.`);
                    }
                    return response.json();
                })
                .then(data => {
                    let item = data.data

                    if (data.success && item) {

                        // Set the analyzed keywords
                        // Check if keywords are in data.data.keywords or data.data.metadata.keywords
                        this.analyzedKeywords = []; // Clear the array first
                        let keywordsToAdd = [];
                        if (item.keywords && Array.isArray(item.keywords)) {
                            keywordsToAdd = item.keywords;
                        }


                        // Add each keyword to the array using push for reactivity
                        keywordsToAdd.forEach(keyword => {
                            this.analyzedKeywords.push(keyword);
                        });

                        // Show success message
                        this.showSuccessAlert = true;
                        this.successMessage = 'Blog analysis completed successfully!';
                    } else {
                        // Extract error message from data object
                        let errorMessage = 'Unknown error occurred';
                        if (data.data) {
                            if (typeof data.data === 'string') {
                                errorMessage = data.data;
                            } else if (typeof data.data === 'object') {
                                // Try to extract a meaningful error message from the object
                                errorMessage = JSON.stringify(data.data);
                            }
                        }
                        throw new Error(errorMessage);
                    }
                })
                .catch(err => {
                    // Extract error message from the error object
                    let errorMessage = 'Failed to analyze blog content';

                    if (err) {
                        if (err.message) {
                            errorMessage += ': ' + err.message;
                        } else if (typeof err === 'string') {
                            errorMessage += ': ' + err;
                        }
                    }

                    console.error('Error analyzing blog content:', errorMessage);

                    // Show error in the UI
                    this.errors.keywords = errorMessage;

                    // For demo purposes, add some sample keywords
                    // Using Vue's reactive array methods to ensure the change is detected
                    this.analyzedKeywords = [];
                    const sampleKeywords = ['wordpress', 'blogging', 'content marketing', 'SEO', 'digital marketing'];
                    sampleKeywords.forEach(keyword => {
                        this.analyzedKeywords.push(keyword);
                    });
                })
                .finally(() => {
                    this.isAnalyzing = false;
                    this.loading = false; // Hide loading overlay
                    this.analysisCompleted = true;
                });
        },
        fetchAutopilotTasks() {
            this.loading = true;

            // Make an AJAX request to the WordPress admin-ajax.php
            const data = {
                action: 'postomatic_get_autopilots',
                nonce: window.PostomaticAutoPilotData.nonce
            };

            // Use the WordPress admin-ajax.php endpoint
            fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(data)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`There is an issue connecting to server. Please try again.`);
                    }
                    return response.json();
                })
                .then(data => {
                    // Check if data has the expected structure
                    // Handle both formats: {status, data: Array} and {status, data: {data: Array}}
                    if (data) {
                        let tasksArray;

                        if (Array.isArray(data.data)) {
                            // Original expected format: {status, data: Array}
                            tasksArray = data.data;
                        } else if (data.data && data.data.data && Array.isArray(data.data.data)) {
                            // New nested format: {status, data: {data: Array}}
                            tasksArray = data.data.data;
                        } else {
                            // Invalid format
                            console.warn('Invalid data format received from API:', data);
                            this.tasks = [];
                            return;
                        }

                        // Transform the API response data to match the expected format for the UI
                        this.tasks = tasksArray.map(task => {
                            // Get the budget for this task (default to 10 if not specified)
                            const taskBudget = task.budget_per_post || 10;

                            // Check if total credits are lower than the task's budget
                            // If total credits are sufficient, the task is active
                            const isActive = this.availableCredits >= taskBudget;

                            // Map API response properties to UI expected properties
                            return {
                                id: task.id,
                                identifier: task.identifier,
                                category: task.category,
                                // Map type_of_autopilot to contentGoal.type
                                contentGoal: {
                                    type: task.type_of_autopilot || 'traffic',
                                    typeKey: task.type_of_autopilot || 'traffic', // Store the original key
                                    typeTitle: this.getContentGoalTypeTitle(task.type_of_autopilot) || this.contentGoalTypeMap['traffic'], // Store the display title
                                    keywords: task.keywords,
                                    budget: taskBudget, // Use the extracted budget
                                    productName: task.category || 'Product', // Use category as product name if available
                                    affiliateProductName: task.category || 'Affiliate Product', // Use category as affiliate product name if available
                                    blogAnalysed: task.blog_analysed || false, // Map blog_analysed
                                    blogId: task.blog_id || 1, // Map blog_id
                                    titles: task.titles || null, // Map titles
                                    productMeta: task.product_meta_data || []
                                },
                                topic: task.category || 'SEO Content', // Use category as topic if available
                                frequency: task.publishing_frequency || 'N/A', // Map publishing_frequency to frequency
                                count: task.number_of_posts || 1, // Map number_of_posts to count
                                status: task.post_status || 'draft', // Map post_status to status
                                postStatus: task.post_status,
                                nextRun: task.next_run_date ? this.formatDateWithTime(task.next_run_date) : this.getNextRunDate(task.publishing_frequency || 'weekly'),
                                createdAt: task.created_at ? this.formatDateWithTime(task.created_at) : '',
                                estimatedCredits: task.budget_per_post || this.minimumBudget, // Use budget_per_post as credits
                                // Additional fields from API response
                                deletedAt: task.deleted_at ? this.formatDateWithTime(task.deleted_at) : '',
                                // updatedAt: task.updated_at,
                                isActive: isActive, // Add isActive property based on credit check
                                inactiveReason: !isActive ? `Insufficient credits (need ${taskBudget}, have ${this.availableCredits})` : null, // Add reason if inactive
                                budgetPerPost: task.budget_per_post || this.minimumBudget, // Map budget_per_post
                                // Add author information
                                author_name: task.author_name || '',
                                contentGoalTypeTitle: task.content_goal_type_title,
                                wordpress_author_name: task.wordpress_author_name || task.author_name || ''
                            }
                        });

                    } else {
                    }
                })
                .catch(err => {
                     this.tasks = [];
                 })
                .finally(() => {
                    this.loading = false;
                });
        },

        processLanguagesArray(array) {
            return array.map(lang => {
                // If the language object already has code and name properties, use them
                if (lang.code && lang.name) {
                    return lang;
                }
                // If the language object has different property names, map them
                else if (lang.id || lang.value || lang.key) {
                    return {
                        code: lang.id || lang.value || lang.key,
                        name: lang.name || lang.label || lang.title || lang.text
                    };
                }
                // If the language is a string, use it for both code and name
                else if (typeof lang === 'string') {
                    return {
                        code: lang.toLowerCase().replace(/\s+/g, '_'),
                        name: lang
                    };
                }
                // Default fallback
                return {
                    code: 'unknown',
                    name: 'Unknown Language'
                };
            });
        },

        fetchLanguagesData() {
            // Make an AJAX request to the WordPress admin-ajax.php
            const data = {
                action: 'postomatic_get_languages',
                nonce: window.PostomaticAutoPilotData.nonce
            };

            // Use the WordPress admin-ajax.php endpoint
            return fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(data)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`There is an issue connecting to server. Please try again.`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success && data.data) {
                        // Process the API response to ensure it has the expected structure
                        let languages = [];

                        // Check if data.data is an array
                        if (Array.isArray(data.data)) {
                            languages = this.processLanguagesArray(data.data);
                        }
                        // Check if data.data is an object with key-value pairs of languages
                        else if (typeof data.data === 'object') {
                            languages = Object.entries(data.data).map(([key, value]) => {
                                return {
                                    code: key,
                                    name: typeof value === 'string' ? value : key
                                };
                            });
                        }

                        this.contentData.languages = languages;
                     }
                    return this.contentData.languages;
                })
                .catch(err => {
                    console.error('Error fetching languages data:', err);
                    this.contentData.languages = []; // Initialize with empty array on error
                    return [];
                });
        },
        resizeKeywordsTextarea() {
            // Auto-resize the keywords textareas to fit their content
            const textareas = [
                document.getElementById('autopilot-keywords'),
                document.getElementById('autopilot-keywords-product')
            ];

            textareas.forEach(textarea => {
                if (textarea) {
                    // Reset height to auto to get the correct scrollHeight
                    textarea.style.height = 'auto';
                    // Set the height to the scrollHeight to fit all content
                    textarea.style.height = textarea.scrollHeight + 'px';
                }
            });
        },
        addKeyword(keyword) {
            // Split keywords by comma, trim, and filter empty entries
            let currentKeywords = (this.form.keywords || '')
                .split(',')
                .map(k => k.trim())
                .filter(k => k.length > 0);

            // Check if the keyword already exists (case-insensitive)
            const keywordIndex = currentKeywords.findIndex(k => k.toLowerCase() === keyword.toLowerCase());

            if (keywordIndex === -1) {
                // Keyword doesn't exist, add it
                currentKeywords.push(keyword);
            } else {
                // Keyword exists, remove it
                currentKeywords.splice(keywordIndex, 1);
            }

            // Update the form keywords
            this.form.keywords = currentKeywords.join(', ');

            // Update the active class on the clicked keyword chip
            this.$nextTick(() => {
                this.watchKeywords();
            });
        },
        watchKeywords() {
            // Handle case where form.keywords is undefined or empty
            const currentKeywords = (this.form.keywords || '')
                .split(',')
                .map(k => k.trim().toLowerCase())
                .filter(k => k.length > 0);

            // Reset all keyword chips
            const keywordChips = document.querySelectorAll('.seo-keyword-chip');
            keywordChips.forEach(chip => {
                const chipKeyword = chip.textContent.trim().toLowerCase();
                if (currentKeywords.includes(chipKeyword)) {
                    chip.classList.add('active');
                } else {
                    chip.classList.remove('active');
                }
            });
        },
        scrollToFirstError() {
            // Get all error fields
            const errorFields = Object.keys(this.errors);

            if (errorFields.length === 0) return;

            // Get the first field with an error
            const firstErrorField = errorFields[0];

            // Find the corresponding input element
            let inputElement;

            // Map error field names to their corresponding input IDs
            const fieldMap = {
                'productName': 'autopilot-product-name',
                'budget': 'autopilot-budget',
                'keywords': 'autopilot-keywords',
                'category': 'autopilot-category',
                'author': 'autopilot-author',
                'count': 'autopilot-count',
                'frequency': 'autopilot-frequency',
                'status': 'autopilot-status',
                'affiliateProductName': 'autopilot-affiliate-product-name',
                'affiliateLink': 'autopilot-affiliate-link',
                'commission': 'autopilot-commission',
                'contentGoalType': 'autopilot-content-goal-type',
                'contentGoalDetails': 'autopilot-content-goal-details',
                'speaker': 'autopilot-speaker',
                'language': 'autopilot-language',
                'writer': 'autopilot-writer'
            };

            // Get the input element ID
            const inputId = fieldMap[firstErrorField];

            if (inputId) {
                inputElement = document.getElementById(inputId);
            }

            if (inputElement) {
                // Scroll to the element
                inputElement.scrollIntoView({behavior: 'smooth', block: 'center'});

                // Add highlight class to make it more visible
                inputElement.classList.add('highlight-error');

                // Focus on the element
                inputElement.focus();

                // Remove the highlight class after animation completes
                setTimeout(() => {
                    inputElement.classList.remove('highlight-error');
                }, 2000);
            } else {
                // If we can't find the specific input, scroll to the validation errors alert
                const errorAlert = document.querySelector('.alert-error');
                if (errorAlert) {
                    errorAlert.scrollIntoView({behavior: 'smooth', block: 'center'});
                }
            }
        }
    },
    watch: {
        'form.keywords': function (newVal, oldVal) {
            this.$nextTick(() => {
                this.watchKeywords();
                this.resizeKeywordsTextarea();
            });
        },
        'form.contentGoalType': function (newVal, oldVal) {
            // When content goal type changes, fetch products
            if (newVal && this.hasProducts) {
                this.fetchProducts();
            }

            // Reset selectedProducts when content goal type changes
            // Ensure it's always an array to prevent "Cannot read properties of undefined" errors
            this.form.selectedProducts = [];

            // Reset selectedProduct as well
            this.form.selectedProduct = '';
        },
        'showTaskModal': function (newVal, oldVal) {
            // Log when showTaskModal changes for debugging

            // Always force showTaskModal back to false during page load
            // This prevents the modal from appearing unexpectedly
            if (newVal === true && !this.currentTask) {
                 // Immediately set it back to false without waiting for nextTick
                this.showTaskModal = false;
            }
        },
        'showDeleteModal': function (newVal, oldVal) {
            // Log when showDeleteModal changes for debugging

            // Always force showDeleteModal back to false during page load
            // This prevents the modal from appearing unexpectedly
            // if (newVal === true && !this.taskToDeleteIndex) {
            //     console.log('Forcing showDeleteModal back to false - no task selected for deletion');
            //     // Immediately set it back to false without waiting for nextTick
            //     this.showDeleteModal = false;
            // }
        },
        'availableCredits': function (newVal, oldVal) {
            // When available credits change, check if form.count exceeds maxPossiblePosts
            if (this.form.count > this.maxPossiblePosts && this.maxPossiblePosts > 0) {
                // Adjust form.count to maxPossiblePosts
                this.form.count = this.maxPossiblePosts;
            }
        },
        'form.count': function (newVal, oldVal) {
            // When form.count changes, check if it exceeds maxPossiblePosts
            if (newVal > this.maxPossiblePosts && this.maxPossiblePosts > 0) {
                // Adjust form.count to maxPossiblePosts
                this.form.count = this.maxPossiblePosts;
            }
        },
        'form.aiFeatureImage': function (newVal, oldVal) {
            // When aiFeatureImage changes, update the minimum budget
            this.updateMinimumCredit();
        },
        'form.writer': function (newVal, oldVal) {
            // Sync writer to author field to fix "Author is required" validation error
            this.form.author = newVal;
        }
    },
    created() {
        // Ensure modals are closed when component is created
        this.showDeleteModal = false;
        this.taskToDeleteIndex = null;
        this.showTaskModal = false;
        this.currentTask = null;
    },
    beforeMount() {
        // Ensure modals are closed before mounting
        this.showDeleteModal = false;
        this.taskToDeleteIndex = null;
        this.showTaskModal = false;
        this.currentTask = null;
    },
    mounted() {
        // Ensure modals are closed on page load/refresh
        this.showDeleteModal = false;
        this.taskToDeleteIndex = null;
        this.showTaskModal = false;
        this.currentTask = null;

        // Add global click event listener to clear errors when any button is clicked
        // except for "Next Step" buttons which need to validate fields
        document.addEventListener('click', (event) => {
            const target = event.target;
            const isButton = target.tagName === 'BUTTON' || 
                target.closest('button') || 
                target.tagName === 'A' || 
                target.closest('a') ||
                target.classList.contains('btn') ||
                target.closest('.btn');

            // Check if it's a "Next Step" button
            const isNextStepButton = 
                (target.textContent && target.textContent.trim() === 'Next Step') ||
                (target.closest('button') && target.closest('button').textContent.trim() === 'Next Step');

            // Only clear errors if it's a button but not a "Next Step" button
            if (isButton && !isNextStepButton) {
                this.clearErrors();
            }
        });

        // Force Vue to re-render with modals closed
        this.$nextTick(() => {
            this.showDeleteModal = false;
            this.taskToDeleteIndex = null;
            this.showTaskModal = false;
            this.currentTask = null;

            // Sync writer to author field on initial load
            if (this.form.writer) {
                this.form.author = this.form.writer;
            }
        });

        // Set loading state to true before fetching data
        this.loading = true;

        // Fetch content goal types first
        this.fetchContentGoalTypes()
            .then(() => {
                // Then fetch products if we have products
                return this.fetchProducts();
            })
            .then(() => {
                // Then fetch available credits
                return this.fetchAvailableCredits();
            })
            .then(() => {
                // Then fetch languages data
                return this.fetchLanguagesData();
            })
            .then(() => {
                // Finally fetch autopilot tasks from the API
                return this.fetchAutopilotTasks();
            })
            .catch(err => {
                console.error('Error during initial data loading:', err);
                // Ensure loading is set to false even if there's an error
                this.loading = false;
            });

        // Initialize textarea height
        this.$nextTick(() => {
            this.resizeKeywordsTextarea();

            // Initialize minimum budget based on checkbox state
            this.updateMinimumCredit();

            // Set initialLoadComplete flag to true after a short delay
            // This ensures all initialization processes have completed
            setTimeout(() => {
                this._initialLoadComplete = true;
                 // Ensure loading is false after initialization
                this.loading = false;
            }, 500);
        });
    }
}).mount('#autopilot-app');
