/**
 * Copy text to the system clipboard.
 *
 * Falls back gracefully when the Clipboard API is unavailable (e.g. non-HTTPS
 * or older browsers) by using a temporary textarea element.
 *
 * @returns true when the copy succeeded, false otherwise.
 */
export async function copyToClipboard(text: string): Promise<boolean> {
	if (typeof navigator === 'undefined') return false;

	if (navigator.clipboard?.writeText) {
		try {
			await navigator.clipboard.writeText(text);
			return true;
		} catch {
			// Fall through to legacy path.
		}
	}

	// Legacy fallback via execCommand.
	try {
		const textarea = document.createElement('textarea');
		textarea.value = text;
		textarea.style.position = 'fixed';
		textarea.style.opacity = '0';
		document.body.appendChild(textarea);
		textarea.focus();
		textarea.select();
		const ok = document.execCommand('copy');
		document.body.removeChild(textarea);
		return ok;
	} catch {
		return false;
	}
}
