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

export const intersectionObserver = defineTrait({
  name: 'intersection-observer',
  category: 'layout-measurement',
  description: 'Visibility detection (viewport)',
  attributes: ['data-intersection-visible', 'data-intersection-ratio'],
  events: ['element-visible', 'element-hidden'],
  config: ['data-intersection-threshold'],
  setup({ host }) {
    // No-op in environments lacking IntersectionObserver (older Safari,
    // happy-dom without polyfill). Trait becomes inert rather than throwing.
    if (typeof IntersectionObserver === 'undefined') return () => {};

    const threshold = parseFloat(host.getAttribute('data-intersection-threshold')) || 0;

    const observer = new IntersectionObserver((entries) => {
      for (const entry of entries) {
        host.setAttribute('data-intersection-ratio', entry.intersectionRatio.toFixed(2));

        if (entry.isIntersecting) {
          host.setAttribute('data-intersection-visible', '');
          host.dispatchEvent(new CustomEvent('element-visible', { bubbles: true }));
        } else {
          host.removeAttribute('data-intersection-visible');
          host.dispatchEvent(new CustomEvent('element-hidden', { bubbles: true }));
        }
      }
    }, { threshold });

    observer.observe(host);

    return () => {
      observer.disconnect();
      host.removeAttribute('data-intersection-visible');
      host.removeAttribute('data-intersection-ratio');
    };
  },
});
