'use client' import { Camera, ChevronLeft, Clock, ImageIcon, RefreshCw, ShieldCheck, Smartphone, Sparkles, Trash2, TriangleAlert, Upload, WifiOff, } from 'lucide-react' import Link from 'next/link' import { useEffect, useRef, useState, type ReactNode } from 'react' import { ARCHIVE_PHOTO_ALBUM_PATH } from '@/lib/archivePhotoPublicCatalog' import type { FaceSearchPhotoView } from '@/lib/faceSearch' import { ARCHIVE_PHOTO_FOCUS, ARCHIVE_PHOTO_PRIMARY_BUTTON, ARCHIVE_PHOTO_SECONDARY_BUTTON, } from './archivePhotoClasses' import { computeSelfieDescriptor, supportsFaceSearchEngine } from './faceSearchEngine' import { SelfieSearchClosed } from './SelfieSearchClosed' import { SelfieSearchResultCard } from './SelfieSearchResultCard' type SelfieSearchIntent = 'search' | 'leave-index' type FlowStep = | { kind: 'consent' } | { kind: 'pick'; intent: SelfieSearchIntent } | { kind: 'confirm-leave' } | { kind: 'processing'; intent: SelfieSearchIntent } | { kind: 'results'; photos: FaceSearchPhotoView[] } | { kind: 'empty' } | { kind: 'no-face' } | { kind: 'presence' } | { kind: 'removed' } | { kind: 'presence-missing' } | { kind: 'unsupported' } | { kind: 'engine-error' } | { kind: 'rate-limited' } | { kind: 'network' } | { kind: 'closed' } type SelfieSearchResponse = | { ok: true; found: true; photos: FaceSearchPhotoView[] } | { ok: true; found: false } | { ok: true; removed: boolean } | { ok: false; error: string } const ACCEPTED_IMAGE = 'image/*' const FOCUSABLE = 'a[href]:not([tabindex="-1"]), button:not([disabled]), input:not([disabled])' /** The wizard steps center on a readable column; the result breaks out to the page grid. */ const STEP_SHELL = 'mx-auto w-full max-w-[650px]' /** * C234 — the selfie search flow (artefato: cenas 02–13). The browser computes * the descriptor on device and posts only the 128-float vector; the component * never puts the image in a request. Every terminal state of the artifact has * an exact counterpart here (empty, no-face, engine/unsupported, rate limit, * network, closed) and none of them shows a score, a percentage or a * third-party name. The consent text arrives rendered from the server (the * approved Consent reachText); the opt-out is authorized by the same face * match, and its no-match case points to the album's configured channel. */ export const SelfieSearchFlow = ({ consentText, removalChannelUrl, }: { consentText: ReactNode removalChannelUrl: string | null }) => { const [step, setStep] = useState({ kind: 'consent' }) const [consented, setConsented] = useState(false) const [activeIntent, setActiveIntent] = useState('search') const [file, setFile] = useState(null) const [previewUrl, setPreviewUrl] = useState(null) const previewRef = useRef(null) const inputRef = useRef(null) const resultsRef = useRef(null) const presenceRef = useRef(null) const pickRef = useRef(null) const processingRef = useRef(null) useEffect( () => () => { if (previewRef.current) URL.revokeObjectURL(previewRef.current) }, [], ) // The async transitions unmount the control that had focus; every new step // starts at its own top (the album scrolls inside its segment container, so // `scrollIntoView` is what reaches it) with focus on the heading region — // keyboard/screen-reader users never land mid-step (the terminal cards focus // and scroll themselves). useEffect(() => { const target = step.kind === 'pick' ? pickRef.current : step.kind === 'processing' ? processingRef.current : step.kind === 'results' ? resultsRef.current : step.kind === 'presence' ? presenceRef.current : null target?.scrollIntoView({ block: 'start' }) target?.focus() }, [step.kind]) const releasePreview = () => { if (previewRef.current) URL.revokeObjectURL(previewRef.current) previewRef.current = null setPreviewUrl(null) } const selectFile = (next: File | null) => { releasePreview() setFile(next) if (next) { previewRef.current = URL.createObjectURL(next) setPreviewUrl(previewRef.current) } } const runSearch = async (intent: SelfieSearchIntent) => { if (!file) return setStep({ kind: 'processing', intent }) const computed = await computeSelfieDescriptor(file) if (!computed.ok) { setStep( computed.reason === 'unsupported' ? { kind: 'unsupported' } : computed.reason === 'empty' ? { kind: 'no-face' } : { kind: 'engine-error' }, ) return } try { const response = await fetch('/api/fotos/selfie', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ vector: computed.descriptor, intent }), }) const body = (await response.json().catch(() => null)) as SelfieSearchResponse | null if (response.status === 429) return setStep({ kind: 'rate-limited' }) if (response.status === 404 || response.status === 503) return setStep({ kind: 'closed' }) if (!response.ok || body === null || !body.ok) return setStep({ kind: 'engine-error' }) if (intent === 'leave-index') { if (!('removed' in body)) return setStep({ kind: 'engine-error' }) return setStep(body.removed ? { kind: 'removed' } : { kind: 'presence-missing' }) } if ('found' in body && body.found) return setStep({ kind: 'results', photos: body.photos }) return setStep({ kind: 'empty' }) } catch { setStep({ kind: 'network' }) } } const startSelfieStep = (intent: SelfieSearchIntent) => { if (!supportsFaceSearchEngine()) { setStep({ kind: 'unsupported' }) return } setActiveIntent(intent) selectFile(null) setStep({ kind: 'pick', intent }) } const openPicker = () => inputRef.current?.click() const onFileChange = (event: React.ChangeEvent) => { const next = event.target.files?.[0] ?? null event.target.value = '' selectFile(next) } const reset = () => { selectFile(null) setConsented(false) setStep({ kind: 'consent' }) } return (
{step.kind === 'consent' ? (

Encontre você nas fotos

) : null} {step.kind === 'consent' ? (
Passo 1 de 3

Antes da sua selfie

{consentText}

Saiba como tratamos seus dados na{' '} Política de Privacidade .

Agora não · voltar ao álbum
) : null} {step.kind === 'pick' ? (

Passo 2 de 3

Escolha uma selfie nítida

Olhe para a câmera, com o rosto bem iluminado e sem outras pessoas na imagem.

{previewUrl ? (
{/* eslint-disable-next-line @next/next/no-img-element -- local blob preview, never uploaded */} Prévia da sua selfie Prévia no aparelho
) : ( )}
) : null} {step.kind === 'processing' ? (
{previewUrl ? ( // eslint-disable-next-line @next/next/no-img-element -- local blob preview, never uploaded ) : null}

{step.intent === 'leave-index' ? 'Saindo do índice' : 'Passo 3 de 3'}

{step.intent === 'leave-index' ? 'Confirmando sua saída do índice…' : 'Procurando você nas fotos aprovadas…'}

Mantenha esta tela aberta. Sua selfie continua somente neste aparelho.

) : null} {step.kind === 'results' ? (

Sua busca por selfie

Encontramos você nestas fotos. Estas são as fotos em que encontramos você.

Só registros públicos aprovados, sem nomes de terceiros. Mostramos apenas registros públicos aprovados. Não exibimos nomes de outras pessoas nem nota de semelhança.

{step.photos.map((photo) => ( ))}
setStep({ kind: 'presence' })} />
) : null} {step.kind === 'empty' ? (
) } const STATE_LINK = `inline-flex min-h-11 items-center text-sm font-bold text-[#184e92] underline underline-offset-4 ${ARCHIVE_PHOTO_FOCUS}` const StepDots = ({ current }: { current: 2 }) => ( ) const PresenceBand = ({ onManage }: { onManage: () => void }) => (

Quer controlar sua presença no álbum?

Saia do índice ou peça a remoção de uma foto.

) /** * The shared terminal-state card (artefato: cenas 06/09–13): the icon circle, * the honest title/body and the single primary action. `tone` only changes the * icon palette — hierarchy and spacing stay identical across states. */ const FlowStateCard = ({ icon, tone = 'info', title, body, note, action, secondary, }: { icon: ReactNode tone?: 'info' | 'danger' | 'warn' title: string body: string note?: string action: ReactNode secondary?: ReactNode }) => { const sectionRef = useRef(null) useEffect(() => { sectionRef.current?.scrollIntoView({ block: 'start' }) sectionRef.current?.focus() }, []) const toneClass = tone === 'danger' ? 'bg-red-50 text-[#b42318]' : tone === 'warn' ? 'bg-amber-50 text-amber-800' : 'bg-[#eef4fb] text-[#184e92]' return (
{icon}

{title}

{body}

{note ?

{note}

: null}
{action}
{secondary ?
{secondary}
: null}
) } /** * The opt-out confirmation (artefato: cena 08, segundo quadro) — a real dialog: * the destructive action asks once, Esc and the backdrop cancel, Tab stays * inside, and focus starts on the cancel action so an accidental Enter never * erases the index entry. */ const LeaveConfirmDialog = ({ onConfirm, onCancel, }: { onConfirm: () => void onCancel: () => void }) => { const cancelRef = useRef(null) const dialogRef = useRef(null) const onCancelRef = useRef(onCancel) onCancelRef.current = onCancel useEffect(() => { cancelRef.current?.focus() const onKeyDown = (event: KeyboardEvent) => { if (event.key === 'Escape') { onCancelRef.current() return } if (event.key !== 'Tab') return const focusables = dialogRef.current?.querySelectorAll(FOCUSABLE) if (!focusables || focusables.length === 0) return const first = focusables[0]! const last = focusables[focusables.length - 1]! if (event.shiftKey && document.activeElement === first) { event.preventDefault() last.focus() } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault() first.focus() } } window.addEventListener('keydown', onKeyDown) return () => window.removeEventListener('keydown', onKeyDown) }, []) return (
) }