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

export const gradientShift = defineTrait({
  name: 'gradient-shift',
  category: 'visual-dynamics',
  description: 'Animated rainbow gradient backgrounds',
  attributes: ['data-gradient-shift-active'],
  events: [],
  config: [],
  setup({ host }) {
    // Reduced-motion: leave the gradient static instead of animating it.
    if (prefersReducedMotion()) {
      host.setAttribute('data-gradient-shift-active', '');
      return () => host.removeAttribute('data-gradient-shift-active');
    }

    const keyframeName = `adia-gradient-${Math.random().toString(36).slice(2, 8)}`;

    const style = document.createElement('style');
    style.textContent = `
      @keyframes ${keyframeName} {
        0% { background-position: 0% 50%; }
        50% { background-position: 100% 50%; }
        100% { background-position: 0% 50%; }
      }
    `;
    document.head.appendChild(style);

    host.style.backgroundSize = '200% 200%';
    host.style.animation = `${keyframeName} 3s ease infinite`;
    host.setAttribute('data-gradient-shift-active', '');

    return () => {
      host.style.backgroundSize = '';
      host.style.animation = '';
      style.remove();
      host.removeAttribute('data-gradient-shift-active');
    };
  },
});
