// 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
    switch (key) {
      case 'return':
      case 'enter':
        emacs_notation += "RET"
        break
      case 'space':
        emacs_notation += "SPC"
        break
      case 'escape':
        emacs_notation += "ESC"
        break
      case 'tab':
        emacs_notation += "TAB"
        break
      case 'backspace':
        emacs_notation += "DEL"
        break
      case 'delete':
        emacs_notation += "delete"
        break
      case 'up':
        emacs_notation += "up"
        break
      case 'down':
        emacs_notation += "down"
        break
      case 'left':
        emacs_notation += "left"
        break
      case 'right':
        emacs_notation += "right"
        break
      default:
        emacs_notation += key
        break
    }
  }
  
  // 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
  if (this.prefix_key) {
    var 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
}
