import type { CmuxClient } from './cmux-client.js';

// Map browser key names to cmux send-key names
const KEY_MAP: Record<string, string> = {
  Enter: 'enter',
  Escape: 'escape',
  Tab: 'tab',
  Backspace: 'backspace',
  Delete: 'delete',
  ArrowUp: 'arrow_up',
  ArrowDown: 'arrow_down',
  ArrowLeft: 'arrow_left',
  ArrowRight: 'arrow_right',
  Home: 'home',
  End: 'end',
  PageUp: 'page_up',
  PageDown: 'page_down',
  Space: 'space',
};

export class InputHandler {
  private client: CmuxClient;

  constructor(client: CmuxClient) {
    this.client = client;
  }

  async handleText(workspace: string, surface: string, text: string): Promise<void> {
    await this.client.sendText(workspace, surface, text);
  }

  async handleKey(workspace: string, surface: string, key: string): Promise<void> {
    // Handle Ctrl+key combos (from frontend: "Ctrl-c", "Ctrl-d", etc.)
    const ctrlMatch = key.match(/^(?:Ctrl|Control)[+-](.+)$/i);
    if (ctrlMatch) {
      const letter = ctrlMatch[1].toLowerCase();
      await this.client.sendKey(workspace, surface, `ctrl+${letter}`);
      return;
    }

    // Handle Alt+key combos
    const altMatch = key.match(/^Alt[+-](.+)$/i);
    if (altMatch) {
      const letter = altMatch[1].toLowerCase();
      await this.client.sendKey(workspace, surface, `alt+${letter}`);
      return;
    }

    // Handle Shift+key combos
    const shiftMatch = key.match(/^Shift[+-](.+)$/i);
    if (shiftMatch) {
      const inner = shiftMatch[1];
      const mapped = KEY_MAP[inner] || inner.toLowerCase();
      await this.client.sendKey(workspace, surface, `shift+${mapped}`);
      return;
    }

    // Map known keys
    const mapped = KEY_MAP[key] || key;
    await this.client.sendKey(workspace, surface, mapped);
  }
}
