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

export const parallax = defineTrait({
  name: 'parallax',
  category: 'visual-dynamics',
  description: 'Layered motion relative to pointer',
  attributes: ['data-parallax-active'],
  events: [],
  config: ['data-parallax-strength'],
  setup({ host }) {
    // Reduced-motion: skip the scroll-driven offset; element stays put.
    if (prefersReducedMotion()) {
      host.setAttribute('data-parallax-active', '');
      return () => host.removeAttribute('data-parallax-active');
    }

    const strength = parseFloat(host.getAttribute('data-parallax-strength')) || 0.5;

    function getScrollParent(el) {
      let node = el.parentElement;
      while (node) {
        const style = getComputedStyle(node);
        if (/(auto|scroll)/.test(style.overflow + style.overflowY)) return node;
        node = node.parentElement;
      }
      return window;
    }

    const scrollParent = getScrollParent(host);

    function onScroll() {
      const scrollY = scrollParent === window
        ? window.scrollY
        : scrollParent.scrollTop;
      const offset = scrollY * strength;
      host.style.translate = `0 ${offset}px`;
    }

    const target = scrollParent === window ? window : scrollParent;
    target.addEventListener('scroll', onScroll, { passive: true });
    host.setAttribute('data-parallax-active', '');
    onScroll();

    return () => {
      target.removeEventListener('scroll', onScroll);
      host.style.translate = '';
      host.removeAttribute('data-parallax-active');
    };
  },
});
