chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.type === 'SYNTRIX_GET_THEME') {
    chrome.storage.sync.get('settings').then(result => {
      const theme = result.settings?.theme || 'dark';
      sendResponse({ theme });
    });
    return true;
  }

  if (msg.type === 'SYNTRIX_OPEN_OPTIONS') {
    chrome.runtime.openOptionsPage();
    return true;
  }

  if (msg.type === 'SYNTRIX_OPEN_SIDEPANEL') {
    chrome.tabs.query({ active: true, currentWindow: true }).then(tabs => {
      if (tabs[0]?.id) {
        chrome.sidePanel.open({ tabId: tabs[0].id }).catch(() => {});
      }
    });
    return true;
  }
});

chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });

chrome.action.onClicked.addListener((tab) => {
  chrome.storage.sync.get('settings').then(result => {
    const uiMode = result.settings?.uiMode || 'sidepanel';
    if (uiMode === 'sidepanel') {
      chrome.sidePanel.open({ tabId: tab.id }).catch(() => {});
    }
  });
});

chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.sync.get('settings').then(result => {
    if (!result.settings) {
      chrome.storage.sync.set({
        settings: {
          defaultProvider: 'openai',
          defaultModel: 'gpt-4o',
          uiMode: 'sidepanel',
          theme: 'dark',
          language: 'de',
          fontSize: 'medium',
          systemPrompt: '',
          systemPromptTemplate: '',
          googleSearchCx: '',
          googleSearchKey: '',
          customBaseUrls: {},
          maxTokens: 4096,
          temperature: 0.7
        }
      });
    }
    if (!result.apiKeys) {
      chrome.storage.sync.set({ apiKeys: {} });
    }
  });
});
