/**
 * AI eShop Chat - Frontend JavaScript
 * Powered by Anthropic Claude
 *
 * @package AI_eShop_Chat
 */

(function($) {
    'use strict';

    var __ = ( window.wp && window.wp.i18n && window.wp.i18n.__ ) ? window.wp.i18n.__ : function (s) { return s; };
    var _x = ( window.wp && window.wp.i18n && window.wp.i18n._x ) ? window.wp.i18n._x : function (s) { return s; };
    var _n = ( window.wp && window.wp.i18n && window.wp.i18n._n ) ? window.wp.i18n._n : function (s, p, n) { return n === 1 ? s : p; };
    var _sprintf = ( window.wp && window.wp.i18n && window.wp.i18n.sprintf ) ? window.wp.i18n.sprintf : function (s) { return s; };

    class AieoChatWidget {
        constructor(element) {
            this.$wrapper = $(element);
            this.$messages = null;
            this.$input = null;
            this.$sendBtn = null;
            this.conversationId = null;
            this.config = null;
            this.isProcessing = false;
            this.selectedCategory = null;
            // Track conversation history per category for context preservation
            this.categoryHistory = {}; // { categoryName: [{ question: '...', answer: '...' }, ...] }

            this.init();
        }

        init() {
            this.loadConfig()
                .then(() => this.buildUI())
                .then(() => this.attachEvents())
                .then(() => {
                    // Determine which category filter to use based on context
                    const productCatEnabled = this.config.category_filter_enabled;
                    const blogCatEnabled = this.config.blog_category_filter_enabled;
                    const cptCatEnabled = this.config.cpt_category_filter_enabled;

                    // Load and show categories based on current context
                    // Rule: If we're on a blog/CPT page AND that filter is enabled, show that type
                    // Otherwise, show product categories if enabled (default fallback)
                    let categoryTypeToShow = null;

                    const currentCategory = aieoChatConfig.currentCategory || '';
                    const currentBlogCategory = aieoChatConfig.currentBlogCategory || '';
                    const currentCptCategory = aieoChatConfig.currentCptCategory || '';

                    if (blogCatEnabled && currentBlogCategory !== '') {
                        // We're on a blog category page and blog filter is enabled - show blog categories
                        categoryTypeToShow = 'blog';
                    } else if (cptCatEnabled && currentCptCategory !== '') {
                        // We're on a CPT category page and CPT filter is enabled - show CPT categories
                        categoryTypeToShow = 'cpt';
                    } else if (productCatEnabled) {
                        // Default to product categories if enabled (works everywhere including blog pages when blog filter is disabled)
                        categoryTypeToShow = 'product';
                    } else if (blogCatEnabled) {
                        // Fall back to blog categories if product categories not enabled
                        categoryTypeToShow = 'blog';
                    } else if (cptCatEnabled) {
                        // Fall back to CPT categories
                        categoryTypeToShow = 'cpt';
                    }

                    if (categoryTypeToShow === 'product') {
                        this.loadAndShowCategories(currentCategory, 'product');
                    } else if (categoryTypeToShow === 'blog') {
                        this.loadAndShowCategories(currentBlogCategory, 'blog');
                    } else if (categoryTypeToShow === 'cpt') {
                        this.loadAndShowCategories(currentCptCategory, 'cpt');
                    }
                })
                .catch((error) => {
                    console.error('Chat initialization error:', error);
                    this.showError(__('Failed to load chat', 'ai-eshop-optimizer'));
                });
        }

        loadConfig() {
            return $.ajax({
                url: aieoChatConfig.restUrl + 'config',
                type: 'GET',
                headers: {
                    'X-WP-Nonce': aieoChatConfig.restNonce
                }
            }).done((response) => {
                this.config = response;
            });
        }

        buildUI() {
            const height = this.$wrapper.data('height') || '600px';
            const pictures = this.$wrapper.data('pictures') || 'enabled';

            const html = `
                <div class="aieo-chat-container" style="height: ${height};">
                    <div class="aieo-chat-header">
                        <div class="aieo-chat-avatar">🤖</div>
                        <div class="aieo-chat-title">
                            <strong>${this.escapeHtml(this.config.bot_name)}</strong>
                            <span class="aieo-chat-status">● ${_x('Online', 'chat status', 'ai-eshop-optimizer')}</span>
                        </div>
                    </div>
                    <div class="aieo-chat-messages"></div>
                    <div class="aieo-chat-input-area">
                        ${this.config.show_terms ? '<div class="aieo-chat-terms">' + __('By using this chat, you agree to our terms of service.', 'ai-eshop-optimizer') + '</div>' : ''}
                        <div class="aieo-chat-input-wrapper">
                            <input type="text" class="aieo-chat-input" placeholder="${this.config.inputPlaceholder || __('Ask about products...', 'ai-eshop-optimizer')}" />
                            <button class="aieo-chat-send-btn">
                                <svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor" transform="scale(-1, 1)">
                                    <path d="M2.553 9.106a1 1 0 000 1.788l14 7a1 1 0 001.409-1.169l-1.429-5A1 1 0 0115.571 11H11a1 1 0 110-2h4.571a1 1 0 00.962-.725l1.428-5a1 1 0 00-1.408-1.17l-14 7z"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
            `;

            this.$wrapper.html(html);
            this.$messages = this.$wrapper.find('.aieo-chat-messages');
            this.$input = this.$wrapper.find('.aieo-chat-input');
            this.$sendBtn = this.$wrapper.find('.aieo-chat-send-btn');

            // Show welcome message only if categories are NOT enabled
            // If categories are enabled, welcome message will be shown by showCategoryBubbles()
            if (!this.config.category_filter_enabled && !this.config.blog_category_filter_enabled && !this.config.cpt_category_filter_enabled) {
                this.addMessage('assistant', this.config.welcome_message);
            }

            this.hidePictures = pictures === 'disabled' || this.config.hide_images;
        }

        attachEvents() {
            this.$sendBtn.on('click', () => this.sendMessage());
            this.$input.on('keypress', (e) => {
                if (e.which === 13 && !this.isProcessing) {
                    this.sendMessage();
                }
            });
        }

        // Log a chat interaction through the EXISTING AIEO Session Tracker so the
        // event (and the page it happened on) lands in wp_aieo_sessions — no
        // separate chat tracker. No-op (with a short retry for the tracker's lazy
        // init) when Session Tracking is off / the global isn't present yet.
        trackSession(type, data, tries) {
            tries = tries || 0;
            try {
                if (window.AIEO_SESSION_TRACKER && typeof window.AIEO_SESSION_TRACKER.track === 'function') {
                    window.AIEO_SESSION_TRACKER.track(type, data || {});
                    return;
                }
            } catch (e) { return; }
            if (tries < 5) { setTimeout(() => this.trackSession(type, data, tries + 1), 300); }
        }

        sendMessage() {
            const message = this.$input.val().trim();

            if (!message || this.isProcessing) {
                return;
            }

            // Check for menu commands
            const menuCommands = ['menu', 'μενού', 'μενου'];
            if (menuCommands.indexOf(message.toLowerCase()) !== -1) {
                this.addMessage('user', message);
                this.$input.val('');

                // Show categories again
                const currentCategory = aieoChatConfig.currentCategory || '';
                this.loadAndShowCategories(currentCategory);
                return;
            }

            // Add user message (visible to user)
            this.addMessage('user', message);
            this.$input.val('');
            this.isProcessing = true;
            this.$sendBtn.prop('disabled', true);

            // Show typing indicator
            const $typing = this.addTypingIndicator();

            // Build the message with conversation context (not visible to user)
            let contextualMessage = message;
            const categoryKey = this.selectedCategory || '__default__';

            // Initialize category history if needed
            if (!this.categoryHistory[categoryKey]) {
                this.categoryHistory[categoryKey] = [];
            }

            // Prepend previous questions from this category session
            if (this.categoryHistory[categoryKey].length > 0) {
                const previousQuestions = this.categoryHistory[categoryKey]
                    .map(item => item.question)
                    .join('\n---\n');
                contextualMessage = '[Previous questions in this session:\n' + previousQuestions + ']\n\nCurrent question: ' + message;
            }

            // Send to API
            const data = {
                message: contextualMessage,
                conversation_id: this.conversationId
            };

            // Add category if selected
            if (this.selectedCategory) {
                data.category = this.selectedCategory;
            }

            // Store original message for history tracking
            const originalMessage = message;

            $.ajax({
                url: aieoChatConfig.restUrl + 'chat',
                type: 'POST',
                headers: {
                    'X-WP-Nonce': aieoChatConfig.restNonce
                },
                data: data
            })
            .done((response) => {
                this.conversationId = response.conversation_id;
                // Unified capture: record the chat turn (+ the page it happened
                // on, stamped by the tracker) against this conversation.
                this.trackSession('chat_message', { conversation_id: this.conversationId });
                $typing.remove();

                // Store this Q&A pair in category history
                this.categoryHistory[categoryKey].push({
                    question: originalMessage,
                    answer: response.message
                });

                // Add assistant message with feedback slider
                this.addMessage('assistant', response.message, response.chat_id);

                // Add products if available
                if (response.products && response.products.length > 0) {
                    this.addProducts(response.products);
                }
            })
            .fail((xhr) => {
                $typing.remove();
                const errorMsg = xhr.responseJSON && xhr.responseJSON.message
                    ? xhr.responseJSON.message
                    : __('Sorry, I encountered an error. Please try again.', 'ai-eshop-optimizer');

                this.addMessage('assistant', errorMsg);
            })
            .always(() => {
                this.isProcessing = false;
                this.$sendBtn.prop('disabled', false);
                this.$input.focus();
            });
        }

        addMessage(role, content, chatId = null) {
            const isUser = role === 'user';
            const $message = $('<div>', {
                class: 'aieo-chat-message aieo-chat-message-' + role
            });

            if (!isUser) {
                $message.append('<div class="aieo-chat-avatar-small">🤖</div>');
            }

            const $contentWrapper = $('<div>', {
                class: 'aieo-chat-message-content-wrapper'
            });

            $contentWrapper.append(
                $('<div>', {
                    class: 'aieo-chat-message-content',
                    html: this.formatMessage(content)
                })
            );

            // Add feedback slider for assistant messages with a chat_id
            if (!isUser && chatId) {
                $contentWrapper.append(this.createFeedbackSlider(chatId));
            }

            $message.append($contentWrapper);

            this.$messages.append($message);
            this.scrollToBottom();

            return $message;
        }

        createFeedbackSlider(chatId) {
            const feedbackText = aieoChatConfig.i18n?.feedbackPrompt || __('Help me improve! Rate this answer:', 'ai-eshop-optimizer');
            const $feedback = $('<div>', {
                class: 'aieo-chat-feedback',
                'data-chat-id': chatId
            });

            $feedback.html(`
                <div class="aieo-chat-feedback-label">${this.escapeHtml(feedbackText)}</div>
                <div class="aieo-chat-feedback-slider-container">
                    <span class="aieo-chat-feedback-emoji">😞</span>
                    <input type="range" class="aieo-chat-feedback-slider" min="0" max="100" value="50" />
                    <span class="aieo-chat-feedback-emoji">😊</span>
                </div>
                <div class="aieo-chat-feedback-status"></div>
            `);

            // Handle slider change
            const $slider = $feedback.find('.aieo-chat-feedback-slider');
            const $status = $feedback.find('.aieo-chat-feedback-status');
            let debounceTimer = null;

            // Update slider track color based on value
            const updateSliderColor = (value) => {
                // Create gradient: red (0) -> yellow (50) -> green (100)
                let color;
                if (value < 50) {
                    // Red to yellow
                    const ratio = value / 50;
                    const r = 239;
                    const g = Math.round(68 + (158 * ratio));
                    const b = 68;
                    color = `rgb(${r}, ${g}, ${b})`;
                } else {
                    // Yellow to green
                    const ratio = (value - 50) / 50;
                    const r = Math.round(239 - (105 * ratio));
                    const g = Math.round(226 - (92 * ratio));
                    const b = Math.round(68 + (62 * ratio));
                    color = `rgb(${r}, ${g}, ${b})`;
                }
                $slider.css('--slider-color', color);
                $slider.css('accent-color', color);
            };

            // Initial color
            updateSliderColor(50);

            $slider.on('input', (e) => {
                const value = parseInt(e.target.value, 10);
                updateSliderColor(value);

                // Clear previous timer
                if (debounceTimer) {
                    clearTimeout(debounceTimer);
                }

                // Debounce the save request
                debounceTimer = setTimeout(() => {
                    this.saveRating(chatId, value, $status);
                }, 500);
            });

            return $feedback;
        }

        saveRating(chatId, rating, $status) {
            // Only save if rating is not the default (50)
            if (rating === 50) {
                $status.text('').removeClass('aieo-chat-feedback-saved aieo-chat-feedback-error');
                return;
            }

            const savedText = aieoChatConfig.i18n?.feedbackSaved || __('Thanks for your feedback!', 'ai-eshop-optimizer');
            const errorText = aieoChatConfig.i18n?.feedbackError || __('Could not save feedback', 'ai-eshop-optimizer');

            $.ajax({
                url: aieoChatConfig.restUrl + 'rating',
                type: 'POST',
                headers: {
                    'X-WP-Nonce': aieoChatConfig.restNonce
                },
                data: {
                    chat_id: chatId,
                    rating: rating
                }
            })
            .done(() => {
                $status.text(savedText)
                    .removeClass('aieo-chat-feedback-error')
                    .addClass('aieo-chat-feedback-saved');
            })
            .fail(() => {
                $status.text(errorText)
                    .removeClass('aieo-chat-feedback-saved')
                    .addClass('aieo-chat-feedback-error');
            });
        }

        addTypingIndicator() {
            const $indicator = $('<div>', {
                class: 'aieo-chat-message aieo-chat-message-assistant aieo-chat-typing'
            });

            $indicator.append('<div class="aieo-chat-avatar-small">🤖</div>');
            $indicator.append(`
                <div class="aieo-chat-message-content">
                    <div class="aieo-chat-typing-dots">
                        <span></span><span></span><span></span>
                    </div>
                </div>
            `);

            this.$messages.append($indicator);
            this.scrollToBottom();

            return $indicator;
        }

        addProducts(products) {
            const $productsContainer = $('<div>', {
                class: 'aieo-chat-products'
            });

            products.forEach((item) => {
                const $item = $('<div>', {
                    class: 'aieo-chat-product'
                });

                let html = '';
                const isProduct = item.type === 'product';

                // Image (products only)
                if (!this.hidePictures && isProduct && item.image) {
                    html += `<div class="aieo-chat-product-image">
                        <img src="${this.escapeHtml(item.image)}" alt="${this.escapeHtml(item.title)}" />
                    </div>`;
                }

                html += `<div class="aieo-chat-product-details">
                    <h4><a href="${this.escapeHtml(item.url)}" target="_blank">${this.escapeHtml(item.title)}</a></h4>`;

                // Type badge for non-products
                if (!isProduct && item.type) {
                    const typeLabels = {
                        'post': __('📝 Article', 'ai-eshop-optimizer'),
                        'page': __('📄 Page', 'ai-eshop-optimizer')
                    };
                    const typeLabel = typeLabels[item.type] || item.type;
                    html += `<div class="aieo-chat-product-type" style="background: #F3F4F6; color: #4B5563; padding: 4px 8px; border-radius: 4px; display: inline-block; font-size: 12px; margin-bottom: 8px;">${typeLabel}</div>`;
                }

                // Variation attributes (for product variations)
                if (isProduct && item.is_variation && item.variation_attributes) {
                    html += '<div class="aieo-chat-variation-attributes" style="margin: 8px 0; padding: 8px; background: #FEF3C7; border-left: 3px solid #F59E0B; border-radius: 4px;">';
                    Object.keys(item.variation_attributes).forEach(attrName => {
                        const attrValue = item.variation_attributes[attrName];
                        html += `<span style="display: inline-block; margin-right: 10px;"><strong>${this.escapeHtml(attrName)}:</strong> ${this.escapeHtml(attrValue)}</span>`;
                    });
                    html += '</div>';
                }

                // Price (products only)
                if (isProduct && item.price_html) {
                    html += `<div class="aieo-chat-product-price">${item.price_html}</div>`;
                }

                // Description/Content
                if (isProduct && item.short_description) {
                    html += `<p>${this.escapeHtml(item.short_description)}</p>`;
                } else if (!isProduct && item.content) {
                    html += `<p>${this.escapeHtml(item.content)}</p>`;
                } else if (!isProduct && item.excerpt) {
                    html += `<p>${this.escapeHtml(item.excerpt)}</p>`;
                }

                // Rating (products only)
                if (isProduct && item.rating > 0) {
                    /* translators: 1: average rating out of 5, 2: review count */
                    const ratingText = _sprintf(
                        _n('⭐ %1$s/5 (%2$s review)', '⭐ %1$s/5 (%2$s reviews)', item.review_count, 'ai-eshop-optimizer'),
                        item.rating,
                        item.review_count
                    );
                    html += `<div class="aieo-chat-product-rating">
                        ${ratingText}
                    </div>`;
                }

                // Stock status (products only)
                if (isProduct) {
                    if (!item.in_stock) {
                        html += '<div class="aieo-chat-product-stock aieo-out-of-stock">' + __('Out of Stock', 'ai-eshop-optimizer') + '</div>';
                    } else if (item.on_sale) {
                        html += '<div class="aieo-chat-product-stock aieo-on-sale">' + __('On Sale!', 'ai-eshop-optimizer') + '</div>';
                    }
                }

                // Published date (posts/pages only)
                if (!isProduct && item.date) {
                    html += `<div class="aieo-chat-product-date" style="font-size: 12px; color: #6B7280; margin-top: 8px;">📅 ${this.escapeHtml(item.date)}</div>`;
                }

                // Button with appropriate text
                const buttonText = isProduct ? __('View Product →', 'ai-eshop-optimizer') : __('Read More →', 'ai-eshop-optimizer');
                html += `<a href="${this.escapeHtml(item.url)}" class="aieo-chat-product-btn" target="_blank">${buttonText}</a>`;
                html += '</div>';

                $item.html(html);
                $productsContainer.append($item);
            });

            this.$messages.append($productsContainer);
            this.scrollToBottom();
        }

        formatMessage(content) {
            // Convert markdown-like formatting while preserving HTML
            // Note: We allow HTML in messages to support rich formatting (prices, links, etc.)

            // Convert markdown links: [text](url) -> <a href="url">text</a>
            content = content.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');

            // Convert bold and italic
            content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            content = content.replace(/\*(.*?)\*/g, '<em>$1</em>');

            // Convert line breaks
            content = content.replace(/\n/g, '<br>');

            return content;
        }

        escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        scrollToBottom() {
            this.$messages.scrollTop(this.$messages[0].scrollHeight);
        }

        showError(message) {
            this.$wrapper.html(`
                <div class="aieo-chat-error">
                    <p>⚠️ ${this.escapeHtml(message)}</p>
                </div>
            `);
        }

        loadAndShowCategories(currentCat, type) {
            type = type || 'product'; // Default to product categories
            let endpoint;
            if (type === 'blog') {
                endpoint = 'blog-categories';
            } else if (type === 'cpt') {
                endpoint = 'cpt-categories';
            } else {
                endpoint = 'categories';
            }

            $.ajax({
                url: aieoChatConfig.restUrl + endpoint,
                type: 'GET',
                headers: {
                    'X-WP-Nonce': aieoChatConfig.restNonce
                }
            })
            .done((response) => {
                if (response.categories && response.categories.length > 0) {
                    this.showCategoryBubbles(response.categories, currentCat, type);
                }
            })
            .fail(() => {
                console.error('Failed to load ' + type + ' categories');
            });
        }

        showCategoryBubbles(categories, currentCat, type) {
            type = type || 'product'; // Default to product categories

            // Check if menu already exists in messages container
            if (this.$messages.find('.aieo-chat-category-menu').length > 0) {
                console.log('Category menu already exists in chat, skipping...');
                return;
            }

            console.log('Creating persistent ' + type + ' category menu with', categories.length, 'categories');

            // STEP 1: Show initial message FIRST
            if (currentCat) {
                // Category detected - tell user we'll help in that category
                let helpingText;
                if (type === 'blog') {
                    /* translators: %s: blog category name */
                    helpingText = (aieoChatConfig.i18n?.helpingWithBlogCategory || _sprintf(__('I\'ll help you find blog posts in the %s category. If you need something else, please select a different category.', 'ai-eshop-optimizer'), '{category}'))
                        .replace('{category}', this.escapeHtml(currentCat));
                } else if (type === 'cpt') {
                    /* translators: %s: CPT category name */
                    helpingText = (aieoChatConfig.i18n?.helpingWithCptCategory || _sprintf(__('I\'ll help you find content in the %s category. If you need something else, please select a different category.', 'ai-eshop-optimizer'), '{category}'))
                        .replace('{category}', this.escapeHtml(currentCat));
                } else {
                    /* translators: %s: product category name */
                    helpingText = (aieoChatConfig.i18n?.helpingWithCategory || _sprintf(__('I\'ll help you find products in the %s category. If you need something else, please select a different category.', 'ai-eshop-optimizer'), '{category}'))
                        .replace('{category}', this.escapeHtml(currentCat));
                }
                this.addMessage('assistant', helpingText);
            } else {
                // No category - ask them to select one
                let promptText;
                if (type === 'blog') {
                    promptText = aieoChatConfig.i18n?.blogCategoryPrompt || __('Please select a blog post category to get started:', 'ai-eshop-optimizer');
                } else if (type === 'cpt') {
                    promptText = aieoChatConfig.i18n?.cptCategoryPrompt || __('Please select a category to get started:', 'ai-eshop-optimizer');
                } else {
                    promptText = aieoChatConfig.i18n?.categoryPrompt || __('Please select a product category to get started:', 'ai-eshop-optimizer');
                }
                this.addMessage('assistant', promptText);
            }

            // STEP 2: Add category menu as a message (not prepended)
            const $categoryMenu = $('<div>', {
                class: 'aieo-chat-message aieo-chat-message-assistant'
            });

            const $bubbles = $('<div>', {
                class: 'aieo-chat-category-bubbles'
            });

            // Get theme-aware border radius
            const theme = aieoChatConfig.theme || 'rounded';
            const borderRadius = theme === 'rounded' ? '12px' : '4px';

            categories.forEach((category) => {
                // Handle both old format (string) and new format (object with id and name)
                const categoryName = typeof category === 'string' ? category : category.name;
                const categoryId = typeof category === 'object' ? category.id : null;

                const $bubble = $('<button>', {
                    class: 'aieo-chat-category-bubble',
                    type: 'button',
                    text: categoryName,
                    'data-category': categoryName,
                    css: {
                        'border-radius': borderRadius
                    }
                });

                if (categoryId) {
                    $bubble.attr('data-category-id', categoryId);
                }

                // Highlight current category
                if (currentCat && categoryName === currentCat) {
                    $bubble.addClass('aieo-chat-category-bubble-highlight');
                }

                $bubble.on('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    this.switchCategory(categoryName);
                });

                $bubbles.append($bubble);
            });

            $categoryMenu.append($bubbles);

            // Append category menu as a message (in order)
            this.$messages.append($categoryMenu);

            // STEP 3: Show welcome message AFTER menu
            const welcomeMsg = aieoChatConfig.welcomeMessage || __('Hello! How can I help you find the perfect product today?', 'ai-eshop-optimizer');
            this.addMessage('assistant', welcomeMsg);

            // Set initial category and enable/disable input
            if (currentCat) {
                this.selectedCategory = currentCat;
                this.$input.prop('disabled', false);
                this.$sendBtn.prop('disabled', false);
            } else {
                this.$input.prop('disabled', true);
                this.$sendBtn.prop('disabled', true);
            }

            this.scrollToBottom();
        }

        switchCategory(newCategory) {
            // Update the selected category
            const previousCategory = this.selectedCategory;
            this.selectedCategory = newCategory;

            // Clear conversation history for new category (start fresh)
            // Each category session is independent
            if (previousCategory !== newCategory) {
                this.categoryHistory[newCategory] = [];
            }

            // Update button highlighting
            this.$messages.find('.aieo-chat-category-bubble').removeClass('aieo-chat-category-bubble-highlight');
            this.$messages.find(`.aieo-chat-category-bubble[data-category="${newCategory}"]`).addClass('aieo-chat-category-bubble-highlight');

            // Show confirmation message
            /* translators: %s: category name */
            const switchText = (aieoChatConfig.i18n?.categorySwitched || _sprintf(__('Switched to %s category. I\'ll help you find products in this category.', 'ai-eshop-optimizer'), '{category}'))
                .replace('{category}', this.escapeHtml(newCategory));
            this.addMessage('assistant', switchText);

            // Enable input
            this.$input.prop('disabled', false);
            this.$sendBtn.prop('disabled', false);
            this.$input.focus();
        }

        getCategoryLink(category) {
            return $.ajax({
                url: aieoChatConfig.restUrl + 'category-link',
                type: 'GET',
                headers: {
                    'X-WP-Nonce': aieoChatConfig.restNonce
                },
                data: {
                    category: category
                }
            }).then((response) => {
                return response.url || '';
            }).fail(() => {
                return '';
            });
        }
    }

    // Initialize all chat widgets on page (exclude floating chat)
    $(document).ready(function() {
        $('.aieo-chat-wrapper').not('.aieo-floating-chat-wrapper').each(function() {
            new AieoChatWidget(this);
        });
    });

})(jQuery);
