(function () {
	'use strict';

	function initAvatarPicker() {
		if (typeof macaTjattAdmin === 'undefined') {
			return;
		}

		var select = document.getElementById('maca_tjatt_avatar');
		var preview = document.getElementById('maca_tjatt_avatar_preview');
		var customWrap = document.getElementById('maca_tjatt_avatar_custom');
		var customInput = document.getElementById('maca_tjatt_avatar_url');

		if (!select || !preview) {
			return;
		}

		function getSelectedUrl() {
			var option = select.options[select.selectedIndex];

			if (!option) {
				return macaTjattAdmin.defaultAvatarUrl || '';
			}

			if (select.value === 'custom') {
				return (customInput && customInput.value) || option.getAttribute('data-url') || macaTjattAdmin.defaultAvatarUrl || '';
			}

			return option.getAttribute('data-url') || macaTjattAdmin.defaultAvatarUrl || '';
		}

		function updatePreview() {
			preview.src = getSelectedUrl();

			if (customWrap) {
				if (select.value === 'custom') {
					customWrap.removeAttribute('hidden');
				} else {
					customWrap.setAttribute('hidden', 'hidden');
				}
			}
		}

		select.addEventListener('change', updatePreview);

		if (customInput) {
			customInput.addEventListener('input', function () {
				if (select.value === 'custom') {
					preview.src = getSelectedUrl();
				}
			});
		}

		updatePreview();
	}

	function initAvatarSizePreview() {
		if (typeof macaTjattAdmin === 'undefined') {
			return;
		}

		var sizeSelect = document.getElementById('maca_tjatt_avatar_size');
		var previewWrap = document.getElementById('maca_tjatt_avatar_preview_wrap');
		var preview = document.getElementById('maca_tjatt_avatar_preview');

		if (!sizeSelect || !previewWrap || !preview) {
			return;
		}

		var sizeClasses = (macaTjattAdmin.avatarSizeClasses || {});
		var dimensions = (macaTjattAdmin.avatarDimensions || {});
		var classNames = Object.keys(sizeClasses).map(function (key) {
			return sizeClasses[key];
		});

		function applyPreviewSize(sizeKey) {
			var nextClass = sizeClasses[sizeKey] || sizeClasses.medium;
			var nextDimensions = dimensions[sizeKey] || dimensions.medium || { toggle: 48 };

			classNames.forEach(function (className) {
				previewWrap.classList.remove(className);
			});

			if (nextClass) {
				previewWrap.classList.add(nextClass);
			}

			preview.width = nextDimensions.toggle;
			preview.height = nextDimensions.toggle;
		}

		sizeSelect.addEventListener('change', function () {
			applyPreviewSize(sizeSelect.value);
		});

		applyPreviewSize(sizeSelect.value);
	}

	function initAvatarColorPicker() {
		if (typeof jQuery === 'undefined' || !jQuery.fn.wpColorPicker || typeof macaTjattAdmin === 'undefined') {
			return;
		}

		var previewWrap = document.getElementById('maca_tjatt_avatar_preview_wrap');
		var previewImg = document.getElementById('maca_tjatt_avatar_preview');
		var colorField = jQuery('#maca_tjatt_avatar_bg_color');
		var hiddenField = document.getElementById('maca_tjatt_avatar_bg_color_hidden');

		if (!colorField.length || !hiddenField) {
			return;
		}

		function applyRingColor(color) {
			var adminTest = document.querySelector('.maca-tjatt--admin-test');

			if (previewWrap) {
				previewWrap.style.setProperty('--maca-tjatt-toggle-bg', color);
				previewWrap.style.setProperty('--maca-tjatt-accent', color);
			}

			if (adminTest) {
				adminTest.style.setProperty('--maca-tjatt-toggle-bg', color);
				adminTest.style.setProperty('--maca-tjatt-accent', color);
			}

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

		function normalizeColor(color) {
			var value = (color || '').toString().trim();
			return value || macaTjattAdmin.defaultAvatarBg || '#1f6f4a';
		}

		function syncColorValue(color) {
			var normalized = normalizeColor(color);
			colorField.val(normalized);
			hiddenField.value = normalized;
			applyRingColor(normalized);

			return normalized;
		}

		colorField.wpColorPicker({
			defaultColor: macaTjattAdmin.defaultAvatarBg || '#1f6f4a',
			change: function (event, ui) {
				syncColorValue(ui.color.toString());
			},
			clear: function () {
				syncColorValue(macaTjattAdmin.defaultAvatarBg || '#1f6f4a');
			}
		});

		syncColorValue(colorField.val() || hiddenField.value);

		var settingsAction = document.querySelector('input[name="maca_tjatt_action"][value="save_settings"]');
		var settingsForm = settingsAction ? settingsAction.closest('form') : null;

		if (settingsForm) {
			settingsForm.addEventListener('submit', function () {
				var currentColor = colorField.val();

				try {
					var pickerColor = colorField.wpColorPicker('color');
					if (pickerColor && pickerColor.toString) {
						currentColor = pickerColor.toString();
					}
				} catch (error) {
					// Keep the current input value when the picker API is unavailable.
				}

				syncColorValue(currentColor);
			});
		}
	}

	function initAdminTestChat() {
		if (typeof macaTjattAdmin === 'undefined') {
			return;
		}

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

		if (!root) {
			return;
		}

		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;

		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' && actions && actions.links && actions.links.length) {
				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);
				}
			}

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

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

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

	initAvatarPicker();
	initAvatarSizePreview();
	initAvatarColorPicker();
	initAdminTestChat();
})();
