/**
 * ScryingPoolCameraViews — replaces Foundry's CameraViews as CONFIG.ui.webrtc.
 *
 * Two responsibilities:
 *   1. Redirect the "configure" camera action to the Scrying Pool Directors Board
 *      instead of Foundry's native AVConfig dialog.
 *   2. Inject the Scrying Pool visibility state (sp-cam-hidden) into each user's
 *      camera context so the dock reflects the same hidden/active state as the
 *      module's state machine.
 *
 * Set as CONFIG.ui.webrtc in the 'init' hook (before Foundry instantiates ui.webrtc).
 * Dependencies are injected after 'ready' via initScryingPoolCameraViews().
 */

// Lazy base class — avoids ReferenceError at module load time in tests where
// foundry globals are not defined.
function _getCameraViewsBase() {
  if (typeof foundry !== 'undefined') {
    const cls = foundry.applications?.apps?.av?.CameraViews;
    if (cls) return cls;
  }
  // Minimal test-environment fallback — mirrors the pattern in DirectorsBoard.js
  return class _FallbackCameraViews {
    static DEFAULT_OPTIONS = {};
    static PARTS = {};
    constructor(options = {}) { this.options = options; }
    async render() {}
    async close() {}
    _prepareUserContext(_id) { return {}; }
    _onConfigure() {}
  };
}

/** @type {object|null} DirectorsBoard instance — set via initScryingPoolCameraViews */
let _directorsBoard = null;

/** @type {object|null} StateStore instance — set via initScryingPoolCameraViews */
let _stateStore = null;

/**
 * Inject module dependencies. Called from module.js after 'ready' resolves.
 * @param {object|null} directorsBoard - The singleton DirectorsBoard (GM only, else null)
 * @param {object} stateStore - The module StateStore
 */
export function initScryingPoolCameraViews(directorsBoard, stateStore) {
  _directorsBoard = directorsBoard;
  _stateStore = stateStore;
}

export class ScryingPoolCameraViews extends _getCameraViewsBase() {
  /**
   * Intercept the configure camera button.
   * Opens the Scrying Pool Directors Board instead of Foundry's AVConfig dialog.
   * For non-GM players, shows an informational notification since A/V config
   * is GM-controlled in this module.
   * @override
   */
  _onConfigure(event, target) {
    if (_directorsBoard) {
      _directorsBoard.render({ force: true });
    } else if (typeof ui !== 'undefined') {
      ui.notifications?.info(
        game?.i18n?.localize('scrying-pool.notifications.avConfigGMOnly') ??
        'A/V settings are managed by the GM.'
      );
    }
  }

  /**
   * Inject Scrying Pool visibility state into each user's camera tile context.
   * Marks hidden users with `spHidden: true` rather than returning null, so
   * Foundry's _configureRenderParts does not crash on a null part context.
   * @override
   * @param {string} id - User ID
   * @returns {object|undefined}
   */
  _prepareUserContext(id) {
    const ctx = super._prepareUserContext(id);
    const spState = _stateStore?.getState?.(id) ?? 'active';
    if (ctx && spState === 'hidden') ctx.spHidden = true;
    return ctx;
  }
}
