import { useEffect, useMemo, useRef, useState } from "react"; import { ShieldCheck, X } from "lucide-react"; import { useTranslation } from "react-i18next"; import { channelUiPresentation } from "@/channel-plugins/registry"; import { Button } from "@/components/ui/button"; import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface"; import { useLogoFallback } from "@/hooks/useLogoFallback"; import type { PairingRequestInfo } from "@/lib/types"; import { cn } from "@/lib/utils"; export function PairingCodePopup({ requests, total, busyCode, error, onApprove, onDismiss, }: { requests: PairingRequestInfo[]; total: number; busyCode: string | null; error: string | null; onApprove: (code: string) => void; onDismiss: (request: PairingRequestInfo) => void; }) { const { t } = useTranslation(); const [value, setValue] = useState(""); const attemptedCode = useRef(null); const normalizedCode = normalizePairingCode(value); const matchedRequest = useMemo( () => requests.find((request) => request.code === normalizedCode) ?? null, [normalizedCode, requests], ); // Keep delivered and legacy requests usable even when another bot cannot reply. const firstRequest = requests.find((request) => ( !request.delivery_status || request.delivery_status === "sent" )) ?? requests[0] ?? null; const displayRequest = matchedRequest ?? firstRequest; const deliveryBlocked = displayRequest?.delivery_status === "failed" || displayRequest?.delivery_status === "sending"; const expires = formatPairingExpiry(displayRequest?.expires_in_seconds); const isCompleteCode = normalizedCode.length === 9; const showNoMatch = isCompleteCode && !matchedRequest && !busyCode; useEffect(() => { if (!matchedRequest || busyCode || attemptedCode.current === matchedRequest.code) return; attemptedCode.current = matchedRequest.code; onApprove(matchedRequest.code); }, [busyCode, matchedRequest, onApprove]); useEffect(() => { if (!requests.length) { setValue(""); attemptedCode.current = null; } }, [requests.length]); if (!firstRequest) return null; const codeInput = ( { attemptedCode.current = null; setValue(formatPairingCodeInput(next)); }} /> ); return (

{t("app.pairing.title", { defaultValue: "Pair a chat user" })}

{displayRequest.delivery_status === "failed" ? t("app.pairing.deliveryFailed", { defaultValue: "Couldn't send the pairing code. Check this bot's send-message permissions and gateway logs, then send it another private message to retry.", }) : displayRequest.delivery_status === "sending" ? t("app.pairing.deliverySending", { defaultValue: "Sending a pairing code to your chat. If it doesn't arrive, send the bot another private message to retry.", }) : t("app.pairing.description", { defaultValue: "Enter the pairing code shown in the chat.", })}

{deliveryBlocked ? (
{t("app.pairing.haveCode", { defaultValue: "Already received a code?" })} {codeInput}
) : ( <> {codeInput} )} {!deliveryBlocked || total > 1 ? (
{matchedRequest && busyCode === matchedRequest.code ? t("app.pairing.matched", { defaultValue: "Matched {{channel}}. Connecting...", channel: channelLabel(matchedRequest.channel), }) : deliveryBlocked ? null : t("app.pairing.expiresInline", { defaultValue: "Code expires {{expires}}.", expires, })} {total > 1 ? ( {t("app.pairing.queueCount", { defaultValue: "{{count}} pending", count: total, })} ) : null}
) : null} {showNoMatch ? (

{t("app.pairing.noMatch", { defaultValue: "No pending request matches this code.", })}

) : null} {error ? (

{error}

{matchedRequest ? ( ) : null}
) : null}
); } function PairingChannelBadge({ channel }: { channel: string }) { const presentation = pairingChannelPresentation(channel); const initials = presentation.initials; const color = presentation.color; const brandLogoUrl = presentation.logoUrl; const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(brandLogoUrl ? [brandLogoUrl] : undefined); return (
{logoUrl ? ( ) : presentation ? ( {initials} ) : ( )}
); } function PairingCodeSlots({ value, disabled, matched, invalid, ariaLabel, onChange, }: { value: string; disabled: boolean; matched: boolean; invalid: boolean; ariaLabel: string; onChange: (value: string) => void; }) { const inputRef = useRef(null); const [focused, setFocused] = useState(false); const compact = compactPairingCode(value); const activeIndex = Math.min(compact.length, 7); const slots = Array.from({ length: 8 }, (_, index) => compact[index] ?? ""); const renderSlot = (char: string, index: number) => { const highlighted = focused && index === activeIndex && !matched && !invalid; return (
{char || " "}
); }; return (
inputRef.current?.focus()} > setFocused(true)} onBlur={() => setFocused(false)} onChange={(event) => onChange(event.target.value)} className="absolute inset-0 z-10 h-full w-full cursor-text opacity-0 disabled:cursor-default" />
{slots.slice(0, 4).map((char, index) => renderSlot(char, index))}
{slots.slice(4).map((char, index) => renderSlot(char, index + 4))}
); } function compactPairingCode(raw: string): string { return raw.replace(/[^a-zA-Z0-9]/g, "").slice(0, 8).toUpperCase(); } function formatPairingCodeInput(raw: string): string { const compact = compactPairingCode(raw); if (compact.length <= 4) return compact; return `${compact.slice(0, 4)}-${compact.slice(4)}`; } function normalizePairingCode(raw: string): string { return formatPairingCodeInput(raw); } function pairingChannelKey(channel: string): string { const raw = channel.trim().toLowerCase(); if (!raw) return ""; return raw.split(/[.:]/)[0] ?? raw; } function channelLabel(channel: string): string { return pairingChannelPresentation(channel).label; } function pairingChannelPresentation(channel: string) { const key = pairingChannelKey(channel); const plugin = channelUiPresentation(key); return { label: plugin?.displayName ?? channel, initials: plugin?.initials ?? channel.slice(0, 2).toUpperCase(), color: plugin?.color ?? "#10B981", logoUrl: plugin?.logoUrl, }; } function formatPairingExpiry(seconds: number | null | undefined): string { if (seconds == null) return "soon"; if (seconds <= 0) return "expired"; if (seconds < 60) return `${seconds}s`; return `${Math.ceil(seconds / 60)} min`; }