/**
 * The desktop app's bridge (`window.electronAPI`, exposed by pharmacy-desktop/preload.js), typed in one place, and
 * how a page tells it is running in the desktop app. Keep the type in step with preload.js.
 */
import { useSyncExternalStore } from "react";

export type ElectronApi = {
  isElectron?: boolean;
  /** The configured API URL: config.json, PHARMAPOS_API_BASE, or main.js's default */
  apiBase?: string;
  setApiBase?: (value: string) => Promise<unknown>;
  getConfigPath?: () => Promise<string>;
  getAppInfo?: () => Promise<unknown>;
  printPage?: () => Promise<unknown>;
  platform?: string;
};

export const electronApi = (): ElectronApi | undefined =>
  typeof window === "undefined" ? undefined : (window as Window & { electronAPI?: ElectronApi }).electronAPI;

export const isDesktopApp = (): boolean =>
  typeof window !== "undefined" && (!!electronApi() || navigator.userAgent.includes("Electron"));

const never = () => () => {};

/** True in the desktop app. False on the server and in the first client render, so hydration matches. */
export const useIsDesktop = (): boolean => useSyncExternalStore(never, isDesktopApp, () => false);
