(function () {
	'use strict';

	function initChatbot(root) {
		if (!window.ChatbotAI || root.dataset.chatbotReady === '1') {
			return;
		}

		root.dataset.chatbotReady = '1';

		const panel = root.querySelector('.replyan-ai-panel');
		const toggle = root.querySelector('.replyan-ai-toggle');
		const close = root.querySelector('.replyan-ai-close');
		const messages = root.querySelector('.replyan-ai-messages');
		const form = root.querySelector('.replyan-ai-form');
		const input = root.querySelector('.replyan-ai-input');
		const send = root.querySelector('.replyan-ai-send');
		const history = [];

		function addMessage(role, content, transient) {
			const bubble = document.createElement('div');
			bubble.className = `replyan-ai-message replyan-ai-message-${role}`;
			bubble.textContent = content;

			if (transient) {
				bubble.dataset.transient = '1';
			}

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

		function setOpen(isOpen) {
			root.classList.toggle('is-open', isOpen);

			if (toggle) {
				toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
			}

			if (isOpen && input) {
				window.setTimeout(() => input.focus(), 80);
			}
		}

		function syncInputSize() {
			if (!input) {
				return;
			}

			input.style.height = 'auto';
			input.style.height = `${Math.min(input.scrollHeight, 120)}px`;
		}

		async function sendMessage(message) {
			const thinking = addMessage('assistant', ChatbotAI.i18n.thinking, true);
			send.disabled = true;
			input.disabled = true;

			try {
				const body = new URLSearchParams();
				body.append('action', 'replyan_ai_send_message');
				body.append('nonce', ChatbotAI.nonce);
				body.append('message', message);
				body.append('history', JSON.stringify(history.slice(-8)));

				const response = await fetch(ChatbotAI.ajaxUrl, {
					method: 'POST',
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
					},
					body,
				});

				const payload = await response.json();
				thinking.remove();

				if (!payload.success) {
					throw new Error(payload.data && payload.data.message ? payload.data.message : ChatbotAI.i18n.error);
				}

				const reply = payload.data.reply;
				addMessage('assistant', reply);
				history.push({ role: 'assistant', content: reply });
			} catch (error) {
				thinking.remove();
				addMessage('error', error.message || ChatbotAI.i18n.error);
			} finally {
				send.disabled = false;
				input.disabled = false;
				input.focus();
			}
		}

		if (ChatbotAI.welcomeMessage) {
			addMessage('assistant', ChatbotAI.welcomeMessage);
		}

		if (toggle) {
			toggle.addEventListener('click', () => setOpen(!root.classList.contains('is-open')));
		}

		if (close) {
			close.addEventListener('click', () => setOpen(false));
		}

		if (input) {
			input.addEventListener('input', syncInputSize);
			input.addEventListener('keydown', (event) => {
				if (event.key === 'Enter' && !event.shiftKey) {
					event.preventDefault();
					form.requestSubmit();
				}
			});
		}

		if (form) {
			form.addEventListener('submit', (event) => {
				event.preventDefault();

				const message = input.value.trim();
				if (!message) {
					addMessage('error', ChatbotAI.i18n.emptyInput, true);
					return;
				}

				input.value = '';
				syncInputSize();
				addMessage('user', message);
				history.push({ role: 'user', content: message });
				sendMessage(message);
			});
		}

		if (root.classList.contains('replyan-ai-inline')) {
			setOpen(true);
		} else if (ChatbotAI.autoOpen) {
			window.setTimeout(() => setOpen(true), 500);
		}
	}

	function boot() {
		document.querySelectorAll('.replyan-ai').forEach(initChatbot);
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', boot);
	} else {
		boot();
	}
})();
