import { isValidElement, ReactElement, useMemo } from 'react';
import { Page } from '@wix/design-system';

type ChildArray = (
  | React.ReactChild
  | React.ReactFragment
  | React.ReactPortal
)[];

export function usePageHeader(childrenArr: ChildArray): {
  header: ReactElement | undefined;
  title?: string;
} {
  const header = useMemo(
    () =>
      childrenArr.find(
        (child): child is ReactElement =>
          isValidElement(child) && child.type === Page.Header,
      ),
    [childrenArr],
  );

  const title =
    typeof header?.props?.title === 'string' ? header?.props?.title : null;

  return { header, title };
}
