chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'injectInterceptor') {
    chrome.scripting.executeScript({
      target: { tabId: sender.tab.id },
      world: 'MAIN',
      func: (code) => {
        eval(code);
        if (typeof initMessageInterceptor === 'function') {
          initMessageInterceptor();
        }
      },
      args: [request.code]
    })
    .then(() => {
      sendResponse({ success: true });
    })
    .catch((err) => {
      sendResponse({ success: false, error: err.message });
    });
    
    return true;
  }
  
  if (request.action === 'executeFunction') {
    chrome.scripting.executeScript({
      target: { tabId: sender.tab.id },
      world: 'MAIN',
      func: async (funcName) => {
        try {
          if (typeof window[funcName] === 'function') {
            const result = await window[funcName]();
            return { success: true, result: result };
          } else {
            return { success: false, error: `Function ${funcName} not found on window` };
          }
        } catch (err) {
          return { success: false, error: err.message || String(err) };
        }
      },
      args: [request.func]
    })
    .then((results) => {
      const result = results[0]?.result;
      if (result && typeof result === 'object' && 'success' in result) {
        sendResponse(result);
      } else {
        sendResponse({ success: false, error: 'Unknown error' });
      }
    })
    .catch((err) => {
      sendResponse({ success: false, error: err.message });
    });
    
    return true;
  }
});

