'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { QrCodeSvg } from '@/components/shared/QrCodeSvg'

export function PassportQrCode({
  passportNo,
  className = '',
}: {
  passportNo: string
  className?: string
}) {
  const [origin, setOrigin] = useState('')
  const normalized = passportNo.trim()

  useEffect(() => {
    setOrigin(window.location.origin)
  }, [])

  const href = normalized ? `/p/${encodeURIComponent(normalized)}` : '#'
  const value = useMemo(() => {
    if (!normalized) return 'NO-PASSPORT'
    const fullUrl = `${origin}${href}`
    return fullUrl.length <= 78 ? fullUrl : href
  }, [href, normalized, origin])

  if (!normalized) {
    return <QrCodeSvg value="NO-PASSPORT" label="通行证二维码待生成" className={className} />
  }

  return (
    <Link href={href} aria-label={`核验通行证 ${normalized}`} className="block">
      <QrCodeSvg value={value} label={`通行证核验二维码 ${normalized}`} className={className} />
    </Link>
  )
}
