import type { MobileMediaAdapter } from '../../contracts/mobile.contracts';
import { loadCapacitorAudioSessionPlugin } from './capacitor-plugin-loader';
import { loadMetoyouMobilePlugin } from './metoyou-mobile.plugin';
import { WebMobileMediaAdapter } from '../web/web-mobile-media.adapter';

/** Capacitor media adapter with native speaker routing and background voice session hooks. */
export class CapacitorMobileMediaAdapter extends WebMobileMediaAdapter implements MobileMediaAdapter {
  private backgroundSessionActive = false;

  override async setSpeakerphoneEnabled(enabled: boolean): Promise<void> {
    const MetoyouMobile = await loadMetoyouMobilePlugin();

    if (MetoyouMobile) {
      try {
        await MetoyouMobile.setSpeakerphoneEnabled({ enabled });
        return;
      } catch {
        // Android plugin unavailable in web builds; fall through to iOS audio session.
      }
    }

    const AudioSession = await loadCapacitorAudioSessionPlugin();

    if (!AudioSession) {
      return;
    }

    await AudioSession.overrideOutput(enabled ? 'speaker' : 'default');
  }

  override async startBackgroundAudioSession(): Promise<void> {
    if (this.backgroundSessionActive) {
      return;
    }

    this.backgroundSessionActive = true;

    const MetoyouMobile = await loadMetoyouMobilePlugin();

    if (!MetoyouMobile) {
      return;
    }

    try {
      await MetoyouMobile.startVoiceForegroundService();
    } catch (error) {
      console.info('[mobile] background voice foreground service unavailable', error);
    }
  }

  override async stopBackgroundAudioSession(): Promise<void> {
    if (!this.backgroundSessionActive) {
      return;
    }

    this.backgroundSessionActive = false;

    const MetoyouMobile = await loadMetoyouMobilePlugin();

    if (!MetoyouMobile) {
      return;
    }

    try {
      await MetoyouMobile.stopVoiceForegroundService();
    } catch (error) {
      console.info('[mobile] failed to stop background voice session', error);
    }
  }

  override isScreenShareSupported(): boolean {
    const userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : '';

    if (/iPhone|iPad|iPod/i.test(userAgent)) {
      return false;
    }

    return !!navigator.mediaDevices?.getDisplayMedia;
  }

  override isPictureInPictureSupported(): boolean {
    return super.isPictureInPictureSupported();
  }
}
