// ========================================
// Text Vault - Content Script
// ========================================

(function() {
  'use strict';

  let tooltip = null;
  let selectedText = '';

  // Create floating tooltip
  function createTooltip() {
    if (tooltip) return;

    tooltip = document.createElement('div');
    tooltip.id = 'highlightvault-tooltip';
    tooltip.innerHTML = `
      <button class="hv-btn hv-btn-save" data-category="uncategorized" title="Quick Save">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M9 11l-6 6v3h9l3-3"/>
          <path d="m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"/>
        </svg>
      </button>
      <div class="hv-dropdown">
        <button class="hv-btn hv-btn-more" title="More options">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <polyline points="6,9 12,15 18,9"/>
          </svg>
        </button>
        <div class="hv-dropdown-menu">
          <button class="hv-option" data-category="quotes">📝 Quote</button>
          <button class="hv-option" data-category="ideas">💡 Idea</button>
          <button class="hv-option" data-category="research">🔬 Research</button>
          <button class="hv-option" data-category="inspiration">✨ Inspiration</button>
        </div>
      </div>
    `;
    document.body.appendChild(tooltip);

    // Event listeners
    // First click expands, second click saves
    tooltip.querySelector('.hv-btn-save').addEventListener('click', function(e) {
      e.stopPropagation();
      saveSelection('uncategorized');
    });

    tooltip.querySelector('.hv-btn-more').addEventListener('click', function(e) {
      e.stopPropagation();
      tooltip.classList.toggle('hv-dropdown-open');
    });

    tooltip.querySelectorAll('.hv-option').forEach(btn => {
      btn.addEventListener('click', function(e) {
        e.stopPropagation();
        saveSelection(this.dataset.category);
      });
    });
  }

  // Show tooltip near selection (directly expanded)
  function showTooltip(x, y) {
    if (!tooltip) createTooltip();

    tooltip.style.left = `${x}px`;
    tooltip.style.top = `${y - 40}px`;
    tooltip.classList.add('hv-visible', 'hv-expanded');
    tooltip.classList.remove('hv-dropdown-open');
  }

  // Hide tooltip
  function hideTooltip() {
    if (tooltip) {
      tooltip.classList.remove('hv-visible', 'hv-dropdown-open');
    }
  }

  // Save selected text
  function saveSelection(category) {
    if (!selectedText) return;

    chrome.runtime.sendMessage({
      action: 'save-highlight',
      text: selectedText,
      category: category
    }, function(response) {
      if (response && response.success) {
        showSavedFeedback();
      }
    });

    hideTooltip();
    window.getSelection().removeAllRanges();
  }

  // Show saved feedback
  function showSavedFeedback() {
    const feedback = document.createElement('div');
    feedback.id = 'highlightvault-feedback';
    feedback.innerHTML = `
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <polyline points="20,6 9,17 4,12"/>
      </svg>
      Saved to Text Vault
    `;
    document.body.appendChild(feedback);

    setTimeout(() => feedback.classList.add('hv-show'), 10);
    setTimeout(() => {
      feedback.classList.remove('hv-show');
      setTimeout(() => feedback.remove(), 300);
    }, 2000);
  }

  // Listen for text selection
  document.addEventListener('mouseup', function(e) {
    // Ignore if clicking on tooltip
    if (tooltip && tooltip.contains(e.target)) return;

    const selection = window.getSelection();
    const text = selection.toString().trim();

    if (text.length > 0 && text.length < 5000) {
      selectedText = text;
      
      const range = selection.getRangeAt(0);
      const rect = range.getBoundingClientRect();
      
      showTooltip(
        rect.left + window.scrollX + (rect.width / 2) - 40,
        rect.top + window.scrollY
      );
    } else {
      selectedText = '';
      hideTooltip();
    }
  });

  // Hide tooltip on scroll or click elsewhere
  document.addEventListener('mousedown', function(e) {
    if (tooltip && !tooltip.contains(e.target)) {
      hideTooltip();
    }
  });

  document.addEventListener('scroll', hideTooltip);

  // Listen for messages from background
  chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === 'highlight-saved') {
      showSavedFeedback();
    }
  });

})();
