window.addEventListener('message', e => {
  if (e.source !== window || e.data?.source !== 'product-workbench') return;
  if (e.data.type === 'EXTENSION_PING') {
    window.postMessage({source: 'product-workbench-extension', type: 'EXTENSION_PONG', version: chrome.runtime.getManifest().version}, '*');
  }
  if (e.data.type === 'AUTOMATE_AI') {
    chrome.runtime.sendMessage({type: 'START_JOB', job: e.data.job}, response => {
      window.postMessage({source: 'product-workbench-extension', type: 'JOB_ACCEPTED', ...(response || {})}, '*');
    });
  }
  if (e.data.type === 'OPEN_SHOPEE_SKU') {
    chrome.runtime.sendMessage({type: 'START_SHOPEE_JOB', job: e.data.job}, response => {
      window.postMessage({source: 'product-workbench-extension', type: 'SHOPEE_JOB_ACCEPTED', ...(response || {})}, '*');
    });
  }
});

chrome.runtime.onMessage.addListener(msg => {
  if (['JOB_PROGRESS', 'JOB_IMAGE', 'JOB_RESULT', 'JOB_ERROR', 'SHOPEE_SKU_RESULT'].includes(msg?.type)) {
    window.postMessage({source: 'product-workbench-extension', ...msg}, '*');
  }
});

window.postMessage({source: 'product-workbench-extension', type: 'EXTENSION_PONG', version: chrome.runtime.getManifest().version}, '*');
