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

export const fadePresence = defineTrait({
  name: 'fade-presence',
  category: 'animation-feedback',
  description: 'Enter/exit fade with lifecycle',
  attributes: ['data-fade-presence-entering', 'data-fade-presence-exiting'],
  events: ['fade-in-done', 'fade-out-done'],
  config: [],
  setup({ host }) {
    host.style.opacity = '0';
    host.style.transition = 'opacity 200ms';

    function onTransitionEnd() {
      if (host.hasAttribute('data-fade-presence-entering')) {
        host.removeAttribute('data-fade-presence-entering');
        host.dispatchEvent(new CustomEvent('fade-in-done', { bubbles: true }));
      } else if (host.hasAttribute('data-fade-presence-exiting')) {
        host.removeAttribute('data-fade-presence-exiting');
        host.dispatchEvent(new CustomEvent('fade-out-done', { bubbles: true }));
      }
    }

    const observer = new MutationObserver(() => {
      const visible = host.hasAttribute('data-fade-presence-visible');
      if (visible) {
        host.setAttribute('data-fade-presence-entering', '');
        host.removeAttribute('data-fade-presence-exiting');
        host.style.opacity = '1';
      } else {
        host.setAttribute('data-fade-presence-exiting', '');
        host.removeAttribute('data-fade-presence-entering');
        host.style.opacity = '0';
      }
    });

    observer.observe(host, { attributes: true, attributeFilter: ['data-fade-presence-visible'] });
    host.addEventListener('transitionend', onTransitionEnd);

    // Apply initial state
    if (host.hasAttribute('data-fade-presence-visible')) {
      host.style.opacity = '1';
    }

    return () => {
      observer.disconnect();
      host.removeEventListener('transitionend', onTransitionEnd);
      host.style.opacity = '';
      host.style.transition = '';
      host.removeAttribute('data-fade-presence-entering');
      host.removeAttribute('data-fade-presence-exiting');
    };
  },
});
