(function installAccountSessionUi(root) {
  const EVENT_TYPE = "MMW_ACCOUNT_REMOTE_LOGIN";
  const STORAGE_KEY = "mmwAccountRemoteLogin";
  const HOST_ID = "mmw-account-remote-login-layer";
  const DEFAULT_MESSAGE = "该账号异地登录，若非本人确认请及时修改密码";

  function hideCard() {
    root.document?.getElementById(HOST_ID)?.remove();
    root.chrome?.storage?.local?.remove?.([STORAGE_KEY]).catch(() => {});
  }

  function showCard(state = {}) {
    if (!root.document || root.document.getElementById(HOST_ID)) return;
    const message = String(state?.message || DEFAULT_MESSAGE);
    const remote = state?.remoteLogin && typeof state.remoteLogin === "object" ? state.remoteLogin : {};
    const details = [
      ["对方 IP", remote.loginIp],
      ["登录时间", remote.loginAt],
      ["登录设备", remote.deviceName]
    ].filter(([, value]) => String(value || "").trim());
    const host = root.document.createElement("div");
    host.id = HOST_ID;
    host.className = "mmw-account-remote-login-layer";
    host.innerHTML = `
      <section class="mmw-account-remote-login-card" role="alertdialog" aria-modal="true" aria-labelledby="mmw-account-remote-login-title">
        <span class="mmw-account-remote-login-icon" aria-hidden="true">
          <svg viewBox="0 0 24 24" width="27" height="27" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M20 13c0 5-3.5 7.5-8 9-4.5-1.5-8-4-8-9V5l8-3 8 3v8Z"/><path d="M12 8v4M12 16h.01"/></svg>
        </span>
        <h2 id="mmw-account-remote-login-title">账号已在其他设备登录</h2>
        <p></p>
        <dl class="mmw-account-remote-login-details" aria-label="新登录信息"></dl>
        <button type="button">返回登录</button>
      </section>`;
    host.querySelector("p").textContent = String(message || DEFAULT_MESSAGE);
    const detailList = host.querySelector("dl");
    if (details.length) {
      details.forEach(([label, value]) => {
        const row = root.document.createElement("div");
        const term = root.document.createElement("dt");
        const description = root.document.createElement("dd");
        term.textContent = label;
        description.textContent = String(value);
        row.append(term, description);
        detailList.append(row);
      });
    } else {
      detailList.remove();
    }
    host.querySelector("button").addEventListener("click", hideCard);
    (root.document.body || root.document.documentElement).append(host);
  }

  root.chrome?.runtime?.onMessage?.addListener?.((message) => {
    if (message?.type === EVENT_TYPE && message.active !== false) showCard(message);
  });
  root.chrome?.storage?.local?.get?.([STORAGE_KEY]).then((stored) => {
    const state = stored?.[STORAGE_KEY];
    if (state?.active) showCard(state);
  }).catch(() => {});
})(globalThis);
