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

  const STYLE_ID = "mmw-aix-douyin-style";
  const LEGAL_CONFIG = globalThis.MMW_LEGAL_CONSENT_CONFIG || {};
  const LEGAL_STORAGE_KEY_CONFIG = LEGAL_CONFIG.storageKeys || {};
  const LEGAL_CONSENT_VERSION = String(LEGAL_CONFIG.version || "");
  const LEGAL_STORAGE_KEYS = {
    accepted: LEGAL_STORAGE_KEY_CONFIG.accepted || "legalConsentAccepted",
    version: LEGAL_STORAGE_KEY_CONFIG.version || "legalConsentVersion",
    acceptedAt: LEGAL_STORAGE_KEY_CONFIG.acceptedAt || "legalConsentAcceptedAt"
  };
  const LEGAL_REQUIRED_MESSAGE = String(LEGAL_CONFIG.requiredMessage || "请先阅读并同意免责声明和用户协议");
  const DOWNLOAD_SELECTOR = ".dy-download-button, .dy-download-panel .dy-download-panel-item";
  const icon = [
    "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'",
    " viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2.4'",
    " stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 3v12'/%3E",
    "%3Cpath d='m7 10 5 5 5-5'/%3E%3Cpath d='M5 21h14'/%3E%3C/svg%3E"
  ].join("");

  const css = `
    .dy-download-wrapper {
      width: 40px !important;
      height: 40px !important;
      z-index: 120 !important;
    }

    .dy-download-button {
      width: 40px !important;
      height: 40px !important;
      min-width: 40px !important;
      min-height: 40px !important;
      padding: 0 !important;
      border: 0 !important;
      border-radius: 12px !important;
      background: rgba(84, 84, 84, 0.72) !important;
      box-shadow: none !important;
      color: #fff !important;
      display: flex !important;
      align-items: center !important;
      justify-content: center !important;
      cursor: pointer !important;
      overflow: hidden !important;
    }

    .dy-download-button:hover {
      background: rgba(84, 84, 84, 0.92) !important;
    }

    .dy-download-button-inner {
      width: 100% !important;
      height: 100% !important;
      display: flex !important;
      align-items: center !important;
      justify-content: center !important;
      gap: 0 !important;
    }

    .dy-download-button-inner img,
    .dy-download-button-inner svg {
      display: none !important;
    }

    .dy-download-button-inner::before {
      content: "" !important;
      width: 24px !important;
      height: 24px !important;
      display: block !important;
      background-image: url("${icon}") !important;
      background-repeat: no-repeat !important;
      background-position: center !important;
      background-size: 24px 24px !important;
    }

    .mmw-legal-locked {
      pointer-events: none !important;
      opacity: 0.62 !important;
      filter: grayscale(0.22) !important;
    }

    #mmw-aix-legal-hint {
      position: fixed !important;
      left: 50% !important;
      top: 88px !important;
      z-index: 2147483647 !important;
      max-width: min(360px, calc(100vw - 32px)) !important;
      padding: 10px 14px !important;
      border-radius: 8px !important;
      background: #111827 !important;
      color: #fff !important;
      box-shadow: 0 12px 30px rgba(0,0,0,0.28) !important;
      font: 600 13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif !important;
      text-align: center !important;
      opacity: 0 !important;
      pointer-events: none !important;
      transform: translate(-50%, -8px) !important;
      transition: opacity 0.18s ease, transform 0.18s ease !important;
    }

    #mmw-aix-legal-hint.is-show {
      opacity: 1 !important;
      transform: translate(-50%, 0) !important;
    }
  `;

  let legalConsentAccepted = false;
  let pendingAixClickTarget = null;
  let pendingAixClickUntil = 0;

  function injectStyle() {
    const root = document.head || document.documentElement;
    if (!root || document.getElementById(STYLE_ID)) return;
    const style = document.createElement("style");
    style.id = STYLE_ID;
    style.textContent = css;
    root.appendChild(style);
  }

  function bindLegalGate() {
    refreshLegalConsentStatus();
    chrome.storage.onChanged.addListener((changes, areaName) => {
      if (areaName !== "local") return;
      if (
        !changes[LEGAL_STORAGE_KEYS.accepted]
        && !changes[LEGAL_STORAGE_KEYS.version]
        && !changes[LEGAL_STORAGE_KEYS.acceptedAt]
      ) return;
      refreshLegalConsentStatus();
    });
    document.addEventListener("click", interceptAixDownloadClick, true);
  }

  function refreshLegalConsentStatus() {
    chrome.storage.local.get(Object.values(LEGAL_STORAGE_KEYS), (values) => {
      legalConsentAccepted = values?.[LEGAL_STORAGE_KEYS.accepted] === true
        && values?.[LEGAL_STORAGE_KEYS.version] === LEGAL_CONSENT_VERSION;
      if (legalConsentAccepted) replayPendingAixClick();
    });
  }

  function interceptAixDownloadClick(event) {
    if (legalConsentAccepted) return;
    const target = event.target instanceof Element ? event.target : event.target?.parentElement;
    const downloadTarget = target?.closest?.(DOWNLOAD_SELECTOR);
    if (!downloadTarget || !document.documentElement.contains(downloadTarget)) return;

    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation();

    pendingAixClickTarget = downloadTarget;
    pendingAixClickUntil = Date.now() + 120000;
    downloadTarget.classList?.add?.("mmw-legal-locked");
    setTimeout(() => downloadTarget.classList?.remove?.("mmw-legal-locked"), 900);
    chrome.runtime.sendMessage({ type: "MMW_OPEN_LEGAL_CONSENT" }, () => {});
    showLegalHint();
  }

  function replayPendingAixClick() {
    const target = pendingAixClickTarget;
    pendingAixClickTarget = null;
    if (!target || Date.now() > pendingAixClickUntil || !target.isConnected) return;
    pendingAixClickUntil = 0;
    setTimeout(() => target.click(), 120);
  }

  function showLegalHint() {
    let hint = document.getElementById("mmw-aix-legal-hint");
    if (!hint) {
      hint = document.createElement("div");
      hint.id = "mmw-aix-legal-hint";
      hint.textContent = LEGAL_REQUIRED_MESSAGE;
      document.documentElement.appendChild(hint);
    }
    hint.classList.add("is-show");
    clearTimeout(showLegalHint.timer);
    showLegalHint.timer = setTimeout(() => hint.classList.remove("is-show"), 1800);
  }

  injectStyle();
  bindLegalGate();
  const observer = new MutationObserver(injectStyle);
  observer.observe(document.documentElement, { childList: true, subtree: true });
})();
