/**
 * 超级讨厌：document_start 预遮挡，避免进入页面后先闪出内容。
 */
(function () {
  "use strict";
  if (window.self !== window.top) return;
  if (window.__biliindexSuperHateEarly) return;
  if (typeof BiliDom === "undefined") return;
  window.__biliindexSuperHateEarly = true;

  const SESSION_MIDS_KEY = "biliindexSuperHateMids";
  const PREHIDE_STYLE_ID = "biliindex-super-hate-prehide-style";
  const SEARCH_PREHIDE_ID = "biliindex-super-hate-search-prehide";
  const EARLY_VEIL_ID = "biliindex-super-hate-early-veil";
  const EARLY_CRITICAL_STYLE_ID = "biliindex-super-hate-early-critical";

  function readMidsFromSession() {
    try {
      const raw = sessionStorage.getItem(SESSION_MIDS_KEY);
      if (!raw) return [];
      const parsed = JSON.parse(raw);
      return Array.isArray(parsed) ? parsed.map(String).filter(Boolean) : [];
    } catch {
      return [];
    }
  }

  function videoOwnerMidEarly() {
    return BiliDom.midFromVideoInitialState();
  }

  function spaceOwnerMidEarly() {
    return BiliDom.midFromSpacePageUrl();
  }

  function isSearchPage() {
    return (
      /search\.bilibili\.com/i.test(location.hostname) ||
      /\/search/i.test(location.pathname || "")
    );
  }

  function ensureCriticalCss() {
    if (document.getElementById(EARLY_CRITICAL_STYLE_ID)) return;
    const style = document.createElement("style");
    style.id = EARLY_CRITICAL_STYLE_ID;
    style.textContent = `
      #${EARLY_VEIL_ID},
      .biliindex-super-hate-page-veil {
        position: fixed !important;
        top: 56px !important;
        left: 0 !important;
        right: 0 !important;
        bottom: 0 !important;
        z-index: 80 !important;
        background: #ffffff !important;
        pointer-events: auto !important;
      }
    `;
    (document.documentElement || document.head)?.appendChild(style);
  }

  let earlyVeilClearTimer = null;
  let earlyVeilMountedAt = 0;

  function clearEarlyVeil() {
    document.getElementById(EARLY_VEIL_ID)?.remove();
    if (earlyVeilClearTimer) {
      clearTimeout(earlyVeilClearTimer);
      earlyVeilClearTimer = null;
    }
    earlyVeilMountedAt = 0;
  }

  /** 白幕挂载后按挂载时刻计时清除（避免 storage 晚到导致 4.5s 定时器已失效、白幕常驻） */
  function scheduleEarlyVeilClear() {
    if (earlyVeilClearTimer) clearTimeout(earlyVeilClearTimer);
    earlyVeilClearTimer = setTimeout(clearEarlyVeil, 3500);
  }

  function mountEarlyVeil() {
    ensureCriticalCss();
    if (document.getElementById(EARLY_VEIL_ID)) {
      scheduleEarlyVeilClear();
      return;
    }
    const veil = document.createElement("div");
    veil.id = EARLY_VEIL_ID;
    veil.className = "biliindex-super-hate-page-veil";
    veil.setAttribute("aria-hidden", "true");
    const root = document.documentElement || document.body;
    if (root) root.appendChild(veil);
    earlyVeilMountedAt = Date.now();
    scheduleEarlyVeilClear();
  }

  function injectSpacePrehideCss() {
    ensureCriticalCss();
    if (document.getElementById(PREHIDE_STYLE_ID)) return;
    const style = document.createElement("style");
    style.id = PREHIDE_STYLE_ID;
    style.textContent = `
      .video-list,
      .video-list-section,
      .video-section,
      .video-section-card,
      .video-section-items,
      .small-item-list,
      #video-list {
        visibility: hidden !important;
      }
    `;
    (document.documentElement || document.head)?.appendChild(style);
  }

  function injectSearchGridPrehide() {
    ensureCriticalCss();
    if (document.getElementById(SEARCH_PREHIDE_ID)) return;
    const style = document.createElement("style");
    style.id = SEARCH_PREHIDE_ID;
    style.textContent = `
      .search-page .video-list .bili-video-card,
      .search-page .video-list bili-video-card,
      .search-page .video-list bili-search-video-card,
      .search-page .video-list-item .bili-video-card__wrap,
      .search-page .bili-video-card__wrap {
        visibility: hidden !important;
      }
    `;
    (document.documentElement || document.head)?.appendChild(style);
  }

  function applyEarlyBlock(mids) {
    if (!mids.length) return;
    const set = new Set(mids.map(String));
    const isSpace = /space\.bilibili\.com/i.test(location.hostname);

    if (isSpace) {
      const owner = spaceOwnerMidEarly();
      if (owner && set.has(owner)) injectSpacePrehideCss();
    }
    /* 播放页白幕改由 document_idle 的 super-hate-block.js 处理，避免刷新时 storage 晚到 + 白幕卡死 */
  }

  function boot(mids) {
    if (!mids?.length) return;
    applyEarlyBlock(mids);
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", () => applyEarlyBlock(mids), {
        once: true,
      });
    }
  }

  function finishBoot(mids) {
    if (!mids?.length) return;
    try {
      sessionStorage.setItem(SESSION_MIDS_KEY, JSON.stringify(mids.map(String)));
    } catch {
      /* ignore */
    }
    boot(mids);
  }

  const sessionMids = readMidsFromSession();
  if (sessionMids.length) boot(sessionMids);

  const loadLocal = () => {
    chrome.storage.local.get(["superHateMids"], (stored) => {
      void chrome.runtime?.lastError;
      const mids = Array.isArray(stored?.superHateMids) ? stored.superHateMids.map(String) : [];
      finishBoot(mids);
    });
  };

  if (chrome.storage?.session) {
    chrome.storage.session.get(["superHateMids"], (stored) => {
      void chrome.runtime?.lastError;
      const mids = Array.isArray(stored?.superHateMids)
        ? stored.superHateMids.map(String)
        : [];
      if (mids.length) {
        finishBoot(mids);
        return;
      }
      loadLocal();
    });
  } else {
    loadLocal();
  }

  /** 兜底：任意残留 early 白幕最长 8s 清除 */
  setTimeout(clearEarlyVeil, 8000);

  window.addEventListener("pageshow", () => {
    clearEarlyVeil();
  });
})();
