// Native shell integration for the Capacitor Android/iOS builds. Kept in its own
// module behind a dynamic import so the web / Telegram / VK / mock bundles never load
// @capacitor/app: initNativeShell early-returns off the native channels, so the import
// statement is only ever reached inside the packaged native app.

import { clientChannel } from './channel';
import { emit } from './netstate.svelte';

/**
 * initNativeShell wires native-shell behaviour that only applies inside the packaged
 * Capacitor app. Currently it binds the Android hardware Back button: at the navigation
 * root it exits the app, otherwise it steps the in-app (hash) history back. It is a
 * no-op on the web/Telegram/VK channels and never loads @capacitor/app there.
 *
 * atNavigationRoot reports whether the current route is a navigation root (the lobby or
 * login screen) — mirror App.svelte's routeDepth(...) === 0.
 */
export async function initNativeShell(atNavigationRoot: () => boolean): Promise<void> {
  const ch = clientChannel();
  if (ch !== 'android' && ch !== 'ios') return;
  try {
    const { App } = await import('@capacitor/app');
    await App.addListener('backButton', () => {
      if (atNavigationRoot()) void App.exitApp();
      else history.back();
    });
  } catch {
    // No Capacitor bridge behind window.Capacitor — an e2e simulating the native channel in a plain
    // browser, or a WebView without the App plugin: the hardware-Back binding is simply unavailable,
    // which is harmless off a real device. Never reached on the web (the early return above).
  }
}

/**
 * initNativeNetwork feeds the OS connectivity hint from @capacitor/network into the net-state machine
 * (osOnline / osOffline) on the packaged native app. It is a hint only — the machine's probe still
 * decides whether to actually go offline or heal to online — so on the web (which keeps navigator's
 * online/offline events, wired by initNetSignals) this is a no-op and never loads the plugin. Tolerates
 * a missing bridge (a WebView without the Network plugin) exactly like initNativeShell.
 */
export async function initNativeNetwork(): Promise<void> {
  const ch = clientChannel();
  if (ch !== 'android' && ch !== 'ios') return;
  try {
    const { Network } = await import('@capacitor/network');
    await Network.addListener('networkStatusChange', (status) => {
      emit(status.connected ? 'osOnline' : 'osOffline');
    });
  } catch {
    // No @capacitor/network bridge behind window.Capacitor (an e2e simulating native in a plain
    // browser, or a WebView without the plugin): the native hint is unavailable, which is harmless —
    // the gateway probe still drives the machine.
  }
}

