import { contextBridge, ipcRenderer } from 'electron';

function createOutputListener(channel: string) {
  return (callback: (output: string) => void): (() => void) => {
    const listener = (_event: any, output: string) => callback(output);
    ipcRenderer.on(channel, listener);
    return () => ipcRenderer.removeListener(channel, listener);
  };
}

import type {
  LearnerHubSetupState,
  SetupWizardStepConfig,
  StepValidationResult,
  InstallResult
} from '../renderer/types';

try {
  contextBridge.exposeInMainWorld('__LEARNER_HUB_PRELOAD_LOADED__', true);

  contextBridge.exposeInMainWorld('learnerHubAPI', {
    getState: async (): Promise<LearnerHubSetupState> => {
      return ipcRenderer.invoke('learner-hub:get-state');
    },

    setState: async (state: LearnerHubSetupState): Promise<void> => {
      return ipcRenderer.invoke('learner-hub:set-state', state);
    },

    getSteps: async (): Promise<SetupWizardStepConfig[]> => {
      return ipcRenderer.invoke('learner-hub:get-steps');
    },

    validateStep: async (stepId: string): Promise<StepValidationResult> => {
      return ipcRenderer.invoke('learner-hub:validate-step', stepId);
    },

    cloneRepository: async (baseDirectory: string): Promise<InstallResult> => {
      return ipcRenderer.invoke('learner-hub:clone-repository', baseDirectory);
    },

    onCloneOutput: createOutputListener('learner-hub:clone-output'),

    getRepositoryStatus: async (baseDirectory?: string): Promise<any> => {
      return ipcRenderer.invoke('learner-hub:get-repository-status', baseDirectory);
    },

    resetRepository: async (baseDirectory: string): Promise<InstallResult> => {
      return ipcRenderer.invoke('learner-hub:reset-repository', baseDirectory);
    },

    onResetOutput: createOutputListener('learner-hub:reset-output'),

    getConfig: async (): Promise<any> => {
      return ipcRenderer.invoke('learner-hub:get-config');
    },

    selectCloneFolder: async (): Promise<string | null> => {
      return ipcRenderer.invoke('learner-hub:select-folder');
    },

    saveCloneFolder: async (folder: string): Promise<void> => {
      return ipcRenderer.invoke('learner-hub:save-folder', folder);
    },

    openCanvasSetup: async (): Promise<void> => {
      return ipcRenderer.invoke('learner-hub:open-canvas-setup');
    },

    updateTrayIcon: async (): Promise<void> => {
      return ipcRenderer.invoke('learner-hub:update-tray-icon');
    },

    getTheme: async (): Promise<string> => {
      return ipcRenderer.invoke('settings:get-theme');
    },

    onThemeChange: createOutputListener('theme-changed')
  });
} catch (error) {
  console.error('[Learner Hub Preload] CRITICAL ERROR during API exposure:', error);
  throw error;
}
