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

export const glowFocus = defineTrait({
  name: 'glow-focus',
  category: 'visual-dynamics',
  description: 'Animated pulsing glow on focus',
  attributes: ['data-glow-focus-active'],
  events: [],
  config: [],
  setup({ host }) {
    let savedBoxShadow = '';
    const reduced = prefersReducedMotion();

    function onFocus() {
      savedBoxShadow = host.style.boxShadow;
      host.style.boxShadow = '0 0 8px 2px rgba(59, 130, 246, 0.6)';
      // Skip the easing under reduced-motion — instant on/off.
      host.style.transition = reduced ? '' : 'box-shadow 200ms ease';
      host.setAttribute('data-glow-focus-active', '');
    }

    function onBlur() {
      host.style.boxShadow = savedBoxShadow;
      host.removeAttribute('data-glow-focus-active');
    }

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

    return () => {
      host.removeEventListener('focus', onFocus);
      host.removeEventListener('blur', onBlur);
      if (host.hasAttribute('data-glow-focus-active')) onBlur();
      host.removeAttribute('data-glow-focus-active');
    };
  },
});
