/**
 * Native chrome for Capacitor shells (#20 Android, #21 iOS).
 * Hardware back (Android), status bar, keyboard resize. No-ops on web.
 */

import { isNativePlatform } from './nativePlatform';

/**
 * Register Android back-button: pop history when possible, else exit app at root.
 * Call once after React mounts.
 * @returns {Promise<(() => void) | undefined>} unsubscribe
 */
export async function setupAndroidBackButton() {
  if (!isNativePlatform()) {
    return undefined;
  }

  const { App } = await import('@capacitor/app');

  const handle = await App.addListener('backButton', ({ canGoBack }) => {
    if (canGoBack || (typeof window !== 'undefined' && window.history.length > 1)) {
      window.history.back();
      return;
    }
    App.exitApp();
  });

  return () => {
    handle.remove();
  };
}

/**
 * Configure status bar + keyboard resize so MUI layout respects safe areas.
 * @returns {Promise<void>}
 */
export async function setupNativeChrome() {
  if (!isNativePlatform()) {
    return;
  }

  try {
    const { StatusBar, Style } = await import('@capacitor/status-bar');
    await StatusBar.setOverlaysWebView({ overlay: false });
    await StatusBar.setStyle({ style: Style.Dark });
  } catch {
    /* plugin optional at runtime */
  }

  try {
    const { Keyboard, KeyboardResize } = await import('@capacitor/keyboard');
    if (typeof Keyboard.setResizeMode === 'function') {
      await Keyboard.setResizeMode({ mode: KeyboardResize.Body });
    }
  } catch {
    /* Keyboard.setResizeMode is Android-only; ignore on iOS / missing plugin */
  }
}
