import { registerPlugin, Capacitor, type PluginListenerHandle } from "@capacitor/core";

export interface InstalledPlayer {
  packageName: string;
  label: string;
}

export interface OpenExternalResult {
  launched: boolean;
  via?: string;
  /** When launched=false: "not-installed" | "activity-not-found". */
  reason?: "not-installed" | "activity-not-found";
  /** When reason=not-installed, the package the caller forced. */
  package?: string;
}

/**
 * Shape of a single entry in the right-side IPTV channel overlay.
 *
 * Sent to the native side ONLY for Live TV launches (the overlay is
 * hidden on VOD). The native player uses `streamUrl` to fast-zap
 * between channels without rebuilding ExoPlayer, and `number` as the
 * key that drives UP/DOWN zapping order.
 *
 * Every field except `name` + `streamUrl` is optional — pass what you
 * have. Missing EPG just hides the secondary text on each row.
 */
export interface NativeOverlayChannel {
  number?: number;
  name: string;
  category?: string;
  streamUrl: string;
  epgNow?: string;
  epgNext?: string;
  favorite?: boolean;
  /** Per-channel UA override; rare but supported. */
  userAgent?: string;
  /** Per-channel extra HTTP headers (Referer, Auth, etc.). */
  headers?: Record<string, string>;
  /** Optional logo URL. Ignored by the current native build but
   *  accepted for forward compatibility. */
  logoUrl?: string;
}

/** Returned by getLastPlayed(); see plugin Javadoc for details. */
export interface LastPlayed {
  hasLastPlayed: boolean;
  title?: string;
  url?: string;
  isLive?: boolean;
  userAgent?: string;
  channelNumber?: number;
  profileId?: string;
  savedAt?: number;
}

export interface NativePlayerPlugin {
  /** Launches the in-app fullscreen player (ExoPlayer / AVPlayer). */
  play(options: {
    url: string;
    title?: string;
    userAgent?: string;
    headers?: Record<string, string>;
    isLive?: boolean;
    /** Live TV only: full channel catalogue for the right-side overlay.
     *  Ignored for VOD. */
    channels?: NativeOverlayChannel[];
    /** Live TV only: which channel number to highlight as "now playing". */
    currentChannelNumber?: number;
  }): Promise<{ launched: boolean; via?: string }>;

  /**
   * Hands the stream URL off to an external video player.
   *
   * If you pass `package` and that app isn't installed, the native
   * side resolves with `{ launched: false, reason: "not-installed",
   * package }` — the UI can then prompt the user to install it.
   *
   * If no `package` is passed, the native side tries the preferred
   * list (VidoPlay → VLC → MX Player → Just Player → YTV Player) and
   * falls through to the system chooser + in-app ExoPlayer as a
   * last resort.
   */
  openExternal(options: {
    url: string;
    title?: string;
    userAgent?: string;
    headers?: Record<string, string>;
    /** Force a specific package, e.g. "org.videolan.vlc". */
    package?: string;
  }): Promise<OpenExternalResult>;

  /** Android: returns the list of apps that can handle m3u8 streams. */
  listInstalledPlayers(): Promise<{ players: InstalledPlayer[] }>;

  /** Android: is a specific package installed? */
  isInstalled(options: { package: string }): Promise<{ installed: boolean }>;

  /** Android: open the Play Store listing for a package. */
  openPlayStore(options: { package: string }): Promise<{ launched: boolean; via?: string }>;

  isAvailable(): Promise<{ available: boolean; engine: string }>;

  /** Last-played live channel persisted in native SharedPreferences.
   *  Used by the LiveTV page's "Resume {name}" cold-start toast. */
  getLastPlayed(): Promise<LastPlayed>;
  /** Wipe the saved last-played channel (e.g. when the user switches profile). */
  clearLastPlayed(): Promise<{ cleared: boolean }>;

  /** BUG FIX (2026-01) — "Clear Cache on logout": nuke every native
   *  storage layer (SharedPreferences, WebView cache, app cache dir)
   *  so the next user signing in starts from a perfectly clean slate.
   *
   *  PRESERVES (re-seeded after the wipe):
   *   • `nadiplay_lang`, `nadiplay_lang_chosen` — language picker
   *   • `nadiplay_device_id`                   — stable device seat ID
   *
   *  Destroys everything else: cached Xtream blobs, last-played
   *  channels, channel-store snapshots, AdMob plugin caches, the
   *  Capacitor WebView cookie jar, etc. */
  clearAppCache(): Promise<{ cleared: boolean }>;

  /** Fires whenever the native PlayerActivity tears down playback
   *  (Back press, swipe-from-Recents, PiP-close). Drives the
   *  interstitial-every-3rd-exit logic in `useExitInterstitial`.
   *
   *  This is the only event the plugin currently emits — using the
   *  standard Capacitor `addListener` signature, so existing consumers
   *  don't need a special API. */
  addListener(
    eventName: "playerExited",
    listenerFunc: () => void,
  ): Promise<PluginListenerHandle> & PluginListenerHandle;
}

export const NativePlayer = registerPlugin<NativePlayerPlugin>("NativePlayer");

export const isNativeApp = (): boolean => Capacitor.isNativePlatform();
export const nativePlatform = (): string => Capacitor.getPlatform();
