import { useState, useLayoutEffect } from 'react';

/** Used to display the postviewer in a portal
 * Prevents CSS/layout conflicts with the parent component
 * Avoids z-index issues
 */

const usePortal = (id: string | undefined, shouldCreate: boolean) => {
  const [element, setElement] = useState<Element | null>(null);

  useLayoutEffect(() => {
    if (!id || !shouldCreate) {
      setElement(null);
      return undefined;
    }

    let portal = document.querySelector(`#${id}`);
    let created = false;
    if (!portal) {
      portal = document.createElement('div');
      portal.id = id;
      document.body.appendChild(portal);
      created = true;
    }
    setElement(portal);

    return () => {
      // Only remove the portal node if THIS hook instance created it AND it is still attached
      if (created && portal && portal.parentNode) {
        portal.parentNode.removeChild(portal);
      }
    };
  }, [id, shouldCreate]);

  return element;
};

export default usePortal;
