// @ts-nocheck
/**
 * Scrying Pool Settings Application
 * Provides a settings panel with a button to reopen the strip
 */

// Conditional base class — test environment lacks foundry globals.
const _AppBase =
  typeof foundry !== 'undefined' &&
  foundry.applications?.api?.HandlebarsApplicationMixin &&
  foundry.applications?.api?.ApplicationV2
    ? foundry.applications.api.HandlebarsApplicationMixin(
        foundry.applications.api.ApplicationV2
      )
    : class _FallbackApp {
        static DEFAULT_OPTIONS = {};
        static PARTS = {};
        constructor(options = {}) { this.options = options; }
        get rendered() { return this._rendered ?? false; }
        set rendered(v) { this._rendered = v; }
        get element() { return this._element ?? null; }
        set element(v) { this._element = v; }
        async render() { this._rendered = true; }
        async close() { this._rendered = false; }
        async _prepareContext() { return {}; }
        _onRender() {}
        _onClose() {}
        _onPosition() {}
      };

export class ScryingPoolSettings extends _AppBase {
  static DEFAULT_OPTIONS = {
    id: 'scrying-pool-settings',
    classes: ['scrying-pool', 'scrying-pool-settings'],
    window: { title: 'Scrying Pool Settings', resizable: true },
    position: { width: 320, height: 200 },
  };

  static PARTS = {
    content: {
      template: 'modules/scrying-pool/templates/settings.hbs',
    },
  };

  /**
   * @param {object} options - Application options
   * @param {object} roleRenderer - The role renderer instance to access openStrip/closeStrip
   */
  constructor(roleRenderer, options = {}) {
    super(options);
    this._roleRenderer = roleRenderer;
  }

  /** @inheritdoc */
  async _prepareContext(options) {
    return {
      hasStrip: this._roleRenderer?._strip?.rendered ?? false,
    };
  }

  /** @inheritdoc */
  async _onRender(context, options) {
    super._onRender(context, options);
    
    // Add click handler for window close button
    const windowCloseBtn = this.element.querySelector('[data-action="close"]');
    if (windowCloseBtn) {
      windowCloseBtn.addEventListener('click', () => this.close());
    }

    // Add click handler for reopen button
    const reopenBtn = this.element.querySelector('[data-action="reopen-strip"]');
    if (reopenBtn) {
      reopenBtn.addEventListener('click', () => {
        this._roleRenderer?.openStrip();
        this.close();
      });
    }

    // Add click handler for close strip button
    const closeBtn = this.element.querySelector('[data-action="close-strip"]');
    if (closeBtn) {
      closeBtn.addEventListener('click', () => {
        this._roleRenderer?.closeStrip();
        this.close();
      });
    }
  }

  /**
   * Toggle the strip open/closed
   */
  _toggleStrip() {
    if (this._roleRenderer?._strip?.rendered) {
      this._roleRenderer.closeStrip();
    } else {
      this._roleRenderer?.openStrip();
    }
  }
}
