window.addEventListener('message', (event) => {
  if (event.source !== window) return;

  if (event.data && event.data.type === 'extension_setup') {
    const { url, api_key } = event.data;
    
    chrome.storage.local.set({ api_url: url, api_key: api_key }, () => {
      window.postMessage({
        type: 'extension_setup_result',
        success: true
      }, window.location.origin);
    });
  }
});

// Automatically check if connected and notify the page on load
if (window.location.pathname.endsWith('/chrome-extension')) {
  setTimeout(async () => {
    const { api_key, api_url } = await chrome.storage.local.get(['api_key', 'api_url']);
    if (api_key && api_url) {
      window.postMessage({
        type: 'extension_setup_result',
        success: true
      }, window.location.origin);
    }
  }, 300);
}
