// Emacs-style input handler
// Converts raw input with modifiers to standard emacs notation

// Valid keys for emacs bindings - only process these
var valid_keys = [
  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 
  'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
  'return', 'enter', 'space', 'escape', 'tab', 'backspace', 'delete',
  'up', 'down', 'left', 'right', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
]

var action = {}
action.prefix_key = null  // Current prefix key (C-x or C-c)
action.on_input = function(action_id, action_data)
{
  if (!action_data.pressed) return

  if (find(valid_keys, action_id) == null)
    return
  
  // Only process key events with modifiers or if we're waiting for a prefix continuation
  if (!action_data.ctrl && !action_data.alt && !this.prefix_key)
    return
  
  var emacs_notation = ""
  
  // Build emacs notation
  if (action_data.ctrl)
    emacs_notation += "C-"

  if (action_data.alt)
    emacs_notation += "M-"
  
  // Convert action_id to emacs key notation
  var key = action_id
  if (length(key) == 1) {
    // Single character keys
    emacs_notation += lower(key)
  } else {
    // Handle special keys
    if (key == 'return' || key == 'enter') {
      emacs_notation += "RET"
    } else if (key == 'space') {
      emacs_notation += "SPC"
    } else if (key == 'escape') {
      emacs_notation += "ESC"
    } else if (key == 'tab') {
      emacs_notation += "TAB"
    } else if (key == 'backspace') {
      emacs_notation += "DEL"
    } else if (key == 'delete') {
      emacs_notation += "delete"
    } else if (key == 'up') {
      emacs_notation += "up"
    } else if (key == 'down') {
      emacs_notation += "down"
    } else if (key == 'left') {
      emacs_notation += "left"
    } else if (key == 'right') {
      emacs_notation += "right"
    } else {
      emacs_notation += key
    }
  }
  
  // Handle prefix keys C-x and C-c
  if (emacs_notation == "C-x" || emacs_notation == "C-c") {
    this.prefix_key = emacs_notation
    return
  }

  // If we have a prefix key, build the full command
  var full_command = null
  if (this.prefix_key) {
    full_command = this.prefix_key + " " + emacs_notation
    this.prefix_key = null  // Reset prefix key
//    scene.recurse(game.root, 'on_input', [full_command, action_data])
  } else {
//    scene.recurse(game.root, 'on_input', [emacs_notation, action_data])
  }
}

return function()
{
  var obj = meme(action)
  return obj
}
