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

export const hapticFeedback = defineTrait({
  name: 'haptic-feedback',
  category: 'audio-haptics-sensory',
  description: 'Vibration API feedback',
  attributes: ['data-haptic-feedback-active'],
  events: [],
  config: ['data-haptic-pattern'],
  setup({ host }) {
    if (!navigator.vibrate) {
      return () => {};
    }

    const patternStr = host.getAttribute('data-haptic-pattern') || '10';
    const pattern = patternStr.split(',').map(Number);

    function onPress() {
      navigator.vibrate(pattern);
    }

    host.addEventListener('press', onPress);
    host.setAttribute('data-haptic-feedback-active', '');

    return () => {
      host.removeEventListener('press', onPress);
      host.removeAttribute('data-haptic-feedback-active');
    };
  },
});
