import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { addGalleryComment, galleryDownloadAllUrl, galleryDownloadUrl, getGalleryStatus, loadGallery, setGalleryPick, setGalleryReview, unlockGallery, } from '../lib/api'; import type { GalleryPayload, GalleryPhoto } from '../lib/api'; /** * The page a client opens from a proofing link. It is entirely session-free: * the token in the URL is the only credential, and the API only ever returns * the shared event's live photos. */ function clientIdentity() { const key = 'lumenroom.proof.client'; let id = ''; let name = ''; try { id = localStorage.getItem(`${key}.id`) ?? ''; name = localStorage.getItem(`${key}.name`) ?? ''; } catch { /* private mode */ } if (!id) { id = `c-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`; try { localStorage.setItem(`${key}.id`, id); } catch { /* private mode */ } } return { id, name }; } function fmtDate(ms: number | null) { if (!ms) return ''; return new Date(ms).toLocaleDateString(undefined, { year: 'numeric', month: 'long', day: 'numeric', }); } function Heart({ filled }: { filled: boolean }) { return ( ); } export default function ProofingGallery({ token }: { token: string }) { const identity = useRef(clientIdentity()); const nameRef = useRef(null); const [clientName, setClientName] = useState(identity.current.name); const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [fatal, setFatal] = useState(null); const [error, setError] = useState(null); const [picks, setPicks] = useState>(new Set()); const [counts, setCounts] = useState>({}); const [onlyPicks, setOnlyPicks] = useState(false); const [lightbox, setLightbox] = useState(null); const [saving, setSaving] = useState>(new Set()); const [commentDraft, setCommentDraft] = useState(''); const [feedbackBusy, setFeedbackBusy] = useState(false); const [locked, setLocked] = useState(false); const [password, setPassword] = useState(''); const [unlocking, setUnlocking] = useState(false); const load = useCallback(async () => { try { // The status call is what turns a locked link into a password prompt // instead of a dead end: the gallery body is a 401 while locked. const status = await getGalleryStatus(token); if (status.locked) { setLocked(true); setData(null); setFatal(null); return; } setLocked(false); const payload = await loadGallery(token, identity.current.id); setData(payload); setPicks(new Set(payload.photos.filter((p) => p.mine).map((p) => p.id))); const next: Record = {}; for (const photo of payload.photos) if (photo.pickCount) next[photo.id] = photo.pickCount; setCounts(next); setFatal(null); setError(null); } catch (err) { setFatal(err instanceof Error ? err.message : 'Could not open this gallery'); } finally { setLoading(false); } }, [token]); useEffect(() => { void load(); }, [load]); useEffect(() => { document.title = data ? `${data.event.name} — Proofing` : 'Proofing gallery'; return () => { document.title = 'Luminary'; }; }, [data]); const unlock = async () => { if (unlocking || !password) return; setUnlocking(true); setError(null); try { await unlockGallery(token, password); setPassword(''); await load(); } catch (err) { setError(err instanceof Error ? err.message : 'That password did not work'); } finally { setUnlocking(false); } }; const rememberName = (name: string) => { setClientName(name); try { localStorage.setItem('lumenroom.proof.client.name', name); } catch { /* private mode */ } }; const togglePick = useCallback( async (photo: GalleryPhoto) => { if (saving.has(photo.id)) return; if (!clientName.trim()) { nameRef.current?.focus(); setError('Add your name so the photographer knows whose picks these are.'); return; } const picked = !picks.has(photo.id); // Optimistic: the heart responds immediately, then reconciles with the // shared count once the server has recorded the pick. setPicks((prev) => { const next = new Set(prev); if (picked) next.add(photo.id); else next.delete(photo.id); return next; }); setCounts((prev) => { const next = { ...prev }; const value = Math.max(0, (next[photo.id] ?? 0) + (picked ? 1 : -1)); if (value) next[photo.id] = value; else delete next[photo.id]; return next; }); setSaving((prev) => new Set(prev).add(photo.id)); try { await setGalleryPick(token, { photoId: photo.id, picked, clientId: identity.current.id, clientName: clientName.trim(), }); } catch { setPicks((prev) => { const next = new Set(prev); if (picked) next.delete(photo.id); else next.add(photo.id); return next; }); setCounts((prev) => { const next = { ...prev }; const value = Math.max(0, (next[photo.id] ?? 0) + (picked ? -1 : 1)); if (value) next[photo.id] = value; else delete next[photo.id]; return next; }); setError('That pick did not save — check the connection and try again.'); setTimeout(() => setError(null), 4000); } finally { setSaving((prev) => { const next = new Set(prev); next.delete(photo.id); return next; }); } }, [clientName, picks, saving, token], ); const submitComment = useCallback( async (photo: GalleryPhoto) => { const body = commentDraft.trim(); if (!body || feedbackBusy) return; setFeedbackBusy(true); try { await addGalleryComment(token, { photoId: photo.id, clientId: identity.current.id, clientName: clientName.trim(), body, }); setCommentDraft(''); await load(); } catch { setError('That comment did not save — check the connection and try again.'); } finally { setFeedbackBusy(false); } }, [clientName, commentDraft, feedbackBusy, load, token], ); const submitReview = useCallback( async (photo: GalleryPhoto, status: 'approved' | 'changes' | 'none') => { if (feedbackBusy) return; if (!clientName.trim()) { nameRef.current?.focus(); setError('Add your name before approving photos or requesting changes.'); return; } setFeedbackBusy(true); try { await setGalleryReview(token, { photoId: photo.id, clientId: identity.current.id, clientName: clientName.trim(), status, }); await load(); } catch { setError('That review did not save — check the connection and try again.'); } finally { setFeedbackBusy(false); } }, [clientName, feedbackBusy, load, token], ); const visible = useMemo(() => { if (!data) return []; return onlyPicks ? data.photos.filter((p) => picks.has(p.id)) : data.photos; }, [data, onlyPicks, picks]); const lightboxIndex = lightbox ? visible.findIndex((p) => p.id === lightbox) : -1; const lightboxPhoto = lightboxIndex >= 0 ? visible[lightboxIndex] : null; useEffect(() => { if (!lightboxPhoto) return; const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') { setLightbox(null); return; } if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { const next = visible[lightboxIndex + (e.key === 'ArrowRight' ? 1 : -1)]; if (next) setLightbox(next.id); return; } if (e.key === ' ') { e.preventDefault(); void togglePick(lightboxPhoto); } }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }, [lightboxIndex, lightboxPhoto, togglePick, visible]); if (loading) { return (
Luminary

Loading your gallery…

); } if (!data && locked) { return (
Luminary

This gallery is private

Enter the password the photographer gave you.

{ e.preventDefault(); void unlock(); }} > setPassword(e.target.value)} />
{error &&

{error}

}
); } if (!data) { return (
Luminary

This gallery isn’t available

{fatal ?? 'The link may have expired, or the photographer turned it off.'}

); } const pickedCount = picks.size; return (
Luminary

{data.event.name}

{fmtDate(data.event.date)} {data.event.date ? ' · ' : ''} {data.photos.length} photo{data.photos.length === 1 ? '' : 's'} {data.event.notes ? ` · ${data.event.notes}` : ''}

0} /> {pickedCount} pick{pickedCount === 1 ? '' : 's'}

Tap the heart on the photos you love. Your picks are saved as you go — no account needed, and you can come back to this link any time.

{pickedCount > 0 && data.downloads?.allowed !== false && ( Download picks )} {data.picks.total ? `${data.picks.total} pick${data.picks.total === 1 ? '' : 's'} from ${ data.picks.clients } client${data.picks.clients === 1 ? '' : 's'} so far` : 'Be the first to choose'}
{error &&
{error}
} {onlyPicks && !visible.length ? (

No picks yet

Tap a heart on any photo and it will show up here.

) : (
{visible.map((photo, i) => { const picked = picks.has(photo.id); return (
{photo.reviewStatus === 'approved' && ✓ Approved} {photo.reviewStatus === 'changes' && ! Changes} {photo.comments.length > 0 && 💬 {photo.comments.length}}
); })}
)}
Proofing gallery by Luminary {clientName.trim() ? `Picks saved for ${clientName.trim()}` : 'Your picks save automatically'}
{lightboxPhoto && (
setLightbox(null)}>
e.stopPropagation()}> {lightboxPhoto.name}
{lightboxPhoto.name} {data.downloads?.allowed !== false && ( Download )}
Review
Comments · {lightboxPhoto.comments.length}
{lightboxPhoto.comments.map((comment) => (
{comment.clientName || 'Client'} {comment.body}
))}
setCommentDraft(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') void submitComment(lightboxPhoto); }} disabled={!clientName.trim() || feedbackBusy} />
)}
); }