const copyWithNavigatorClipboard = async (text: string): Promise<boolean> => {
  if (
    typeof navigator === 'undefined' ||
    !navigator.clipboard?.writeText ||
    (typeof window !== 'undefined' && window.isSecureContext === false)
  ) {
    return false;
  }

  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    return false;
  }
};

const copyWithFallback = (text: string): boolean => {
  if (
    typeof document === 'undefined' ||
    !document.body ||
    typeof document.execCommand !== 'function'
  ) {
    return false;
  }

  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.setAttribute('readonly', '');
  textarea.style.position = 'fixed';
  textarea.style.top = '-9999px';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);

  const selection = document.getSelection();
  const originalRange = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;

  textarea.focus();
  textarea.select();
  textarea.setSelectionRange(0, textarea.value.length);

  let copied = false;
  try {
    copied = document.execCommand('copy');
  } catch {
    copied = false;
  }

  document.body.removeChild(textarea);

  if (originalRange && selection) {
    selection.removeAllRanges();
    selection.addRange(originalRange);
  }

  return copied;
};

export const copyTextToClipboard = async (text: string): Promise<boolean> => (
  (await copyWithNavigatorClipboard(text)) || copyWithFallback(text)
);
