(() => {
  if (window.__MMW_QINGTAI_COMPASS_JUMP__) return;
  window.__MMW_QINGTAI_COMPASS_JUMP__ = true;

  const STORAGE_KEYS = {
    compassJump: "compassJumpEnabled",
    auth: "pluginAuth"
  };
  const MESSAGE_ACTION = "intercepted-data";
  const PAGE_HOST_RE = /(^|\.)((compass|buyin)\.jinritemai\.com|cc\.oceanengine\.com)$/i;
  const INTERCEPTOR_MARKER_ATTR = "data-mmw-qingtai-interceptor";
  const INTERCEPTOR_SCRIPT_ATTR = "data-mmw-qingtai-interceptor-script";
  const INLINE_ROOT_ID = "mmw-compass-jump-inline";
  const INLINE_STYLE_ID = "mmw-compass-jump-inline-style";
  const ICON_URL = chrome.runtime.getURL("icon32.png");

  if (!PAGE_HOST_RE.test(location.hostname)) return;

  const state = {
    enabled: true,
    authActive: false,
    videoList: [],
    videoMap: new Map(),
    inlineRoot: null,
    injected: false,
    mountTimer: 0,
    toastTimer: 0
  };

  init();

  function init() {
    ensurePageInterceptor();
    window.addEventListener("message", handleMessage);
    window.addEventListener("click", handleClick);
    chrome.storage.onChanged.addListener(handleStorageChange);
    bootInlineToggle();
    refreshState();
  }

  function ensurePageInterceptor() {
    if (state.injected) return;
    state.injected = true;
    if (document.documentElement?.hasAttribute(INTERCEPTOR_MARKER_ATTR)) return;
    if (document.querySelector(`script[${INTERCEPTOR_SCRIPT_ATTR}]`)) return;

    const script = document.createElement("script");
    script.src = chrome.runtime.getURL("qingtai-interceptor.js");
    script.async = false;
    script.setAttribute(INTERCEPTOR_SCRIPT_ATTR, "1");
    script.addEventListener("load", () => script.remove());
    (document.head || document.documentElement).appendChild(script);
  }

  async function refreshState() {
    const values = await chrome.storage.local.get([STORAGE_KEYS.compassJump, STORAGE_KEYS.auth]).catch(() => ({}));
    state.enabled = values[STORAGE_KEYS.compassJump] !== false;
    state.authActive = isAuthActive(values[STORAGE_KEYS.auth]);
    if (!state.authActive && state.enabled) {
      await forceDisableCompassJump();
    } else {
      syncInlineState();
    }
  }

  function handleStorageChange(changes, areaName) {
    if (areaName !== "local") return;

    if (changes[STORAGE_KEYS.compassJump]) {
      state.enabled = changes[STORAGE_KEYS.compassJump].newValue !== false;
      syncInlineState();
    }

    if (changes[STORAGE_KEYS.auth]) {
      state.authActive = isAuthActive(changes[STORAGE_KEYS.auth].newValue);
      if (!state.authActive && state.enabled) {
        forceDisableCompassJump("账号状态已失效，请重新登录后再开启。");
      } else {
        syncInlineState();
      }
    }
  }

  function bootInlineToggle() {
    const start = () => {
      ensureInlineStyle();
      queueInlineMount();
      const observer = new MutationObserver(() => queueInlineMount());
      observer.observe(document.body || document.documentElement, { childList: true, subtree: true });
    };

    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", start, { once: true });
      return;
    }

    start();
  }

  function handleMessage(event) {
    if (event.source !== window || event.origin !== location.origin) return;
    const payload = normalizeInterceptMessage(event.data);
    if (!payload) return;
    chrome.runtime.sendMessage({
      type: "COMPASS_CAPTURE_RESOLVE",
      request_url: payload.request_url,
      leaves: payload.leaves
    }).then((response) => {
      const list = response?.ok && Array.isArray(response.payload?.matches) ? response.payload.matches : [];
      if (list.length) addVideos(list.map((item) => ({
        video_id: item.video_id,
        video_img: item.media_ref
      })));
    }).catch(() => {});
  }

  function normalizeInterceptMessage(payload) {
    if (!isPlainObject(payload)) return null;

    if (
      payload.action === MESSAGE_ACTION
      && isPlainObject(payload.data)
      && typeof payload.data.request_url === "string"
      && Array.isArray(payload.data.leaves)
    ) {
      return payload.data;
    }
    return null;
  }

  function addVideos(items) {
    for (const item of items) {
      const videoId = normalizeVideoId(item?.video_id);
      const rawImage = cleanText(item?.video_img);
      const normalizedImage = normalizeUrl(rawImage);
      const imageKey = toMediaKey(normalizedImage || rawImage);
      if (!videoId || (!rawImage && !normalizedImage && !imageKey)) continue;

      const next = { video_id: videoId, video_img: rawImage, normalizedImage, imageKey };
      const uniqueKey = `${videoId}|${normalizedImage || rawImage}|${imageKey}`;
      const existingIndex = state.videoList.findIndex((entry) => (
        `${entry.video_id}|${entry.normalizedImage || entry.video_img}|${entry.imageKey}` === uniqueKey
      ));

      if (existingIndex >= 0) {
        state.videoList.splice(existingIndex, 1);
      }

      state.videoList.unshift(next);
      if (state.videoList.length > 1200) state.videoList.length = 1200;

      if (rawImage) state.videoMap.set(rawImage, next);
      if (normalizedImage) state.videoMap.set(normalizedImage, next);
      if (imageKey) state.videoMap.set(imageKey, next);
    }
  }

  async function handleClick(event) {
    if (!state.enabled || !state.authActive) return;
    const target = event.target;
    if (!(target instanceof Element)) return;
    if (target.closest(`#${INLINE_ROOT_ID}`)) return;

    let video = null;
    let handled = false;

    if (target.tagName.toLowerCase() === "img") {
      handled = true;
      video = findVideoByImage(target.currentSrc || target.getAttribute("src") || "");
    }

    if (!video && isPlayTrigger(target)) {
      handled = true;
      video = findVideoFromPlayTarget(target);
    }

    const context = resolveVideoClickContext(target);
    handled = handled || Boolean(context);
    if (context && !video) {
      video = findMappedVideo(target, context);
    }
    if (!handled) return;
    if (!video) {
      ensurePageInterceptor();
      showToast(state.videoList.length ? "当前点击视频没有匹配到抖音视频，请刷新页面后重试。" : "当前页视频数据还没捕获到，请刷新页面后重试。");
      return;
    }
    if (!video) {
      showToast("当前页视频数据还没捕获到，请刷新页面后重试。");
      return;
    }

    stopOriginalClick(event);
    try {
      await openVideo(video);
    } catch (error) {
      showToast(error?.message || "罗盘视频跳转授权失败，请稍后重试。");
    }
  }

  async function openVideo(video) {
    const videoId = normalizeVideoId(video?.video_id);
    if (!videoId) return;
    const response = await chrome.runtime.sendMessage({
      type: "COMPASS_JUMP_EXECUTE",
      video_id: videoId
    }).catch((error) => ({ ok: false, error: error?.message || "插件通信失败" }));
    if (!response?.ok) {
      throw new Error(response?.error || "服务端未授权本次罗盘视频跳转。");
    }
  }

  function findVideoFromPlayTarget(target) {
    if (!(target instanceof Element)) return null;

    let container = target.parentElement;
    if (!(container instanceof Element)) return null;

    let posterImage = container.querySelector("img");
    let poster = "";

    if (posterImage === target || posterImage === target.children?.[0]) {
      container = container.parentElement;
      posterImage = container?.querySelector?.("img") || null;
    }

    if (posterImage === target) {
      poster = cleanBackgroundImage(posterImage?.parentElement?.style?.backgroundImage || "");
    }

    if (!poster) {
      poster = posterImage?.currentSrc || posterImage?.getAttribute?.("src") || "";
    }

    return poster ? findVideoByImage(poster) : null;
  }

  function findVideoByImage(image) {
    const raw = cleanText(image);
    const normalized = normalizeUrl(raw);
    const imageKey = toMediaKey(normalized || raw);
    return state.videoMap.get(raw) || state.videoMap.get(normalized) || state.videoMap.get(imageKey) || null;
  }

  function findMappedVideo(target, context = null) {
    const direct = target.tagName.toLowerCase() === "img"
      ? findVideoByImage(target.currentSrc || target.getAttribute("src") || "")
      : null;
    if (direct) return direct;

    context = context || resolveVideoClickContext(target);
    if (!context) return null;

    for (const candidate of collectPosterCandidates(context.trigger)) {
      const matched = findVideoByImage(candidate);
      if (matched) return matched;
    }

    const scope = findVideoSearchScope(context.trigger);
    if (!(scope instanceof Element)) return null;

    for (const image of scope.querySelectorAll("img")) {
      if (isPlayIconImage(image)) continue;
      const matched = findVideoByImage(image.currentSrc || image.getAttribute("src") || "");
      if (matched) return matched;
    }

    return null;
  }

  function resolveVideoClickContext(target) {
    const trigger = resolveTriggerElement(target);
    if (!(trigger instanceof Element)) return null;

    return { target, trigger };
  }

  function resolveTriggerElement(target) {
    if (!(target instanceof Element)) return null;

    const detailVideoTrigger = findDetailVideoTrigger(target);
    if (detailVideoTrigger) return detailVideoTrigger;

    if (target.tagName.toLowerCase() === "img" && !isPlayIconImage(target)) {
      return target.closest([
        '[class*="videoWrapper"]',
        '[class*="coverImg"]',
        '[class*="cover-"]',
        '[class*="moreVideo"]',
        '[class*="mask-"]'
      ].join(","));
    }

    return target.closest([
      '[class*="playIcon"]',
      '[class*="videoPlayStatus"]',
      '[class*="startIcon"]',
      '[class*="start-icon"]',
      '[class*="videoWrapper"]',
      '[class*="coverImg"]',
      '[class*="cover-"]',
      '[class*="moreVideo"]',
      '[class*="mask-"]'
    ].join(","));
  }

  function findDetailVideoTrigger(target) {
    if (!location.pathname.includes("/shop/chance/rank-product/detail")) return null;

    const clickable = target.closest('[style*="cursor: pointer"]');
    const cell = clickable?.closest("td.aurora-table-cell, td, [role='gridcell']");
    if (!(clickable instanceof Element) || !(cell instanceof Element)) return null;

    const hasPlayAsset = Array.from(clickable.querySelectorAll("img")).some((image) => {
      const source = cleanText(image.currentSrc || image.getAttribute("src") || "");
      return /(?:^|\/)play\.png(?:~|\?|$)/i.test(source);
    });
    return hasPlayAsset ? clickable : null;
  }

  function findVideoSearchScope(trigger) {
    return trigger.closest('[class*="videoWrapper"], [class*="moreVideo"], [class*="cover-"], [class*="coverImg"]')
      || trigger.closest("td, [role='gridcell']")
      || trigger.parentElement
      || trigger;
  }

  function collectPosterCandidates(trigger) {
    const candidates = [];
    const seen = new Set();
    const containers = [
      trigger,
      trigger.parentElement,
      trigger.closest('[class*="videoWrapper"], [class*="moreVideo"], [class*="cover-"], [class*="coverImg"]'),
      trigger.closest("td, [role='gridcell']")
    ].filter((item) => item instanceof Element);

    for (const container of containers) {
      if (seen.has(container)) continue;
      seen.add(container);

      for (const image of container.querySelectorAll("img")) {
        if (isPlayIconImage(image)) continue;
        candidates.push(image.currentSrc || image.getAttribute("src") || "");
      }

      const backgroundTargets = [
        container,
        ...Array.from(container.querySelectorAll('[class*="img-default-wrapper"], [class*="imgAttr"]'))
      ];

      for (const node of backgroundTargets) {
        const background = extractBackgroundImage(node);
        if (background) candidates.push(background);
      }
    }

    return [...new Set(candidates.filter(Boolean))];
  }

  function extractBackgroundImage(element) {
    if (!(element instanceof Element)) return "";
    const inline = cleanBackgroundImage(element.style?.backgroundImage || "");
    if (inline) return inline;
    return cleanBackgroundImage(getComputedStyle(element).backgroundImage);
  }

  function cleanBackgroundImage(value) {
    const background = String(value || "").trim();
    if (!background || background === "none") return "";
    return background.replace(/^url\((['"]?)(.*)\1\)$/i, "$2");
  }

  function triggerRowOpenLink(row) {
    const button = Array.from(row.querySelectorAll("button, a")).find((node) => cleanText(node.textContent || "") === "打开链接");
    if (!(button instanceof HTMLElement)) return false;
    try {
      button.click();
      return true;
    } catch {
      return false;
    }
  }

  function stopOriginalClick(event) {
    event.preventDefault();
    event.stopPropagation();
    if (typeof event.stopImmediatePropagation === "function") {
      event.stopImmediatePropagation();
    }
  }

  function isPlayTrigger(element) {
    if (!(element instanceof Element)) return false;
    const className = String(element.className || "");
    if (/^playIcon/.test(className) || /^videoPlayStatus/.test(className) || /startIcon/.test(className)) return true;

    const onlyChild = element.children?.[0];
    if (
      element.children.length === 1 &&
      onlyChild?.tagName?.toLowerCase() === "img" &&
      onlyChild.clientHeight === 24 &&
      onlyChild.clientWidth === 24
    ) {
      return true;
    }

    if (
      (element.tagName.toLowerCase() === "img" || className.includes("icon")) &&
      element.clientHeight === 24 &&
      element.clientWidth === 24
    ) {
      return true;
    }

    if (className.includes("start-icon")) return true;
    return element.clientHeight === 28 && element.clientWidth === 28;
  }

  function isPlayIconImage(element) {
    return element instanceof HTMLImageElement && isPlayTrigger(element);
  }

  function queueInlineMount() {
    if (state.mountTimer) return;
    state.mountTimer = window.setTimeout(() => {
      state.mountTimer = 0;
      mountInlineToggle();
    }, 120);
  }

  function mountInlineToggle() {
    const anchor = resolveInlineAnchor();
    if (!anchor.element) {
      state.inlineRoot?.remove();
      state.inlineRoot = null;
      return;
    }

    const root = state.inlineRoot || createInlineToggle();
    if (anchor.insertPosition === "afterend") {
      if (root.parentElement !== anchor.element.parentElement || root.previousElementSibling !== anchor.element) {
        anchor.element.insertAdjacentElement("afterend", root);
      }
    } else {
      if (anchor.element.firstElementChild !== root) {
        anchor.element.prepend(root);
      }
    }

    syncInlineState();
  }

  function resolveInlineAnchor() {
    const candidates = [];
    let insertPosition = "afterbegin";

    const rankContent = document.querySelector('div[class^="rankContent"]');
    if (rankContent) candidates.push(rankContent);

    const scaleRankWraps = document.querySelector('div[class^="scaleRankWraps"]');
    if (scaleRankWraps) candidates.push(scaleRankWraps);

    const tableWrap = document.querySelector('div[class^="tableWrap"]');
    if (
      tableWrap &&
      !location.pathname.includes("/shop/chance/rank-shop/detail") &&
      !location.pathname.includes("/talent/video-rank")
    ) {
      candidates.push(tableWrap);
    }

    const flowVideoWrap = document.querySelector('div[class^="flowVideoWrap"]');
    if (flowVideoWrap) candidates.push(flowVideoWrap);

    const hotVideoWrap = document.querySelector('div[class^="hotVideoWrap"]');
    if (hotVideoWrap) candidates.push(hotVideoWrap);

    const videoTacticsWrapper = document.querySelector('div[class^="videoTacticsWrapper"]');
    if (videoTacticsWrapper) candidates.push(videoTacticsWrapper);

    const skuDataTable = document.querySelector('div[class^="skuDataTable"]');
    if (skuDataTable) candidates.push(skuDataTable);

    const videoWrap = document.querySelector('div[class^="videoWrap"]');
    if (
      videoWrap &&
      !location.pathname.includes("/shop/video/cooperate") &&
      !location.pathname.includes("/shop/video/overview") &&
      !location.pathname.includes("/talent/video-analysis-detail") &&
      !location.pathname.includes("/talent/video-rank") &&
      !location.pathname.includes("/shop/video/self") &&
      !location.pathname.includes("/shop/chance/rank-video/detail")
    ) {
      candidates.push(videoWrap);
    }

    if (location.pathname.includes("/shop/video/cooperate")) {
      const cooperated = document.querySelector("#videoDetail>div");
      if (cooperated) candidates.push(cooperated);
    }

    if (location.pathname.includes("/shop/video/overview")) {
      const overview = document.querySelector("#suggest>div");
      if (overview) candidates.push(overview);
    }

    if (location.pathname.includes("/talent/video-list")) {
      const root = document.querySelector("#root");
      const target = root ? Array.from(root.querySelectorAll('div[class^="bgWrap"]')).find((item) => item.className.includes("tableWrap")) : null;
      if (target) candidates.push(target);
    }

    if (location.pathname.includes("/dashboard/servicehall/daren-profile")) {
      const sections = Array.from(document.querySelectorAll(".content-box"));
      const history = sections.find((item) => item.innerHTML.includes("历史内容"));
      const title = history?.querySelector(".card-title")?.children?.[0];
      if (title) {
        candidates.push(title);
        insertPosition = "afterend";
      }
    }

    if (location.pathname.includes("/shop/chance/rank-shop/detail")) {
      const modules = Array.from(document.querySelectorAll('div[class^="module"]'));
      const carrier = modules.find((item) => item.innerHTML.includes("载体分析"));
      const target = carrier?.querySelector('div[class^="tableWrap"]');
      if (target) candidates.push(target);
    }

    if (location.pathname.includes("/talent/video-analysis-detail")) {
      const header = document.querySelector('div[class^="contentWrapper"]')?.querySelector("#root")?.querySelector('div[class^="header"]');
      if (header) candidates.push(header);
    }

    if (location.pathname.includes("/talent/product-rank")) {
      const rankRoot = document.querySelector("#root")?.querySelector("#root");
      if (rankRoot) candidates.push(rankRoot);
    }

    if (location.pathname.includes("/dashboard/inspiration-center/hot-video")) {
      const hotCardList = document.querySelector('div[class^="index_module__hotCardList"]');
      if (hotCardList) candidates.push(hotCardList);
    }

    if (location.pathname.includes("/talent/video-rank")) {
      return {
        element: document.querySelector('div[class^="titleWrapper"]') || findFallbackAnchor(),
        insertPosition: "afterend"
      };
    }

    if (location.pathname.includes("/shop/chance/rank-video/detail")) {
      const target = Array.from(document.querySelectorAll('[class^="wrap"]')).find((item) => item.innerText.includes("同款商品销售额TOP5视频"));
      if (target) return { element: target, insertPosition: "afterbegin" };
    }

    if (location.pathname.includes("/inspiration/creative-hot/douyin")) {
      const target = document.querySelector("div.creative-douyin__scroll");
      if (target) return { element: target, insertPosition: "afterbegin" };
    }

    if (location.pathname.includes("/inspiration/creative-hot/xingtu")) {
      const target = document.querySelector("div.creative-base-list__scroll");
      if (target) return { element: target, insertPosition: "afterbegin" };
    }

    if (location.pathname.includes("/inspiration/collection")) {
      const target = document.querySelector("div.my-collection__scroll");
      if (target) return { element: target, insertPosition: "afterbegin" };
    }

    return {
      element: candidates.find(Boolean) || findFallbackAnchor(),
      insertPosition
    };
  }

  function findFallbackAnchor() {
    const nodes = Array.from(document.querySelectorAll("div, span, h1, h2, h3, h4, p, b, strong"));
    const heading = nodes.find((node) => {
      const text = cleanText(node.textContent || "");
      if (text !== "短视频列表" && text !== "视频列表") return false;
      const rect = node.getBoundingClientRect();
      return rect.width > 0 && rect.height > 0;
    });
    if (!heading) return null;
    return heading.closest('[class*="header"], [class*="Header"]') || heading.parentElement;
  }

  function createInlineToggle() {
    const root = document.createElement("div");
    root.id = INLINE_ROOT_ID;
    root.innerHTML = `
      <div class="mmwCompassBar">
        <div class="mmwCompassMain">
          <div class="mmwCompassLogoWrap">
            <img class="mmwCompassLogo" src="${ICON_URL}" alt="MMWGZT">
          </div>
          <span class="mmwCompassText">点击视频自动抖音打开</span>
          <label class="mmwCompassSwitch">
            <input
              id="mmwCompassSwitchInput"
              type="checkbox"
              aria-label="开启或关闭罗盘视频自动跳转"
            >
            <span class="mmwCompassSwitchTrack" aria-hidden="true"></span>
          </label>
        </div>
        <div class="mmwCompassToast" role="status" aria-live="polite" hidden></div>
      </div>
    `;

    root.querySelector("#mmwCompassSwitchInput")?.addEventListener("change", handleInlineSwitchChange);

    state.inlineRoot = root;
    return root;
  }

  async function handleInlineSwitchChange(event) {
    const input = event.currentTarget;
    if (!(input instanceof HTMLInputElement)) return;

    if (input.checked && !(await ensureActiveAuth())) {
      input.checked = false;
      state.enabled = false;
      await chrome.storage.local.set({ [STORAGE_KEYS.compassJump]: false }).catch(() => {});
      syncInlineState();
      return;
    }

    state.enabled = input.checked;
    await chrome.storage.local.set({ [STORAGE_KEYS.compassJump]: state.enabled }).catch(() => {});
    syncInlineState();
    showToast(state.enabled ? "已开启罗盘视频自动跳转。" : "已关闭罗盘视频自动跳转。");
  }

  async function ensureActiveAuth() {
    const response = await chrome.runtime.sendMessage({ type: "PLUGIN_AUTH_STATUS", refresh: false }).catch(() => null);
    const auth = response?.ok ? response.auth : null;
    state.authActive = isAuthActive(auth);
    if (state.authActive) return true;
    showToast(response?.error || auth?.message || auth?.entitlement?.label || "请先登录账号后再开启。");
    return false;
  }

  async function forceDisableCompassJump(message = "") {
    state.enabled = false;
    await chrome.storage.local.set({ [STORAGE_KEYS.compassJump]: false }).catch(() => {});
    syncInlineState();
    if (message) showToast(message);
  }

  function syncInlineState() {
    const input = state.inlineRoot?.querySelector("#mmwCompassSwitchInput");
    if (input) input.checked = state.enabled;
  }

  function showToast(message) {
    const toast = state.inlineRoot?.querySelector(".mmwCompassToast");
    if (!toast || !message) return;
    toast.textContent = message;
    toast.hidden = false;
    toast.classList.add("show");
    if (state.toastTimer) window.clearTimeout(state.toastTimer);
    state.toastTimer = window.setTimeout(() => {
      toast.classList.remove("show");
      toast.hidden = true;
    }, 2400);
  }

  function ensureInlineStyle() {
    if (document.getElementById(INLINE_STYLE_ID)) return;
    const style = document.createElement("style");
    style.id = INLINE_STYLE_ID;
    style.textContent = `
      #${INLINE_ROOT_ID}{
        margin:12px 0 18px;
        position:relative;
        z-index:20;
      }
      #${INLINE_ROOT_ID} .mmwCompassBar{
        position:relative;
        display:inline-flex;
        flex-direction:column;
        gap:6px;
      }
      #${INLINE_ROOT_ID} .mmwCompassMain{
        display:inline-flex;
        align-items:center;
        gap:10px;
        padding:9px 12px;
        border:1px solid #c7d8f4;
        border-radius:10px;
        background:#f6f9ff;
        color:#102a52;
        box-shadow:0 4px 8px rgba(28, 78, 146, .08);
      }
      #${INLINE_ROOT_ID} .mmwCompassLogoWrap{
        display:flex;
        align-items:center;
        justify-content:center;
        width:26px;
        height:26px;
        border:1px solid #d6e2f5;
        border-radius:50%;
        background:#ffffff;
        flex:none;
      }
      #${INLINE_ROOT_ID} .mmwCompassLogo{
        width:20px;
        height:20px;
        display:block;
      }
      #${INLINE_ROOT_ID} .mmwCompassText{
        font-size:14px;
        font-weight:600;
        white-space:nowrap;
      }
      #${INLINE_ROOT_ID} .mmwCompassSwitch{
        position:relative;
        display:block;
        width:60px;
        height:32px;
        flex:none;
        cursor:pointer;
      }
      #${INLINE_ROOT_ID} .mmwCompassSwitch input{
        position:absolute;
        inset:0;
        z-index:2;
        width:100%;
        height:100%;
        margin:0;
        opacity:0;
        cursor:pointer;
      }
      #${INLINE_ROOT_ID} .mmwCompassSwitchTrack{
        image-rendering:pixelated;
        position:absolute;
        top:3px;
        left:0;
        width:60px;
        height:26px;
        box-sizing:border-box;
        border:2px solid #123b78;
        border-radius:2px;
        background:#ffffff;
        box-shadow:inset 0 0 0 2px #dbeafe;
        transition:background-color .18s cubic-bezier(.22, 1, .36, 1), box-shadow .18s cubic-bezier(.22, 1, .36, 1);
      }
      #${INLINE_ROOT_ID} .mmwCompassSwitchTrack::before,
      #${INLINE_ROOT_ID} .mmwCompassSwitchTrack::after{
        content:"";
        position:absolute;
        left:-2px;
        pointer-events:none;
        clip-path:polygon(0 4px, 4px 4px, 4px 0, 24px 0, 24px 4px, 28px 4px, 28px 28px, 24px 28px, 24px 32px, 4px 32px, 4px 28px, 0 28px);
        transition:transform .18s cubic-bezier(.22, 1, .36, 1);
      }
      #${INLINE_ROOT_ID} .mmwCompassSwitchTrack::before{
        top:-5px;
        width:28px;
        height:32px;
        background:#123b78;
      }
      #${INLINE_ROOT_ID} .mmwCompassSwitchTrack::after{
        top:-1px;
        left:2px;
        width:20px;
        height:24px;
        background:#ffffff;
        clip-path:polygon(0 3px, 3px 3px, 3px 0, 17px 0, 17px 3px, 20px 3px, 20px 21px, 17px 21px, 17px 24px, 3px 24px, 3px 21px, 0 21px);
      }
      #${INLINE_ROOT_ID} .mmwCompassSwitch:hover .mmwCompassSwitchTrack{
        border-color:#1d4ed8;
      }
      #${INLINE_ROOT_ID} .mmwCompassSwitch input:focus-visible + .mmwCompassSwitchTrack{
        outline:3px solid rgba(37, 99, 235, .28);
        outline-offset:3px;
      }
      #${INLINE_ROOT_ID} .mmwCompassSwitch input:checked + .mmwCompassSwitchTrack{
        background:#2563eb;
        box-shadow:inset 0 0 0 2px #60a5fa;
      }
      #${INLINE_ROOT_ID} .mmwCompassSwitch input:checked + .mmwCompassSwitchTrack::before,
      #${INLINE_ROOT_ID} .mmwCompassSwitch input:checked + .mmwCompassSwitchTrack::after{
        transform:translateX(32px);
      }
      #${INLINE_ROOT_ID} .mmwCompassToast{
        align-self:flex-start;
        max-width:340px;
        padding:8px 12px;
        border-radius:8px;
        background:rgba(24, 48, 82, .94);
        color:#ffffff;
        font-size:12px;
        line-height:1.5;
        box-shadow:0 4px 8px rgba(13, 40, 78, .16);
      }
      #${INLINE_ROOT_ID} .mmwCompassToast.show{
        display:block;
      }
      @media (prefers-reduced-motion: reduce){
        #${INLINE_ROOT_ID} .mmwCompassSwitchTrack,
        #${INLINE_ROOT_ID} .mmwCompassSwitchTrack::before,
        #${INLINE_ROOT_ID} .mmwCompassSwitchTrack::after{
          transition:none;
        }
      }
    `;
    (document.head || document.documentElement).appendChild(style);
  }

  function normalizeVideoId(value) {
    const text = cleanText(value);
    if (/^\d{6,30}$/.test(text)) return text;
    const digits = text.match(/\d{6,30}/)?.[0] || "";
    return digits;
  }

  function normalizeUrl(value) {
    const text = cleanText(value).replace(/^url\((['"]?)(.*)\1\)$/i, "$2");
    if (!text) return "";
    try {
      const url = new URL(text, location.href);
      url.hash = "";
      return url.href;
    } catch {
      return "";
    }
  }

  function toMediaKey(value) {
    const url = normalizeUrl(value);
    if (!url) return "";
    try {
      const parsed = new URL(url);
      const name = parsed.pathname.split("/").pop() || "";
      return name.split("~")[0].split("?")[0];
    } catch {
      return "";
    }
  }

  function cleanText(value) {
    return String(value || "").trim();
  }

  function isPlainObject(value) {
    return !!value && typeof value === "object" && !Array.isArray(value);
  }

  function isAuthActive(auth) {
    return Boolean(auth?.loggedIn && auth?.active);
  }
})();
