import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import {
parsePaytoUri,
buildPaytoUri,
getCanonicalPaytoType,
getPaytoTypeInfo,
getPaytoIconChar,
getPaytoLogoPath,
getPaytoProfileUrl,
isKnownPaytoType,
isLightningPaytoType
} from '@/lib/payto'
import PaytoDialog from '@/components/PaytoDialog'
import { HelpCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
export default function PaytoLink({
paytoUri,
type: typeProp,
authority: authorityProp,
pubkey,
onOpenZap,
className,
children,
/** When set (e.g. Markdown link title), used as the native `title` tooltip instead of the default payto hint. */
linkTitle
}: {
paytoUri?: string
type?: string
authority?: string
/** When set with lightning type, clicking can open Zap dialog via onOpenZap */
pubkey?: string
onOpenZap?: (pubkey: string) => void
className?: string
children?: React.ReactNode
linkTitle?: string
}) {
const { t } = useTranslation()
const [dialogOpen, setDialogOpen] = useState(false)
const parsed = paytoUri
? parsePaytoUri(paytoUri)
: typeProp && authorityProp
? {
type: getCanonicalPaytoType(typeProp),
authority: authorityProp,
raw: buildPaytoUri(typeProp, authorityProp)
}
: null
if (!parsed) {
return children ? {children} : null
}
const { type, authority, raw } = parsed
const info = getPaytoTypeInfo(type)
const known = isKnownPaytoType(type)
const isLightning = isLightningPaytoType(type)
const canZap = isLightning && !!pubkey && !!onOpenZap
const handleClick = (e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
if (canZap) {
onOpenZap(pubkey!)
return
}
if (!known) {
navigator.clipboard.writeText(raw)
toast.success(t('Copied payto address'))
return
}
setDialogOpen(true)
}
const displayLabel = info?.label ?? type
const categoryLabel = (() => {
const c = info?.category
if (!c) return ''
if (c === 'bitcoin-layer') return 'Bitcoin layer'
return c.charAt(0).toUpperCase() + c.slice(1)
})()
const logoPath = getPaytoLogoPath(type)
const iconChar = getPaytoIconChar(type)
const profileUrl = getPaytoProfileUrl(type, authority)
const content = children ?? {authority}
const overrideTip = linkTitle?.trim()
const iconEl = (
{logoPath ? (
) : iconChar != null ? (
{iconChar}
) : (
)}
)
if (profileUrl) {
return (
e.stopPropagation()}
>
{iconEl}
{content}
)
}
return (
<>
{known && (
)}
>
)
}