/**
 * Pro — Gallery lightbox (single vehicle page).
 *
 * Opens the .aii-lightbox from the .aii-gallery links; keyboard nav, focus
 * trap, swipe, thumb strip. Image list is provided via wp_localize_script.
 *
 * @package AutomotiveFeedImport
 */
(function () {
	'use strict';

	if (typeof window.aiiLightbox === 'undefined') { return; }
	var images = window.aiiLightbox.images || [];
	if (!images.length) { return; }

	var lb = document.getElementById('afi-lightbox');
	if (!lb) { return; }

	var imgEl = document.getElementById('afi-lb-img');
	var countEl = document.getElementById('afi-lb-count');
	var thumbsEl = document.getElementById('afi-lb-thumbs');
	var idx = 0;
	var lastFocus = null;

	var $$ = function (s, c) { return Array.prototype.slice.call((c || document).querySelectorAll(s)); };

	thumbsEl.innerHTML = images.map(function (im, i) {
		return '<button type="button" class="aii-thumb" data-lbthumb="' + i + '">' +
			'<div class="aii-photo"><img src="' + im.thumb + '" alt="" loading="lazy"></div></button>';
	}).join('');
	var thumbBtns = $$('.aii-thumb', thumbsEl);

	function show(i) {
		idx = (i + images.length) % images.length;
		imgEl.src = images[idx].full;
		imgEl.alt = images[idx].alt || '';
		countEl.textContent = (idx + 1) + ' / ' + images.length;
		thumbBtns.forEach(function (b, bi) { b.classList.toggle('is-active', bi === idx); });
		var active = thumbBtns[idx];
		if (active && active.scrollIntoView) { active.scrollIntoView({ block: 'nearest', inline: 'center' }); }
	}

	function open(i) {
		lastFocus = document.activeElement;
		show(i);
		lb.classList.add('is-open');
		document.body.style.overflow = 'hidden';
		var c = lb.querySelector('.aii-lightbox__close');
		if (c) { c.focus(); }
	}

	function close() {
		lb.classList.remove('is-open');
		document.body.style.overflow = '';
		if (lastFocus) { lastFocus.focus(); }
	}

	document.addEventListener('click', function (e) {
		var trigger = e.target.closest('.aii-gallery [data-aii-index]');
		if (trigger) { e.preventDefault(); open(parseInt(trigger.dataset.aiiIndex, 10) || 0); return; }
		if (e.target.closest('#afi-lightbox [data-lbclose]')) { close(); return; }
		var nav = e.target.closest('#afi-lightbox [data-lbnav]');
		if (nav) { show(idx + (parseInt(nav.dataset.lbnav, 10) || 0)); return; }
		var th = e.target.closest('#afi-lightbox [data-lbthumb]');
		if (th) { show(parseInt(th.dataset.lbthumb, 10) || 0); }
	});

	document.addEventListener('keydown', function (e) {
		if (!lb.classList.contains('is-open')) { return; }
		if (e.key === 'Escape') { close(); }
		else if (e.key === 'ArrowLeft') { show(idx - 1); }
		else if (e.key === 'ArrowRight') { show(idx + 1); }
		else if (e.key === 'Tab') {
			var f = $$('button', lb).filter(function (el) { return el.offsetParent !== null; });
			if (!f.length) { return; }
			var first = f[0], last = f[f.length - 1];
			if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
			else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
		}
	});

	var sx = 0;
	lb.addEventListener('touchstart', function (e) { sx = e.changedTouches[0].clientX; }, { passive: true });
	lb.addEventListener('touchend', function (e) {
		var d = sx - e.changedTouches[0].clientX;
		if (Math.abs(d) > 50) { show(idx + (d > 0 ? 1 : -1)); }
	});
})();
