/**
 * AI Platform - Chatbot Widget JavaScript
 *
 * Handles frontend chatbot widget functionality with new CSS classes
 *
 * @package    AI_Platform
 */

(function ($) {
    'use strict';

    class AiProChatbot {
        constructor(element) {
            this.container = $(element);
            this.chatbotId = this.container.data('chatbot-id');
            this.config = {};
            this.forms = [];
            this.configLoaded = false;
            this.configLoading = false;
            this.isOpen = false;
            this.messages = [];
            this.conversationId = null;
            this.hasInteracted = false;
            this.messageCount = 0;
            this.shownForms = new Set();
            this.isEndingSession = false;
            this.welcomeMessage = '';
            this.historyPage = 0;
            this.historyPageSize = 20;
            this.historyHasMore = false;
            this.isLoadingHistory = false;
            this.loadedConversationId = null;

            this.init();
        }

        isWidgetMode() {
            return this.container.hasClass('ai-platform-chatbot-container--widget');
        }

        init() {
            this.widget = this.container.find('.chatbot-preview');
            this.messagesContainer = this.container.find('.chatbot-preview__messages');
            this.inputField = this.container.find('.ai-platform-chatbot-input');
            this.sendButton = this.container.find('.ai-platform-chatbot-send');
            this.suggestionsContainer = this.container.find('.chatbot-preview__suggestions');
            this.menu = this.container.find('.chatbot-preview__menu');
            this.menuToggle = this.container.find('.chatbot-preview__menu-toggle');

            // Keep input disabled until config is ready
            this.inputField.prop('disabled', true);
            this.sendButton.prop('disabled', true);

            this.bindEvents();

            if (!this.isWidgetMode()) {
                // Inline / fullpage: load config after page is fully loaded
                this.showLoadingState();
                if (document.readyState === 'complete') {
                    this.initWithConfig();
                } else {
                    $(window).one('load', () => this.initWithConfig());
                }
            }
            // Widget mode: config is fetched on first open
        }

        showLoadingState() {
            this.messagesContainer.empty().append(
                '<div class="chatbot-preview__loading"><div class="chatbot-preview__loading-spinner"></div></div>'
            );
        }

        hideLoadingState() {
            this.messagesContainer.find('.chatbot-preview__loading').remove();
        }

        async loadConfig() {
            if (this.configLoaded || this.configLoading) {
                return;
            }
            this.configLoading = true;
            try {
                const formData = new FormData();
                formData.append('action', 'kitsune_ai_platform_get_chatbot_config');
                formData.append('nonce', kitsuneAiPlatformPublic.nonce);
                formData.append('chatbot_id', this.chatbotId);

                const response = await fetch(kitsuneAiPlatformPublic.ajaxUrl, { method: 'POST', body: formData });
                const data = await response.json();

                if (data.success) {
                    this.config = data.data.config || {};
                    this.forms  = data.data.forms  || [];
                    this.configLoaded = true;
                    this.welcomeMessage = this.getWelcomeMessage();
                }
            } catch (error) {
                console.error('Failed to load chatbot config:', error);
            }
            this.configLoading = false;
        }

        async initWithConfig() {
            await this.loadConfig();
            this.hideLoadingState();
            if (this.configLoaded) {
                this.enableInput();
                this.loadSessionHistory({ reset: true });
            }
        }

        bindEvents() {
            // Toggle chatbot window (widget mode only)
            this.container.find('.chatbot-widget-button').on('click', () => {
                this.toggle();
            });

            // Close chatbot (widget mode only)
            this.container.find('.ai-platform-chatbot-close').on('click', () => {
                this.close();
            });

            // Menu toggle
            this.menuToggle.on('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.toggleMenu();
            });

            $(document).on('click', (e) => {
                if (!this.menu.length) {
                    return;
                }
                if ($(e.target).closest(this.menu).length) {
                    return;
                }
                this.closeMenu();
            });

            // End session
            this.container.find('.ai-platform-chatbot-end-session').on('click', (e) => {
                e.preventDefault();
                this.closeMenu();
                this.endSession();
            });

            // Send message on button click
            this.sendButton.on('click', () => {
                this.sendMessage();
            });

            // Send message on Enter key
            this.inputField.on('keypress', (e) => {
                if (e.which === 13) {
                    e.preventDefault();
                    this.sendMessage();
                }
            });

            // Suggested questions
            this.container.find('.chatbot-preview__suggestion').on('click', (e) => {
                const question = $(e.currentTarget).data('question');
                if (question) {
                    this.inputField.val(question);
                    this.sendMessage();
                    // Hide suggestions after use
                    this.suggestionsContainer.fadeOut(200);
                }
            });

            this.messagesContainer.on('scroll', () => {
                if (this.isLoadingHistory || !this.historyHasMore) {
                    return;
                }
                if (this.messagesContainer.scrollTop() <= 20) {
                    this.loadSessionHistory({ reset: false });
                }
            });
        }

        toggle() {
            if (this.isOpen) {
                this.close();
            } else {
                this.open();
            }
        }

        async open() {
            this.widget.stop(true).css({ display: 'flex', opacity: 0 }).animate({ opacity: 1 }, 300);
            this.container.find('.chatbot-widget-button').addClass('active');
            this.isOpen = true;

            if (!this.configLoaded) {
                this.showLoadingState();
                await this.initWithConfig();
            } else {
                this.inputField.focus();
                this.loadSessionHistory({ reset: true });
            }
        }

        close() {
            this.widget.stop(true).animate({ opacity: 0 }, 300, () => {
                this.widget.css('display', 'none');
            });
            this.container.find('.chatbot-widget-button').removeClass('active');
            this.isOpen = false;
            this.closeMenu();
        }

        toggleMenu() {
            if (!this.menu.length) {
                return;
            }
            if (this.menu.hasClass('is-open')) {
                this.closeMenu();
            } else {
                this.openMenu();
            }
        }

        openMenu() {
            if (!this.menu.length) {
                return;
            }
            this.menu.addClass('is-open');
            this.menuToggle.attr('aria-expanded', 'true');
        }

        closeMenu() {
            if (!this.menu.length) {
                return;
            }
            this.menu.removeClass('is-open');
            this.menuToggle.attr('aria-expanded', 'false');
        }

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

            if (!message) {
                return;
            }

            // Add user message to chat
            this.addMessage(message, 'user');
            if (!this.hasInteracted) {
                this.hasInteracted = true;
                // Reveal suggestions on first user interaction if trigger is set accordingly
                const suggTrigger = this.config?.behavior?.suggestedQuestionsTrigger || 'immediate';
                if (suggTrigger === 'first_interaction' && this.suggestionsContainer?.length) {
                    this.suggestionsContainer.show();
                }
                this.showFormsByTrigger('first_interaction');
            }

            // Clear input
            this.inputField.val('');

            // Disable input while processing
            this.inputField.prop('disabled', true);
            this.sendButton.prop('disabled', true);

            // Show typing indicator
            this.showTypingIndicator();

            // Send to backend
            this.sendToBackend(message);
        }

        async endSession() {
            if (this.isEndingSession) {
                return;
            }
            const confirmMessage = this.t('endSessionConfirm', 'End this chat session?');
            if (typeof window !== 'undefined' && !window.confirm(confirmMessage)) {
                return;
            }

            this.isEndingSession = true;
            const conversationId = this.conversationId || this.peekConversationId();
            if (!conversationId) {
                this.resetSessionState();
                this.isEndingSession = false;
                return;
            }

            const success = await this.endSessionOnBackend(conversationId);

            if (success) {
                this.resetSessionState();
            } else {
                this.addMessage(this.t('error', 'Sorry, something went wrong. Please try again.'), 'bot');
            }

            this.isEndingSession = false;
        }

        async endSessionOnBackend(conversationId) {
            try {
                const formData = new FormData();
                formData.append('action', 'kitsune_ai_platform_end_session');
                formData.append('nonce', kitsuneAiPlatformPublic.nonce);
                formData.append('chatbot_id', this.chatbotId);
                formData.append('conversation_id', conversationId);

                const response = await fetch(kitsuneAiPlatformPublic.ajaxUrl, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                if (data?.success) {
                    return true;
                }

                return false;
            } catch (error) {
                console.error('Error ending session:', error);
                return false;
            }
        }

        async loadSessionHistory(options = {}) {
            const reset = options.reset === true;
            if (this.isLoadingHistory) {
                return;
            }

            const conversationId = this.peekConversationId();
            if (!conversationId) {
                if (reset) {
                    this.historyPage = 0;
                    this.historyHasMore = false;
                    this.loadedConversationId = null;
                    this.conversationId = null;
                    this.renderWelcomeState();
                }
                return;
            }

            if (reset || this.loadedConversationId !== conversationId) {
                this.historyPage = 0;
                this.historyHasMore = false;
                this.loadedConversationId = conversationId;
                this.conversationId = conversationId;
            }

            const nextPage = reset ? 1 : this.historyPage + 1;
            this.isLoadingHistory = true;

            const response = await this.fetchSessionMessages(conversationId, nextPage);
            if (!response) {
                if (reset) {
                    this.renderWelcomeState();
                }
                this.isLoadingHistory = false;
                return;
            }

            const messages = Array.isArray(response.messages) ? response.messages : [];
            const total = Number.isFinite(Number(response.total)) ? Number(response.total) : messages.length;
            const hasMore = !!response.has_more;

            if (reset) {
                this.messagesContainer.empty();
                if (messages.length === 0) {
                    this.renderWelcomeState();
                } else {
                    this.renderMessages(messages, { prepend: false });
                    if (this.suggestionsContainer && this.suggestionsContainer.length) {
                        this.suggestionsContainer.hide();
                    }
                    this.scrollToBottom();
                }
                this.hasInteracted = messages.some((message) => message?.role === 'user');
                this.messageCount = total;
            } else if (messages.length > 0) {
                const containerEl = this.messagesContainer[0];
                const previousHeight = containerEl.scrollHeight;
                this.renderMessages(messages, { prepend: true });
                const newHeight = containerEl.scrollHeight;
                this.messagesContainer.scrollTop(newHeight - previousHeight);
            }

            this.historyPage = nextPage;
            this.historyHasMore = hasMore;
            this.isLoadingHistory = false;
        }

        async fetchSessionMessages(conversationId, page) {
            try {
                const formData = new FormData();
                formData.append('action', 'kitsune_ai_platform_get_session_messages');
                formData.append('nonce', kitsuneAiPlatformPublic.nonce);
                formData.append('chatbot_id', this.chatbotId);
                formData.append('conversation_id', conversationId);
                formData.append('page', String(page));
                formData.append('per_page', String(this.historyPageSize));

                const response = await fetch(kitsuneAiPlatformPublic.ajaxUrl, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                if (!data?.success) {
                    return null;
                }
                return data.data || {};
            } catch (error) {
                console.error('Error loading session history:', error);
                return null;
            }
        }

        renderMessages(messages, options = {}) {
            if (!Array.isArray(messages) || messages.length === 0) {
                return;
            }
            const html = messages.map((message) => this.renderMessageHtml(message)).join('');
            if (options.prepend) {
                this.messagesContainer.prepend(html);
            } else {
                this.messagesContainer.append(html);
            }
        }

        renderMessageHtml(message) {
            const role = message?.role === 'user' ? 'user' : 'bot';
            const isSystem = message?.role === 'system';
            const classes = isSystem
                ? `chatbot-preview__message chatbot-preview__message--${role} chatbot-preview__message--system`
                : `chatbot-preview__message chatbot-preview__message--${role}`;
            return `
                <div class="${classes}">
                    <div class="chatbot-preview__bubble">
                        ${this.escapeHtml(message?.content || '')}
                    </div>
                </div>
            `;
        }

        renderWelcomeState() {
            this.messagesContainer.empty();
            this.messagesContainer.append(this.buildWelcomeMessage());
            if (this.suggestionsContainer && this.suggestionsContainer.length) {
                const trigger = this.config?.behavior?.suggestedQuestionsTrigger || 'immediate';
                if (trigger === 'immediate') {
                    this.suggestionsContainer.show();
                } else {
                    this.suggestionsContainer.hide();
                }
            }
            this.showFormsByTrigger('immediate');
            this.scrollToBottom();
        }

        resetSessionState() {
            this.hideTypingIndicator();
            this.clearConversationId();
            this.messages = [];
            this.messageCount = 0;
            this.hasInteracted = false;
            this.shownForms = new Set();
            this.historyPage = 0;
            this.historyHasMore = false;
            this.loadedConversationId = null;
            this.isLoadingHistory = false;
            this.inputField.val('');
            this.enableInput();
            this.renderWelcomeState();
        }

        buildWelcomeMessage() {
            return `
                <div class="chatbot-preview__message chatbot-preview__message--bot">
                    <div class="chatbot-preview__bubble">
                        ${this.escapeHtml(this.welcomeMessage)}
                    </div>
                </div>
            `;
        }

        getWelcomeMessage() {
            return this.config?.behavior?.welcomeMessage || this.t('welcomeMessage', 'Hi! How can I help you today?');
        }

        addMessage(text, type) {
            const isBot = type === 'bot';
            const messageHtml = `
                <div class="chatbot-preview__message chatbot-preview__message--${type}">
                    <div class="chatbot-preview__bubble">
                        ${this.escapeHtml(text)}
                    </div>
                </div>
            `;

            this.messagesContainer.append(messageHtml);
            this.messageCount += 1;
            this.scrollToBottom();
        }

        showTypingIndicator() {
            const indicator = `
                <div class="chatbot-preview__message chatbot-preview__message--bot ai-platform-typing">
                    <div class="chatbot-preview__bubble chatbot-preview__typing">
                        <span class="chatbot-preview__typing-dot"></span>
                        <span class="chatbot-preview__typing-dot"></span>
                        <span class="chatbot-preview__typing-dot"></span>
                    </div>
                </div>
            `;
            this.messagesContainer.append(indicator);
            this.scrollToBottom();
        }

        hideTypingIndicator() {
            this.container.find('.ai-platform-typing').remove();
        }

        async sendToBackend(message, retried = false) {
            try {
                const existingConversationId = this.getConversationId();
                const formData = new FormData();
                formData.append('action', 'kitsune_ai_platform_chatbot_message');
                formData.append('nonce', kitsuneAiPlatformPublic.nonce);
                formData.append('chatbot_id', this.chatbotId);
                formData.append('message', message);
                formData.append('conversation_id', existingConversationId);

                const response = await fetch(kitsuneAiPlatformPublic.ajaxUrl, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                this.hideTypingIndicator();
                this.enableInput();

                if (data.success && data.data.response) {
                    if (data.data.conversation_id) {
                        this.setConversationId(data.data.conversation_id);
                    }
                    this.addMessage(data.data.response, 'bot');
                    if (data.data.form_id) {
                        this.showFormById(data.data.form_id);
                    }
                } else {
                    this.addMessage(this.t('error', 'Sorry, something went wrong. Please try again.'), 'bot');
                }
            } catch (error) {
                console.error('Error sending message:', error);
                this.hideTypingIndicator();
                this.enableInput();
                this.addMessage(this.t('error', 'Sorry, something went wrong. Please try again.'), 'bot');
            }
        }

        enableInput() {
            this.inputField.prop('disabled', false);
            this.sendButton.prop('disabled', false);
            this.inputField.focus();
        }

        generateUUID() {
            if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
                return crypto.randomUUID().replace(/-/g, '');
            }
            // Fallback for older browsers
            return 'xxxxxxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                const r = Math.random() * 16 | 0;
                const v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }

        getConversationId() {
            if (!this.conversationId) {
                const storageKey = 'ai_platform_conversation_' + this.chatbotId;
                const storage = this.getPreferredStorage();
                if (storage) {
                    try {
                        const stored = storage.getItem(storageKey);
                        if (stored) {
                            this.conversationId = stored;
                        } else {
                            // Generate a UUID on first send and persist it so the same
                            // conversation is resumed across page loads.
                            const uuid = this.generateUUID();
                            storage.setItem(storageKey, uuid);
                            this.conversationId = uuid;
                        }
                    } catch (error) {
                        this.conversationId = null;
                    }
                }
            }
            return this.conversationId || '';
        }

        setConversationId(conversationId) {
            const normalized = String(conversationId || '').trim();
            if (!normalized) {
                return;
            }

            this.conversationId = normalized;
            const storageKey = 'ai_platform_conversation_' + this.chatbotId;
            const storage = this.getPreferredStorage();
            if (storage) {
                try {
                    storage.setItem(storageKey, normalized);
                } catch (error) {
                    // Ignore storage errors and keep in-memory conversation ID.
                }
            }
        }

        clearConversationId() {
            const storageKey = 'ai_platform_conversation_' + this.chatbotId;
            const storage = this.getPreferredStorage();
            if (storage) {
                try {
                    storage.removeItem(storageKey);
                } catch (error) {
                    // Ignore storage errors
                }
            }
            this.conversationId = null;
        }

        peekConversationId() {
            const storageKey = 'ai_platform_conversation_' + this.chatbotId;
            const storage = this.getPreferredStorage();
            if (!storage) {
                return null;
            }
            try {
                return storage.getItem(storageKey);
            } catch (error) {
                return null;
            }
        }

        getPreferredStorage() {
            try {
                if (window.localStorage) {
                    return window.localStorage;
                }
            } catch (error) {
                // Fall through to sessionStorage
            }
            try {
                if (window.sessionStorage) {
                    return window.sessionStorage;
                }
            } catch (error) {
                return null;
            }
            return null;
        }

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

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

        parseJsonAttribute(name, fallback) {
            const raw = this.container.attr(`data-${name}`);
            if (!raw) {
                return fallback;
            }
            try {
                return JSON.parse(raw);
            } catch (error) {
                console.warn(`Failed to parse data-${name}`, error);
                return fallback;
            }
        }

        t(key, fallback) {
            return kitsuneAiPlatformPublic?.i18n?.[key] || fallback;
        }

        showFormsByTrigger(trigger) {
            if (!Array.isArray(this.forms) || this.forms.length === 0) {
                return;
            }

            this.forms.forEach((form) => {
                if (!form || !form.id) {
                    return;
                }
                const formTrigger = this.getFormTrigger(form);
                if (formTrigger !== trigger) {
                    return;
                }
                if (this.shownForms.has(form.id)) {
                    return;
                }

                this.renderForm(form);
                this.shownForms.add(form.id);
            });
        }

        showFormById(formId) {
            if (!Array.isArray(this.forms) || this.forms.length === 0) {
                return;
            }

            const numericId = Number(formId);
            const form = this.forms.find((item) => Number(item?.id) === numericId);
            if (!form || this.shownForms.has(form.id)) {
                return;
            }

            this.renderForm(form);
            this.shownForms.add(form.id);
        }

        getFormTrigger(form) {
            const features = this.config?.features || {};
            const chatbotTrigger = features.formDisplayTrigger || 'immediate';
            if (chatbotTrigger === 'conversation_start') {
                return 'immediate';
            }
            return chatbotTrigger;
        }

        renderForm(form) {
            const fields = Array.isArray(form?.config?.fields) ? form.config.fields : [];
            const hasSubmitField = fields.some((field) => {
                const type = String(field?.type || '').toLowerCase();
                return type === 'submit';
            });
            const formHtml = `
                <div class="chatbot-preview__message chatbot-preview__message--bot chatbot-preview__message--form" data-form-id="${this.escapeHtml(String(form.id))}">
                    <div class="chatbot-preview__bubble chatbot-preview__bubble--form">
                        <div class="chatbot-preview__form">
                            <div class="chatbot-preview__form-title">${this.escapeHtml(form.name || this.t('formDefaultTitle', 'Form'))}</div>
                            ${form.description ? `<div class="chatbot-preview__form-description">${this.escapeHtml(form.description)}</div>` : ''}
                            <form class="chatbot-preview__form-fields" data-form-id="${this.escapeHtml(String(form.id))}">
                                ${this.renderFormFields(fields)}
                                ${hasSubmitField ? '' : `
                                    <button type="submit" class="chatbot-preview__form-submit">
                                        ${this.escapeHtml(this.t('formSubmit', 'Submit'))}
                                    </button>
                                `}
                            </form>
                        </div>
                    </div>
                </div>
            `;

            this.messagesContainer.append(formHtml);
            const formWrapper = this.messagesContainer.find(`.chatbot-preview__message--form[data-form-id="${form.id}"]`);
            this.bindFormHandler(formWrapper, form);
            this.scrollToBottom();
        }

        renderFormFields(fields) {
            if (!fields.length) {
                return `<div class="chatbot-preview__form-empty">${this.escapeHtml(this.t('formNoFields', 'No fields configured.'))}</div>`;
            }

            return fields.map((field, index) => {
                const label = field.label || `Field ${index + 1}`;
                const fieldKey = this.buildFieldKey(field, index);
                const required = field.required ? 'required' : '';
                const requiredMark = field.required ? '<span class="chatbot-preview__form-required">*</span>' : '';
                const placeholder = field.placeholder ? this.escapeHtml(field.placeholder) : '';
                const type = field.type || 'text';

                if (type === 'textarea') {
                    return `
                        <label class="chatbot-preview__form-label">
                            ${this.escapeHtml(label)} ${requiredMark}
                            <textarea name="${this.escapeHtml(fieldKey)}" placeholder="${placeholder}" ${required}></textarea>
                        </label>
                    `;
                }

                if (type === 'select') {
                    const options = Array.isArray(field.options) ? field.options : [];
                    const optionsHtml = options.map((opt) => `<option value="${this.escapeHtml(opt)}">${this.escapeHtml(opt)}</option>`).join('');
                    return `
                        <label class="chatbot-preview__form-label">
                            ${this.escapeHtml(label)} ${requiredMark}
                            <select name="${this.escapeHtml(fieldKey)}" ${required}>
                                <option value="">${this.escapeHtml(this.t('formSelect', 'Select'))}</option>
                                ${optionsHtml}
                            </select>
                        </label>
                    `;
                }

                if (type === 'checkbox') {
                    const options = Array.isArray(field.options) ? field.options : [];
                    const optionsHtml = options.map((opt, optIndex) => `
                        <label class="chatbot-preview__form-option">
                            <input type="checkbox" name="${this.escapeHtml(fieldKey)}" value="${this.escapeHtml(opt)}" ${field.required && optIndex === 0 ? 'required' : ''} />
                            <span>${this.escapeHtml(opt)}</span>
                        </label>
                    `).join('');
                    return `
                        <div class="chatbot-preview__form-group">
                            <div class="chatbot-preview__form-label">
                                ${this.escapeHtml(label)} ${requiredMark}
                            </div>
                            ${optionsHtml || `<div class="chatbot-preview__form-empty">${this.escapeHtml(this.t('formNoOptions', 'No options'))}</div>`}
                        </div>
                    `;
                }

                if (type === 'radio') {
                    const options = Array.isArray(field.options) ? field.options : [];
                    const optionsHtml = options.map((opt, optIndex) => `
                        <label class="chatbot-preview__form-option">
                            <input type="radio" name="${this.escapeHtml(fieldKey)}" value="${this.escapeHtml(opt)}" ${field.required && optIndex === 0 ? 'required' : ''} />
                            <span>${this.escapeHtml(opt)}</span>
                        </label>
                    `).join('');
                    return `
                        <div class="chatbot-preview__form-group">
                            <div class="chatbot-preview__form-label">
                                ${this.escapeHtml(label)} ${requiredMark}
                            </div>
                            ${optionsHtml || `<div class="chatbot-preview__form-empty">${this.escapeHtml(this.t('formNoOptions', 'No options'))}</div>`}
                        </div>
                    `;
                }

                if (type === 'captcha') {
                    return `
                        <div class="chatbot-preview__form-group">
                            <div class="chatbot-preview__form-label">
                                ${this.escapeHtml(label)} ${requiredMark}
                            </div>
                            <div class="chatbot-preview__form-captcha">${this.escapeHtml(this.t('formCaptchaPlaceholder', 'Captcha placeholder'))}</div>
                        </div>
                    `;
                }

                if (type === 'rating') {
                    const options = Array.isArray(field.options) && field.options.length > 0
                        ? field.options
                        : ['1', '2', '3', '4', '5'];
                    const optionsHtml = options.map((opt) => `<option value="${this.escapeHtml(opt)}">${this.escapeHtml(opt)}</option>`).join('');
                    return `
                        <label class="chatbot-preview__form-label">
                            ${this.escapeHtml(label)} ${requiredMark}
                            <select name="${this.escapeHtml(fieldKey)}" ${required}>
                                <option value="">${this.escapeHtml(this.t('formSelect', 'Select'))}</option>
                                ${optionsHtml}
                            </select>
                        </label>
                    `;
                }

                if (type === 'submit') {
                    const submitLabel = field.label || this.t('formSubmit', 'Submit');
                    return `
                        <button type="submit" class="chatbot-preview__form-submit">
                            ${this.escapeHtml(submitLabel)}
                        </button>
                    `;
                }

                const inputType = ['email', 'tel', 'number', 'time', 'date'].includes(type) ? type : 'text';
                return `
                    <label class="chatbot-preview__form-label">
                        ${this.escapeHtml(label)} ${requiredMark}
                        <input type="${inputType}" name="${this.escapeHtml(fieldKey)}" placeholder="${placeholder}" ${required} />
                    </label>
                `;
            }).join('');
        }

        buildFieldKey(field, index) {
            const base = field.name || field.id || field.label || `field_${index + 1}`;
            const key = String(base)
                .toLowerCase()
                .replace(/[^a-z0-9]+/g, '_')
                .replace(/^_+|_+$/g, '');
            return key || `field_${index + 1}`;
        }

        bindFormHandler(wrapper, form) {
            const formEl = wrapper.find('.chatbot-preview__form-fields');
            const submitButton = formEl.find('.chatbot-preview__form-submit');

            formEl.on('submit', async (event) => {
                event.preventDefault();
                if (formEl.data('submitting')) {
                    return;
                }

                formEl.data('submitting', true);
                submitButton.prop('disabled', true);
                submitButton.text(this.t('formSubmitting', 'Submitting...'));

                const payload = this.collectFormPayload(formEl[0]);

                try {
                    const formData = new FormData();
                    formData.append('action', 'kitsune_ai_platform_submit_form');
                    formData.append('nonce', kitsuneAiPlatformPublic.nonce);
                    formData.append('form_id', form.id);
                    formData.append('data', JSON.stringify(payload));
                    formData.append('chatbot_id', this.chatbotId);
                    formData.append('conversation_id', this.getConversationId());

                    const response = await fetch(kitsuneAiPlatformPublic.ajaxUrl, {
                        method: 'POST',
                        body: formData
                    });
                    const data = await response.json();

                    if (data.success) {
                        const resp                = data.data || {};
                        const settings           = form?.config?.settings || {};
                        const confirmationType   = resp.confirmationType   || settings.confirmationType   || 'message';
                        const confirmationMessage = resp.confirmationMessage || settings.confirmationMessage || this.t('formSuccess', 'Thanks! Your submission has been received.');
                        const redirectUrl        = resp.redirectUrl        || settings.redirectUrl        || '';

                        formEl.find('input, select, textarea, button').prop('disabled', true);
                        submitButton.text(this.t('formSubmitted', 'Submitted'));

                        if (confirmationType === 'redirect' && redirectUrl) {
                            setTimeout(() => { window.location.href = redirectUrl; }, 800);
                        } else {
                            this.addMessage(confirmationMessage, 'bot');
                        }
                    } else {
                        submitButton.text(this.t('formSubmit', 'Submit'));
                        this.addMessage(this.t('formError', 'Sorry, we could not submit the form.'), 'bot');
                        submitButton.prop('disabled', false);
                        formEl.data('submitting', false);
                    }
                } catch (error) {
                    console.error('Form submission error', error);
                    submitButton.text(this.t('formSubmit', 'Submit'));
                    this.addMessage(this.t('formError', 'Sorry, we could not submit the form.'), 'bot');
                    submitButton.prop('disabled', false);
                    formEl.data('submitting', false);
                }
            });
        }

        collectFormPayload(formElement) {
            const data = new FormData(formElement);
            const payload = {};
            for (const [key, value] of data.entries()) {
                const cleanKey = key.replace(/\[\]$/, '');
                if (Object.prototype.hasOwnProperty.call(payload, cleanKey)) {
                    if (!Array.isArray(payload[cleanKey])) {
                        payload[cleanKey] = [payload[cleanKey]];
                    }
                    payload[cleanKey].push(value);
                } else {
                    payload[cleanKey] = value;
                }
            }
            return payload;
        }
    }

    // Initialize chatbots when DOM is ready
    $(document).ready(function () {
        $('.ai-platform-chatbot-container').each(function () {
            new AiProChatbot(this);
        });
    });

})(jQuery);
