import { forwardRef, type AnchorHTMLAttributes } from 'react'
import { Link as RouterLink } from '@tanstack/react-router'

export type LinkProps = AnchorHTMLAttributes<HTMLAnchorElement> & {
  href: string
}

const Link = forwardRef<HTMLAnchorElement, LinkProps>(function Link(props, ref) {
  const { href, ...rest } = props

  if (/^(https?:|mailto:|tel:)/.test(href)) {
    return <a ref={ref} href={href} {...rest} />
  }

  return <RouterLink ref={ref} to={href as never} {...(rest as Record<string, unknown>)} />
})

export default Link
