import { mergeProps } from '@zag-js/solid'
import type { JSX } from 'solid-js'
import { createSplitProps } from '../../utils/create-split-props.ts'
import { PresenceProvider, type UsePresenceProps, splitPresenceProps, usePresence } from '../presence/index.tsx'
import { type UseHoverCardProps, useHoverCard } from './use-hover-card.ts'
import { HoverCardProvider } from './use-hover-card-context.ts'

export interface HoverCardRootBaseProps extends UseHoverCardProps, UsePresenceProps {}
export interface HoverCardRootProps extends HoverCardRootBaseProps {
  children?: JSX.Element
}

export const HoverCardRoot = (props: HoverCardRootProps) => {
  const [presenceProps, hoverCardProps] = splitPresenceProps(props)
  const [useHoverCardProps, localProps] = createSplitProps<UseHoverCardProps>()(hoverCardProps, [
    'closeDelay',
    'defaultOpen',
    'disabled',
    'id',
    'ids',
    'onFocusOutside',
    'onInteractOutside',
    'onOpenChange',
    'onPointerDownOutside',
    'open',
    'openDelay',
    'positioning',
    'triggerValue',
    'defaultTriggerValue',
    'onTriggerValueChange',
  ])
  const api = useHoverCard(useHoverCardProps)
  const apiPresence = usePresence(mergeProps(presenceProps, () => ({ present: api().open })))

  return (
    <HoverCardProvider value={api}>
      <PresenceProvider value={apiPresence}>{localProps.children}</PresenceProvider>
    </HoverCardProvider>
  )
}
