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

export const typewriter = defineTrait({
  name: 'typewriter',
  category: 'audio-haptics-sensory',
  description: 'Animated text reveal character by character',
  attributes: ['data-typewriter-active'],
  events: ['typewriter-done'],
  config: ['data-typewriter-speed'],
  setup({ host }) {
    const speed = parseInt(host.getAttribute('data-typewriter-speed'), 10) || 50;
    const originalText = host.textContent;

    // Reduced-motion: show the full text immediately and fire the done event.
    if (prefersReducedMotion()) {
      host.setAttribute('data-typewriter-active', '');
      queueMicrotask(() => {
        host.removeAttribute('data-typewriter-active');
        host.dispatchEvent(new CustomEvent('typewriter-done', { bubbles: true }));
      });
      return () => {
        host.textContent = originalText;
        host.removeAttribute('data-typewriter-active');
      };
    }

    let index = 0;
    let timerId = null;

    host.textContent = '';
    host.setAttribute('data-typewriter-active', '');

    function tick() {
      if (index < originalText.length) {
        host.textContent = originalText.slice(0, ++index);
        timerId = setTimeout(tick, speed);
      } else {
        host.removeAttribute('data-typewriter-active');
        host.dispatchEvent(new CustomEvent('typewriter-done', { bubbles: true }));
      }
    }

    timerId = setTimeout(tick, speed);

    return () => {
      if (timerId) clearTimeout(timerId);
      host.textContent = originalText;
      host.removeAttribute('data-typewriter-active');
    };
  },
});
