(function () {
  "use strict";

  if (window.self !== window.top) {
    return;
  }

  let lastUpMid = null;

  function isExtensionAlive() {
    try {
      return Boolean(chrome.runtime?.id);
    } catch {
      return false;
    }
  }

  window.addEventListener("biliindex:up-target", (ev) => {
    if (ev.detail?.upMid) lastUpMid = ev.detail.upMid;
  });

  chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
    if (msg.type === "GET_LAST_UP_MID") {
      sendResponse({ upMid: lastUpMid });
    }
  });

  if (isExtensionAlive()) {
    chrome.runtime.sendMessage({ type: "GET_QUICK_TAGS", force: false }, () => {
      void chrome.runtime.lastError;
    });
  }
})();
