chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.target === 'offscreen-doc' && message.type === 'copy-to-clipboard') {
    const text = message.data;
    const textArea = document.getElementById('text-to-copy');
    
    if (textArea) {
      textArea.value = text;
      textArea.select();
      
      try {
        if (navigator.clipboard) {
          navigator.clipboard.writeText(text)
            .then(() => sendResponse({ success: true }))
            .catch(err => {
              console.error('Clipboard API write failed:', err);
              // Fallback to execCommand
              document.execCommand('copy');
              sendResponse({ success: true });
            });
          return true; // Keep message channel open for async response
        } else {
          document.execCommand('copy');
          sendResponse({ success: true });
        }
      } catch (err) {
        console.error('Copy failed:', err);
        sendResponse({ success: false, error: err.message });
      }
    } else {
      sendResponse({ success: false, error: 'Textarea not found' });
    }
  }
});
