/**
 * Pro — Advanced AJAX search & filter (vehicle archive).
 *
 * Vanilla JS, no dependencies. Reads the filter controls, fetches matching
 * vehicles over admin-ajax, and swaps the grid + count + chips without a reload.
 * Keeps state in the URL (history API) so filtered views are shareable.
 *
 * @package AutomotiveFeedImport
 */
(function () {
	'use strict';

	if (typeof window.aiiFilter === 'undefined') {
		return;
	}

	var cfg = window.aiiFilter;
	var root = document.getElementById('afi-archive');
	if (!root) {
		return;
	}

	var results = document.getElementById('afi-results');
	var countEl = document.getElementById('afi-count');
	var chipsEl = document.getElementById('afi-chips');
	var fgroups = document.getElementById('afi-fgroups');
	var moreWrap = root.querySelector('.aii-archive__more');
	var moreBtn = document.getElementById('afi-load-more');
	var drawer = document.getElementById('afi-drawer');
	var drawerBody = document.getElementById('afi-drawer-body');

	var fgroupsHome = fgroups.parentNode;
	var currentPage = 1;
	var maxPages = moreBtn ? parseInt(moreBtn.dataset.max, 10) || 1 : 1;
	var fetchSeq = 0;
	var debounceTimer = null;
	var lastFocus = null;

	var $ = function (s, c) { return (c || document).querySelector(s); };
	var $$ = function (s, c) { return Array.prototype.slice.call((c || document).querySelectorAll(s)); };
	var escHtml = function (s) { var d = document.createElement('div'); d.textContent = s == null ? '' : s; return d.innerHTML; };
	var money = function (v) { return '$' + (+v).toLocaleString(); };

	/* ---------------------------------------------------------- range sliders */
	function initRange(range) {
		var lo = $('.aii-range__lo', range), hi = $('.aii-range__hi', range);
		var loI = $('.aii-range__loInput', range), hiI = $('.aii-range__hiInput', range);
		var fill = $('.aii-range__fill', range);
		var MIN = +range.dataset.min, MAX = +range.dataset.max, STEP = +range.dataset.step;
		var isMoney = range.dataset.money === '1';
		[lo, hi].forEach(function (s) { s.min = MIN; s.max = MAX; s.step = STEP; });
		lo.value = +range.dataset.lo;
		hi.value = +range.dataset.hi;

		var fmt = function (v) { return (isMoney ? '$' : '') + (+v).toLocaleString(); };

		function paint() {
			var a = +lo.value, b = +hi.value;
			if (a > b - STEP) {
				if (document.activeElement === lo) { a = b - STEP; lo.value = a; }
				else { b = a + STEP; hi.value = b; }
			}
			var pa = (a - MIN) / (MAX - MIN) * 100, pb = (b - MIN) / (MAX - MIN) * 100;
			fill.style.left = pa + '%';
			fill.style.width = (pb - pa) + '%';
			loI.value = fmt(a);
			hiI.value = fmt(b);
			range._lo = a;
			range._hi = b;
		}
		var parse = function (s) { return +String(s).replace(/[^0-9]/g, '') || MIN; };

		lo.addEventListener('input', paint);
		hi.addEventListener('input', paint);
		lo.addEventListener('change', function () { apply(true); });
		hi.addEventListener('change', function () { apply(true); });
		loI.addEventListener('change', function () { lo.value = Math.min(Math.max(parse(loI.value), MIN), (+hi.value) - STEP); paint(); apply(true); });
		hiI.addEventListener('change', function () { hi.value = Math.max(Math.min(parse(hiI.value), MAX), (+lo.value) + STEP); paint(); apply(true); });

		range._reset = function () { lo.value = MIN; hi.value = MAX; paint(); };
		range._setLoHi = function (a, b) { lo.value = a; hi.value = b; paint(); };
		range._MIN = MIN;
		range._MAX = MAX;
		paint();
	}

	/* ------------------------------------------------------------- collect state */
	function collect() {
		var p = {};
		var kw = $('[data-key="kw"]', fgroups);
		if (kw && kw.value.trim()) { p.afi_kw = kw.value.trim(); }

		$$('[data-multi]', fgroups).forEach(function (g) {
			var vals = $$('.aii-opt.is-active', g).map(function (b) { return b.dataset.value; });
			if (vals.length) { p['afi_' + g.dataset.key] = vals; }
		});

		$$('.aii-range', fgroups).forEach(function (r) {
			var pre = r.dataset.range === 'price' ? 'afi_p' : 'afi_m';
			if (r._lo > r._MIN) { p[pre + 'min'] = r._lo; }
			if (r._hi < r._MAX) { p[pre + 'max'] = r._hi; }
		});

		var sort = $('[data-key="sort"]');
		if (sort && sort.value) { p.afi_sort = sort.value; }
		return p;
	}

	function appendParams(target, p, append) {
		Object.keys(p).forEach(function (k) {
			var v = p[k];
			if (Array.isArray(v)) { v.forEach(function (x) { target.append(k + '[]', x); }); }
			else if (append) { target.append(k, v); }
			else { target.set(k, v); }
		});
	}

	function buildForm(p, page) {
		var fd = new FormData();
		fd.append('action', 'afi_filter_vehicles');
		fd.append('nonce', cfg.nonce);
		fd.append('paged', page || 1);
		appendParams(fd, p, true);
		return fd;
	}

	/* ---------------------------------------------------------------- chips */
	function chipDefs(p) {
		var defs = [];
		var kw = $('[data-key="kw"]', fgroups);
		if (p.afi_kw) { defs.push({ label: '“' + p.afi_kw + '”', clear: function () { if (kw) { kw.value = ''; } } }); }

		['makes', 'years', 'conditions', 'bodies'].forEach(function (key) {
			var arr = p['afi_' + key];
			if (!arr) { return; }
			var g = $('[data-multi][data-key="' + key + '"]', fgroups);
			arr.forEach(function (val) {
				var btn = g ? $$('.aii-opt', g).filter(function (b) { return b.dataset.value === val; })[0] : null;
				defs.push({ label: btn ? btn.textContent.trim() : val, clear: function () { if (btn) { btn.classList.remove('is-active'); } } });
			});
		});

		$$('.aii-range', fgroups).forEach(function (r) {
			if (r._lo > r._MIN || r._hi < r._MAX) {
				var isMoney = r.dataset.money === '1';
				var f = function (v) { return (isMoney ? '$' : '') + (+v).toLocaleString(); };
				var label = f(r._lo) + '–' + f(r._hi) + (r.dataset.range === 'miles' ? ' mi' : '');
				defs.push({ label: label, clear: function () { r._reset(); } });
			}
		});
		return defs;
	}

	function renderChips(p) {
		var defs = chipDefs(p);
		if (!defs.length) { chipsEl.hidden = true; chipsEl.innerHTML = ''; chipsEl._defs = []; return; }
		chipsEl.hidden = false;
		var html = '<span class="aii-applied__label">' + escHtml(cfg.i18n.active) + '</span>';
		defs.forEach(function (d, i) {
			html += '<span class="aii-chip" data-ci="' + i + '">' + escHtml(d.label) +
				' <button type="button" class="aii-chip__x" aria-label="' + escHtml(cfg.i18n.remove) +
				'"><svg aria-hidden="true" focusable="false"><use href="#i-x"></use></svg></button></span>';
		});
		html += '<button type="button" class="aii-chip aii-chip--clear" id="afi-chip-clear">' + escHtml(cfg.i18n.clearAll) + '</button>';
		chipsEl.innerHTML = html;
		chipsEl._defs = defs;
	}

	/* ------------------------------------------------------------- skeleton */
	function skeleton() {
		var card = '<div class="aii-skel-card"><div class="aii-skel-card__media aii-skeleton"></div>' +
			'<div class="aii-skel-card__body"><div class="aii-skel-line aii-skeleton" style="width:46%;height:18px;"></div>' +
			'<div class="aii-skel-line aii-skeleton" style="width:80%;"></div>' +
			'<div class="aii-skel-line aii-skeleton" style="width:60%;"></div></div></div>';
		results.innerHTML = new Array(6).join(card) + card;
	}

	/* ------------------------------------------------------------- fetch/apply */
	function apply(pushUrl) {
		var p = collect();
		var seq = ++fetchSeq;
		currentPage = 1;
		results.setAttribute('aria-busy', 'true');
		skeleton();
		renderChips(p);
		if (pushUrl) { pushState(p); }

		fetch(cfg.ajaxUrl, { method: 'POST', body: buildForm(p, 1), credentials: 'same-origin' })
			.then(function (r) { return r.json(); })
			.then(function (res) {
				if (seq !== fetchSeq) { return; }
				results.setAttribute('aria-busy', 'false');
				if (!res || !res.success) { return; }
				var d = res.data;
				results.innerHTML = d.cards || d.empty || '';
				countEl.innerHTML = d.countHtml;
				maxPages = d.maxPages;
				currentPage = d.page;
				updateMore();
				updateDrawerCount(d.count);
			})
			.catch(function () {
				if (seq === fetchSeq) { results.setAttribute('aria-busy', 'false'); }
			});
	}

	function loadMore() {
		if (!moreBtn) { return; }
		var p = collect();
		moreBtn.disabled = true;
		fetch(cfg.ajaxUrl, { method: 'POST', body: buildForm(p, currentPage + 1), credentials: 'same-origin' })
			.then(function (r) { return r.json(); })
			.then(function (res) {
				moreBtn.disabled = false;
				if (!res || !res.success) { return; }
				results.insertAdjacentHTML('beforeend', res.data.cards || '');
				currentPage = res.data.page;
				maxPages = res.data.maxPages;
				updateMore();
			})
			.catch(function () { moreBtn.disabled = false; });
	}

	function updateMore() {
		if (!moreWrap) { return; }
		moreWrap.hidden = currentPage >= maxPages;
	}

	function updateDrawerCount(n) {
		var el = $('#afi-drawer-count');
		if (el) { el.textContent = cfg.i18n.showN.replace('%s', (+n).toLocaleString()); }
	}

	function schedule() {
		clearTimeout(debounceTimer);
		debounceTimer = setTimeout(function () { apply(true); }, 280);
	}

	/* ------------------------------------------------------------- reset */
	function resetAll() {
		var kw = $('[data-key="kw"]', fgroups);
		if (kw) { kw.value = ''; }
		$$('.aii-opt.is-active', fgroups).forEach(function (b) { b.classList.remove('is-active'); });
		$$('.aii-range', fgroups).forEach(function (r) { if (r._reset) { r._reset(); } });
		var sort = $('[data-key="sort"]');
		if (sort) { sort.value = ''; }
	}

	/* ------------------------------------------------------------- URL state */
	function pushState(p) {
		var u = new URLSearchParams();
		appendParams(u, p, false);
		var qs = u.toString();
		history.pushState({ afi: 1 }, '', location.pathname + (qs ? '?' + qs : ''));
	}

	function applyFromUrl() {
		var u = new URLSearchParams(location.search);
		var kw = $('[data-key="kw"]', fgroups);
		if (kw) { kw.value = u.get('afi_kw') || ''; }

		['makes', 'years', 'conditions', 'bodies'].forEach(function (key) {
			var vals = u.getAll('afi_' + key + '[]');
			var g = $('[data-multi][data-key="' + key + '"]', fgroups);
			if (!g) { return; }
			$$('.aii-opt', g).forEach(function (b) { b.classList.toggle('is-active', vals.indexOf(b.dataset.value) > -1); });
		});

		$$('.aii-range', fgroups).forEach(function (r) {
			var pre = r.dataset.range === 'price' ? 'afi_p' : 'afi_m';
			var lo = u.get(pre + 'min'), hi = u.get(pre + 'max');
			r._setLoHi(lo != null ? +lo : r._MIN, hi != null ? +hi : r._MAX);
		});

		var sort = $('[data-key="sort"]');
		if (sort) { sort.value = u.get('afi_sort') || ''; }
		apply(false);
	}

	/* ------------------------------------------------------------- drawer */
	function openDrawer() {
		lastFocus = document.activeElement;
		drawerBody.appendChild(fgroups);
		drawer.classList.add('is-open');
		document.body.style.overflow = 'hidden';
		var c = drawer.querySelector('.aii-drawer__close');
		if (c) { c.focus(); }
	}
	function closeDrawer() {
		drawer.classList.remove('is-open');
		document.body.style.overflow = '';
		fgroupsHome.appendChild(fgroups);
		if (lastFocus) { lastFocus.focus(); }
	}
	function trapFocus(e) {
		if (e.key !== 'Tab' || !drawer.classList.contains('is-open')) { return; }
		var f = $$('button, input, select, [tabindex]:not([tabindex="-1"])', drawer.querySelector('.aii-drawer__panel'))
			.filter(function (el) { return !el.disabled && 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(); }
	}

	/* ------------------------------------------------------------- wire up */
	$$('.aii-range', fgroups).forEach(initRange);

	fgroups.addEventListener('click', function (e) {
		var opt = e.target.closest('.aii-opt');
		if (!opt) { return; }
		opt.classList.toggle('is-active');
		apply(true);
	});

	fgroups.addEventListener('input', function (e) {
		if (e.target.matches('[data-key="kw"]')) { schedule(); }
	});

	document.addEventListener('change', function (e) {
		if (e.target.matches('[data-key="sort"]')) { apply(true); }
	});

	chipsEl.addEventListener('click', function (e) {
		var x = e.target.closest('.aii-chip__x');
		if (x) {
			var ci = +x.closest('.aii-chip').dataset.ci;
			var defs = chipsEl._defs || [];
			if (defs[ci]) { defs[ci].clear(); }
			apply(true);
			return;
		}
		if (e.target.closest('#afi-chip-clear')) { resetAll(); apply(true); }
	});

	var resetBtn = document.getElementById('afi-reset');
	if (resetBtn) { resetBtn.addEventListener('click', function () { resetAll(); apply(true); }); }
	var drawerClear = document.getElementById('afi-drawer-clear');
	if (drawerClear) { drawerClear.addEventListener('click', function () { resetAll(); apply(true); }); }
	if (moreBtn) { moreBtn.addEventListener('click', loadMore); }

	var openBtn = document.getElementById('afi-open-drawer');
	if (openBtn) { openBtn.addEventListener('click', openDrawer); }
	drawer.addEventListener('click', function (e) { if (e.target.closest('[data-close]')) { closeDrawer(); } });
	document.addEventListener('keydown', function (e) {
		if (e.key === 'Escape' && drawer.classList.contains('is-open')) { closeDrawer(); }
		trapFocus(e);
	});

	window.addEventListener('popstate', applyFromUrl);

	/* Initial paint: the server already rendered filtered controls + grid, so
	   just reflect chips/counts without an extra fetch. */
	var initial = collect();
	renderChips(initial);
	updateMore();
	updateDrawerCount(parseInt((countEl && countEl.getAttribute('data-count')) || '0', 10));
})();
