'use client'

import type { LinkProps } from '@zag-js/navigation-menu'
import { mergeProps } from '@zag-js/react'
import { forwardRef } from 'react'
import type { Assign } from '../../types.ts'
import { createSplitProps } from '../../utils/create-split-props.ts'
import { type HTMLProps, type PolymorphicProps, ark } from '../factory.ts'
import { useNavigationMenuContext } from './use-navigation-menu-context.ts'
import { useNavigationMenuItemPropsContext } from './use-navigation-menu-item-props-context.ts'

export interface NavigationMenuLinkBaseProps extends Partial<LinkProps>, PolymorphicProps {}
export interface NavigationMenuLinkProps extends Assign<HTMLProps<'a'>, NavigationMenuLinkBaseProps> {}

const splitLinkProps = createSplitProps<LinkProps>()

export const NavigationMenuLink = forwardRef<HTMLAnchorElement, NavigationMenuLinkProps>((props, ref) => {
  const itemContext = useNavigationMenuItemPropsContext()
  const value = props.value ?? itemContext?.value

  const [linkProps, localProps] = splitLinkProps({ ...props, value }, ['current', 'onSelect', 'value', 'closeOnClick'])
  const navigationMenu = useNavigationMenuContext()
  const mergedProps = mergeProps(navigationMenu.getLinkProps(linkProps), localProps)

  return <ark.a {...mergedProps} ref={ref} />
})

NavigationMenuLink.displayName = 'NavigationMenuLink'
