// Background script for service worker
// Currently minimal, can be extended for additional functionality

function setupContextMenus() {
  chrome.contextMenus.removeAll(() => {
    if (chrome.runtime.lastError) {
      console.warn('FB Tracker: context menu reset warning:', chrome.runtime.lastError.message);
    }

    chrome.contextMenus.create({
      id: 'fb-tracker-reparse',
      title: 'FB Tracker: Post neu parsen',
      contexts: ['all'],
      documentUrlPatterns: ['*://*.facebook.com/*']
    });

    chrome.contextMenus.create({
      id: 'fb-tracker-selection-ai',
      title: 'FB Tracker: Auswahl mit AI beantworten',
      contexts: ['selection'],
      documentUrlPatterns: ['*://*.facebook.com/*']
    });
  });
}

chrome.runtime.onInstalled.addListener((details) => {
  console.log('Facebook Post Tracker extension installed/updated');

  if (details.reason === 'install') {
    chrome.storage.sync.get(['profileNumber'], (result) => {
      if (!result.profileNumber) {
        chrome.storage.sync.set({ profileNumber: 1 });
      }
    });
  }

  setupContextMenus();
});

if (chrome.runtime.onStartup) {
  chrome.runtime.onStartup.addListener(() => {
    setupContextMenus();
  });
}

// Ensure menus exist after service worker restarts
setupContextMenus();

chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'fb-tracker-reparse') {
    chrome.tabs.sendMessage(tab.id, {
      type: 'reparsePost',
      x: info.pageX || 0,
      y: info.pageY || 0
    });
  } else if (info.menuItemId === 'fb-tracker-selection-ai') {
    chrome.tabs.sendMessage(tab.id, {
      type: 'generateSelectionAI',
      selectionText: info.selectionText || ''
    }, (response) => {
      if (chrome.runtime.lastError) {
        console.warn('FB Tracker selection AI error:', chrome.runtime.lastError.message);
      }
      return true;
    });
  }
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message && message.type === 'captureScreenshot') {
    const windowId = sender && sender.tab ? sender.tab.windowId : chrome.windows.WINDOW_ID_CURRENT;

    chrome.tabs.captureVisibleTab(windowId, { format: 'jpeg', quality: 80 }, (imageData) => {
      if (chrome.runtime.lastError) {
        sendResponse({ error: chrome.runtime.lastError.message });
        return;
      }

      sendResponse({ imageData });
    });
    return true;
  }
  return false;
});
