import { contextBridge, ipcRenderer } from 'electron'
import { IPC_CHANNELS } from '../shared/types'
import type { Channel, AppSettings, BurnVote, NotificationType, HeartbeatStats } from '../shared/types'

// Expose protected methods to renderer
contextBridge.exposeInMainWorld('electron', {
  // Window controls
  minimize: () => ipcRenderer.send('window:minimize'),
  maximize: () => ipcRenderer.send('window:maximize'),
  close: () => ipcRenderer.send('window:close'),

  // IP Service
  getIpInfo: () => ipcRenderer.invoke(IPC_CHANNELS.GET_IP_INFO),

  // Channel Management
  parseM3u8: (url: string) => ipcRenderer.invoke(IPC_CHANNELS.PARSE_M3U8, url),
  getChannels: () => ipcRenderer.invoke(IPC_CHANNELS.GET_CHANNELS),
  updateChannel: (channel: Channel) => ipcRenderer.invoke(IPC_CHANNELS.UPDATE_CHANNEL, channel),
  setChannelMonitored: (channelId: string, monitored: boolean) => 
    ipcRenderer.invoke(IPC_CHANNELS.SET_MONITORED, channelId, monitored),

  // Monitoring
  startMonitoring: () => ipcRenderer.invoke(IPC_CHANNELS.START_MONITORING),
  stopMonitoring: () => ipcRenderer.invoke(IPC_CHANNELS.STOP_MONITORING),
  getMonitoringStatus: () => ipcRenderer.invoke(IPC_CHANNELS.GET_MONITORING_STATUS),
  onMonitoringUpdate: (callback: (result: unknown) => void) => {
    const handler = (_event: Electron.IpcRendererEvent, result: unknown) => callback(result)
    ipcRenderer.on(IPC_CHANNELS.MONITORING_UPDATE, handler)
    return () => ipcRenderer.removeListener(IPC_CHANNELS.MONITORING_UPDATE, handler)
  },

  // Ping
  pingHost: (host: string) => ipcRenderer.invoke(IPC_CHANNELS.PING_HOST, host),

  // Notifications
  sendNotification: (title: string, body: string, type?: NotificationType) => 
    ipcRenderer.invoke(IPC_CHANNELS.SEND_NOTIFICATION, title, body, type),
  testNotification: (type: NotificationType) => 
    ipcRenderer.invoke(IPC_CHANNELS.TEST_NOTIFICATION, type),

  // Panel API
  panelRegister: (config: unknown) => ipcRenderer.invoke(IPC_CHANNELS.PANEL_REGISTER, config),
  panelGetIps: () => ipcRenderer.invoke(IPC_CHANNELS.PANEL_GET_IPS),
  panelSendVote: (vote: BurnVote) => ipcRenderer.invoke(IPC_CHANNELS.PANEL_SEND_VOTE, vote),
  panelHeartbeat: (stats: HeartbeatStats) => ipcRenderer.invoke(IPC_CHANNELS.PANEL_HEARTBEAT, stats),

  // Settings
  getSettings: () => ipcRenderer.invoke(IPC_CHANNELS.GET_SETTINGS),
  saveSettings: (settings: AppSettings) => ipcRenderer.invoke(IPC_CHANNELS.SAVE_SETTINGS, settings),

  // Error Log
  getErrorLog: () => ipcRenderer.invoke('errorlog:get'),
  clearErrorLog: () => ipcRenderer.invoke('errorlog:clear'),

  // App Info
  getAppInfo: () => ipcRenderer.invoke('app:info'),
})

