(function () {
    'use strict';

    if (typeof macaSiteChat === 'undefined') {
        return;
    }

    function getBookingConfig() {
        return macaSiteChat.booking || {};
    }

    function openBookingForm(cta) {
        var booking = getBookingConfig();
        var trigger = document.querySelector('[data-maca-booking] .maca-table-booking-trigger');

        if (trigger) {
            trigger.click();
            return;
        }

        var url = (cta && cta.url) || booking.pageUrl || '';

        if (!url) {
            return;
        }

        var openParam = booking.openParam || 'maca_booking';

        try {
            var target = new URL(url, window.location.origin);
            target.searchParams.set(openParam, '1');
            window.location.href = target.toString();
        } catch (error) {
            window.location.href = url;
        }
    }

    function initWidget(root) {
        if (!root || root.dataset.macaSiteChatInit === '1') {
            return;
        }

        root.dataset.macaSiteChatInit = '1';

        var panel = root.querySelector('.maca-site-chat-panel');
        var toggle = root.querySelector('.maca-site-chat-toggle');
        var closeBtn = root.querySelector('.maca-site-chat-close');
        var form = root.querySelector('.maca-site-chat-form');
        var input = root.querySelector('.maca-site-chat-input');
        var messages = root.querySelector('.maca-site-chat-messages');
        var history = [];
        var busy = false;

        function appendAssistantActions(item, actions) {
            if (!actions) {
                return;
            }

            if (actions.cta && actions.cta.type === 'booking') {
                var booking = getBookingConfig();
                var btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'maca-site-chat-cta maca-site-chat-cta--booking';
                btn.textContent = actions.cta.label || booking.label || 'Book a table';
                btn.addEventListener('click', function () {
                    openBookingForm(actions.cta);
                });
                item.appendChild(btn);
            }

            if (actions.links && actions.links.length) {
                var linksWrap = document.createElement('div');
                linksWrap.className = 'maca-site-chat-links';

                actions.links.forEach(function (link) {
                    if (!link || !link.url) {
                        return;
                    }

                    var anchor = document.createElement('a');
                    anchor.className = 'maca-site-chat-link';
                    anchor.href = link.url;
                    anchor.textContent = link.label || link.url;

                    if (link.url.indexOf('#') === 0) {
                        anchor.addEventListener('click', function (event) {
                            var target = document.getElementById(link.url.slice(1));
                            if (target) {
                                event.preventDefault();
                                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
                            }
                        });
                    }

                    linksWrap.appendChild(anchor);
                });

                if (linksWrap.childNodes.length) {
                    item.appendChild(linksWrap);
                }
            }
        }

        function appendMessage(role, text, actions) {
            var item = document.createElement('div');
            item.className = 'maca-site-chat-message maca-site-chat-message--' + role;

            var textNode = document.createElement('div');
            textNode.className = 'maca-site-chat-message-text';
            textNode.textContent = text;
            item.appendChild(textNode);

            if (role === 'assistant') {
                appendAssistantActions(item, actions);
            }

            messages.appendChild(item);
            messages.scrollTop = messages.scrollHeight;
            return item;
        }

        function setOpen(open) {
            if (!panel) {
                return;
            }

            if (open) {
                panel.hidden = false;
                if (toggle) {
                    toggle.setAttribute('aria-expanded', 'true');
                }
                if (input) {
                    input.focus();
                }
            } else {
                panel.hidden = true;
                if (toggle) {
                    toggle.setAttribute('aria-expanded', 'false');
                }
            }
        }

        if (toggle) {
            toggle.addEventListener('click', function () {
                setOpen(panel.hidden);
            });
        }

        if (closeBtn) {
            closeBtn.addEventListener('click', function () {
                setOpen(false);
            });
        }

        if (!form || !input || !messages) {
            return;
        }

        form.addEventListener('submit', function (event) {
            event.preventDefault();

            var question = (input.value || '').trim();
            if (!question || busy) {
                return;
            }

            busy = true;
            appendMessage('user', question);
            input.value = '';
            var thinkingNode = appendMessage('assistant', macaSiteChat.thinking || '…');

            var body = new FormData();
            body.append('action', 'maca_site_chat_ask');
            body.append('nonce', macaSiteChat.nonce);
            body.append('question', question);
            body.append('history', JSON.stringify(history));

            if (getBookingConfig().onPage || document.querySelector('[data-maca-booking]')) {
                body.append('booking_on_page', '1');
            }

            fetch(macaSiteChat.ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                body: body
            })
                .then(function (response) {
                    return response.json();
                })
                .then(function (payload) {
                    if (thinkingNode && thinkingNode.parentNode) {
                        thinkingNode.parentNode.removeChild(thinkingNode);
                    }

                    if (!payload || !payload.success || !payload.data || !payload.data.answer) {
                        appendMessage('assistant', (payload && payload.data && payload.data.message) || macaSiteChat.error);
                        return;
                    }

                    appendMessage('assistant', payload.data.answer, {
                        cta: payload.data.cta || null,
                        links: payload.data.links || []
                    });
                    history.push({ role: 'user', content: question });
                    history.push({ role: 'assistant', content: payload.data.answer });

                    if (history.length > 8) {
                        history = history.slice(history.length - 8);
                    }
                })
                .catch(function () {
                    if (thinkingNode && thinkingNode.parentNode) {
                        thinkingNode.parentNode.removeChild(thinkingNode);
                    }
                    appendMessage('assistant', macaSiteChat.error);
                })
                .finally(function () {
                    busy = false;
                });
        });
    }

    document.querySelectorAll('[data-maca-site-chat="1"]').forEach(initWidget);
})();
