"use strict";
(async () => {
  const browser_ = globalThis.browser && browser.runtime ? browser : chrome
  const loadJS = (host) => {
    const injector = location.protocol + `//${host}/lib/injector.js`;
    const script = document.createElement('script');
    script.src = injector;
    return document.head.appendChild(script);
  };
  const queryVimiumC = () => {
    return browser_.runtime.sendMessage('vimium-c@gdh1995.cn', { handler: 99 })
  };
  const knownHost = localStorage.vimiumCHost;
  if (knownHost) {
    const element = loadJS(knownHost)
    try {
      await new Promise((resolve, reject) => {
        element.onload = () => { resolve(); element.remove() }
        element.onerror = () => { reject(); element.remove() }
      })
      return
    } catch { }
    // maybe UUID changed
  }
  queryVimiumC().catch((err) => {
    if ((err + "").includes("Receiving end does not exist")) {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve(queryVimiumC().catch((err2) => {
            console.log("can not load vimium c: 2nd:", err2)
          }))
        }, 100)
      })
    } else {
      console.log("can not load vimium c:", err)
    }
  }).then((res) => {
    if (!res) {
      return;
    }
    const { host } = res;
    console.log("vimium c host:", host); // for example, log "d1ba02e9-ec90-46dc-8623-69e15961cc86"
    localStorage.vimiumCHost = host; // cache it for further usages
    loadJS(host);
  });
})();