// @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} roleRenderer - The role renderer instance to access openStrip/closeStrip
   * @param {object} adapter - FoundryAdapter instance
   * @param {object} options - Application options
   */
  constructor(roleRenderer, adapter, options = {}) {
    super(options);
    this._roleRenderer = roleRenderer;
    this._adapter = adapter;
    this._changingLayout = false;
  }

  /** @inheritdoc */
  async _prepareContext(options) {
    const currentDockLayout = this._adapter?.settings?.get?.('dockLayout') ?? 'vertical-sm';
    const DOCK_LAYOUTS = [
      { key: 'vertical-sm',    icon: 'fa-grip-vertical',   size: 'S', sepAfter: false },
      { key: 'vertical-md',    icon: 'fa-grip-vertical',   size: 'L', sepAfter: true  },
      { key: 'horizontal-sm',  icon: 'fa-grip-horizontal', size: 'S', sepAfter: false },
      { key: 'horizontal-md',  icon: 'fa-grip-horizontal', size: 'L', sepAfter: true  },
      { key: 'mosaic-sm',      icon: 'fa-border-all',      size: 'S', sepAfter: false },
      { key: 'mosaic-md',      icon: 'fa-border-all',      size: 'L', sepAfter: false },
      { key: 'freeform',       icon: 'fa-window-restore',  size: 'W', sepAfter: false },
    ];
    const dockLayouts = DOCK_LAYOUTS.map(l => ({
      ...l,
      isActive: l.key === currentDockLayout,
      label: l.key,
    }));

    return {
      hasStrip: this._roleRenderer?._strip?.rendered ?? false,
      dockLayouts,
      currentDockLayout,
    };
  }

  /** @inheritdoc */
  async _onRender(context, options) {
    super._onRender(context, options);

    // Prevent re-entrant layout changes
    if (this._changingLayout) return;

    // Delegate all button clicks via a single listener
    const handler = (e) => {
      const btn = e.target.closest('[data-action]');
      if (!btn) return;

      switch (btn.dataset.action) {
        case 'close':
          this.close();
          break;
        case 'reopen-strip':
          this._roleRenderer?.openStrip();
          this.close();
          break;
        case 'close-strip':
          this._roleRenderer?.closeStrip();
          this.close();
          break;
        case 'set-dock-layout':
          this._onSetDockLayout(btn.dataset.layout);
          break;
      }
    };

    this.element.addEventListener('click', handler);
  }

  /**
   * Changes the dock layout via the adapter setting.
   * @param {string} layoutKey
   */
  async _onSetDockLayout(layoutKey) {
    if (this._changingLayout) return;
    this._changingLayout = true;
    try {
      await this._adapter?.settings?.set?.('dockLayout', layoutKey);
      await this._adapter?.settings?.set?.('dockLayoutExpanded', '');
      this.close();
    } catch (err) {
      console.error('[ScryingPool] Failed to set dockLayout:', err);
    } finally {
      this._changingLayout = false;
    }
  }

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