import { BrowserWindow, globalShortcut } from "electron"
import type { VoiceConfig } from "./voice-types"

export type VoiceShortcutController = {
  register: (hotkey: string) => boolean
  unregister: () => void
  getHotkey: () => string
}

/**
 * Electron globalShortcut only fires on keydown (not keyup), so true hold-to-talk
 * is approximated: first press starts recording, second press stops.
 * Double-press within 400ms is handled by VoiceManager as an explicit toggle.
 */
export function createVoiceShortcut(input: {
  getConfig: () => VoiceConfig
  onPress: () => void
}): VoiceShortcutController {
  let current = ""

  const unregister = () => {
    if (!current) return
    try {
      globalShortcut.unregister(current)
    } catch {}
    current = ""
  }

  const register = (hotkey: string) => {
    unregister()
    if (!hotkey || !input.getConfig().enabled) return false
    const accelerator = toAccelerator(hotkey)
    const ok = globalShortcut.register(accelerator, () => {
      const win = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0]
      if (win && !win.isDestroyed()) {
        if (win.isMinimized()) win.restore()
        win.show()
        win.focus()
      }
      input.onPress()
    })
    if (ok) current = accelerator
    return ok
  }

  return {
    register,
    unregister,
    getHotkey: () => current,
  }
}

function toAccelerator(hotkey: string) {
  return hotkey
    .split("+")
    .map((part) => {
      const key = part.trim()
      if (/^alt$/i.test(key)) return "Alt"
      if (/^ctrl|control$/i.test(key)) return "Control"
      if (/^shift$/i.test(key)) return "Shift"
      if (/^meta|cmd|command|super|win$/i.test(key)) return "Super"
      if (/^space$/i.test(key)) return "Space"
      return key.length === 1 ? key.toUpperCase() : key
    })
    .join("+")
}
