(function ($) {
	'use strict';

	var adminVars = window.noesia_admin_vars || {};
	var adminStrings = adminVars.strings || {};

	function t(key) {
		if (
			adminStrings &&
			Object.prototype.hasOwnProperty.call(adminStrings, key) &&
			adminStrings[key] !== undefined &&
			adminStrings[key] !== null &&
			String(adminStrings[key]) !== ''
		) {
			return String(adminStrings[key]);
		}

		return key;
	}

	function getAjaxUrl() {
		return adminVars.ajax_url || window.ajaxurl || '';
	}

	function getNonce() {
		return adminVars.nonce || '';
	}

	function text(value) {
		return value === undefined || value === null ? '' : String(value);
	}

	function setLoading($root, isLoading) {
		$root.toggleClass('is-loading', !!isLoading);
	}

	function setStatus($target, message, type) {
		if (!$target.length) {
			return;
		}

		$target
			.removeClass('is-error is-success is-working')
			.addClass(type ? 'is-' + type : '')
			.text(message || '');
	}

	function setInstallStatus($root, message, type) {
		setStatus($root.find('[data-synapse-install-status]'), message, type);
	}

	function setSettingsStatus($root, message, type) {
		setStatus($root.find('[data-synapse-settings-status]'), message, type);
	}

	function setSetup($root, isOpen) {
		var $panel = $root.find('[data-synapse-setup]');

		$panel.toggleClass('is-open', !!isOpen);
		$panel.attr('aria-hidden', isOpen ? 'false' : 'true');
	}

	function setAnswerWrap($root, isOpen) {
		var $panel = $root.find('[data-synapse-answer-wrap]');

		$panel.toggleClass('is-open', !!isOpen);
		$panel.attr('aria-hidden', isOpen ? 'false' : 'true');
	}

	function renderError($root, message) {
		$root.find('[data-synapse-answer]').text(message || t('project_synapse_request_failed'));
		setAnswerWrap($root, true);
	}

	function renderAnswer($root, payload) {
		var data = payload || {};

		$root.find('[data-synapse-answer]').text(data.answer || '');
		setAnswerWrap($root, true);
		appendHistory($root, text($root.data('synapse-last-question')), data.answer || '');
	}

	function getSceneHistory($root) {
		var scene = text($root.attr('data-current-scene')).trim() || 'default';
		var all = $root.data('synapse-history') || {};

		if (!all[scene]) {
			all[scene] = [];
			$root.data('synapse-history', all);
		}

		return all[scene];
	}

	function appendHistory($root, question, answer) {
		var history = getSceneHistory($root);

		if (!question || !answer) {
			return;
		}

		history.push({
			question: question,
			answer: answer
		});

		if (history.length > 6) {
			history.splice(0, history.length - 6);
		}
	}

	function serializeHistory($root) {
		return JSON.stringify(getSceneHistory($root).slice(-6));
	}

	function activateScene($root, $button) {
		var image = $button.data('synapse-scene-image') || '';
		var title = $button.data('synapse-scene-title') || '';
		var kicker = $button.data('synapse-scene-kicker') || '';
		var mode = $button.data('synapse-scene-mode') || '';
		var description = $button.data('synapse-scene-description') || '';
		var question = $button.data('synapse-scene-question') || '';
		var microcopy = $button.data('synapse-scene-microcopy') || '';
		var key = $button.data('synapse-scene-key') || '';

		$root.find('[data-synapse-scene]').removeClass('is-active');
		$button.addClass('is-active');

		if (image) {
			$root.css('--synapse-bg', 'url("' + image + '")');
		}

		$root.attr('data-current-scene', key);
		$root.attr('data-current-mode', mode || 'meaning-library');
		$root.find('[data-synapse-stage-kicker]').text(kicker || (mode === 'aether' ? t('project_synapse_aether_kicker') : t('project_synapse_default_kicker')));
		$root.find('[data-synapse-stage-title]').text(title);
		$root.find('[data-synapse-stage-description]').text(description);
		$root.find('[data-synapse-mini-note]').text(microcopy || description);
		$root.find('[data-synapse-question]').attr('placeholder', question || t('project_synapse_default_question_placeholder'));
		setAnswerWrap($root, false);

		if (mode === 'aether') {
			$root.addClass('is-focus');
			$root.find('[data-synapse-question]').trigger('focus');
		}
	}

	function releaseToAether($root) {
		var $textarea = $root.find('[data-synapse-question]');
		var message = text($textarea.val()).trim();

		if (!message) {
			renderError($root, t('project_synapse_aether_release_first'));
			return;
		}

		if ($root.hasClass('is-aether-releasing')) {
			return;
		}

		var releaseDuration = 10000;
		var releaseHold = 11800;
		var letters = message.replace(/\s+/g, ' ').slice(0, 180).split('');
		var $field = $root.find('[data-synapse-release-field]');
		var centerX = ($root.outerWidth() || window.innerWidth) / 2;
		var centerY = ($root.outerHeight() || window.innerHeight) * 0.52;
		var dustCount = Math.max(260, letters.length * 6);

		$root.addClass('is-aether-releasing');
		setAnswerWrap($root, false);
		$field.addClass('is-active').empty();
		$textarea.css({
			transition: 'opacity 8.8s ease-out, filter 9.2s ease-out, transform 9.6s ease-out, letter-spacing 9.6s ease-out',
			opacity: '0',
			filter: 'blur(18px)',
			transform: 'translateY(-58px) scale(.94)',
			'letter-spacing': '.24em'
		});

		letters.forEach(function (letter, index) {
			var $particle = $('<span class="noesia-swa-synapse__particle"></span>').text(letter);
			var drift = (Math.random() * 760) - 380;
			var depthPull = 420 + Math.random() * 1080;
			var delay = Math.min(2600, index * 32) + Math.random() * 420;
			var dx = drift.toFixed(0) + 'px';
			var dy = (0 - depthPull).toFixed(0) + 'px';
			var spin = ((Math.random() > 0.5 ? 1 : -1) * (260 + Math.random() * 980)).toFixed(0) + 'deg';

			$particle.css({
				left: (centerX + (index - letters.length / 2) * 8) + 'px',
				top: centerY + 'px',
				'--dx': dx,
				'--dy': dy,
				'--spin': spin,
				'animation-duration': releaseDuration + 'ms',
				'animation-delay': delay + 'ms'
			});

			$field.append($particle);
			window.setTimeout(function () {
				$particle.remove();
			}, releaseDuration + delay + 700);
		});

		for (var i = 0; i < dustCount; i++) {
			(function () {
				var $dust = $('<span class="noesia-swa-synapse__particle is-dust"></span>');
				var delay = Math.random() * 2800;
				var drift = (Math.random() * 980) - 490;
				var depthPull = 260 + Math.random() * 1160;

				$dust.css({
					left: (centerX + (Math.random() * 180 - 90)) + 'px',
					top: (centerY + (Math.random() * 92 - 46)) + 'px',
					'--dx': drift.toFixed(0) + 'px',
					'--dy': (0 - depthPull).toFixed(0) + 'px',
					'--spin': ((Math.random() > 0.5 ? 1 : -1) * (120 + Math.random() * 720)).toFixed(0) + 'deg',
					'animation-duration': releaseDuration + 'ms',
					'animation-delay': delay + 'ms'
				});

				$field.append($dust);
				window.setTimeout(function () {
					$dust.remove();
				}, releaseDuration + delay + 700);
			})();
		}

		window.setTimeout(function () {
			$root.find('[data-synapse-answer]').text(t('project_synapse_aether_released'));
			setAnswerWrap($root, true);
			$root.find('[data-synapse-answer]').css({
				opacity: '0',
				transition: 'opacity 3s ease-in'
			});
		}, 7600);

		window.setTimeout(function () {
			$root.find('[data-synapse-answer]').css('opacity', '1');
		}, 8300);

		window.setTimeout(function () {
			$root.removeClass('is-aether-releasing');
			$field.removeClass('is-active').empty();
			$textarea.val('').css({
				transition: 'none',
				opacity: '1',
				filter: 'blur(0)',
				transform: 'translateY(0)',
				'letter-spacing': ''
			});
		}, releaseHold);
	}

	function installPack($root) {
		var ajaxUrl = getAjaxUrl();
		var nonce = getNonce();

		if (!ajaxUrl || !nonce) {
			setInstallStatus($root, t('project_synapse_install_missing_endpoint'), 'error');
			renderError($root, t('project_synapse_install_missing_endpoint'));
			setSetup($root, true);
			return;
		}

		setLoading($root, true);
		setSetup($root, true);
		setInstallStatus($root, t('project_synapse_installing'), 'working');

		$.post(ajaxUrl, {
			action: 'noesia_swa_project_synapse_install_pack',
			nonce: nonce
		}).done(function (response) {
			if (!response || !response.success) {
				setInstallStatus($root, response && response.data ? response.data.message : t('project_synapse_install_failed'), 'error');
				return;
			}

			setInstallStatus($root, response.data.message || t('project_synapse_install_success'), 'success');
			$root.find('[data-synapse-pack-pill]').removeClass('is-waiting').addClass('is-ready').text(t('project_synapse_knowledge_ready'));

			window.setTimeout(function () {
				window.location.reload();
			}, 850);
		}).fail(function (xhr) {
			var message = xhr && xhr.responseJSON && xhr.responseJSON.data ? xhr.responseJSON.data.message : '';
			setInstallStatus($root, message || t('project_synapse_install_failed_detailed'), 'error');
		}).always(function () {
			setLoading($root, false);
		});
	}

	function saveSettings($root) {
		var ajaxUrl = getAjaxUrl();
		var nonce = getNonce();
		var apiKey = text($root.find('[data-synapse-openai-key]').val()).trim();
		var model = text($root.find('[data-synapse-openai-model]').val()).trim();

		if (!ajaxUrl || !nonce) {
			setSettingsStatus($root, t('project_synapse_settings_missing_endpoint'), 'error');
			return;
		}

		setLoading($root, true);
		setSettingsStatus($root, t('project_synapse_settings_saving'), 'working');

		$.post(ajaxUrl, {
			action: 'noesia_swa_project_synapse_save_settings',
			nonce: nonce,
			api_key: apiKey,
			model: model
		}).done(function (response) {
			var settings = response && response.data && response.data.settings ? response.data.settings : {};

			if (!response || !response.success) {
				setSettingsStatus($root, response && response.data ? response.data.message : t('project_synapse_settings_save_failed'), 'error');
				return;
			}

			setSettingsStatus($root, response.data.message || t('project_synapse_settings_saved'), 'success');
			$root.find('[data-synapse-openai-key]').val('').attr('placeholder', settings.openai_masked || t('project_synapse_openai_key_saved'));
			$root.find('[data-synapse-openai-pill]').removeClass('is-waiting').addClass('is-ready').text(t('project_synapse_ai_ready'));
			$root.find('[data-synapse-openai-status-text]').text(t('project_synapse_openai_key_saved'));
		}).fail(function (xhr) {
			var message = xhr && xhr.responseJSON && xhr.responseJSON.data ? xhr.responseJSON.data.message : '';
			setSettingsStatus($root, message || t('project_synapse_settings_save_failed_detailed'), 'error');
		}).always(function () {
			setLoading($root, false);
		});
	}

	function askSynapse($root) {
		var question = text($root.find('[data-synapse-question]').val()).trim();
		var mode = text($root.attr('data-current-mode')).trim() || 'meaning-library';
		var scene = text($root.attr('data-current-scene')).trim() || '';
		var history = serializeHistory($root);

		if (!question) {
			renderError($root, t('project_synapse_empty_question'));
			return;
		}

		setLoading($root, true);
		$root.data('synapse-last-question', question);
		$root.find('[data-synapse-answer]').text(t('project_synapse_thinking'));
		setAnswerWrap($root, true);

		$.post(getAjaxUrl(), {
			action: 'noesia_swa_project_synapse_ask',
			nonce: getNonce(),
			question: question,
			mode: mode,
			scene: scene,
			history: history
		}).done(function (response) {
			if (!response || !response.success) {
				renderError($root, response && response.data ? response.data.message : '');
				return;
			}

			renderAnswer($root, response.data || {});
		}).fail(function (xhr) {
			var message = xhr && xhr.responseJSON && xhr.responseJSON.data ? xhr.responseJSON.data.message : '';
			renderError($root, message || t('project_synapse_answer_failed'));
		}).always(function () {
			setLoading($root, false);
		});
	}

	function initRoot(root) {
		var $root = $(root);

		if ($root.data('synapse-ready')) {
			return;
		}

		$root.data('synapse-ready', true);

		$root.on('click', '[data-synapse-scene]', function () {
			activateScene($root, $(this));
		});

		$root.on('click', '[data-synapse-install]', function () {
			installPack($root);
		});

		$root.on('click', '[data-synapse-save-settings]', function () {
			saveSettings($root);
		});

		$root.on('click', '[data-synapse-ask]', function () {
			askSynapse($root);
		});

		$root.on('click', '[data-synapse-release]', function () {
			releaseToAether($root);
		});

		$root.on('click', '[data-synapse-open-setup]', function () {
			setSetup($root, true);
		});

		$root.on('click', '[data-synapse-close-setup]', function () {
			setSetup($root, false);
		});

		$root.on('click', '[data-synapse-setup]', function (event) {
			if (event.target === this) {
				setSetup($root, false);
			}
		});

		$root.on('click', '[data-synapse-open-aether]', function () {
			var $aether = $root.find('[data-synapse-scene-key="aether"]');

			if ($aether.length) {
				activateScene($root, $aether);
			}
		});

		$root.on('focus click input', '[data-synapse-question], [data-synapse-query-box]', function () {
			$root.addClass('is-focus');
		});

		$root.on('click', '[data-synapse-focus-exit]', function () {
			$root.removeClass('is-focus');
			$root.find('[data-synapse-question]').trigger('blur');
		});

		$(document).on('keydown.noesiaSynapse', function (event) {
			if (event.key === 'Escape') {
				$root.removeClass('is-focus');
				setSetup($root, false);
				setAnswerWrap($root, false);
			}
		});
	}

	function boot() {
		$('[data-synapse-root]').each(function () {
			initRoot(this);
		});
	}

	window.noesiaSwaAdminModules = window.noesiaSwaAdminModules || {};
	window.noesiaSwaAdminModules.projectSynapse = {
		boot: boot,
		mount: boot,
		init: boot,
		onSectionOpen: boot,
		onShow: boot,
		show: boot
	};

	$(boot);
})(jQuery);
