import {
  isRegistered,
  register,
  type ShortcutEvent,
  unregister,
} from '@tauri-apps/plugin-global-shortcut';

// Maps a KeyboardEvent.code (what our PTT settings store) into the shortcut
// string accepted by tauri-plugin-global-shortcut. The plugin follows the
// [keyboard-types] crate naming which mostly matches DOM `event.code`, but
// single-key aliases (e.g. "Space", "F5") work as-is.
export function codeToShortcut(code: string): string {
  if (code.startsWith('Key')) return code.slice(3); // KeyV -> V
  if (code.startsWith('Digit')) return code.slice(5); // Digit1 -> 1
  // Space, F1..F24, Escape, Enter, Tab, Arrow*, etc. pass through unchanged.
  return code;
}

export async function registerPttShortcut(
  code: string,
  onPress: () => void,
  onRelease: () => void,
): Promise<boolean> {
  const shortcut = codeToShortcut(code);
  try {
    if (await isRegistered(shortcut)) {
      await unregister(shortcut);
    }
    await register(shortcut, (event: ShortcutEvent) => {
      if (event.state === 'Pressed') onPress();
      else if (event.state === 'Released') onRelease();
    });
    return true;
  } catch (err: unknown) {
    console.warn('registerPttShortcut failed', { code, err });
    return false;
  }
}

export async function unregisterPttShortcut(code: string): Promise<void> {
  const shortcut = codeToShortcut(code);
  try {
    if (await isRegistered(shortcut)) {
      await unregister(shortcut);
    }
  } catch (err: unknown) {
    console.warn('unregisterPttShortcut failed', { code, err });
  }
}

// Detects whether we're running under Tauri. When running in a pure web
// preview (vite dev in a browser without Tauri), importing the plugin still
// works but calls fall through to window.__TAURI_INTERNALS__ which doesn't
// exist — use this guard to skip registration cleanly.
export function isTauriRuntime(): boolean {
  return typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
}
