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

export const focusable = defineTrait({
  name: 'focusable',
  category: 'input-interaction',
  description: 'Keyboard-only focus ring, ignores pointer focus',
  attributes: ['data-focusable-keyboard'],
  events: [],
  config: [],
  setup({ host }) {
    let hadMouseDown = false;

    function onMouseDown() {
      hadMouseDown = true;
    }

    function onFocus() {
      if (!hadMouseDown) {
        host.setAttribute('data-focusable-keyboard', '');
      }
      hadMouseDown = false;
    }

    function onBlur() {
      host.removeAttribute('data-focusable-keyboard');
      hadMouseDown = false;
    }

    host.addEventListener('mousedown', onMouseDown);
    host.addEventListener('focus', onFocus);
    host.addEventListener('blur', onBlur);

    return () => {
      host.removeEventListener('mousedown', onMouseDown);
      host.removeEventListener('focus', onFocus);
      host.removeEventListener('blur', onBlur);
      host.removeAttribute('data-focusable-keyboard');
    };
  },
});
