import { useState, useEffect, useCallback, useRef } from 'react' import Button from '@/components/ui/Button' import Card from '@/components/ui/Card' interface KeyDisplayProps { keyCode: string qrCodeUrl: string onDownloadWord: () => void /** Optional — when provided, shows a "建立新紀錄" button (e.g. so the same * page can start another record without navigating away). */ onReset?: () => void } /** Calculate remaining time until 7 days from now (or from a given creation time). */ function useCountdown(daysFromNow: number = 7) { const [target] = useState(() => Date.now() + daysFromNow * 24 * 60 * 60 * 1000) const [remaining, setRemaining] = useState(() => target - Date.now()) useEffect(() => { const timer = setInterval(() => { const diff = target - Date.now() setRemaining(diff > 0 ? diff : 0) }, 1000) return () => clearInterval(timer) }, [target]) const days = Math.floor(remaining / (1000 * 60 * 60 * 24)) const hours = Math.floor((remaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) const minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60)) const seconds = Math.floor((remaining % (1000 * 60)) / 1000) return { days, hours, minutes, seconds } } export default function KeyDisplay({ keyCode, qrCodeUrl, onDownloadWord, onReset, }: KeyDisplayProps) { const [copied, setCopied] = useState(false) const timerRef = useRef | null>(null) const countdown = useCountdown(7) useEffect(() => { return () => { if (timerRef.current) clearTimeout(timerRef.current) } }, []) const handleCopy = useCallback(async () => { try { await navigator.clipboard.writeText(keyCode) setCopied(true) timerRef.current = setTimeout(() => setCopied(false), 2000) } catch { // Fallback for older browsers / insecure contexts const textarea = document.createElement('textarea') textarea.value = keyCode textarea.style.position = 'fixed' textarea.style.opacity = '0' document.body.appendChild(textarea) textarea.select() document.execCommand('copy') document.body.removeChild(textarea) setCopied(true) timerRef.current = setTimeout(() => setCopied(false), 2000) } }, [keyCode]) return ( {/* Success icon */}

資料已安全儲存

請妥善保存以下金鑰,作為日後查閱資料的唯一憑證

{/* Key code display */}

您的專屬金鑰

{keyCode}

{/* QR Code */} {qrCodeUrl && (
金鑰 QR Code
)} {/* Action buttons */}
{/* Warning */}

請務必保存此金鑰,遺失將無法取回資料

{/* Countdown */}

7 日後自動銷毀

剩餘{' '} {countdown.days} 天 {String(countdown.hours).padStart(2, '0')}: {String(countdown.minutes).padStart(2, '0')}: {String(countdown.seconds).padStart(2, '0')}

{onReset && ( )}
) }