/**
 * Platform adapter — abstracts Electron-specific capabilities behind a
 * uniform interface so the same React components run in both Electron and
 * a standalone web SPA.
 *
 * Usage:
 *   <PlatformProvider value={electronPlatform}>  (Electron entry point)
 *   <PlatformProvider value={webPlatform}>        (Web entry point)
 *
 *   const platform = usePlatform();
 *   if (platform.isElectron) { ... }
 */
import { createContext, useContext, type ReactNode } from 'react';

export interface FileDialogResult {
  canceled: boolean;
  filePaths: string[];
}

export interface FileDialogOptions {
  properties?: string[];
  title?: string;
  defaultPath?: string;
  filters?: { name: string; extensions: string[] }[];
  multiSelections?: boolean;
}

export interface Platform {
  /** Runtime identifier. */
  readonly id: 'electron' | 'web';
  /** True when running inside Electron. */
  readonly isElectron: boolean;
  /** True when running as a standalone web SPA. */
  readonly isWeb: boolean;
  /** True when local agent filesystem features are available. */
  readonly hasLocalAgents: boolean;
  /** True when a native file dialog is available. */
  readonly hasFileDialog: boolean;
  /** Open a native (or web-fallback) file/directory picker. */
  showOpenDialog(options: FileDialogOptions): Promise<FileDialogResult>;
}

// ── Electron platform ────────────────────────────────────────────────

export const electronPlatform: Platform = {
  id: 'electron',
  isElectron: true,
  isWeb: false,
  hasLocalAgents: true,
  hasFileDialog: true,
  showOpenDialog(options: FileDialogOptions): Promise<FileDialogResult> {
    return window.electronDialog.showOpenDialog(options);
  },
};

// ── Web platform ─────────────────────────────────────────────────────

export const webPlatform: Platform = {
  id: 'web',
  isElectron: false,
  isWeb: true,
  hasLocalAgents: false,
  hasFileDialog: false,
  async showOpenDialog(): Promise<FileDialogResult> {
    // Web has no native directory picker — return canceled.
    return { canceled: true, filePaths: [] };
  },
};

// ── React context ────────────────────────────────────────────────────

const PlatformContext = createContext<Platform>(electronPlatform);

export function PlatformProvider({
  value,
  children,
}: {
  value: Platform;
  children: ReactNode;
}) {
  return (
    <PlatformContext.Provider value={value}>{children}</PlatformContext.Provider>
  );
}

export function usePlatform(): Platform {
  return useContext(PlatformContext);
}
