/**
 * WakeLock manages the screen wake lock to prevent the display from
 * dimming during active use (recording or processing).
 */
export class WakeLock {
  constructor() {
    this.wakeLock = null;
  }

  /**
   * acquire requests a screen wake lock. Idempotent.
   */
  async acquire() {
    if (this.wakeLock) return;
    if (!('wakeLock' in navigator)) return;

    try {
      this.wakeLock = await navigator.wakeLock.request('screen');
    } catch (e) {
      console.debug('wake lock acquire failed:', e);
    }
  }

  /**
   * release releases the active wake lock. Idempotent.
   */
  async release() {
    if (!this.wakeLock) return;

    try {
      await this.wakeLock.release();
    } catch (e) {
      console.debug('wake lock release failed:', e);
    }

    this.wakeLock = null;
  }

  /**
   * handleVisibilityChange reacquires the wake lock when the tab
   * becomes visible, if the app is currently active.
   * @param {boolean} isActive - Whether the app is recording or processing.
   */
  async handleVisibilityChange(isActive) {
    if (document.visibilityState !== 'visible') return;
    if (!isActive) return;
    await this.acquire();
  }
}
