import { trackSplit, track } from 'ripple';
import type { MaybeTracked } from '../../types';
import { PopoverApiContext } from './use-popover-context';
import { PresenceApiContext } from '../presence/use-presence-context';
import { splitPresenceProps } from '../presence/split-presence-props.ripple';
import { usePresence, type UsePresenceProps } from '../presence/use-presence.ripple';
import { usePopover, type UsePopoverProps } from './use-popover.ripple';
import { splitPopoverProps } from './split-popover-props.ripple';
import {
  splitRenderStrategyProps,
  RenderStrategyContext,
} from '../../utils/render-strategy.ripple';

export interface PopoverRootBaseProps extends UsePopoverProps, UsePresenceProps {
  children?: any;
}
export interface PopoverRootProps extends PopoverRootBaseProps {}

export component PopoverRoot(props: MaybeTracked<PopoverRootProps>) {
  const [children, rest] = trackSplit(props, ['children']);
  const [presenceProps, localProps] = splitPresenceProps(@rest);
  const [renderStrategyProps] = splitRenderStrategyProps(@presenceProps);
  const [popoverProps] = splitPopoverProps(@localProps);

  const popover = usePopover(popoverProps);
  const present = track(() => @popover.open);
  const presence = usePresence({ present, ...@presenceProps });

  PopoverApiContext.set(popover);
  RenderStrategyContext.set(renderStrategyProps);
  PresenceApiContext.set(presence);

  <@children />
}
