import React, { memo, useEffect } from 'react';
import { usePortal } from './usePortal';
import { usePortalState } from './usePortalState';
import type { PortalType } from './contexts';

export interface PortalHostProps {
  /*
   * Name of the portal
   * */
  name: string;
}
const PortalHostComponent = ({ name }: PortalHostProps) => {
  const state = usePortalState(name);
  const { registerHost, deregisterHost } = usePortal(name);

  useEffect(() => {
    registerHost();
    return () => {
      deregisterHost();
    };
  }, []);

  return <>{state.map((item: PortalType) => item.node)}</>;
};

export const PortalHost = memo(PortalHostComponent);
PortalHost.displayName = 'PortalHost';
