/**
 * AI Summarize — optional clipboard assist + accessible dialog.
 * Prefill URLs stay on the link href/data-open-url (never stripped when copying).
 */
(function () {
	'use strict';

	var L = typeof wppsAiSummarize === 'object' && wppsAiSummarize ? wppsAiSummarize : {};

	function announce(root, message) {
		if (!root || !message) {
			return;
		}
		var el = root.querySelector('.wpps-ai-summarize__status');
		if (!el) {
			return;
		}
		el.textContent = message;
		window.setTimeout(function () {
			if (el.textContent === message) {
				el.textContent = '';
			}
		}, 4000);
	}

	function copyText(text) {
		if (!text) {
			return Promise.resolve(false);
		}
		if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
			return navigator.clipboard.writeText(text).then(
				function () {
					return true;
				},
				function () {
					return fallbackCopy(text);
				}
			);
		}
		return Promise.resolve(fallbackCopy(text));
	}

	function fallbackCopy(text) {
		var ta = document.createElement('textarea');
		ta.value = text;
		ta.setAttribute('readonly', '');
		ta.style.position = 'fixed';
		ta.style.left = '-9999px';
		ta.style.top = '0';
		document.body.appendChild(ta);
		ta.focus();
		ta.select();
		var ok = false;
		try {
			ok = document.execCommand('copy');
		} catch (e) {
			ok = false;
		}
		document.body.removeChild(ta);
		return ok;
	}

	function openUrl(url, newTab) {
		if (!url) {
			return null;
		}
		if (newTab) {
			var win = window.open(url, '_blank', 'noopener,noreferrer');
			if (win) {
				try {
					win.opener = null;
				} catch (e) {
					/* ignore */
				}
			}
			return win;
		}
		window.location.assign(url);
		return window;
	}

	function openDialog(root) {
		var dialog = root.querySelector('.wpps-ai-summarize__dialog');
		if (!dialog) {
			return;
		}
		dialog.hidden = false;
		var ta = dialog.querySelector('.wpps-ai-summarize__dialog-text');
		var closeBtn = dialog.querySelector('.wpps-ai-summarize__dialog-close');
		if (ta) {
			ta.focus();
			ta.select();
		} else if (closeBtn) {
			closeBtn.focus();
		}
	}

	function closeDialog(root) {
		var dialog = root.querySelector('.wpps-ai-summarize__dialog');
		if (!dialog) {
			return;
		}
		dialog.hidden = true;
	}

	function handleProviderClick(e, link) {
		var root = link.closest('.wpps-ai-summarize');
		if (!root) {
			return;
		}

		var needsClipboard = link.getAttribute('data-clipboard') === '1';
		if (!needsClipboard) {
			// Prefill URL is already in href — allow default navigation.
			return;
		}

		e.preventDefault();

		var prompt = link.getAttribute('data-prompt') || '';
		// Prefer prefilled launch URL; never fall back to a bare base URL.
		var openUrlAttr = link.getAttribute('data-open-url') || link.getAttribute('href') || '';
		var newTab = (link.getAttribute('target') || '') === '_blank';

		var win = openUrl(openUrlAttr, newTab);
		if (newTab && !win) {
			announce(root, L.popupBlocked || 'Pop-up blocked.');
		}

		copyText(prompt).then(function (ok) {
			if (ok) {
				announce(root, L.copied || 'Prompt copied. Paste it into the AI chat if it did not prefill.');
			} else {
				announce(root, L.copyFailed || 'Could not copy the prompt automatically.');
				openDialog(root);
			}
		});
	}

	function onClick(e) {
		var target = e.target;
		if (!target || !target.closest) {
			return;
		}

		var closeEl = target.closest('[data-dialog-close]');
		if (closeEl) {
			var rootClose = closeEl.closest('.wpps-ai-summarize');
			if (rootClose) {
				e.preventDefault();
				closeDialog(rootClose);
			}
			return;
		}

		var copyBtn = target.closest('.wpps-ai-summarize__dialog-copy');
		if (copyBtn) {
			var rootCopy = copyBtn.closest('.wpps-ai-summarize');
			if (!rootCopy) {
				return;
			}
			e.preventDefault();
			var ta = rootCopy.querySelector('.wpps-ai-summarize__dialog-text');
			var text = ta ? ta.value : '';
			if (ta) {
				ta.focus();
				ta.select();
			}
			copyText(text).then(function (ok) {
				announce(rootCopy, ok ? (L.copied || 'Prompt copied.') : (L.copyFailed || 'Could not copy.'));
			});
			return;
		}

		var link = target.closest('a.wpps-ai-summarize__btn');
		if (link) {
			handleProviderClick(e, link);
		}
	}

	function onKeydown(e) {
		if (e.key !== 'Escape') {
			return;
		}
		var openDialogs = document.querySelectorAll('.wpps-ai-summarize__dialog:not([hidden])');
		if (!openDialogs.length) {
			return;
		}
		var dialog = openDialogs[openDialogs.length - 1];
		var root = dialog.closest('.wpps-ai-summarize');
		if (root) {
			closeDialog(root);
		}
	}

	document.addEventListener('click', onClick, false);
	document.addEventListener('keydown', onKeydown, false);
})();
