import type { MobilePictureInPictureAdapter } from '../../contracts/mobile.contracts';
import { loadMetoyouMobilePlugin } from './metoyou-mobile.plugin';
import { WebMobilePictureInPictureAdapter } from '../web/web-mobile-picture-in-picture.adapter';

/** Capacitor PiP adapter with Document PiP first and native Android PiP fallback. */
export class CapacitorMobilePictureInPictureAdapter extends WebMobilePictureInPictureAdapter implements MobilePictureInPictureAdapter {
  private nativeSupported: boolean | null = null;

  override isSupported(): boolean {
    if (super.isSupported()) {
      return true;
    }

    return this.nativeSupported === true;
  }

  override async enter(videoElement: HTMLVideoElement): Promise<void> {
    if (super.isSupported()) {
      await super.enter(videoElement);
      return;
    }

    const MetoyouMobile = await loadMetoyouMobilePlugin();

    if (!MetoyouMobile) {
      return;
    }

    const result = await MetoyouMobile.enterNativePictureInPicture();

    this.nativeSupported = result.supported;

    if (!result.supported) {
      return;
    }

    if (videoElement.paused) {
      await videoElement.play().catch(() => {});
    }
  }

  override async exit(): Promise<void> {
    if (document.pictureInPictureElement) {
      await super.exit();
    }

    const MetoyouMobile = await loadMetoyouMobilePlugin();

    if (!MetoyouMobile) {
      return;
    }

    await MetoyouMobile.exitNativePictureInPicture().catch(() => {});
  }
}
