import type { MobileAppLifecycleAdapter } from '../../contracts/mobile.contracts';
import { loadCapacitorAppPlugin } from './capacitor-plugin-loader';

/** Capacitor App plugin lifecycle bridge. */
export class CapacitorMobileAppLifecycleAdapter implements MobileAppLifecycleAdapter {
  private handler: ((isActive: boolean) => void) | null = null;

  async initialize(): Promise<void> {
    const App = await loadCapacitorAppPlugin();

    if (!App) {
      return;
    }

    await App.addListener('appStateChange', (state) => {
      this.handler?.(state.isActive);
    });
  }

  onAppStateChange(handler: (isActive: boolean) => void): void {
    this.handler = handler;
  }
}
