/**
 * Admin JavaScript for FoodOrd License page.
 *
 * @package Foodord
 */

(function($) {
	'use strict';

	$(document).ready(function() {
		let copyResetTimer = null;

		$('.foodord-license-pricing-toggle').on('click', function() {
			const button = this;
			const targetId = button.getAttribute('aria-controls');
			const target = targetId ? document.getElementById(targetId) : null;
			if (!target) {
				return;
			}

			const expanded = button.getAttribute('aria-expanded') === 'true';
			const nextExpanded = !expanded;
			const label = button.querySelector('.foodord-license-pricing-toggle__label');
			const collapsedLabel = button.getAttribute('data-collapsed-label') || 'See features';
			const expandedLabel = button.getAttribute('data-expanded-label') || 'Hide features';

			button.setAttribute('aria-expanded', nextExpanded ? 'true' : 'false');
			target.hidden = !nextExpanded;
			if (label) {
				label.textContent = nextExpanded ? expandedLabel : collapsedLabel;
			}
		});

		$(document).on('click', '[data-foodord-license-copy]', async function() {
			const button = this;
			const input = document.getElementById('foodord_license_key');
			const value = input ? input.value.trim() : '';

			if (!input || !value) {
				input?.focus();
				return;
			}

			let copied = false;
			if (navigator.clipboard && window.isSecureContext) {
				try {
					await navigator.clipboard.writeText(value);
					copied = true;
				} catch {
					copied = false;
				}
			}

			if (!copied) {
				try {
					input.focus();
					input.select();
					copied = document.execCommand('copy');
					input.setSelectionRange(input.value.length, input.value.length);
				} catch {
					copied = false;
				}
			}

			if (!copied) {
				return;
			}

			const copyLabel = button.getAttribute('data-copy-label') || 'Copy to clipboard';
			const copiedLabel = button.getAttribute('data-copied-label') || 'Copied';

			window.clearTimeout(copyResetTimer);
			button.classList.add('is-copied');
			button.setAttribute('aria-label', copiedLabel);
			button.setAttribute('title', copiedLabel);

			copyResetTimer = window.setTimeout(function() {
				button.classList.remove('is-copied');
				button.setAttribute('aria-label', copyLabel);
				button.setAttribute('title', copyLabel);
			}, 1800);
		});

		// Auto hide notices after 5 seconds
		const $notices = $('.notice.is-dismissible');
		if ($notices.length > 0) {
			setTimeout(function() {
				$notices.fadeOut(500, function() {
					$(this).remove();
				});
			}, 5000);
		}
	});
})(jQuery);
