(function () {
    'use strict';

    function getSettings() {
        return (typeof aiBotKitPep !== 'undefined') ? aiBotKitPep : null;
    }

    function findProductData(productId) {
        var localized = getSettings();
        if (localized) {
            // If no productId provided, or it matches the localized data, use localized
            if (!productId || String(localized.productId) === String(productId)) {
                return localized;
            }
        }
        if (!productId) {
            return null;
        }
        var el = document.querySelector('.ai-botkit-product-data[data-product-id="' + productId + '"]');
        if (el) {
            return {
                productId: el.dataset.productId,
                productName: el.dataset.productName,
                productPrice: el.dataset.productPrice,
                chatbotId: el.dataset.chatbotId,
                buttonLabel: el.dataset.buttonLabel || 'Get Quote'
            };
        }
        return null;
    }

    function extractProductId(button) {
        // Try data-product-id first
        if (button.dataset.productId) {
            return button.dataset.productId;
        }
        // Try id attribute: wdm-quoteup-trigger-242
        var match = button.id.match(/(\d+)$/);
        if (match) {
            return match[1];
        }
        return null;
    }

    function openChatbot(productId, productName, productPrice, chatbotId, customMessage) {
        var host = document.getElementById('ai-botkit-chatbox');
        var widget = document.getElementById('ai-bot-kit-chatbot');
        if (!widget) {
            console.warn('AI BotKit widget not found on this page.');
            return;
        }

        var loadedChatbotId = widget.dataset.chatbotId;
        if (loadedChatbotId !== chatbotId) {
            console.warn('AI BotKit widget chatbot does not match the PEP selected chatbot.');
            return;
        }

        var shadow = host.shadowRoot;
        var widgetIcon = shadow.querySelector('.widget-icon');
        var chatWindow = shadow.querySelector('.chatbot-window');

        if (!widgetIcon || !chatWindow) {
            console.warn('AI BotKit widget elements not found.');
            return;
        }

        if (chatWindow.style.display !== 'flex') {
            widgetIcon.click();
        }

        // Expand to fullscreen mode
        if (!chatWindow.classList.contains('expanded')) {
            chatWindow.classList.add('expanded');
            var headerButtons = shadow.querySelector('.chat-header-buttons');
            if (headerButtons) {
                var buttons = headerButtons.querySelectorAll('button');
                buttons.forEach(function (btn) {
                    if (btn.innerHTML.indexOf('icon-tabler-maximize') > -1) {
                        btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-minimize"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 8v-2a2 2 0 0 1 2 -2h2" /><path d="M4 16v2a2 2 0 0 0 2 2h2" /><path d="M16 4h2a2 2 0 0 1 2 2v2" /><path d="M16 20h2a2 2 0 0 0 2 -2v-2" /></svg>';
                    }
                });
            }
        }

        var message = customMessage;
        if (!message && productName) {
            message = 'I want quotation for "' + productName + '"';
        }

        if (!message) {
            return;
        }

        var attempts = 0;
        var maxAttempts = 20;
        var interval = setInterval(function () {
            var input = shadow.querySelector('.chat-input');
            var sendBtn = shadow.querySelector('.chat-send');

            if (input && sendBtn) {
                clearInterval(interval);
                input.value = message;
                input.focus();
                var enterEvent = new KeyboardEvent('keydown', {
                    key: 'Enter',
                    code: 'Enter',
                    keyCode: 13,
                    which: 13,
                    bubbles: true,
                    cancelable: true
                });
                input.dispatchEvent(enterEvent);
            } else {
                attempts++;
                if (attempts >= maxAttempts) {
                    clearInterval(interval);
                    console.warn('AI BotKit chat input not available.');
                }
            }
        }, 100);
    }

    document.addEventListener('DOMContentLoaded', function () {
        var localized = getSettings();
        var isOverride = localized && localized.buttonMode === 'override';
        var hasHiddenData = document.querySelectorAll('.ai-botkit-product-data').length > 0;

        if (isOverride || hasHiddenData) {
            var pepSelectors = [
                '.pep-request-quote-btn',
                '.request-a-quote-btn',
                '[class*="pep"][class*="quote"]',
                '.woocommerce_product_enquiry_button',
                '#product_enquiry_button',
                '.wdm_enquiry_button',
                '.wdm_enquiry',
                '[id^="wdm-quoteup-trigger-"]',
                '#enquiry .contact.pe-show-enq-modal'
            ];

            pepSelectors.forEach(function (selector) {
                document.querySelectorAll(selector).forEach(function (targetBtn) {
                    var productId = extractProductId(targetBtn);
                    var data = findProductData(productId);
                    if (!data) {
                        return;
                    }

                    targetBtn.textContent = data.buttonLabel;

                    var newBtn = targetBtn.cloneNode(true);
                    newBtn.removeAttribute('onclick');
                    newBtn.removeAttribute('data-toggle');
                    newBtn.removeAttribute('data-target');
                    // Strip classes that free/PEP plugins use to bind modal openers,
                    // so late-running jQuery selectors don't attach to our clone.
                    newBtn.classList.remove('pe-show-enq-modal');

                    targetBtn.parentNode.replaceChild(newBtn, targetBtn);

                    // Use capture phase + stopImmediatePropagation so our handler
                    // fires first and suppresses any jQuery click binding that the
                    // PEP plugin may have attached (directly or via delegation).
                    newBtn.addEventListener('click', function (e) {
                        e.preventDefault();
                        e.stopImmediatePropagation();
                        openChatbot(
                            data.productId,
                            data.productName,
                            data.productPrice,
                            data.chatbotId
                        );
                    }, true);
                });
            });
        }

        // Product page buttons (new mode)
        document.querySelectorAll('.ai-botkit-ask-ai-btn').forEach(function (button) {
            button.addEventListener('click', function () {
                openChatbot(
                    this.dataset.productId,
                    this.dataset.productName,
                    this.dataset.productPrice,
                    this.dataset.chatbotId
                );
            });
        });

        // Enquiry cart button (MPE mode)
        document.querySelectorAll('.ai-botkit-enquiry-cart-btn').forEach(function (button) {
            button.addEventListener('click', function () {
                openChatbot(
                    null,
                    null,
                    null,
                    this.dataset.chatbotId,
                    this.dataset.message || 'I have products in my enquiry cart and would like a quotation.'
                );
            });
        });
    });
})();
