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

function isMac() {
  if (typeof navigator !== 'undefined') {
    if (navigator.platform) return /Mac|iPhone|iPad|iPod/.test(navigator.platform);
    if (navigator.userAgent) return /Mac|iPhone|iPad|iPod/.test(navigator.userAgent);
  }
  return false;
}

function parseCombo(str) {
  const parts = str.toLowerCase().split('+').map((s) => s.trim());
  const mac = isMac();
  return {
    ctrl: parts.includes('ctrl'),
    meta: parts.includes('meta') || (parts.includes('mod') && mac),
    alt: parts.includes('alt'),
    shift: parts.includes('shift'),
    ctrlOrMod: parts.includes('mod') && !mac,
    key: parts.find((p) => !['ctrl', 'meta', 'alt', 'shift', 'mod'].includes(p)) || '',
  };
}

function matchesCombo(e, combo) {
  const ctrlMatch = combo.ctrlOrMod ? e.ctrlKey : combo.ctrl ? e.ctrlKey : !e.ctrlKey;
  const metaMatch = combo.meta ? e.metaKey : !e.metaKey;
  const altMatch = combo.alt ? e.altKey : !e.altKey;
  const shiftMatch = combo.shift ? e.shiftKey : !e.shiftKey;
  const keyMatch = e.key.toLowerCase() === combo.key;
  return ctrlMatch && metaMatch && altMatch && shiftMatch && keyMatch;
}

export const hotkey = defineTrait({
  name: 'hotkey',
  category: 'keyboard-navigation',
  description: 'Global or scoped keyboard shortcuts',
  attributes: [],
  events: ['hotkey'],
  config: ['data-hotkey', 'data-hotkey-global'],
  setup({ host }) {
    const comboStr = host.getAttribute('data-hotkey');
    if (!comboStr) return () => {};

    const combo = parseCombo(comboStr);
    const isGlobal = host.hasAttribute('data-hotkey-global');
    const target = isGlobal ? document : host;

    function onKeyDown(e) {
      if (matchesCombo(e, combo)) {
        e.preventDefault();
        host.dispatchEvent(new CustomEvent('hotkey', {
          bubbles: true,
          detail: { combo: comboStr, originalEvent: e },
        }));
      }
    }

    target.addEventListener('keydown', onKeyDown);

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