// Content script to capture text selection
let debounceTimer = null;

document.addEventListener('mouseup', (event) => {
  // Clear previous timer
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }

  // Debounce to avoid too many updates
  debounceTimer = setTimeout(() => {
    const selection = window.getSelection();
    const selectedText = selection?.toString().trim();

    if (selectedText && selectedText.length > 0 && selectedText.length < 100) {
      // Extract first word only for dictionary lookup
      const firstWord = selectedText.split(/\s+/)[0].replace(/[^\w'-]/g, '');

      if (firstWord && firstWord.length >= 2) {
        chrome.storage.local.set({
          selectedText: firstWord,
          pageUrl: window.location.href
        });
      }
    }
  }, 300);
});

// Also capture on keyboard selection (Shift+Arrow keys)
document.addEventListener('keyup', (event) => {
  if (event.shiftKey) {
    if (debounceTimer) {
      clearTimeout(debounceTimer);
    }

    debounceTimer = setTimeout(() => {
      const selection = window.getSelection();
      const selectedText = selection?.toString().trim();

      if (selectedText && selectedText.length > 0 && selectedText.length < 100) {
        const firstWord = selectedText.split(/\s+/)[0].replace(/[^\w'-]/g, '');

        if (firstWord && firstWord.length >= 2) {
          chrome.storage.local.set({
            selectedText: firstWord,
            pageUrl: window.location.href
          });
        }
      }
    }, 300);
  }
});
