/**
 * UX-212: Clipboard utility with graceful fallback.
 *
 * navigator.clipboard.writeText can reject in several cases:
 *   - Permissions denied (browser policy / user choice)
 *   - Non-secure context (HTTP)
 *   - Safari gesture-timing restriction
 *
 * The execCommand fallback covers most of those cases in older/restricted envs.
 */

import { toast } from 'sonner';

/**
 * Copy text to the clipboard. Returns true on success, false on failure.
 *
 * On failure shows a toast instructing the user to copy manually and ensures
 * the copy target stays user-selectable so they can Ctrl+A / Cmd+A.
 *
 * @param text - The text to copy
 * @returns Promise<boolean> — true if copy succeeded
 */
export async function copyToClipboard(text: string): Promise<boolean> {
  // Modern path — available in secure contexts with permission
  if (navigator.clipboard?.writeText) {
    try {
      await navigator.clipboard.writeText(text);
      return true;
    } catch {
      // Fall through to legacy path
    }
  }

  // Legacy execCommand path — works in most non-secure / permission-denied cases
  try {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    // Keep off-screen but readable so screen readers and selection still work
    textarea.style.position = 'fixed';
    textarea.style.top = '0';
    textarea.style.left = '0';
    textarea.style.opacity = '0';
    textarea.setAttribute('aria-hidden', 'true');
    document.body.appendChild(textarea);
    textarea.focus();
    textarea.select();
    const success = document.execCommand('copy');
    document.body.removeChild(textarea);
    if (success) return true;
  } catch {
    // Fall through to error toast
  }

  // Both paths failed — tell the user to copy manually
  toast.error("Couldn't copy — select the text and copy manually.");
  return false;
}
