import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';

// Expose protected methods to renderer
contextBridge.exposeInMainWorld('electron', {
  // Rich Presence
  setRichPresence: (activity: any) => ipcRenderer.invoke('set-rich-presence', activity),

  // Screen Sharing
  getSources: () => ipcRenderer.invoke('get-sources'),

  // Notifications
  showNotification: (notification: any) => ipcRenderer.send('show-notification', notification),

  // Auto-launch
  getAutoLaunch: () => ipcRenderer.invoke('get-auto-launch'),
  setAutoLaunch: (enabled: boolean) => ipcRenderer.invoke('set-auto-launch', enabled),

  // Badge count
  setBadgeCount: (count: number) => ipcRenderer.invoke('set-badge-count', count),

  // Window controls
  minimizeWindow: () => ipcRenderer.send('minimize-window'),
  maximizeWindow: () => ipcRenderer.send('maximize-window'),
  closeWindow: () => ipcRenderer.send('close-window'),

  // Event listeners
  onPushToTalkPressed: (callback: () => void) => {
    ipcRenderer.on('push-to-talk-pressed', callback);
  },

  onToggleMute: (callback: (muted: boolean) => void) => {
    ipcRenderer.on('toggle-mute', (event: IpcRendererEvent, muted: boolean) => callback(muted));
  },

  onToggleDeafen: (callback: (deafened: boolean) => void) => {
    ipcRenderer.on('toggle-deafen', (event: IpcRendererEvent, deafened: boolean) =>
      callback(deafened)
    );
  },

  onOpenSettings: (callback: () => void) => {
    ipcRenderer.on('open-settings', callback);
  },

  onDeepLink: (callback: (url: string) => void) => {
    ipcRenderer.on('deep-link', (event: IpcRendererEvent, url: string) => callback(url));
  },

  // Remove listeners
  removeListener: (channel: string, callback: any) => {
    ipcRenderer.removeListener(channel, callback);
  },
});

// Type definitions for window.electron
export interface ElectronAPI {
  setRichPresence: (activity: any) => Promise<any>;
  getSources: () => Promise<Array<{ id: string; name: string; thumbnail: string }>>;
  showNotification: (notification: { title: string; body: string; icon?: string }) => void;
  getAutoLaunch: () => Promise<boolean>;
  setAutoLaunch: (enabled: boolean) => Promise<{ success: boolean }>;
  setBadgeCount: (count: number) => Promise<{ success: boolean }>;
  minimizeWindow: () => void;
  maximizeWindow: () => void;
  closeWindow: () => void;
  onPushToTalkPressed: (callback: () => void) => void;
  onToggleMute: (callback: (muted: boolean) => void) => void;
  onToggleDeafen: (callback: (deafened: boolean) => void) => void;
  onOpenSettings: (callback: () => void) => void;
  onDeepLink: (callback: (url: string) => void) => void;
  removeListener: (channel: string, callback: any) => void;
}

declare global {
  interface Window {
    electron: ElectronAPI;
  }
}
