(function () {
	'use strict';

	var config = window.niwaHistoryReader;
	var layout = document.querySelector('.niwa-history-layout');
	var list = layout && layout.querySelector('.niwa-history-session-list');
	var activeRequest = null;

	if (!config || !layout || !list) {
		return;
	}

	function selectSession(item) {
		list.querySelectorAll('.niwa-history-session-item').forEach(function (link) {
			var selected = link === item;
			link.classList.toggle('is-active', selected);
			if (selected) {
				link.setAttribute('aria-current', 'page');
			} else {
				link.removeAttribute('aria-current');
			}
		});
	}

	function showError(pane) {
		var error = document.createElement('div');
		error.className = 'niwa-history-load-error';
		error.setAttribute('role', 'alert');
		error.textContent = config.error || 'Conversation could not be loaded. Try again.';
		pane.appendChild(error);
	}

	async function loadSession(item, updateUrl) {
		var session = item.dataset.session || '';
		var pane = layout.querySelector('.niwa-history-chat-pane');
		if (!session || !pane || pane.dataset.session === session) {
			return;
		}

		if (activeRequest) {
			activeRequest.abort();
		}
		var request = new AbortController();
		activeRequest = request;
		layout.classList.add('is-loading');
		pane.querySelectorAll('.niwa-history-load-error').forEach(function (error) {
			error.remove();
		});

		try {
			var body = new URLSearchParams({
				action: config.action,
				nonce: config.nonce,
				session: session
			});
			var response = await fetch(config.ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
				body: body.toString(),
				signal: request.signal
			});
			var payload = await response.json();
			if (!response.ok || !payload.success || !payload.data || !payload.data.html) {
				throw new Error('History transcript request failed');
			}

			var template = document.createElement('template');
			template.innerHTML = payload.data.html.trim();
			var nextPane = template.content.firstElementChild;
			if (!nextPane || !nextPane.classList.contains('niwa-history-chat-pane')) {
				throw new Error('History transcript response is invalid');
			}

			pane.replaceWith(nextPane);
			selectSession(item);
			if (updateUrl) {
				window.history.pushState({niwaHistorySession: session}, '', item.href);
			}
			nextPane.focus({preventScroll: true});
		} catch (error) {
			if (error.name !== 'AbortError') {
				showError(layout.querySelector('.niwa-history-chat-pane'));
			}
		} finally {
			if (activeRequest === request) {
				activeRequest = null;
				layout.classList.remove('is-loading');
			}
		}
	}

	// ponytail: only the transcript changes here; search and pagination stay native.
	list.addEventListener('click', function (event) {
		var item = event.target.closest('.niwa-history-session-item');
		if (!item || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
			return;
		}
		event.preventDefault();
		loadSession(item, true);
	});

	var initial = list.querySelector('.niwa-history-session-item.is-active');
	if (initial) {
		window.history.replaceState({niwaHistorySession: initial.dataset.session}, '', initial.href);
	}

	window.addEventListener('popstate', function () {
		var session = new URL(window.location.href).searchParams.get('session');
		var item = Array.from(list.querySelectorAll('.niwa-history-session-item')).find(function (link) {
			return link.dataset.session === session;
		});
		if (item) {
			loadSession(item, false);
		}
	});
}());
