import { defineTrait } from '../define.js';

const KEY_MAP = {
  ArrowUp: 'nav-up',
  ArrowDown: 'nav-down',
  ArrowLeft: 'nav-left',
  ArrowRight: 'nav-right',
  Enter: 'nav-enter',
  Escape: 'nav-escape',
  Home: 'nav-home',
  End: 'nav-end',
};

export const keyboardNav = defineTrait({
  name: 'keyboard-nav',
  category: 'keyboard-navigation',
  description: 'Arrow keys, Enter, Escape — semantic navigation events',
  attributes: [],
  events: ['nav-up', 'nav-down', 'nav-left', 'nav-right', 'nav-enter', 'nav-escape', 'nav-home', 'nav-end'],
  config: [],
  setup({ host }) {
    function onKeyDown(e) {
      const eventName = KEY_MAP[e.key];
      if (!eventName) return;
      e.preventDefault();
      host.dispatchEvent(new CustomEvent(eventName, {
        bubbles: true,
        detail: { originalEvent: e },
      }));
    }

    host.addEventListener('keydown', onKeyDown);

    return () => {
      host.removeEventListener('keydown', onKeyDown);
    };
  },
});
