/**
 * Kantan Analytics — AI prompt modal handler.
 *
 * Event-delegated, so a single bound instance covers every prompt row/modal on
 * the page. Opens/closes the modal and copies a prompt to the clipboard,
 * prefixing it with the target subagent name so the copied text delegates to
 * the right Kantan agent.
 */
(function () {
	if (window.__kantanAiInit) {
		return;
	}
	window.__kantanAiInit = true;
	document.addEventListener('click', function (e) {
		var open = e.target.closest('[data-ai-open]');
		if (open) {
			var m = document.getElementById('kantan-ai-modal-' + open.getAttribute('data-ai-open'));
			if (m) {
				m.classList.remove('hidden');
			}
			return;
		}
		if (e.target.closest('[data-ai-close]')) {
			var md = e.target.closest('.kantan-ai-modal');
			if (md) {
				md.classList.add('hidden');
			}
			return;
		}
		var copy = e.target.closest('[data-ai-copy]');
		if (copy) {
			var row = copy.closest('.kantan-ai-row');
			var pre = row ? row.querySelector('[data-ai-prompt]') : null;
			if (!pre) {
				return;
			}
			// Prepend the subagent name so the copied prompt delegates to the
			// right Kantan agent (works in Claude Code, Gemini CLI, and any
			// tool that invokes subagents by name). Displayed text is unchanged.
			var modalEl = copy.closest('.kantan-ai-modal');
			var agentName = modalEl ? modalEl.getAttribute('data-ai-agent') : '';
			var text = pre.textContent.trim();
			if (agentName) {
				text = 'Use the ' + agentName + ': ' + text;
			}
			navigator.clipboard.writeText(text).then(function () {
				var orig = copy.textContent;
				copy.textContent = (window.kantanAiL10n && window.kantanAiL10n.copied) || 'Copied!';
				setTimeout(function () {
					copy.textContent = orig;
				}, 1500);
			});
		}
	});
	document.addEventListener('keydown', function (e) {
		if (e.key === 'Escape') {
			document.querySelectorAll('.kantan-ai-modal:not(.hidden)').forEach(function (m) {
				m.classList.add('hidden');
			});
		}
	});
})();
