// ========================================
// Text Vault - Background Service Worker
// ========================================

// Create context menu on install
chrome.runtime.onInstalled.addListener(function() {
  chrome.contextMenus.create({
    id: 'save-highlight',
    title: 'Save to Text Vault',
    contexts: ['selection']
  });

  // Create sub-menus for categories
  const categories = [
    { id: 'quotes', title: '📝 Save as Quote' },
    { id: 'ideas', title: '💡 Save as Idea' },
    { id: 'research', title: '🔬 Save as Research' },
    { id: 'inspiration', title: '✨ Save as Inspiration' }
  ];

  categories.forEach(cat => {
    chrome.contextMenus.create({
      id: `save-${cat.id}`,
      parentId: 'save-highlight',
      title: cat.title,
      contexts: ['selection']
    });
  });

  // Quick save option
  chrome.contextMenus.create({
    id: 'save-quick',
    parentId: 'save-highlight',
    title: '⚡ Quick Save',
    contexts: ['selection']
  });
});

// Handle context menu clicks
chrome.contextMenus.onClicked.addListener(function(info, tab) {
  if (info.menuItemId.startsWith('save-')) {
    const categoryMap = {
      'save-quotes': 'quotes',
      'save-ideas': 'ideas',
      'save-research': 'research',
      'save-inspiration': 'inspiration',
      'save-quick': 'uncategorized'
    };

    const category = categoryMap[info.menuItemId] || 'uncategorized';
    
    saveHighlight({
      text: info.selectionText,
      sourceUrl: tab.url,
      sourceTitle: tab.title || 'Unknown',
      category: category
    });
  }
});

// Save highlight to storage
function saveHighlight(data) {
  chrome.storage.local.get(['highlights'], function(result) {
    const highlights = result.highlights || [];
    
    const newHighlight = {
      id: generateId(),
      text: data.text,
      sourceUrl: data.sourceUrl,
      sourceTitle: data.sourceTitle,
      category: data.category,
      createdAt: new Date().toISOString()
    };

    highlights.unshift(newHighlight);
    
    chrome.storage.local.set({ highlights: highlights }, function() {
      // Send notification to content script
      chrome.tabs.sendMessage(data.tabId || chrome.tabs.TAB_ID_NONE, {
        action: 'highlight-saved',
        category: data.category
      }).catch(() => {
        // Tab might not have content script, that's ok
      });
    });
  });
}

// Listen for messages from content script
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === 'save-highlight') {
    saveHighlight({
      text: request.text,
      sourceUrl: sender.tab.url,
      sourceTitle: sender.tab.title,
      category: request.category,
      tabId: sender.tab.id
    });
    sendResponse({ success: true });
  }
  return true;
});

// Generate unique ID
function generateId() {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}
