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

export const shimmerLoading = defineTrait({
  name: 'shimmer-loading',
  category: 'visual-dynamics',
  description: 'Skeleton shimmer effect',
  attributes: ['data-shimmer-loading-active'],
  events: [],
  config: [],
  setup({ host }) {
    // Reduced-motion: render a static skeleton (subtle muted background) instead of the sweeping shimmer.
    if (prefersReducedMotion()) {
      const overlay = document.createElement('div');
      overlay.style.cssText = `
        position: absolute; inset: 0; pointer-events: none; z-index: 1;
        border-radius: inherit;
        background: rgba(0,0,0,0.06);
      `;
      host.style.position = host.style.position || 'relative';
      host.appendChild(overlay);
      host.setAttribute('data-shimmer-loading-active', '');
      return () => {
        overlay.remove();
        host.removeAttribute('data-shimmer-loading-active');
      };
    }

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

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

    const overlay = document.createElement('div');
    overlay.style.cssText = `
      position: absolute; inset: 0; overflow: hidden; pointer-events: none; z-index: 1;
      border-radius: inherit;
    `;

    const shimmer = document.createElement('div');
    shimmer.style.cssText = `
      position: absolute; inset: 0;
      background: linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.3) 50%, transparent 100%);
      animation: ${keyframeName} 1.5s ease-in-out infinite;
    `;

    overlay.appendChild(shimmer);
    host.style.position = host.style.position || 'relative';
    host.appendChild(overlay);
    host.setAttribute('data-shimmer-loading-active', '');

    return () => {
      overlay.remove();
      style.remove();
      host.removeAttribute('data-shimmer-loading-active');
    };
  },
});
