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

export const noiseTexture = defineTrait({
  name: 'noise-texture',
  category: 'visual-dynamics',
  description: 'Procedural grain overlay',
  attributes: ['data-noise-texture-active'],
  events: [],
  config: ['data-noise-strength'],
  setup({ host }) {
    // Strength governs the SVG rect's opacity (0..1). Default 0.15 — visibly
    // textured without dominating the underlying surface. Earlier defaults
    // multiplied the rect opacity (0.08) by the overlay's CSS opacity (0.5)
    // for an effective 0.04, which read as no-grain.
    const strength = Math.max(0, Math.min(1, parseFloat(host.getAttribute('data-noise-strength')) || 0.15));
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><filter id="n"><feTurbulence type="fractalNoise" baseFrequency="0.65" numOctaves="3" stitchTiles="stitch"/></filter><rect width="100%" height="100%" filter="url(#n)" opacity="${strength}"/></svg>`;
    const encoded = `url("data:image/svg+xml,${encodeURIComponent(svg)}")`;

    const overlay = document.createElement('div');
    overlay.style.cssText = `
      position: absolute; inset: 0; pointer-events: none; z-index: 1;
      background-image: ${encoded};
      background-repeat: repeat;
      border-radius: inherit;
    `;

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

    return () => {
      overlay.remove();
      host.removeAttribute('data-noise-texture-active');
    };
  },
});
