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

export const portal = defineTrait({
  name: 'portal',
  category: 'layout-measurement',
  description: 'Renders content in a different DOM root',
  attributes: ['data-portal-active'],
  events: [],
  config: ['data-portal-target'],
  setup({ host }) {
    const targetSel = host.getAttribute('data-portal-target') || 'body';
    const originalParent = host.parentNode;
    const originalNext = host.nextSibling;
    const target = document.querySelector(targetSel);

    if (target && target !== originalParent) {
      target.appendChild(host);
    }

    host.setAttribute('data-portal-active', '');

    return () => {
      host.removeAttribute('data-portal-active');
      if (originalParent && host.parentNode !== originalParent) {
        originalParent.insertBefore(host, originalNext);
      }
    };
  },
});
