import type { PropsWithChildren } from 'react'
import cx from 'classnames'
import { m } from 'framer-motion'

import type { PropsWithClassName } from '@/lib/types'
import { DEFAULT_SPRING_TRANSITION } from '@/lib/constants'

type Props = PropsWithChildren &
  PropsWithClassName & {
    as?: keyof HTMLElementTagNameMap
    viewportOffset?: string
  }

export default function AnimateUnderline({ as: Component = 'div', viewportOffset, className = '', children }: Props) {
  const offset = viewportOffset ? `-${viewportOffset}` : '0px'

  return (
    <Component className={cx('relative', className)}>
      {children}
      <m.span
        className="block w-full h-1 mt-1 bg-current origin-left"
        initial={{ opacity: 0, scaleX: 0 }}
        whileInView={{ opacity: 1, scaleX: 1 }}
        viewport={{
          once: true,
          margin: `0px 0px ${offset} 0px`,
        }}
        transition={DEFAULT_SPRING_TRANSITION}
        aria-hidden
      />
    </Component>
  )
}
