(() => {
  "use strict";

  const GLOBAL_KEY = "__IGBLUE_UNLOAD_COMPAT_V277__";
  const STORAGE_KEY = "IGBLUE/unload_compat_v277";
  const SCHEMA = "igblue_unload_compat_v277";

  const previous = window[GLOBAL_KEY];
  if (previous && previous.schema === SCHEMA && previous.installed === true) {
    previous.reinjection_count = Number(previous.reinjection_count || 0) + 1;
    previous.last_reinjected_at = Date.now();
    try { previous.persist(); } catch (_) {}
    return;
  }

  const originalAdd = window.addEventListener;
  const originalRemove = window.removeEventListener;
  const originalAddOwnDescriptor = Object.getOwnPropertyDescriptor(window, "addEventListener");
  const originalRemoveOwnDescriptor = Object.getOwnPropertyDescriptor(window, "removeEventListener");
  if (typeof originalAdd !== "function" || typeof originalRemove !== "function") return;

  const state = {
    schema: SCHEMA,
    installed: false,
    installed_at: Date.now(),
    last_reinjected_at: 0,
    reinjection_count: 0,
    add_converted: 0,
    remove_converted: 0,
    last_action: "installing",
    last_action_at: Date.now(),
    last_error: "",
    snapshot() {
      return {
        schema: this.schema,
        installed: this.installed === true,
        installed_at: Number(this.installed_at || 0),
        last_reinjected_at: Number(this.last_reinjected_at || 0),
        reinjection_count: Number(this.reinjection_count || 0),
        add_converted: Number(this.add_converted || 0),
        remove_converted: Number(this.remove_converted || 0),
        last_action: String(this.last_action || ""),
        last_action_at: Number(this.last_action_at || 0),
        last_error: String(this.last_error || "")
      };
    },
    persist() {
      try { localStorage.setItem(STORAGE_KEY, JSON.stringify(this.snapshot())); } catch (_) {}
    }
  };

  function record(action) {
    state.last_action = action;
    state.last_action_at = Date.now();
    state.persist();
  }

  function addEventListenerCompat(type, listener, options) {
    if (this === window && type === "unload") {
      state.add_converted += 1;
      record("add:unload->pagehide");
      return Reflect.apply(originalAdd, this, ["pagehide", listener, options]);
    }
    return Reflect.apply(originalAdd, this, arguments);
  }

  function removeEventListenerCompat(type, listener, options) {
    if (this === window && type === "unload") {
      state.remove_converted += 1;
      record("remove:unload->pagehide");
      return Reflect.apply(originalRemove, this, ["pagehide", listener, options]);
    }
    return Reflect.apply(originalRemove, this, arguments);
  }

  let addInstalled = false;
  let removeInstalled = false;
  let stateInstalled = false;
  try {
    Object.defineProperty(window, "addEventListener", {
      configurable: true,
      enumerable: false,
      writable: true,
      value: addEventListenerCompat
    });
    addInstalled = true;
    Object.defineProperty(window, "removeEventListener", {
      configurable: true,
      enumerable: false,
      writable: true,
      value: removeEventListenerCompat
    });
    removeInstalled = true;
    Object.defineProperty(window, GLOBAL_KEY, {
      configurable: true,
      enumerable: false,
      writable: false,
      value: state
    });
    stateInstalled = true;
    state.installed = true;
    record("installed");
    try { console.info("[IGBLUE v277] window unload listeners are mapped to pagehide"); } catch (_) {}
  } catch (error) {
    state.last_error = String(error && error.message || error || "install_failed");
    state.last_action = "install_failed";
    state.last_action_at = Date.now();
    state.persist();
    try {
      if (stateInstalled) delete window[GLOBAL_KEY];
      if (removeInstalled) {
        if (originalRemoveOwnDescriptor) Object.defineProperty(window, "removeEventListener", originalRemoveOwnDescriptor);
        else delete window.removeEventListener;
      }
      if (addInstalled) {
        if (originalAddOwnDescriptor) Object.defineProperty(window, "addEventListener", originalAddOwnDescriptor);
        else delete window.addEventListener;
      }
    } catch (_) {}
    try { console.warn("[IGBLUE v277] unload compatibility install failed", error); } catch (_) {}
  }
})();
