const handleCopy = (text: string) => {
  // 首先尝试使用现代浏览器的 Clipboard API
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text)
      .then(() => {
        showToast('复制成功');
      })
      .catch((error) => {
        console.error('Copy failed:', error);
        fallbackCopyTextToClipboard(text);  // Clipboard API 失败后,使用降级方案
      });
  } else {
    // 如果不支持 Clipboard API,则使用降级方案
    fallbackCopyTextToClipboard(text);
  }
};

const fallbackCopyTextToClipboard = (text: string) => {
  // 创建一个临时的 textarea 元素
  const textArea = document.createElement('textarea');
  textArea.value = text;

  // 使 textarea 不在可视区域内,但仍可被访问
  textArea.style.position = 'fixed';
  textArea.style.top = '-9999px';
  textArea.style.left = '-9999px';
  textArea.style.opacity = '0';

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    // 执行复制操作
    const successful = document.execCommand('copy');
    if (successful) {
      showToast('复制成功');
    } else {
      showToast('复制失败');
    }
  } catch (err) {
    console.error('Fallback: Oops, unable to copy', err);
    showToast('复制失败');
  } finally {
    // 移除临时的 textarea 元素
    document.body.removeChild(textArea);
  }
};

export default handleCopy;