/* Quick Variable Products — lightweight coach-mark tour engine.
 * Shared by the free Add screen and the Pro Bulk / Add-to-existing screens
 * (ships in BOTH builds — it carries no premium logic, only the generic engine).
 * Zero dependencies. A "spotlight" box dims the page except one target element and
 * a bubble explains it. Steps whose target is missing/hidden are skipped. Keyboard:
 * Esc = skip, ←/→ = prev/next. Theme-aware + RTL + prefers-reduced-motion (CSS).
 *
 * Usage:  ErenqvpTour.run(steps, { onDone: function(skipped){} })
 *   steps: [ { target: '#id' | fn | Element, title, body, center?, before? } ]
 */
(function () {
	'use strict';
	var win = window;
	var T = win.ErenqvpTour = win.ErenqvpTour || {};

	// Engine UI strings come from whichever localize bag is present on this screen
	// (ERENQVP on the free Add screen, ERENQVPP on the Pro screens); English is the fallback.
	function ui() {
		var bag = (win.ERENQVP && win.ERENQVP.tourUI) || (win.ERENQVPP && win.ERENQVPP.tourUI) || {};
		return {
			next: bag.next || 'Next',
			prev: bag.prev || 'Back',
			done: bag.done || 'Got it',
			skip: bag.skip || 'Skip',
			counter: bag.counter || '%1$d / %2$d',
		};
	}

	function el(tag, cls, txt) {
		var e = document.createElement(tag);
		if (cls) { e.className = cls; }
		if (txt != null) { e.textContent = txt; }
		return e;
	}
	function fmt(tpl) {
		var a = arguments, i = 1;
		return String(tpl || '').replace(/%(\d+)\$d|%d/g, function (m, p) { return p ? a[+p] : a[i++]; });
	}
	function resolve(step) {
		var t = step.target;
		if (typeof t === 'function') { try { t = t(); } catch (e) { t = null; } }
		if (typeof t === 'string') { t = document.querySelector(t); }
		if (!t) { return null; }
		if (t !== document.body && t.offsetParent === null) { return null; } // hidden / display:none
		return t;
	}

	function Tour(steps, opts) {
		this.steps = steps || [];
		this.opts = opts || {};
		this.i = 0;
		this.built = false;
	}

	Tour.prototype.build = function () {
		if (this.built) { return; }
		var self = this, U = ui();
		this.spot = el('div', 'qvp-tour-spot');
		this.bubble = el('div', 'qvp-tour-bubble');
		this.bubble.setAttribute('role', 'dialog');
		this.bubble.setAttribute('aria-live', 'polite');
		this.arrow = el('div', 'qvp-tour-arrow');
		this.hTitle = el('div', 'qvp-tour-title');
		this.hBody = el('div', 'qvp-tour-body');
		var foot = el('div', 'qvp-tour-foot');
		this.counter = el('span', 'qvp-tour-count');
		var nav = el('div', 'qvp-tour-nav');
		this.bSkip = el('button', 'qvp-tour-x', U.skip); this.bSkip.type = 'button';
		this.bPrev = el('button', 'qvp-tour-btn qvp-tour-ghost', U.prev); this.bPrev.type = 'button';
		this.bNext = el('button', 'qvp-tour-btn qvp-tour-go', U.next); this.bNext.type = 'button';
		nav.appendChild(this.bPrev); nav.appendChild(this.bNext);
		foot.appendChild(this.bSkip); foot.appendChild(nav);
		this.bubble.appendChild(this.arrow);
		this.bubble.appendChild(this.hTitle);
		this.bubble.appendChild(this.hBody);
		this.bubble.appendChild(foot);
		document.body.appendChild(this.spot);
		document.body.appendChild(this.bubble);
		this.bSkip.onclick = function () { self.finish(true); };
		this.bPrev.onclick = function () { self.go(-1); };
		this.bNext.onclick = function () { self.go(1); };
		this._key = function (e) {
			if (e.key === 'Escape') { self.finish(true); }
			else if (e.key === 'ArrowRight') { self.go(1); }
			else if (e.key === 'ArrowLeft') { self.go(-1); }
		};
		this._rep = function () { self.position(); };
		document.addEventListener('keydown', this._key);
		win.addEventListener('resize', this._rep);
		win.addEventListener('scroll', this._rep, true);
		this.built = true;
	};

	Tour.prototype.available = function (n) {
		var s = this.steps[n];
		if (!s) { return false; }
		// center steps have no target; steps with a before() hook may reveal/create
		// their target (e.g. open an accordion, switch a tab) — trust them.
		if (s.center || s.before) { return true; }
		return !!resolve(s);
	};

	Tour.prototype.start = function () {
		this.build();
		// jump to the first available step
		for (var k = 0; k < this.steps.length; k++) {
			if (this.available(k)) { this.i = k; this.show(); return; }
		}
		this.finish(false); // nothing to show
	};

	Tour.prototype.go = function (dir) {
		var n = this.i;
		while (true) {
			n += dir;
			if (n < 0 || n >= this.steps.length) { break; }
			if (this.available(n)) { this.i = n; this.show(); return; }
		}
		if (n >= this.steps.length) { this.finish(false); } // past the end = complete
		// n < 0 (before start): stay put
	};

	Tour.prototype.show = function () {
		var s = this.steps[this.i], U = ui();
		if (s.before) { try { s.before(); } catch (e) {} }
		this.hTitle.textContent = s.title || '';
		this.hBody.textContent = s.body || '';
		var total = 0, cur = 0;
		for (var k = 0; k < this.steps.length; k++) {
			if (this.available(k)) { total++; if (k === this.i) { cur = total; } }
		}
		this.counter.textContent = fmt(U.counter, cur, total);
		this.bPrev.style.visibility = (cur <= 1) ? 'hidden' : '';
		this.bNext.textContent = (cur >= total) ? U.done : U.next;
		this.position();
	};

	Tour.prototype.position = function () {
		var s = this.steps[this.i];
		if (!s) { return; }
		var t = s.center ? null : resolve(s);
		if (!t) {
			this.spot.style.display = 'none';
			this.bubble.classList.add('is-center');
			this.arrow.style.display = 'none';
			this.bubble.style.left = ''; this.bubble.style.top = '';
			return;
		}
		this.bubble.classList.remove('is-center');
		try { t.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'smooth' }); }
		catch (e) { try { t.scrollIntoView(); } catch (e2) {} }
		var r = t.getBoundingClientRect(), pad = 6;
		this.spot.style.display = '';
		this.spot.style.left = (r.left - pad) + 'px';
		this.spot.style.top = (r.top - pad) + 'px';
		this.spot.style.width = (r.width + pad * 2) + 'px';
		this.spot.style.height = (r.height + pad * 2) + 'px';
		var bw = Math.min(320, win.innerWidth - 24);
		this.bubble.style.width = bw + 'px';
		var bh = this.bubble.offsetHeight || 170;
		var below = (r.bottom + 14 + bh) <= win.innerHeight;
		var top = below ? (r.bottom + 14) : Math.max(12, r.top - 14 - bh);
		var left = Math.min(Math.max(12, r.left + r.width / 2 - bw / 2), win.innerWidth - bw - 12);
		this.bubble.style.left = left + 'px';
		this.bubble.style.top = top + 'px';
		this.arrow.style.display = '';
		this.arrow.className = 'qvp-tour-arrow ' + (below ? 'is-up' : 'is-down');
		this.arrow.style.left = Math.max(14, Math.min(bw - 26, r.left + r.width / 2 - left - 7)) + 'px';
	};

	Tour.prototype.finish = function (skipped) {
		if (this.built) {
			this.spot.remove();
			this.bubble.remove();
			document.removeEventListener('keydown', this._key);
			win.removeEventListener('resize', this._rep);
			win.removeEventListener('scroll', this._rep, true);
			this.built = false;
		}
		if (this.opts.onDone) { try { this.opts.onDone(!!skipped); } catch (e) {} }
	};

	/**
	 * Run a tour. steps: array of { target, title, body, center?, before? }.
	 * Returns the Tour instance.
	 */
	T.run = function (steps, opts) {
		var tr = new Tour(steps, opts || {});
		tr.start();
		return tr;
	};

	/**
	 * Build a small "❓ label" replay pill and append it to a container.
	 * onClick launches the tour.
	 */
	T.pill = function (container, label, onClick) {
		if (!container) { return null; }
		var b = el('button', 'qvp-tour-pill', '❓ ' + (label || 'Tips'));
		b.type = 'button';
		b.onclick = onClick;
		container.appendChild(b);
		return b;
	};
})();
