(function () {
	'use strict';

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

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

		root.dataset.macaTjattInit = '1';

		var panel = root.querySelector('.maca-tjatt-panel');
		var toggle = root.querySelector('.maca-tjatt-toggle');
		var avatarImg = root.querySelector('.maca-tjatt-toggle-avatar');
		var closeBtn = root.querySelector('.maca-tjatt-close');
		var form = root.querySelector('.maca-tjatt-form');
		var input = root.querySelector('.maca-tjatt-input');
		var messages = root.querySelector('.maca-tjatt-messages');
		var history = [];
		var busy = false;
		var chatOpened = false;
		var attentionTimer = null;
		var attentionDelay = 30000;
		var avatarBgColor = macaTjatt.avatarBgColor || root.getAttribute('data-maca-tjatt-bg') || '';

		if (avatarBgColor) {
			root.style.setProperty('--maca-tjatt-toggle-bg', avatarBgColor);
			root.style.setProperty('--maca-tjatt-accent', avatarBgColor);

			if (avatarImg) {
				avatarImg.style.boxShadow = '0 0 0 4px ' + avatarBgColor + ',0 8px 24px rgba(0,0,0,0.18)';
			}
		}

		function prefersReducedMotion() {
			return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
		}

		function clearAttentionReminder() {
			if (attentionTimer) {
				clearTimeout(attentionTimer);
				attentionTimer = null;
			}

			if (toggle) {
				toggle.classList.remove('maca-tjatt-toggle--attention');
			}
		}

		function playAttentionAnimation() {
			if (!toggle || chatOpened || prefersReducedMotion()) {
				return;
			}

			toggle.classList.remove('maca-tjatt-toggle--attention');
			void toggle.offsetWidth;
			toggle.classList.add('maca-tjatt-toggle--attention');
		}

		function scheduleAttentionReminder() {
			if (!toggle || !root.classList.contains('maca-tjatt--floating') || prefersReducedMotion()) {
				return;
			}

			clearAttentionReminder();
			attentionTimer = window.setTimeout(function () {
				if (!chatOpened) {
					playAttentionAnimation();
				}
			}, attentionDelay);
		}

		function markChatOpened() {
			if (chatOpened) {
				return;
			}

			chatOpened = true;
			clearAttentionReminder();
		}

		function appendAssistantActions(item, actions) {
			if (!actions || !actions.links || !actions.links.length) {
				return;
			}

			var linksWrap = document.createElement('div');
			linksWrap.className = 'maca-tjatt-links';

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

				var anchor = document.createElement('a');
				anchor.className = 'maca-tjatt-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);
			}
		}

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

			var textNode = document.createElement('div');
			textNode.className = 'maca-tjatt-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) {
				markChatOpened();
				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);
			});

			toggle.addEventListener('animationend', function (event) {
				if (event.animationName === 'maca-tjatt-attention') {
					toggle.classList.remove('maca-tjatt-toggle--attention');
				}
			});

			scheduleAttentionReminder();
		}

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

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

			fetch(macaTjatt.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) || macaTjatt.error);
						return;
					}

					appendMessage('assistant', payload.data.answer, {
						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', macaTjatt.error);
				})
				.finally(function () {
					busy = false;
				});
		});
	}

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