/* ============================================================
   input.js - Maps keyboard keys and on-screen hardware buttons
   to abstract game actions: up, down, hit, gameA, gameB.
   ============================================================ */
(function (ST) {
  "use strict";

  var handlers = {};   // action -> fn
  function on(action, fn) { handlers[action] = fn; }
  function fire(action) {
    var fn = handlers[action];
    if (fn) { try { fn(); } catch (e) { console.error("[input] handler error for " + action, e); } }
  }

  /* Default, intuitive key map (also shown on the Keyboard page) */
  var keyMap = {
    "ArrowUp": "up",    "KeyW": "up",
    "ArrowDown": "down","KeyS": "down",
    "Space": "hit",     "Enter": "hit", "KeyJ": "hit", "ArrowLeft": "hit",
    "KeyA": "gameA",    "Digit1": "gameA",
    "KeyB": "gameB",    "Digit2": "gameB"
  };

  function pressVisual(id) {
    var el = document.getElementById(id);
    if (!el) return;
    el.classList.add("is-pressed");
    setTimeout(function () { el.classList.remove("is-pressed"); }, 90);
  }
  var actionBtn = { up: "btn-up", down: "btn-down", hit: "btn-hit", gameA: "btn-gamea", gameB: "btn-gameb" };

  function bindKeyboard() {
    window.addEventListener("keydown", function (e) {
      // ignore when typing in a modal / input
      if (document.getElementById("modal").classList.contains("is-open")) return;
      var action = keyMap[e.code];
      if (!action) return;
      e.preventDefault();
      if (e.repeat && (action === "hit" || action === "gameA" || action === "gameB")) return;
      pressVisual(actionBtn[action]);
      fire(action);
    }, { passive: false });
  }

  function bindButton(id, action) {
    var el = document.getElementById(id);
    if (!el) { console.warn("[input] missing button #" + id); return; }
    var trigger = function (ev) {
      ev.preventDefault();
      if (el.disabled || el.classList.contains("is-disabled")) return;
      fire(action);
    };
    // pointerdown gives the snappiest feel; fall back to click
    el.addEventListener("pointerdown", trigger);
  }

  function bindButtons() {
    bindButton("btn-up", "up");
    bindButton("btn-down", "down");
    bindButton("btn-hit", "hit");
    bindButton("btn-gamea", "gameA");
    bindButton("btn-gameb", "gameB");
  }

  ST.Input = {
    on: on,
    init: function () { bindKeyboard(); bindButtons(); },
    keyMap: keyMap
  };
})(window.ST = window.ST || {});
