/**
 * CartCue — Confetti + first-activation forecast modal.
 *
 * Two responsibilities:
 *   1. expose window.cartcueConfetti() — a vanilla canvas confetti burst.
 *   2. on a successful first activation, render a modal showing the
 *      revenue forecast for the play's trigger category, mark "seen" on the
 *      server, and fire confetti when the user dismisses.
 *
 * No external libs. Designed to stay under 6KB minified.
 */
(function () {
	'use strict';

	// -------------------------------------------------------------------
	// Confetti (canvas, GPU-friendly, ~5s burst)
	// -------------------------------------------------------------------

	function fire(opts) {
		if ( window.matchMedia && window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches ) {
			return;
		}
		opts = opts || {};
		var COLORS = opts.colors || ['#534AB7', '#FFCC4D', '#FF6B6B', '#4ECDC4', '#FFD93D', '#A855F7'];
		var count  = opts.count || 140;
		var canvas = document.createElement('canvas');
		canvas.className = 'cartcue-confetti-canvas';
		canvas.style.cssText = 'position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;z-index:999999';
		document.body.appendChild(canvas);

		var dpr = window.devicePixelRatio || 1;
		canvas.width  = window.innerWidth  * dpr;
		canvas.height = window.innerHeight * dpr;
		var ctx = canvas.getContext('2d');
		ctx.scale(dpr, dpr);

		var W = window.innerWidth;
		var H = window.innerHeight;
		var particles = [];
		for (var i = 0; i < count; i++) {
			particles.push({
				x:  W / 2 + (Math.random() - 0.5) * 200,
				y:  H / 3,
				vx: (Math.random() - 0.5) * 12,
				vy: -Math.random() * 14 - 6,
				size: Math.random() * 8 + 4,
				color: COLORS[i % COLORS.length],
				rot: Math.random() * Math.PI * 2,
				vr:  (Math.random() - 0.5) * 0.3,
				life: 1
			});
		}

		var start = performance.now();
		function tick(now) {
			var t = (now - start) / 1000;
			ctx.clearRect(0, 0, W, H);
			var alive = false;
			for (var j = 0; j < particles.length; j++) {
				var p = particles[j];
				if (p.life <= 0) { continue; }
				alive = true;
				p.vy += 0.45;          // gravity
				p.vx *= 0.99;
				p.x  += p.vx;
				p.y  += p.vy;
				p.rot += p.vr;
				p.life = Math.max(0, 1 - t / 5);

				ctx.save();
				ctx.translate(p.x, p.y);
				ctx.rotate(p.rot);
				ctx.fillStyle = p.color;
				ctx.globalAlpha = p.life;
				ctx.fillRect(-p.size / 2, -p.size / 2, p.size, p.size * 0.6);
				ctx.restore();
			}
			if (alive) {
				requestAnimationFrame(tick);
			} else {
				canvas.remove();
			}
		}
		requestAnimationFrame(tick);
	}

	window.cartcueConfetti = fire;

	// -------------------------------------------------------------------
	// First-activation modal
	// -------------------------------------------------------------------

	function getConfig() {
		return (window.cartcueAdmin && window.cartcueAdmin.buildFeatures) || {};
	}

	function getStrings() {
		var cfg = getConfig();
		return (cfg && cfg.strings) || {};
	}

	function getForecastFor(triggerSlug) {
		var cfg = getConfig();
		var fc  = cfg && cfg.forecast;
		if (!fc) { return null; }
		return fc[triggerSlug] || null;
	}

	function markSeenOnServer() {
		var cfg = getConfig();
		if (!cfg || !cfg.firstActSeenNonce) { return; }
		if (!window.cartcueAdmin || !cartcueAdmin.ajaxUrl) { return; }
		var fd = new FormData();
		fd.append('action', 'cartcue_first_activation_seen');
		fd.append('nonce',  cfg.firstActSeenNonce);
		fetch(cartcueAdmin.ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' });
	}

	function escapeHtml(s) {
		return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
			return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c];
		});
	}

	function hideDuplicateActivationUi() {
		var banner = document.getElementById('ap-activate-banner');
		if (banner) { banner.remove(); }
		document.querySelectorAll('.ap-wrap > .notice.notice-success').forEach(function (el) {
			el.remove();
		});
	}

	function resolveActivatedPlay() {
		var cfg = getConfig();
		var act = (cfg && cfg.activation) || {};
		var name = (act.playName || '').trim();
		var triggerSlug = act.triggerSlug || '';

		var highlight = document.getElementById('cartcue-highlight-play');
		var card = highlight || null;
		if (!card) {
			var firstActive = document.querySelector('.ap-play-card .ap-toggle-link.is-on');
			card = firstActive ? firstActive.closest('.ap-play-card') : null;
		}

		if (!name && card) {
			var nameEl = card.querySelector('.ap-play-name');
			name = nameEl ? (nameEl.textContent || '').trim() : '';
		}
		if (!triggerSlug && card && card.dataset) {
			triggerSlug = card.dataset.triggerSlug || '';
		}

		return { name: name, triggerSlug: triggerSlug };
	}

	function showModal(forecast, playName) {
		var s = getStrings();
		var note = forecast && forecast.note ? forecast.note : '';
		var formatted = forecast && forecast.formatted ? forecast.formatted : '';
		var truth = s.celebrateTruth || "We'll track real revenue as it happens — no inflated numbers, just what your store actually recovered.";

		hideDuplicateActivationUi();

		var html =
			'<div class="ap-celebrate-backdrop" data-celebrate></div>' +
			'<div class="ap-celebrate-modal" role="dialog" aria-modal="true" aria-labelledby="ap-celebrate-title">' +
				'<div class="ap-celebrate-modal__icon" aria-hidden="true">🎉</div>' +
				'<h2 id="ap-celebrate-title" class="ap-celebrate-modal__title">' +
					escapeHtml(s.celebrateTitle || "You're live. 🎉") +
				'</h2>' +
				(playName
					? '<p class="ap-celebrate-modal__sub"><strong>' + escapeHtml(playName) + '</strong> is now sending.</p>'
					: ''
				) +
				(formatted
					? '<div class="ap-celebrate-modal__forecast">' +
						'<span class="ap-celebrate-modal__forecast-num">' + escapeHtml(formatted) + '</span>' +
						'<span class="ap-celebrate-modal__forecast-period">/ month, typical</span>' +
					  '</div>'
					: ''
				) +
				(note
					? '<p class="ap-celebrate-modal__note">' + escapeHtml(note) + '</p>'
					: ''
				) +
				'<p class="ap-celebrate-modal__truth">' + escapeHtml(truth) + '</p>' +
				'<button type="button" class="ap-celebrate-modal__cta" data-celebrate-close>' +
					escapeHtml(s.celebrateClose || 'Show me the dashboard') +
				'</button>' +
			'</div>';

		var wrap = document.createElement('div');
		wrap.className = 'ap-celebrate-wrap';
		wrap.innerHTML = html;
		document.body.appendChild(wrap);

		// Animate in.
		requestAnimationFrame(function () { wrap.classList.add('is-open'); });

		// Fire confetti staggered.
		setTimeout(function () { fire({ count: 90 }); }, 250);
		setTimeout(function () { fire({ count: 60 }); }, 800);

		function close() {
			wrap.classList.remove('is-open');
			setTimeout(function () { wrap.remove(); }, 320);
			markSeenOnServer();
		}
		wrap.addEventListener('click', function (e) {
			if (e.target.matches('[data-celebrate], [data-celebrate-close]')) { close(); }
		});
		document.addEventListener('keydown', function onEsc(e) {
			if (e.key === 'Escape') { close(); document.removeEventListener('keydown', onEsc); }
		});
	}

	// -------------------------------------------------------------------
	// Trigger logic.
	// Fires when the plays list URL has ?ap_activated=… AND this user has
	// never seen the modal before.
	// -------------------------------------------------------------------

	function maybeShowOnActivate() {
		var cfg = getConfig();
		if (!cfg) { return; }
		if (cfg.firstActivationShown) { return; }

		var params = new URLSearchParams(window.location.search);
		if (!params.has('ap_activated')) {
			return;
		}

		var play = resolveActivatedPlay();
		var forecast = getForecastFor(play.triggerSlug || 'cart_abandoned')
			|| getForecastFor('cart_abandoned');

		showModal(forecast, play.name);
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', maybeShowOnActivate);
	} else {
		maybeShowOnActivate();
	}

})();
