(function () {
    'use strict';

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

    var root = document.querySelector('[data-maca-site-chat-admin="1"]');

    if (!root) {
        return;
    }

    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 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' && actions) {
            if (actions.cta && actions.cta.type === 'booking') {
                var btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'maca-site-chat-cta maca-site-chat-cta--booking';
                btn.textContent = actions.cta.label || 'Book a table';
                btn.addEventListener('click', function () {
                    if (actions.cta.url) {
                        window.open(actions.cta.url, '_blank', 'noopener');
                    }
                });
                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.target = '_blank';
                    anchor.rel = 'noopener noreferrer';
                    anchor.textContent = link.label || link.url;
                    linksWrap.appendChild(anchor);
                });

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

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

    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', macaSiteChatAdmin.thinking || '…');

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

        fetch(macaSiteChatAdmin.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) || macaSiteChatAdmin.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', macaSiteChatAdmin.error);
            })
            .finally(function () {
                busy = false;
            });
    });
})();
