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

export const soundFeedback = defineTrait({
  name: 'sound-feedback',
  category: 'audio-haptics-sensory',
  description: 'Synthesized tones via Web Audio API',
  attributes: ['data-sound-feedback-active'],
  events: [],
  config: ['data-sound-type'],
  setup({ host }) {
    const soundType = host.getAttribute('data-sound-type');
    let audio = null;

    function onPress() {
      if (!soundType) return;
      if (!audio) {
        audio = new Audio(soundType);
      }
      audio.currentTime = 0;
      audio.play().catch(() => {});
    }

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

    return () => {
      host.removeEventListener('press', onPress);
      if (audio) { audio.pause(); audio = null; }
      host.removeAttribute('data-sound-feedback-active');
    };
  },
});
