/**
 * Dashboard Gamification UI
 *
 * Handles achievement celebration modal and confetti animation
 * for the usage statistics dashboard.
 *
 * @file
 * @since 1.0.0
 * @package AgenticWP
 * @namespace AgenticWPAdmin.dashboardGamification
 */

(function($) {
	'use strict';

	const AgenticWPAdmin = window.AgenticWPAdmin = window.AgenticWPAdmin || {};

	/**
	 * Achievement modal element.
	 *
	 * @type {jQuery|null}
	 */
	let $modal = null;

	/**
	 * Confetti canvas element.
	 *
	 * @type {HTMLCanvasElement|null}
	 */
	let confettiCanvas = null;

	/**
	 * Confetti animation frame ID.
	 *
	 * @type {number|null}
	 */
	let confettiAnimationId = null;

	/**
	 * Tier colors for badges.
	 *
	 * @type {Object}
	 */
	const tierColors = {
		bronze: {
			primary: '#CD7F32',
			gradient: ['#E8A87C', '#CD7F32', '#8B5A2B']
		},
		silver: {
			primary: '#C0C0C0',
			gradient: ['#E8E8E8', '#C0C0C0', '#A8A8A8']
		},
		gold: {
			primary: '#FFD700',
			gradient: ['#FFE066', '#FFD700', '#DAA520']
		},
		platinum: {
			primary: '#E5E4E2',
			gradient: ['#F5F5F5', '#E5E4E2', '#B8B8B8']
		}
	};

	/**
	 * Initializes gamification features.
	 */
	function init() {
		createModal();
		createConfettiCanvas();
		bindEvents();

		// Check for newly unlocked achievements passed from PHP.
		checkNewAchievements();
	}

	/**
	 * Creates the achievement celebration modal.
	 */
	function createModal() {
		if ($('#agenticwp-achievement-modal').length) {
			$modal = $('#agenticwp-achievement-modal');
			return;
		}

		const modalHtml = `
			<div id="agenticwp-achievement-modal" class="agenticwp-modal" aria-hidden="true" role="dialog" aria-modal="true" aria-labelledby="agenticwp-modal-title">
				<div class="agenticwp-modal-backdrop"></div>
				<div class="agenticwp-modal-content">
					<button type="button" class="agenticwp-modal-close" aria-label="Close">&times;</button>
					<div class="agenticwp-modal-header">
						<span class="agenticwp-modal-confetti-text">🎉</span>
						<h2 id="agenticwp-modal-title" class="agenticwp-modal-title">Achievement Unlocked!</h2>
					</div>
					<div class="agenticwp-modal-body">
						<div class="agenticwp-modal-badge-container">
							<div class="agenticwp-modal-badge"></div>
							<div class="agenticwp-modal-badge-glow"></div>
						</div>
						<h3 class="agenticwp-modal-achievement-name"></h3>
						<p class="agenticwp-modal-achievement-desc"></p>
						<span class="agenticwp-modal-tier-badge"></span>
					</div>
					<div class="agenticwp-modal-footer">
						<button type="button" class="agenticwp-modal-btn agenticwp-modal-btn-primary">Awesome!</button>
					</div>
				</div>
			</div>
		`;

		$('body').append(modalHtml);
		$modal = $('#agenticwp-achievement-modal');
	}

	/**
	 * Creates the confetti canvas element.
	 */
	function createConfettiCanvas() {
		if (document.getElementById('agenticwp-confetti-canvas')) {
			confettiCanvas = document.getElementById('agenticwp-confetti-canvas');
			return;
		}

		confettiCanvas = document.createElement('canvas');
		confettiCanvas.id = 'agenticwp-confetti-canvas';
		confettiCanvas.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:999999;';
		document.body.appendChild(confettiCanvas);
	}

	/**
	 * Binds event handlers.
	 */
	function bindEvents() {
		$(document).on('click', '.agenticwp-modal-close, .agenticwp-modal-backdrop, .agenticwp-modal-btn-primary', closeModal);
		$(document).on('keydown', function(e) {
			if (e.key === 'Escape' && $modal && $modal.hasClass('is-open')) {
				closeModal();
			}
		});

		// Listen for achievement unlocked events from other parts of the app.
		$(document).on('agenticwp:achievement_unlocked', function(e, achievement) {
			showAchievement(achievement);
		});
	}

	/**
	 * Checks for newly unlocked achievements.
	 */
	function checkNewAchievements() {
		const data = window.agenticwpDashboard || {};
		const newAchievements = data.newAchievements || [];

		if (newAchievements.length > 0) {
			// Show achievements with a slight delay between each.
			showAchievementQueue(newAchievements);
		}
	}

	/**
	 * Shows a queue of achievements one by one.
	 *
	 * @param {Array} achievements List of achievements to show.
	 * @param {number} index Current index.
	 */
	function showAchievementQueue(achievements, index = 0) {
		if (index >= achievements.length) {
			return;
		}

		showAchievement(achievements[index], function() {
			setTimeout(function() {
				showAchievementQueue(achievements, index + 1);
			}, 500);
		});
	}

	/**
	 * Shows an achievement celebration modal.
	 *
	 * @param {Object} achievement Achievement data.
	 * @param {Function} callback Callback after modal closes.
	 */
	function showAchievement(achievement, callback) {
		if (!$modal || !achievement) {
			return;
		}

		const tier = achievement.tier || 'bronze';
		const colors = tierColors[tier] || tierColors.bronze;

		// Update modal content.
		$modal.find('.agenticwp-modal-achievement-name').text(achievement.name || 'Achievement');
		$modal.find('.agenticwp-modal-achievement-desc').text(achievement.description || '');
		$modal.find('.agenticwp-modal-tier-badge')
			.text(tier.charAt(0).toUpperCase() + tier.slice(1))
			.css('background-color', colors.primary);

		// Create badge SVG.
		const badgeHtml = createBadgeSvg(tier, achievement.icon || '🏆', 120);
		$modal.find('.agenticwp-modal-badge').html(badgeHtml);
		$modal.find('.agenticwp-modal-badge-glow').css('background-color', colors.primary);

		// Store callback.
		$modal.data('closeCallback', callback);

		// Open modal with animation.
		$modal.addClass('is-open').attr('aria-hidden', 'false');
		$('body').addClass('agenticwp-modal-open');

		// Trigger confetti for gold and platinum achievements.
		if (tier === 'gold' || tier === 'platinum') {
			fireConfetti(colors.primary);
		}
	}

	/**
	 * Creates an SVG badge with emoji.
	 *
	 * @param {string} tier Achievement tier.
	 * @param {string} icon Emoji icon.
	 * @param {number} size Badge size.
	 * @return {string} Badge HTML.
	 */
	function createBadgeSvg(tier, icon, size) {
		const colors = tierColors[tier] || tierColors.bronze;
		const id = 'modal-badge-' + Math.random().toString(36).substr(2, 9);

		const sparkle = tier === 'platinum'
			? `<path d="M32 8 L33.5 12 L38 12 L34.5 14.5 L36 19 L32 16 L28 19 L29.5 14.5 L26 12 L30.5 12 Z" fill="${colors.primary}" opacity="0.8"/>`
			: '';

		return `
			<div class="agenticwp-modal-badge-wrapper">
				<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="${size}" height="${size}" fill="none" class="agenticwp-modal-badge-svg">
					<defs>
						<linearGradient id="${id}-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
							<stop offset="0%" style="stop-color:${colors.gradient[0]}"/>
							<stop offset="50%" style="stop-color:${colors.gradient[1]}"/>
							<stop offset="100%" style="stop-color:${colors.gradient[2]}"/>
						</linearGradient>
					</defs>
					<circle cx="32" cy="32" r="28" fill="url(#${id}-gradient)"/>
					<circle cx="32" cy="32" r="24" fill="#FEFEFE" stroke="${colors.gradient[1]}" stroke-width="2"/>
					<circle cx="32" cy="32" r="20" fill="none" stroke="${colors.gradient[1]}" stroke-width="1" stroke-dasharray="3 3" opacity="0.5"/>
					${sparkle}
				</svg>
				<span class="agenticwp-modal-badge-emoji">${icon}</span>
			</div>
		`;
	}

	/**
	 * Closes the achievement modal.
	 */
	function closeModal() {
		if (!$modal) {
			return;
		}

		$modal.removeClass('is-open').attr('aria-hidden', 'true');
		$('body').removeClass('agenticwp-modal-open');

		// Execute callback if exists.
		const callback = $modal.data('closeCallback');
		if (typeof callback === 'function') {
			callback();
			$modal.removeData('closeCallback');
		}
	}

	/**
	 * Fires confetti animation.
	 *
	 * @param {string} color Primary color for confetti.
	 */
	function fireConfetti(color) {
		if (!confettiCanvas) {
			return;
		}

		const ctx = confettiCanvas.getContext('2d');
		const width = window.innerWidth;
		const height = window.innerHeight;

		confettiCanvas.width = width;
		confettiCanvas.height = height;

		const particles = [];
		const particleCount = 150;
		const colors = [color, '#FFD700', '#FF6B6B', '#4ECDC4', '#1e3a8a', '#F59E0B'];

		// Create particles.
		for (let i = 0; i < particleCount; i++) {
			particles.push({
				x: width / 2 + (Math.random() - 0.5) * 200,
				y: height / 2,
				vx: (Math.random() - 0.5) * 15,
				vy: Math.random() * -20 - 10,
				color: colors[Math.floor(Math.random() * colors.length)],
				size: Math.random() * 8 + 4,
				rotation: Math.random() * 360,
				rotationSpeed: (Math.random() - 0.5) * 10,
				gravity: 0.3 + Math.random() * 0.2,
				opacity: 1,
				shape: Math.random() > 0.5 ? 'rect' : 'circle'
			});
		}

		// Cancel any existing animation.
		if (confettiAnimationId) {
			cancelAnimationFrame(confettiAnimationId);
		}

		let frame = 0;
		const maxFrames = 180;

		/**
		 * Animation loop.
		 */
		function animate() {
			ctx.clearRect(0, 0, width, height);

			particles.forEach(function(p) {
				p.vy += p.gravity;
				p.x += p.vx;
				p.y += p.vy;
				p.vx *= 0.99;
				p.rotation += p.rotationSpeed;
				p.opacity = Math.max(0, 1 - frame / maxFrames);

				ctx.save();
				ctx.translate(p.x, p.y);
				ctx.rotate((p.rotation * Math.PI) / 180);
				ctx.globalAlpha = p.opacity;
				ctx.fillStyle = p.color;

				if (p.shape === 'rect') {
					ctx.fillRect(-p.size / 2, -p.size / 2, p.size, p.size / 2);
				} else {
					ctx.beginPath();
					ctx.arc(0, 0, p.size / 2, 0, Math.PI * 2);
					ctx.fill();
				}

				ctx.restore();
			});

			frame++;

			if (frame < maxFrames) {
				confettiAnimationId = requestAnimationFrame(animate);
			} else {
				ctx.clearRect(0, 0, width, height);
				confettiAnimationId = null;
			}
		}

		animate();
	}

	/**
	 * Manually triggers an achievement celebration.
	 *
	 * @param {Object} achievement Achievement data with name, description, tier, icon.
	 */
	function celebrate(achievement) {
		showAchievement(achievement);
	}

	/**
	 * Manually triggers confetti without modal.
	 *
	 * @param {string} color Primary color.
	 */
	function triggerConfetti(color) {
		fireConfetti(color || '#FFD700');
	}

	// Export module.
	AgenticWPAdmin.dashboardGamification = {
		init: init,
		celebrate: celebrate,
		confetti: triggerConfetti
	};

	// Initialize on document ready.
	$(document).ready(function() {
		AgenticWPAdmin.dashboardGamification.init();
	});

})(jQuery);
