/* eslint-disable @typescript-eslint/ban-ts-comment */

import { useStyleConfig, v, vui } from '../core'
import { cs, mergeRefs, MouseEvent } from '../utils'
import { usePopoverContext } from './context'
import { PopoverTriggerProps } from './popover.types'

/**
 * Displays a trigger component to toggle display of the popover content.
 * Can be rendered as any component using the 'as' prop. By default renders as a plain button.
 */
export const PopoverTrigger = vui<'button', PopoverTriggerProps>((props, ref) => {
  // @ts-ignore - TS incorrectly doesn't recognize 'as' prop
  const { as, className, onClick: onClickProp, ...rest } = props
  const { setReference, ...popoverProps } = usePopoverContext() ?? {}
  const styles = useStyleConfig('Popover', { ...popoverProps, ...props })

  const Element = as || v.button

  const onClick = (e: MouseEvent<HTMLButtonElement>) => {
    // Avoids triggering parent's onClick, like when inside a ListItem
    e.stopPropagation()
    onClickProp?.(e)
  }

  return (
    <Element
      className={cs('vui-popoverTrigger', className)}
      onClick={onClick}
      ref={mergeRefs(setReference, ref)}
      {...styles.trigger}
      {...rest}
    />
  )
})

PopoverTrigger.displayName = 'PopoverTrigger'

export default PopoverTrigger
