'use client'; import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; import type { CfImage } from '@/app/lib/cf-images'; // Admin CDN browser. Lazy on two axes so it scales to thousands of images: // 1. DOM — only `limit` cards are mounted; an IntersectionObserver sentinel // reveals the next BATCH as you scroll (so we never mount 5,000 nodes). // 2. Bytes — each thumbnail is a plain , so the browser // only fetches images near the viewport. const BATCH = 60; const btn: CSSProperties = { padding: '5px 10px', borderRadius: 6, border: '1px solid var(--rule)', background: 'transparent', cursor: 'pointer', fontSize: 11.5, color: 'var(--ink-soft)', }; // "lifestyle-koda-named-v4.jpg" → "Koda · named" — used to prefill the pin // title with something readable instead of the raw filename. function prettifyName(filename: string): string { const base = filename.replace(/\.(png|jpe?g|webp)$/i, '').replace(/-v\d+$/i, ''); const parts = base.split('-').filter(Boolean); if (parts.length === 0) return filename; const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); // Drop the leading "before/after/lifestyle/hero" prefix; capitalize the // pet name; comma-separate any trailing style descriptors. const known = new Set(['before', 'after', 'lifestyle', 'hero']); const rest = known.has(parts[0]) ? parts.slice(1) : parts; if (rest.length === 0) return cap(parts[0]); if (rest.length === 1) return cap(rest[0]); return `${cap(rest[0])} · ${rest.slice(1).map(cap).join(' ')}`; } // Filename style-token → human descriptor. Used to compose a default pin // description so we're not posting empty captions to Pinterest. const STYLE_BLURBS: Record = { watercolor: 'watercolor', popart: 'pop-art', charcoal: 'charcoal', lineart: 'line-drawing', vector: 'vector-outline', named: 'modern painted', mixedmedia: 'impasto mixed-media', impasto: 'impasto oil', cubist: 'cubist', ukiyoe: 'ukiyo-e', thangka: 'thangka', neoexpressionist: 'neo-expressionist', risograph: 'risograph', athome: 'mid-century home-portrait', landscape: 'landscape oil', }; // "lifestyle-koda-named-v4.jpg" → a brand-voiced default pin description // that includes a style keyword (good for Pinterest's in-app search), // the value proposition, and a CTA. ~250 chars, well under the 500 limit. function defaultDescriptionFor(filename: string): string { const base = filename.replace(/\.(png|jpe?g|webp)$/i, '').replace(/-v\d+$/i, '').toLowerCase(); const tokens = new Set(base.split('-')); let style = 'custom'; for (const key of Object.keys(STYLE_BLURBS)) { if (tokens.has(key)) { style = STYLE_BLURBS[key]; break; } } const article = /^[aeiou]/.test(style) ? 'An' : 'A'; return `${article} ${style} pet portrait by Lumen & Gesso — a small studio crafting custom portraits of the family pet. Share a photo, pick a style, and we'll send a proof within one business day. Archival giclée prints on paper or canvas, framed if you like. Start yours at lumengesso.com.`; } type PinBoard = { id: string; name: string }; export function CdnBrowser({ images: initialImages, deliveryBase, pinterestReady, }: { images: CfImage[]; deliveryBase: string; pinterestReady: boolean; }) { // Track the displayed set in state so successful deletes can drop a tile // without a full server refetch. Initialised from the server-fetched list. const [images, setImages] = useState(initialImages); const [scope, setScope] = useState<'portraits' | 'all'>('portraits'); const [q, setQ] = useState(''); const [limit, setLimit] = useState(BATCH); const [copied, setCopied] = useState(null); const [deleting, setDeleting] = useState(null); const [error, setError] = useState(null); const sentinel = useRef(null); // Pinterest pin modal — opened from a per-tile button. Boards are lazy- // loaded the first time the modal opens (and cached for the rest of the // session) so we don't hit Pinterest until the admin actually pins. const [pinTarget, setPinTarget] = useState(null); const [boards, setBoards] = useState(null); const [boardsLoading, setBoardsLoading] = useState(false); const [boardsError, setBoardsError] = useState(null); const [boardId, setBoardId] = useState(''); const [pinTitle, setPinTitle] = useState(''); const [pinDescription, setPinDescription] = useState(''); const [pinLink, setPinLink] = useState('https://lumengesso.com/gallery'); const [pinning, setPinning] = useState(false); const [pinSuccess, setPinSuccess] = useState<{ id: string; url?: string } | null>(null); // Pin-flow error displayed INSIDE the modal — separate from the page-level // `error` (used for delete failures), which lives above the grid and would // be hidden behind the modal overlay if a pin failed. const [pinError, setPinError] = useState(null); const portraitCount = useMemo( () => images.filter((im) => im.id.startsWith('portraits/')).length, [images], ); const filtered = useMemo(() => { const ql = q.trim().toLowerCase(); return images .filter((im) => (scope === 'portraits' ? im.id.startsWith('portraits/') : true)) .filter((im) => (ql ? im.id.toLowerCase().includes(ql) : true)) .sort((a, b) => a.id.localeCompare(b.id)); }, [images, scope, q]); // Reset paging whenever the visible set changes. useEffect(() => { setLimit(BATCH); }, [q, scope]); // Reveal more as the sentinel nears the viewport. useEffect(() => { const el = sentinel.current; if (!el) return; const io = new IntersectionObserver( (entries) => { if (entries[0].isIntersecting) setLimit((l) => l + BATCH); }, { rootMargin: '800px' }, ); io.observe(el); return () => io.disconnect(); }, [filtered.length]); const shown = filtered.slice(0, limit); const fileName = (id: string) => id.replace(/^portraits\//, ''); const remove = async (id: string) => { const name = fileName(id); if (!confirm(`Delete "${name}" from the CDN?\n\nThis is permanent. Any page that uses this image will return 404 until the URL is updated.`)) return; setDeleting(id); setError(null); try { const res = await fetch('/api/admin/images/delete', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id }), }); const json = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string }; if (!res.ok || !json.ok) throw new Error(json.error || `HTTP ${res.status}`); // Optimistic: drop the tile from the visible grid. setImages((arr) => arr.filter((im) => im.id !== id)); } catch (e) { setError(`Couldn't delete ${name}: ${e instanceof Error ? e.message : 'unknown error'}`); } finally { setDeleting(null); } }; const openPin = (im: CfImage) => { setPinTarget(im); setPinSuccess(null); setPinError(null); const name = fileName(im.id); setPinTitle(prettifyName(name)); setPinDescription(defaultDescriptionFor(name)); // Lazy-load boards on first open. if (!boards && !boardsLoading) { setBoardsLoading(true); setBoardsError(null); fetch('/api/admin/pinterest/boards') .then((r) => r.json().then((j) => ({ ok: r.ok, j }))) .then(({ ok, j }) => { if (!ok) throw new Error(j?.error || 'failed to load boards'); const list: PinBoard[] = (j.boards || []).map((b: PinBoard) => ({ id: b.id, name: b.name })); setBoards(list); if (list.length > 0) setBoardId(list[0].id); }) .catch((e) => setBoardsError(e instanceof Error ? e.message : 'failed to load boards')) .finally(() => setBoardsLoading(false)); } }; const submitPin = async () => { if (!pinTarget || !boardId) return; setPinning(true); setPinError(null); try { const url = `${deliveryBase}/${pinTarget.id}/public`; const res = await fetch('/api/admin/pinterest/pin', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ boardId, imageUrl: url, title: pinTitle, description: pinDescription, link: pinLink || undefined, altText: pinTitle, }), }); const json = (await res.json().catch(() => ({}))) as { ok?: boolean; error?: string; pin?: { id: string; url?: string } }; if (!res.ok || !json.ok || !json.pin) throw new Error(json.error || `HTTP ${res.status}`); setPinSuccess(json.pin); } catch (e) { setPinError(e instanceof Error ? e.message : 'unknown error'); } finally { setPinning(false); } }; const closePinModal = () => { setPinTarget(null); setPinSuccess(null); setPinError(null); }; const copy = async (text: string, key: string) => { try { await navigator.clipboard.writeText(text); setCopied(key); setTimeout(() => setCopied((c) => (c === key ? null : c)), 1300); } catch { /* clipboard blocked — ignore */ } }; return (
setQ(e.target.value)} onKeyDown={(e) => { if (e.key === 'Escape' && q) { e.preventDefault(); setQ(''); } }} placeholder="Filter by filename… (e.g. lifestyle, before-, popart, ziggy)" style={{ width: '100%', padding: '10px 36px 10px 12px', borderRadius: 8, boxSizing: 'border-box', border: '1px solid var(--rule)', font: 'inherit', color: 'var(--ink)', background: '#fff', }} /> {q && ( )}
{(['portraits', 'all'] as const).map((s) => ( ))}

Showing {Math.min(limit, filtered.length)} of {filtered.length} {q ? ` matching “${q}”` : ''}. Click a filename to copy it.

{error && (
{error}
)}
{shown.map((im) => { const name = fileName(im.id); const url = `${deliveryBase}/${im.id}/public`; return (
{/* eslint-disable-next-line @next/next/no-img-element */} {name} {/* Top-right delete affordance — small circle, semi-transparent so it never fights with the image. Sits as a sibling of the link so the button click doesn't bubble into the new-tab navigation. */} {pinterestReady && ( )}
{copied === im.id ? 'name copied ✓' : 'click name ↑'}
); })}
{limit < filtered.length && ( <>