(function () {
	'use strict';

	function ready(fn) {
		if (document.readyState !== 'loading') {
			fn();
			return;
		}
		document.addEventListener('DOMContentLoaded', fn);
	}

	ready(function () {
		var root = document.getElementById('orsc-chatbot');
		if (!root || !window.ORSC_CHATBOT) {
			return;
		}

		var data = window.ORSC_CHATBOT;
		var toggle = root.querySelector('.orsc-chatbot__toggle');
		var close = root.querySelector('.orsc-chatbot__close');
		var messagesEl = root.querySelector('.orsc-chatbot__messages');
		var form = root.querySelector('.orsc-chatbot__form');
		var input = root.querySelector('.orsc-chatbot__input');
		var send = root.querySelector('.orsc-chatbot__send');
		var history = loadHistory();

		root.style.setProperty('--orsc-primary', data.primaryColor || '#2563eb');
		input.placeholder = data.placeholder || '';

		if (!history.length && data.welcome) {
			history.push({ role: 'assistant', content: data.welcome });
		}

		render();

		toggle.addEventListener('click', function () {
			setOpen(root.getAttribute('data-open') !== 'true');
		});

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

		input.addEventListener('input', function () {
			input.style.height = 'auto';
			input.style.height = Math.min(input.scrollHeight, 120) + 'px';
		});

		form.addEventListener('submit', function (event) {
			event.preventDefault();
			ask(input.value);
		});

		function setOpen(open) {
			root.setAttribute('data-open', open ? 'true' : 'false');
			toggle.setAttribute('aria-label', open ? data.strings.close : data.strings.open);
			if (open) {
				setTimeout(function () {
					input.focus();
				}, 120);
			}
		}

		function ask(text) {
			var question = String(text || '').trim();
			if (!question) {
				return;
			}

			history.push({ role: 'user', content: question });
			input.value = '';
			input.style.height = 'auto';
			setLoading(true);
			render(data.strings.thinking);

			var payload = new FormData();
			payload.append('action', 'orsc_chat');
			payload.append('nonce', data.nonce);
			payload.append('message', question);
			payload.append('history', JSON.stringify(history.slice(-8, -1)));

			fetch(data.ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				body: payload
			})
				.then(function (response) {
					return response.json();
				})
				.then(function (json) {
					if (!json || !json.success) {
						throw new Error(json && json.data && json.data.message ? json.data.message : data.strings.error);
					}

					history.push({
						role: 'assistant',
						content: json.data.answer || data.strings.error,
						sources: json.data.sources || []
					});
					saveHistory();
					render();
				})
				.catch(function (error) {
					history.push({ role: 'assistant', content: error.message || data.strings.error });
					render();
				})
				.finally(function () {
					setLoading(false);
				});
		}

		function render(loadingText) {
			messagesEl.innerHTML = '';

			history.forEach(function (message) {
				messagesEl.appendChild(messageNode(message));
			});

			if (loadingText) {
				messagesEl.appendChild(messageNode({ role: 'assistant', content: loadingText, loading: true }));
			}

			messagesEl.scrollTop = messagesEl.scrollHeight;
		}

		function messageNode(message) {
			var wrap = document.createElement('div');
			var bubble = document.createElement('div');
			wrap.className = 'orsc-chatbot__message orsc-chatbot__message--' + (message.role === 'user' ? 'user' : 'assistant');
			bubble.className = 'orsc-chatbot__bubble';
			if (message.loading) {
				bubble.className += ' orsc-chatbot__bubble--loading';
			}
			bubble.textContent = message.content;
			wrap.appendChild(bubble);

			if (message.sources && message.sources.length) {
				var sources = document.createElement('div');
				sources.className = 'orsc-chatbot__sources';
				message.sources.slice(0, 3).forEach(function (source) {
					var link = document.createElement('a');
					link.href = source.url;
					link.target = '_blank';
					link.rel = 'noopener noreferrer';
					link.textContent = source.title;
					sources.appendChild(link);
				});
				wrap.appendChild(sources);
			}

			return wrap;
		}

		function setLoading(isLoading) {
			send.disabled = isLoading;
			input.disabled = isLoading;
		}

		function loadHistory() {
			try {
				var saved = window.sessionStorage.getItem(data.historyKey);
				return saved ? JSON.parse(saved) : [];
			} catch (error) {
				return [];
			}
		}

		function saveHistory() {
			try {
				window.sessionStorage.setItem(data.historyKey, JSON.stringify(history.slice(-16)));
			} catch (error) {}
		}
	});
}());

