// Redirect globals to window.opener.
["Math", "foundry", "game", "ui"].forEach(p => window[p] = window.opener[p]);

// Handle requests to open a child popup in this window's execution context.
window.document.addEventListener("foundry:openChildWindow", e => {
  e.result = window.open("detached/index.html", e.detail.id, e.detail.attrs);
});

// Handle closing.
window.addEventListener("beforeunload", () => foundry.applications.detached._onWindowClosed(window));

/**
 * A class responsible for handling resize events on this window.
 */
class ResizeManager {
  /**
   * This detached window's primary application.
   * @type {ApplicationV2}
   */
  get primary() {
    const app = foundry.applications.detached.windows.get(window.id)?.applications.get(window.id);
    if ( app ) {
      Object.defineProperty(this, "primary", { value: app, writable: false });
      return app;
    }
  }

  /* -------------------------------------------- */

  /**
   * Whether events are throttled.
   * @type {boolean}
   */
  #throttled = false;

  /* -------------------------------------------- */

  /**
   * Handle resizing the window.
   */
  onResize() {
    if ( this.#throttled || !this.primary?.options.window?.resizable ) return;
    this.#throttled = true;
    const { position } = this.primary;
    this.primary.setPosition({ width: window.innerWidth - position.left, height: window.innerHeight - position.top });
    requestAnimationFrame(() => this.#throttled = false);
  }

  /* -------------------------------------------- */

  /**
   * Attach resize listeners.
   */
  static activateListeners() {
    const manager = new this();
    window.addEventListener("resize", manager.onResize.bind(manager), { passive: true });
  }
}

ResizeManager.activateListeners();
