(() => {
  const LEGAL_CONFIG = globalThis.MMW_LEGAL_CONSENT_CONFIG || {};
  const STORAGE_KEY_CONFIG = LEGAL_CONFIG.storageKeys || {};
  const CONSENT_VERSION = String(LEGAL_CONFIG.version || "");
  const STORAGE_KEYS = {
    accepted: STORAGE_KEY_CONFIG.accepted || "legalConsentAccepted",
    version: STORAGE_KEY_CONFIG.version || "legalConsentVersion",
    acceptedAt: STORAGE_KEY_CONFIG.acceptedAt || "legalConsentAcceptedAt"
  };
  const AGREEMENT_PATH = String(LEGAL_CONFIG.agreementPath || "legal/consent-agreement.html");
  const REQUIRED_MESSAGE = String(
    LEGAL_CONFIG.requiredMessageLong
    || LEGAL_CONFIG.requiredMessage
    || "请先阅读并同意免责声明和用户协议后再使用插件功能。"
  );

  let status = { accepted: false, version: "", acceptedAt: 0 };
  let changeHandler = null;
  let mounted = false;
  let storageListenerBound = false;

  async function init(options = {}) {
    changeHandler = typeof options.onChange === "function" ? options.onChange : null;
    status = await getStatus();
    mount();
    notify();
    if (!status.accepted) show();
    bindStorage();
    return status;
  }

  async function getStatus() {
    const values = await chrome.storage.local.get(Object.values(STORAGE_KEYS)).catch(() => ({}));
    return {
      accepted: values[STORAGE_KEYS.accepted] === true && values[STORAGE_KEYS.version] === CONSENT_VERSION,
      version: String(values[STORAGE_KEYS.version] || ""),
      acceptedAt: Number(values[STORAGE_KEYS.acceptedAt] || 0)
    };
  }

  async function accept() {
    const acceptedAt = Date.now();
    await chrome.storage.local.set({
      [STORAGE_KEYS.accepted]: true,
      [STORAGE_KEYS.version]: CONSENT_VERSION,
      [STORAGE_KEYS.acceptedAt]: acceptedAt
    });
    status = { accepted: true, version: CONSENT_VERSION, acceptedAt };
    notify();
    hide();
    return status;
  }

  async function requireAccepted() {
    status = await getStatus();
    notify();
    if (status.accepted) return true;
    show();
    return false;
  }

  function bindStorage() {
    if (storageListenerBound) return;
    storageListenerBound = true;
    chrome.storage.onChanged.addListener((changes, areaName) => {
      if (areaName !== "local") return;
      if (!Object.values(STORAGE_KEYS).some((key) => Object.prototype.hasOwnProperty.call(changes, key))) return;
      getStatus().then((nextStatus) => {
        status = nextStatus;
        notify();
      }).catch(() => {});
    });
  }

  function mount() {
    if (mounted) return;
    mounted = true;
    const root = document.createElement("section");
    root.className = "legalBackdrop";
    root.id = "legalConsentDialog";
    root.setAttribute("role", "dialog");
    root.setAttribute("aria-modal", "true");
    root.setAttribute("aria-labelledby", "legalConsentTitle");
    root.hidden = true;
    const iconUrl = chrome.runtime.getURL("icon128.png");
    root.innerHTML = `
      <div class="legalDialog">
        <span class="legalIconBadge" aria-hidden="true">
          <img src="${escapeHtml(iconUrl)}" alt="">
        </span>
        <header class="legalHeader">
          <span class="legalVersion">v${escapeHtml(chrome.runtime.getManifest().version)}</span>
          <h1 id="legalConsentTitle">免责声明与用户协议</h1>
          <p>使用插件功能前，请确认你会在合法授权范围内操作。</p>
        </header>
        <div class="legalBody" tabindex="0">
          <p>协议正文加载中...</p>
        </div>
        <label class="legalCheck">
          <input id="legalConsentCheck" type="checkbox">
          <span>我已阅读、理解并同意以上免责声明和用户协议。</span>
        </label>
        <footer class="legalActions">
          <button class="legalSecondary" id="legalDeclineButton" type="button">拒绝</button>
          <button class="legalPrimary" id="legalAcceptButton" type="button" disabled>同意并继续</button>
        </footer>
      </div>
    `;
    document.body.appendChild(root);
    loadAgreementBody(root.querySelector(".legalBody"));

    const checkbox = root.querySelector("#legalConsentCheck");
    const acceptButton = root.querySelector("#legalAcceptButton");
    checkbox?.addEventListener("change", () => {
      acceptButton.disabled = checkbox.checked !== true;
    });
    acceptButton?.addEventListener("click", () => {
      if (acceptButton.disabled) return;
      acceptButton.disabled = true;
      accept().catch(() => {
        acceptButton.disabled = checkbox?.checked !== true;
      });
    });
    root.querySelector("#legalDeclineButton")?.addEventListener("click", () => window.close());
  }

  function show() {
    mount();
    const root = document.querySelector("#legalConsentDialog");
    if (!root) return;
    root.hidden = false;
    root.querySelector("#legalConsentCheck").checked = false;
    root.querySelector("#legalAcceptButton").disabled = true;
    setTimeout(() => root.querySelector(".legalBody")?.focus?.(), 20);
  }

  function hide() {
    const root = document.querySelector("#legalConsentDialog");
    if (root) root.hidden = true;
  }

  async function loadAgreementBody(container) {
    if (!container) return;
    try {
      const response = await fetch(chrome.runtime.getURL(AGREEMENT_PATH));
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      container.innerHTML = await response.text();
    } catch {
      container.innerHTML = "<p><strong>协议正文加载失败：</strong>请确认 legal/consent-agreement.html 已随插件包发布。</p>";
    }
  }

  function notify() {
    if (changeHandler) changeHandler({ ...status });
  }

  function escapeHtml(value) {
    return String(value || "").replace(/[&<>"']/g, (char) => ({
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#39;"
    }[char]));
  }

  window.MMWLegalConsent = {
    CONSENT_VERSION,
    STORAGE_KEYS,
    REQUIRED_MESSAGE,
    init,
    getStatus,
    requireAccepted,
    show,
    hide
  };
})();
