import { contextBridge, ipcRenderer } from 'electron';

console.log('[Career Wizard Preload] Electron modules imported');

// Inline the createOutputListener to avoid module resolution issues in preload context
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);
    };
  };
}

console.log('[Career Wizard Preload] Listener helpers defined');

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

console.log('[Career Wizard Preload] Starting to load preload script...');

// CRITICAL: Expose API BEFORE any imports or complex logic
try {
  console.log('[Career Wizard Preload] About to expose API...');

  // Add a marker to verify preload loaded
  contextBridge.exposeInMainWorld('__CAREER_PRELOAD_LOADED__', true);
  console.log('[Career Wizard Preload] Marker exposed');

  // Expose protected methods that allow the renderer process to use
  // ipcRenderer without exposing the entire object
  contextBridge.exposeInMainWorld('careerWizardAPI', {
    // State management
    getState: async (): Promise<CareerSetupState> => {
      return ipcRenderer.invoke('career-wizard:get-state');
    },

    setState: async (state: CareerSetupState): Promise<void> => {
      return ipcRenderer.invoke('career-wizard:set-state', state);
    },

    // Step management
    getSteps: async (): Promise<SetupWizardStepConfig[]> => {
      return ipcRenderer.invoke('career-wizard:get-steps');
    },

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

    // Career-specific operations
    cloneRepositories: async (baseDirectory: string): Promise<InstallResult> => {
      return ipcRenderer.invoke('career-wizard:clone-repositories', baseDirectory);
    },

    onCloneOutput: createOutputListener('career:clone-output'),

    getRepositoriesStatus: async (baseDirectory?: string): Promise<any> => {
      return ipcRenderer.invoke('career-wizard:get-repositories-status', baseDirectory);
    },

    resetRepositories: async (baseDirectory: string): Promise<InstallResult> => {
      return ipcRenderer.invoke('career-wizard:reset-repositories', baseDirectory);
    },

    onResetOutput: createOutputListener('career:reset-output'),

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

    createConfig: async (config: any): Promise<InstallResult> => {
      return ipcRenderer.invoke('career-wizard:create-config', config);
    },

    // Folder selection
    selectCloneFolder: async (): Promise<string | null> => {
      return ipcRenderer.invoke('career-wizard:select-folder');
    },

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

    // Helper to open Canvas Setup
    openCanvasSetup: async (): Promise<void> => {
      return ipcRenderer.invoke('career-wizard:open-canvas-setup');
    },

    // Tray icon update
    updateTrayIcon: async (): Promise<void> => {
      return ipcRenderer.invoke('career-wizard:update-tray-icon');
    },

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

    // Theme change listener
    onThemeChange: createOutputListener('theme-changed')
  });

  console.log('[Career Wizard Preload] API exposed successfully');
} catch (error) {
  console.error('[Career Wizard Preload] CRITICAL ERROR during API exposure:', error);
  throw error;
}

console.log('[Career Wizard Preload] Preload script loaded successfully');
