(function () {
  "use strict";

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

  let lastUpMid = null;

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

  function extractMidFromHref(href) {
    if (!href) return null;
    const m = String(href).match(/space\.bilibili\.com\/(\d+)|\/space\/(\d+)/i);
    return m ? m[1] || m[2] : null;
  }

  function midFromSpacePageUrl() {
    if (!/space\.bilibili\.com/i.test(location.hostname)) return null;
    const m = location.pathname.match(/^\/(\d{5,})/);
    return m ? m[1] : null;
  }

  function midFromVideoInitialState() {
    try {
      const st = window.__INITIAL_STATE__;
      const candidates = [
        st?.videoData?.owner,
        st?.upData,
        st?.elecFullInfo?.up_info,
      ].filter(Boolean);
      for (const up of candidates) {
        const mid = up?.mid ?? up?.uid;
        if (mid != null && mid !== "" && mid !== 0 && mid !== "0") {
          return String(mid);
        }
      }
    } catch {
      /* ignore */
    }
    return null;
  }

  function midFromVideoDom() {
    const selectors = [
      "a.up-name[href*='space.bilibili.com']",
      ".up-detail-top a[href*='space.bilibili.com']",
      "#v_upinfo a[href*='space.bilibili.com']",
      ".up-info-container a[href*='space.bilibili.com']",
    ];
    for (const sel of selectors) {
      const link = document.querySelector(sel);
      if (!(link instanceof HTMLAnchorElement)) continue;
      const mid = extractMidFromHref(link.getAttribute("href") || link.href);
      if (mid) return mid;
    }
    return null;
  }

  function midFromMountedBar() {
    const bar = document.querySelector(".biliindex-bar[data-up-mid]");
    const mid = bar?.dataset?.upMid;
    return mid && /^\d+$/.test(mid) ? mid : null;
  }

  /** 从当前页推断 UP 主 mid（不依赖是否点过标签槽） */
  function detectUpMidFromPage() {
    if (lastUpMid && /^\d+$/.test(String(lastUpMid))) {
      return String(lastUpMid);
    }

    const fromBar = midFromMountedBar();
    if (fromBar) return fromBar;

    const fromSpace = midFromSpacePageUrl();
    if (fromSpace) return fromSpace;

    const fromVideoState = midFromVideoInitialState();
    if (fromVideoState) return fromVideoState;

    const fromVideoDom = midFromVideoDom();
    if (fromVideoDom) return fromVideoDom;

    return null;
  }

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

  chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
    if (msg.type === "GET_LAST_UP_MID") {
      const upMid = detectUpMidFromPage();
      if (upMid) lastUpMid = upMid;
      sendResponse({ upMid, ok: Boolean(upMid) });
      return false;
    }
    return false;
  });

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