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
}: {
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
}) {
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 = info?.category ? info.category.charAt(0).toUpperCase() + info.category.slice(1) : ''
const logoPath = getPaytoLogoPath(type)
const iconChar = getPaytoIconChar(type)
const profileUrl = getPaytoProfileUrl(type, authority)
const content = children ?? {authority}
const iconEl = (
{logoPath ? (
) : iconChar != null ? (
{iconChar}
) : (
)}
)
if (profileUrl) {
return (
e.stopPropagation()}
>
{iconEl}
{content}
)
}
return (
<>
{known && (
)}
>
)
}