import React, { createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { createPortal } from 'react-dom';
import { ArrowRight, ArrowUpRight, ArrowUpDown, Focus, MoreHorizontal, Plus, ShieldCheck, ListChecks, UserRound, Check, X, Info, ImagePlus, Trash2, LockKeyhole, Search, ExternalLink, CheckCircle2, AlertTriangle, Camera, Pencil, BookOpen, Link2, Flag, KeyRound, Copy, Download, Share2, Send, CreditCard, Puzzle, FileText, LifeBuoy, CalendarDays, SlidersHorizontal, Image as ImageIcon } from 'lucide-react';
import { photoRequestAvailable, requestLink, createPhotoRequest, getPhotoRequest, fetchRequestPhotos, uploadRequestPhoto } from './photoRequest';
import { VIEWS, CHECKS, detectBrand, money, evidenceCoverage, estimateRange, parsePrice, emptyChecks } from './domain';
import { readState, writeState, eraseAll } from './storage';
import { loadPrices, cachedPrice, savePrice, clearPrices } from './prices';
import { initNative, hideSplash, openMail, notify, tap, takePhoto, isNative } from './native';
import { flushSync } from 'react-dom';
import { checkImageFile, fileToDataUrl, resizeImage } from './images';
import { analysisAvailable, requestAnalysis, RATINGS } from './analysis';
import { TickScale } from './instruments';
import { Button, EmptyState, Field, GroupedList, GroupedRow, IconTile, Sheet, TabBar, TabIcon, TickDial, PassDial, Verdict, VerdictMark, WORD, CheckIcon, CloseIcon, InfoIcon, PlusIcon, ShieldIcon, Chevron, ArrowOut } from './ui';
import { NavBarProvider, NavBar, useNavBar, NavBack, NavAction, LargeTitle, Banner, ModalSheet, SheetFooter, Segmented, TickSpinner, Skeleton, EditorialArt, EmptyState as PageEmpty, useEdgeSwipeBack, useContextMenu, useOverlay, ActionSheet, Alert, SwipeRow, SkeletonRows, usePullToRefresh } from './native-ui';
import { listingPreviewAvailable, fetchListingPreview, fetchListingWatch, guessFromTitle } from './listing';
import { listingChanges } from './watch';
import { listingKey } from './listing-key';
import { buildReport, questionMessage, splitChecks, worstFirst, CHECK_NAMES, PART_NAMES, VERDICTS } from './report';
import { SAMPLE } from './sample';
import { currentValue, monthlySeries, inRange as monthsInRange, rangeSummary, RANGES as SPANS } from './collection';
import { scanAvailable, pendingClaim, deleteAccount, reportSignInFailure, extensionKey, fetchListing as fetchScanListing, scanListing, quickReview, marketValue, identifyFromPhotos, walletStatus, accountScans, saveAccountScans, forgetAccountScan, pendingForgets, startCheckout, paymentMethods, removePaymentMethod, openBillingPortal, track, accessCode, setAccessCode, ASSESSMENTS, SELLER_RISK } from './scan';
import { PHOTO_CREDITS } from './imagery';
import { authEnabled, enabledProviders, knownProviders, watchUser, sendCode, verifyCode, signInWith, signOut } from './auth';
import { captureClick } from './meta';
import { loadPixels, mirror } from './pixels';
import coverage from '../knowledge/coverage.json';
import '@fontsource-variable/hanken-grotesk/wght.css';
import '@fontsource-variable/newsreader/opsz.css';
import { AddCardSheet } from './add-card';
import './style.css';
import './ios.css';
import './native-ui.css';

const APP_VERSION = import.meta.env.VITE_APP_VERSION || 'dev';
const reduceMotion = () => { try { return window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch { return false; } };
const ONBOARDED_KEY = 'wabi-onboarded-v1';
// The signed-in user and a way to ask for sign-in, for the paywall wherever it appears.
const Account = createContext({ user: null, askSignIn: () => {} });
const PRIVACY_URL = 'https://wabi-watch.vercel.app/privacy';
const TERMS_URL = 'https://wabi-watch.vercel.app/terms';
const SUPPORT_URL = 'https://wabi-watch.vercel.app/support';
// Sections and listing detail have their own addresses (#/listings/<id>), so they can be bookmarked and the browser's Back button works.
const ROUTES = ['authenticity', 'check', 'markers', 'listings', 'collection', 'profile', 'guide', 'scan', 'send'];
const isRoute = hash => !hash || hash.startsWith('#/');
// Pages that sit on top of a tab: Guide, the library and the manual check are pushed, a report is pushed or lifted.
// Each remembers the tab it was opened from (its origin), so Back returns there and that tab stays lit meanwhile.
const PUSHED = ['check', 'markers', 'guide'];
const isPushed = r => Boolean(r.id) || PUSHED.includes(r.page);
const HOME_TAB = { check: 'authenticity', markers: 'authenticity', guide: 'profile', listings: 'listings' };
const TAB_LABEL = { authenticity: 'Check', listings: 'Listings', collection: 'Collection', profile: 'Profile' };
const hashOf = r => `#/${r.page}${r.id ? `/${encodeURIComponent(r.id)}` : ''}`;
function readRoute() {
  const [page, id] = (isRoute(window.location.hash) ? window.location.hash : '').replace(/^#\/?/, '').split('/');
  // #/listings/<id> opens a saved listing; #/scan/<link> (from the browser extension) starts a scan of that link.
  let listing = null; try { listing = (page === 'listings' || page === 'scan') && id ? decodeURIComponent(id) : null; } catch { listing = null; }
  const route = { page: ROUTES.includes(page) ? page : 'authenticity', id: listing };
  if (!isPushed(route)) return route;
  // The origin travels in history.state, so the browser's Back and Forward know it too; a page opened cold from its
  // address falls back to the tab it belongs to.
  const state = window.history.state || {};
  return { ...route, origin: TAB_LABEL[state.origin] ? state.origin : HOME_TAB[route.page] || 'authenticity', via: state.via === 'lift' ? 'lift' : 'push' };
}
// A new scan result laid over a saved listing. The person's own photos, notes, comparable sales and wording are kept.
function mergeScan(current, scan) {
  return { ...current, ...scan, id: current.id, created: current.created, model: current.model || scan.model, reference: current.reference || scan.reference, description: current.description || scan.description, photos: { ...scan.photos, ...current.photos }, checks: current.checks || scan.checks, comps: current.comps?.length ? current.comps : scan.comps };
}
// The same listing opened from different links (eBay with or without the title, tracking parameters) is one listing.
const listingId = url => listingKey(url) || '';
const sourceOf = url => { try { return new URL(url).hostname.replace(/^www\./, ''); } catch { return ''; } };
const WATCH_EVERY = 12 * 3600 * 1000;
const SECTIONS = [
  { id: 'authenticity', label: 'Check', tab: 'check', pages: ['authenticity', 'check', 'markers'] },
  { id: 'listings', label: 'Listings', tab: 'listings', pages: ['listings'] },
  { id: 'collection', label: 'Collection', tab: 'collection', pages: ['collection'] },
  { id: 'profile', label: 'Profile', tab: 'profile', pages: ['profile', 'guide'] },
];

const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
const tally = (n, one, many) => count(n, one, many).replace(/^\d+/, n.toLocaleString('en-US'));
const signed = n => `${n >= 0 ? '+' : '−'}${money(Math.abs(n))}`;
const percent = n => `${n > 0 ? '+' : n < 0 ? '−' : ''}${Math.abs(n * 100).toFixed(1)}%`;
// Dates in the current year drop the year, which keeps ledger rows on one line on a phone.
const shortDate = iso => { const d = new Date(iso); return new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric', ...(d.getFullYear() === new Date().getFullYear() ? {} : { year: 'numeric' }) }).format(d); };
// Asking price relative to the AI's indicative mid; negative means the listing asks less than the estimate.
function spread(record) {
  const ask = parsePrice(record.price ?? ''); const mid = record.analysis?.value.mid ?? null;
  return ask && mid ? (ask - mid) / mid : null;
}

// The listing's own first photo when it was fetched, otherwise the dial evidence photo, otherwise the scanned gallery.
const coverOf = record => record.photos.cover || record.photos.dial || (record.scan?.images?.[0] ? { url: record.scan.images[0] } : null);
async function listingCover(preview) {
  return preview.image ? { id: crypto.randomUUID(), name: 'listing.jpg', url: await resizeImage(preview.image, 1600) } : null;
}

function DialGlyph() {
  return <svg className="dial-glyph" viewBox="0 0 48 48" aria-hidden="true"><circle cx="24" cy="24" r="21"/><circle cx="24" cy="24" r="16.5"/>{Array.from({ length: 12 }, (_, i) => <line key={i} x1="24" y1="9" x2="24" y2={i % 3 ? 11 : 12.5} transform={`rotate(${i * 30} 24 24)`}/>)}<line x1="24" y1="24" x2="17.1" y2="20" className="hand"/><line x1="24" y1="24" x2="34.4" y2="18" className="hand"/></svg>;
}
// What a page puts in the navigation bar, for pages that fill it from a branch of their render.
function NavSlots(slots) { useNavBar(slots); return null; }
// A page's head: its back control and action go into the navigation bar (so they never scroll away), and the large
// title sits under the bar and hands over to the bar's small title as it scrolls beneath it.
function PageHead({ title, sub, action, back }) {
  useNavBar({ leading: back && <NavBack label={back.label} onClick={back.onClick}/>, title, trailing: action });
  return <header className={`page-head${back ? ' inner' : ''}`}><LargeTitle>{title}</LargeTitle>{sub && <p>{sub}</p>}</header>;
}
const claimFiles = import.meta.glob('../knowledge/claims/*/*.json', { import: 'default' });
let claimsPromise;
function loadAllClaims() {
  claimsPromise ??= Promise.all(Object.values(claimFiles).map(load => load())).then(files => files.flatMap(f => f.claims.map(c => ({ ...c, brand: f.brand, family: c.family || null }))));
  return claimsPromise;
}
function useClaims() {
  const [claims, setClaims] = useState(null); const [error, setError] = useState(''); const [tries, setTries] = useState(0);
  useEffect(() => { let live = true; setError(''); loadAllClaims().then(c => live && setClaims(c)).catch(() => { claimsPromise = null; if (live) setError('The library couldn’t be loaded.'); }); return () => { live = false; }; }, [tries]);
  return [claims, error, () => setTries(n => n + 1)];
}

// A watch photo as a thumbnail with 16px corners, or a calm placeholder until one exists. Never a drawn watch.
function PhotoTile({ src, alt = '', size = 56, className = '' }) {
  return <span className={`photo-tile ${className}`} style={{ width: size, height: size }}>{src ? <img src={src} alt={alt} referrerPolicy="no-referrer" width={size} height={size}/> : <Camera size={Math.round(size * .34)} strokeWidth={1.4} aria-hidden="true"/>}</span>;
}
// Loading, loaded or failed, for one image. A photo that is already in the cache can finish before React listens, so
// the ref checks it straight away.
function useImageState(src) {
  const [seen, setSeen] = useState({ src, state: 'loading' });
  const state = seen.src === src ? seen.state : 'loading';
  const set = next => setSeen(s => (s.src === src && s.state === next ? s : { src, state: next }));
  const ref = img => { if (img?.complete && state === 'loading') set(img.naturalWidth ? 'ok' : 'error'); };
  return [state, () => set('ok'), () => set('error'), ref];
}
// A listing photo in the check and part sheets: a calm block while it loads, and a short note (plus a way to the
// listing) if it never arrives, so the sheet never shows a blank box. The picture sits whole inside its frame, in a
// box of its own size, so a mark given as a fraction of the photo lands on the photo. onOpen makes it a button.
function Photo({ src, alt, url, label, children, onOpen }) {
  const [state, onLoad, onError, ref] = useImageState(src);
  if (state === 'error') return <div className="check-photo-frame" data-state="error"><div className="photo-fallback">{label && <span aria-hidden="true">{label}</span>}<span>Photo couldn’t load</span>{url && <a className="text-button" href={url} target="_blank" rel="noopener noreferrer">Open the listing</a>}</div></div>;
  const img = <img ref={ref} src={src} alt={alt} referrerPolicy="no-referrer" onLoad={onLoad} onError={onError} draggable="false"/>;
  return <div className="check-photo-frame" data-state={state}><span className="photo-fit">{onOpen ? <button type="button" className="photo-open" onClick={onOpen} aria-label={`${alt}. Open it full screen`}>{img}</button> : img}{state === 'ok' && children}</span>{state === 'loading' && label && <span className="photo-fallback" aria-hidden="true">{label}</span>}</div>;
}
// Screen changes ride the View Transitions API where the browser has it (Safari 18, Chrome): a push and its pop slide
// like a navigation stack, a pass lifts into its report and drops back, tabs cross-fade. Reduce Motion keeps the
// change but turns every one of them into a short cross-dissolve. Without the API, and on the desktop, it is instant.
// update commits the new screen; settle then runs with the new screen in place (scroll, focus, naming the element a
// pass drops into) and may return a cleanup for when the transition has finished.
let navRun = 0;
function transition(kind, update, settle) {
  const reduce = (() => { try { return window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch { return true; } })();
  if (!document.startViewTransition || window.innerWidth > 860) { flushSync(update); settle?.(kind)?.(); return; }
  const root = document.documentElement; const run = ++navRun; let done;
  root.dataset.nav = reduce ? 'fade' : kind;
  const t = document.startViewTransition(() => { flushSync(update); done = settle?.(kind); });
  // A second change can start before the first has finished; only the latest clears the shared state.
  t.finished.finally(() => { done?.(); if (run === navRun) delete root.dataset.nav; });
}
function App() {
  const [route, setRoute] = useState(readRoute);
  const page = route.page; const selectedId = route.id;
  const [data, setData] = useState({ assessments: [], watches: [] });
  const [ready, setReady] = useState(false);
  const [storageError, setStorageError] = useState('');
  // The one banner: its text, and an optional action ("Open") that belongs to that text.
  const [toast, setToast] = useState(''); const [said, setSaid] = useState(0); const toastAction = useRef(null);
  const [modal, setModal] = useState(null);
  // Someone arriving from the browser extension came to scan a listing, so the introduction waits for another visit.
  const [onboarding, setOnboarding] = useState(() => { try { return readRoute().page !== 'scan' && !localStorage.getItem(ONBOARDED_KEY); } catch { return false; } });
  // The launch layer is 'up' until the app is ready beneath it, 'out' while it dissolves, then 'gone'.
  const [launch, setLaunch] = useState('up');
  const [incoming, setIncoming] = useState(null);
  // The sample report (Check, when it is open), and a link carried over to the manual check from a listing wabi could not open.
  const [sample, setSample] = useState(false); const [manual, setManual] = useState({});
  const addPhotos = from => { setManual(typeof from === 'string' ? { url: from } : from?.model ? from : {}); navigate('check'); };
  useEffect(() => {
    if (route.page !== 'scan') return;
    setIncoming(route.id ? { url: route.id, at: Date.now() } : null);
    window.history.replaceState(null, '', '#/authenticity'); setRoute({ page: 'authenticity', id: null });
  }, [route.page, route.id]);
  const main = useRef();
  const dataRef = useRef(data); dataRef.current = data;
  const routeRef = useRef(route); routeRef.current = route;
  const selected = data.assessments.find(a => a.id === selectedId) || null;
  // A pushed or lifted page keeps the tab it was opened from lit.
  const pushed = isPushed(route);
  const section = SECTIONS.find(s => s.id === route.origin) || SECTIONS.find(s => s.pages.includes(page)) || SECTIONS[0];
  useEffect(() => {
    initNative();
    // WKWebView only applies :active to an element once something listens for touches, so presses would not show.
    document.addEventListener('touchstart', () => {}, { passive: true });
    // The app restores scroll itself (inside the transition), so the browser must not also jump on Back.
    try { window.history.scrollRestoration = 'manual'; } catch { /* older WebKit */ }
    Promise.all([readState(), loadPrices()]).then(([d]) => { setData(d); setReady(true); }).catch(() => { setStorageError('This device isn’t letting wabi save. You can look around, but nothing will be kept.'); setReady(true); });
    // The launch layer lifts the native launch image once it has drawn the same picture itself. If that ever stalls
    // (or this is a page without the layer), the image still goes after four seconds rather than staying up for good.
    const safety = setTimeout(hideSplash, 4000);
    return () => clearTimeout(safety);
  }, []);
  // Where each screen was scrolled to when it was left, by address, so Back puts it back.
  const scrolls = useRef(new Map());
  // After a screen change: put the scroll where it belongs, move focus to the new page's title (never to its back
  // button), and on a drop name the row or strip the pass came from so it lands there.
  const settle = (from, y, focus) => kind => {
    window.scrollTo(0, y);
    if (focus) { const h = main.current?.querySelector('h1'); if (h && !h.hasAttribute('tabindex')) h.tabIndex = -1; (h || main.current)?.focus({ preventScroll: true }); }
    const strip = kind === 'drop' && from.id && [...document.querySelectorAll('[data-pass-id]')].find(el => el.dataset.passId === from.id);
    if (!strip) return undefined;
    strip.dataset.landing = ''; return () => { delete strip.dataset.landing; };
  };
  useEffect(() => {
    // The browser's own Back and Forward (and an edge swipe in Safari) take the same road as the app's: a page that
    // was pushed pops, a pass that was lifted drops, and the screen underneath is where it was left.
    // In-page anchors such as "Skip to content" (#main) are not routes and leave the page alone.
    const onHash = () => {
      if (!isRoute(window.location.hash)) return;
      const from = routeRef.current; const to = readRoute();
      setToast(''); track('PageView');
      scrolls.current.set(hashOf(from), window.scrollY);
      const kind = isPushed(from) && !isPushed(to) ? (from.via === 'lift' ? 'drop' : 'pop') : isPushed(to) && !isPushed(from) ? to.via : 'tab';
      transition(kind, () => setRoute(to), settle(from, scrolls.current.get(hashOf(to)) || 0, false));
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []); // eslint-disable-line react-hooks/exhaustive-deps
  // A step into a pushed page slides in from the right and the way back slides it off, as an iOS navigation stack
  // does; a pass lifts into its report and drops back; a tab switch changes in place. origin is the tab a pushed page
  // returns to (by default the tab it was opened from).
  function go(next, id, motion, origin) {
    const from = routeRef.current; const to = { page: next, id: id || null };
    if (isPushed(to)) { to.origin = origin || from.origin || SECTIONS.find(s => s.pages.includes(from.page))?.id || 'authenticity'; to.via = motion === 'lift' ? 'lift' : 'push'; }
    const back = isPushed(from) && !isPushed(to) && next === from.origin;
    const kind = motion || (isPushed(to) ? 'push' : back ? (from.via === 'lift' ? 'drop' : 'pop') : 'tab');
    scrolls.current.set(hashOf(from), window.scrollY);
    const hash = hashOf(to);
    if (window.location.hash !== hash) { window.history.pushState(isPushed(to) ? { origin: to.origin, via: to.via } : null, '', hash); track('PageView'); }
    // A tab, like a page you go back to, opens where it was left (tapping the lit tab again still scrolls it to the top).
    transition(kind, () => setRoute(to), settle(from, kind === 'pop' || kind === 'drop' || kind === 'tab' ? scrolls.current.get(hash) || 0 : 0, true));
  }
  // Back from a pushed or lifted page, with the transition it arrived by reversed.
  const back = () => { setToast(''); go(route.origin || 'authenticity', null, route.via === 'lift' ? 'drop' : 'pop'); };
  const backTo = { label: TAB_LABEL[route.origin] || 'Check', onClick: back };
  useEdgeSwipeBack(back, pushed);
  // A banner belongs to the section it was raised in: it clears on a tab change or a Back/Forward, but not when the app
  // itself moves on (saving a listing opens it, and its confirmation should land there).
  function navigate(next) {
    setToast(''); if (sample) setSample(false);
    // The tab that is already lit: from a pushed page it pops back to the tab's root, at the root it scrolls to the top.
    if (next === section.id && SECTIONS.some(s => s.id === next)) { if (pushed) back(); else if (page !== next) go(next); else window.scrollTo({ top: 0, behavior: 'smooth' }); return; }
    go(next);
  }
  // A report opens over Listings unless it was lifted from somewhere else (the recent stack on Check).
  function openReport(id, motion, origin = 'listings') { go('listings', id, motion, origin); }
  // The real reason goes to the console and, for a full disk, to the person; anything else is a plain retry message.
  async function persist(next, failure = 'Couldn’t save that. Please try again.') {
    // dataRef moves on at once, not at the next render, so work that follows a save (a watch check, a sync) reads it.
    try { const saved = await writeState(next); dataRef.current = saved; setData(saved); return true; }
    catch (e) { console.error('save failed', e); setStorageError(e?.name === 'QuotaExceededError' ? 'Your device is out of space, so wabi couldn’t save.' : failure); notify('error'); return false; }
  }
  // An ordinary banner is silent. The few that mark a real outcome ask for their haptic by name. One that would land on
  // something still arriving (a result being revealed) can be held back until it has (after, in ms).
  function say(message, { haptic, action = null, after = 0 } = {}) {
    if (after > 0) { setTimeout(() => say(message, { haptic, action }), after); return; }
    toastAction.current = action; setToast(message); setSaid(n => n + 1); if (haptic) notify(haptic);
  }
  async function saveAssessment(a) {
    const record = { ...a, id: crypto.randomUUID(), created: new Date().toISOString() };
    const latest = dataRef.current;
    if (await persist({ ...latest, assessments: [record, ...latest.assessments] })) { openReport(record.id, 'push', 'listings'); say('Listing saved on this device'); }
  }
  // Scan credits: loaded on start, and a Stripe checkout that sent the buyer back here is claimed once.
  const [wallet, setWallet] = useState(null); const [walletDown, setWalletDown] = useState(false);
  const [user, setUser] = useState(null);
  const userRef = useRef(user); userRef.current = user;
  // The session loads first, so a returning buyer's purchase is claimed into their account's wallet.
  useEffect(() => {
    captureClick(); loadPixels(); track('PageView');
    let first = true;
    return watchUser(u => { setUser(u); if (!scanAvailable) return; if (first) { first = false; loadWallet(); } else refreshWallet(); });
  }, []);
  async function refreshWallet(options) { try { const w = await walletStatus(options); mirror(w.events); setWallet(w); setWalletDown(false); return w; } catch (e) { if (options) throw e; setWalletDown(true); return null; } }
  // The checkout id is kept on the device until the purchase is claimed, so a dropped connection on the way back from
  // Stripe is retried on the next visit. (Stripe's webhook credits the purchase regardless; this makes it show at once.)
  function loadWallet() {
    const fromUrl = new URLSearchParams(window.location.search).get('checkout');
    if (fromUrl) { pendingClaim(fromUrl); window.history.replaceState(null, '', window.location.pathname); }
    const claim = pendingClaim();
    if (!claim) { refreshWallet(); return; }
    refreshWallet({ claim })
      .then(w => { pendingClaim(null); say(w.subscription?.active ? `You’re subscribed · ${count(w.subscription.scansLeft, 'full scan')} this month` : `Payment received · ${count(w.credits, 'full scan')} available`); })
      .catch(e => {
        if (e.status >= 400 && e.status < 500) pendingClaim(null); // not this device's to claim, or not paid
        setStorageError(fromUrl ? `${e.message} If you were charged, your scans will appear shortly.` : e.message);
        refreshWallet();
      });
  }
  // Market values for the collection: each watch is priced when the Collection opens and its price is a few days
  // old. Lookups are shared per reference on the server, so most of these are cache hits.
  const marketTried = useRef(new Set()); const [marketBusy, setMarketBusy] = useState([]); const [marketErrors, setMarketErrors] = useState({});
  async function priceWatch(id) {
    const w = dataRef.current.watches.find(x => x.id === id); if (!w || !canPrice(w)) return;
    const q = marketQuery(w); const local = cachedPrice(queryKey(q));
    const apply = async market => { const latest = dataRef.current; const current = latest.watches.find(x => x.id === id); if (current) await persist({ ...latest, watches: latest.watches.map(x => x.id === id ? withMarket(current, market) : x) }); };
    // A fresh copy in the local price database is used without going to the network.
    if (marketFresh(local, q)) { if (!marketFresh(w.market, q)) await apply(local); return; }
    setMarketBusy(b => [...b, id]); setMarketErrors(e => ({ ...e, [id]: false }));
    try {
      const market = await savePrice(queryKey(q), asMarket(await marketValue(q), q));
      await apply(market);
    } catch (e) { console.warn('market value not loaded:', e.message); setMarketErrors(x => ({ ...x, [id]: true })); if (e.status === 429) throw e; }
    finally { setMarketBusy(b => b.filter(x => x !== id)); }
  }
  useEffect(() => {
    if (!ready || page !== 'collection') return;
    const due = data.watches.filter(w => canPrice(w) && !marketFresh(w.market, marketQuery(w)) && !marketTried.current.has(w.id));
    if (!due.length) return;
    due.forEach(w => marketTried.current.add(w.id));
    (async () => { for (const w of due) { try { await priceWatch(w.id); } catch { break; } } })();
  }, [ready, page, data.watches]);
  // An unlocked full scan replaces the free review saved for the same listing.
  // A report is only ever laid over the same listing; anything else is saved as its own listing.
  async function upgradeScan(id, record, told) {
    const current = dataRef.current.assessments.find(r => r.id === id);
    if (current && listingId(current.url) && listingId(record.url) && listingId(current.url) !== listingId(record.url)) return saveScan(record, told);
    if (current) await updateAssessment(mergeScan(current, record), 'Full report unlocked', told);
  }
  // A scan can finish after other edits, so it is added to the latest collection; the scan screen stays open.
  // Scanning a link already in Listings updates that listing instead of adding a second one, and a free review never replaces a full report.
  async function saveScan(a, told) {
    const now = new Date().toISOString(); const latest = dataRef.current; const key = listingId(a.url);
    // Only an earlier scan of the same link is updated; a listing the person built by hand is never touched.
    // Signed in, a listing that belongs to another account on this device is left alone; this scan gets its own.
    const me0 = userRef.current?.id;
    const current = key ? latest.assessments.find(r => r.scan && listingId(r.url) === key && (!me0 || !r.account || r.account === me0)) : null;
    if (current) {
      const keep = current.scan.tier !== 'mini' && a.scan?.tier === 'mini';
      const me = userRef.current?.id; const account = me || current.account;
      // A scan run while signed in is the account's again, even if the listing had been set aside as this device's only.
      const tag = account ? { account, ...(me && { localOnly: undefined }) } : {};
      const record = keep ? { ...current, scanned: now, ...tag } : { ...mergeScan(current, a), scanned: now, ...tag };
      if (me) dropForgets(me, key);
      if (await persist({ ...latest, assessments: latest.assessments.map(r => r.id === current.id ? record : r) })) { say(a.scan?.tier === 'mini' ? 'Updated your saved check of this listing' : 'Updated your saved report of this listing', told); return record.id; }
      return null;
    }
    // A scan run while signed in is already kept with the account (the server records it), so it is marked as the account's.
    const record = { ...a, id: crypto.randomUUID(), created: now, scanned: now, ...(userRef.current?.id && { account: userRef.current.id }) };
    if (userRef.current?.id) dropForgets(userRef.current.id, key);
    if (await persist({ ...latest, assessments: [record, ...latest.assessments] })) { say(a.scan?.tier === 'mini' ? 'Check saved to Listings' : 'Full report saved to Listings', told); return record.id; }
    return null;
  }
  // An AI review can finish after other edits, so merge into the latest collection rather than the one captured at the start.
  async function updateAssessment(a, message = 'Listing updated', told) {
    const latest = dataRef.current;
    if (!latest.assessments.some(r => r.id === a.id)) return;
    if (await persist({ ...latest, assessments: latest.assessments.map(r => r.id === a.id ? a : r) }) && message) say(message, told);
  }
  // Watched listings are re-read when the app opens, each at most every 12 hours, so a buyer hears about a price drop,
  // swapped photos or a sale without checking by hand.
  const watching = useRef(false);
  async function checkWatched({ only, force = false } = {}) {
    if (watching.current || !listingPreviewAvailable) return;
    watching.current = true;
    try {
      const due = dataRef.current.assessments.filter(r => r.watch?.on && r.url && (only ? r.id === only : true) && (force || !r.watch.last || Date.now() - Date.parse(r.watch.last.checkedAt) > WATCH_EVERY)).slice(0, only ? 1 : 5);
      for (const r of due) {
        try {
          const now = await fetchListingWatch(r.url);
          const latest = dataRef.current.assessments.find(x => x.id === r.id); if (!latest?.watch?.on) continue;
          const changes = listingChanges(latest.watch.last, now).map(c => ({ ...c, at: now.checkedAt }));
          await patchAssessment(r.id, { watch: { ...latest.watch, last: now, history: [...changes, ...(latest.watch.history || [])].slice(0, 20), unseen: latest.watch.unseen || changes.length > 0 } }, only && force ? (changes.length ? changes[0].text : 'No changes since the last check') : '');
        } catch (e) { if (only && force) say(e.message); }
      }
    } finally { watching.current = false; }
  }
  useEffect(() => { if (ready) checkWatched(); }, [ready]); // eslint-disable-line react-hooks/exhaustive-deps
  async function patchAssessment(id, patch, message) {
    const current = dataRef.current.assessments.find(r => r.id === id);
    if (current) await updateAssessment({ ...current, ...patch }, message);
  }
  async function eraseData() {
    try { setData(await eraseAll()); clearPrices(); setConsent(false); setModal(null); say('All wabi data was deleted from this device'); } catch { setStorageError('Couldn’t delete your data. Try again.'); }
  }
  // Deleting a listing that belongs to an account also removes it there, so it doesn't come back. The delete is noted
  // on the device first and retried on the next signed-in open if the account can't be reached now (or someone else,
  // or nobody, is signed in).
  const removeListing = async id => {
    const latest = dataRef.current; const gone = latest.assessments.find(a => a.id === id);
    if (!(await persist({ ...latest, assessments: latest.assessments.filter(a => a.id !== id) }, 'Couldn’t delete that listing. Please try again.'))) return;
    say('Listing deleted');
    if (gone?.url) deletedNow.current.add(listingId(gone.url));
    const owner = gone?.account || (gone?.scan && !gone.localOnly && userRef.current?.id);
    if (!owner || !gone.url) return;
    pendingForgets([...pendingForgets(), { account: owner, url: gone.url }]);
    if (userRef.current?.id === owner) flushForgets(owner);
  };
  // A new scan of a listing cancels a delete of it that hasn't reached the account yet.
  const dropForgets = (account, key) => { const list = pendingForgets(); const left = list.filter(f => !(f.account === account && listingId(f.url) === key)); if (left.length !== list.length) pendingForgets(left); };
  const deletedNow = useRef(new Set());
  async function flushForgets(account) {
    for (const f of pendingForgets().filter(f => f.account === account)) {
      try { await forgetAccountScan(f.url); pendingForgets(pendingForgets().filter(x => !(x.account === account && x.url === f.url))); }
      catch (e) { console.warn('account scan not removed yet', e.message); return; }
    }
  }
  // Scans follow the account. On sign-in, and each time the app opens signed in: deletes made on this device reach
  // the account; the account's scans come into Listings (new ones added, newer ones laid over the device's copy,
  // ones deleted on another device removed); and listings scanned on this device before anyone signed in are handed
  // over once. Listings that belong to another account are never handed over.
  const syncing = useRef(null); const [synced, setSynced] = useState(null);
  async function syncAccount() {
    const me = userRef.current?.id;
    if (!me || !scanAvailable) return;
    if (syncing.current) { syncing.current.again = true; return; }
    syncing.current = { again: false }; deletedNow.current = new Set();
    try {
      await flushForgets(me);
      const answer = await accountScans();
      if (userRef.current?.id !== me) return;
      const entries = Array.isArray(answer?.scans) ? answer.scans.filter(e => e && listingId(e.url)) : [];
      const goneKeys = new Set(Array.isArray(answer?.gone) ? answer.gone : []);
      const built = [];
      for (const entry of entries) {
        try { built.push({ entry, key: listingId(entry.url), record: await recordFromAccount(entry) }); } catch (e) { console.warn('account scan skipped', e.message); }
      }
      // Applied to the latest listings, so edits made meanwhile are kept, and a listing deleted meanwhile stays deleted.
      const deleting = new Set([...pendingForgets().filter(f => f.account === me).map(f => listingId(f.url)), ...deletedNow.current, ...goneKeys]);
      let list = [...dataRef.current.assessments]; let brought = 0; let changed = false;
      // A listing deleted on another device leaves this one too, unless the person added their own work to it here
      // (photos, notes on the checks, comparables, a photo request or a price watch): then it stays, as this device's only.
      const ownCopy = r => !Object.keys(r.photos || {}).some(k => k !== 'cover') && !Object.values(r.checks || {}).some(c => (c.status && c.status !== 'unknown') || c.note)
        && !r.comps?.length && !r.watch?.on && !r.watch?.history?.length && !r.sellerReview && !r.sellerRequest && !edited(r);
      list = list.flatMap(r => {
        if (!(r.account === me && r.scan && goneKeys.has(listingId(r.url)))) return [r];
        changed = true;
        return ownCopy(r) ? [] : [{ ...r, account: undefined, localOnly: true }];
      });
      for (const { entry, key, record } of built) {
        if (deleting.has(key)) continue;
        // A listing that belongs to another account on this device is left alone; this account's copy is its own listing.
        const at = list.findIndex(r => r.scan && listingId(r.url) === key && (!r.account || r.account === me));
        if (at === -1) { list.push({ ...record, id: crypto.randomUUID(), created: entry.at, scanned: entry.at, account: me }); brought += 1; continue; }
        const local = list[at];
        // A copy set aside as this device's only (deleted elsewhere, then scanned again) is the account's again.
        const adopt = { account: me, localOnly: undefined };
        const localFull = Boolean(local.analysis?.details); const theirsFull = Boolean(record.analysis?.details);
        const newer = Date.parse(entry.at) - Date.parse(local.scanned || local.created || 0) > 120_000;
        if ((theirsFull && !localFull) || (newer && (theirsFull || !localFull))) { list[at] = { ...mergeScan(local, record), scanned: entry.at, ...adopt }; brought += 1; }
        else if (local.account !== me || local.localOnly) { list[at] = { ...local, ...adopt }; changed = true; }
      }
      if (brought || changed) {
        list.sort((a, b) => String(b.scanned || b.created || '').localeCompare(String(a.scanned || a.created || '')));
        if (await persist({ ...dataRef.current, assessments: list }) && brought) say(brought === 1 ? 'Brought in 1 scan from your account' : `Brought in ${brought} scans from your account`);
      }
      // Listings this device scanned before anyone signed in, that the account lacks (or has only as a free review),
      // are offered once, newest first; each is then marked as this account's whether the account kept it or not.
      const held = new Map(entries.map(e => [listingId(e.url), e.kind]));
      const offer = dataRef.current.assessments.filter(r => r.scan && r.url && !r.account && !r.localOnly && listingId(r.url) && !goneKeys.has(listingId(r.url))
        && (!held.has(listingId(r.url)) || (held.get(listingId(r.url)) === 'mini' && r.analysis?.details))).slice(0, 60);
      for (let i = 0; i < offer.length; i += 10) {
        const batch = offer.slice(i, i + 10);
        await saveAccountScans(batch.map(forAccount));
        if (userRef.current?.id !== me) return;
        const ids = new Set(batch.map(r => r.id));
        await persist({ ...dataRef.current, assessments: dataRef.current.assessments.map(r => (ids.has(r.id) ? { ...r, account: me } : r)) });
      }
    } catch (e) { console.warn('account scans not synced', e.message); }
    finally { const again = syncing.current?.again; syncing.current = null; setSynced(me); if (again) syncAccount(); }
  }
  useEffect(() => { if (ready && user?.id) syncAccount(); }, [ready, user?.id]); // eslint-disable-line react-hooks/exhaustive-deps
  // With accounts on, the first check is free once the person has signed in, so the introduction ends at the sign-in sheet.
  const signInFirst = Boolean(authEnabled && wallet?.authEnabled && !user && !wallet?.accessCodeValid);
  // Which of Apple and Google the sheet can offer is asked for as soon as accounts are known to be on, so the sheet
  // opens at its full height with its buttons already in it.
  useEffect(() => { if (authEnabled && wallet?.authEnabled) enabledProviders(); }, [wallet?.authEnabled]);
  // A seller opening a buyer's photo request sees only the upload page: no tabs, no onboarding, nothing of the buyer's.
  if (page === 'send') return <main id="main" className="send-page"><SellerUpload token={selectedId}/></main>;
  return <Account.Provider value={{ user, askSignIn: (from, after) => setModal({ type: 'signin', from, after }) }}><NavBarProvider><div className="app-shell">
    <a className="skip-link" href="#main">Skip to content</a>
    <aside className="rail">
      <button className="wordmark" onClick={() => navigate('authenticity')} aria-label="wabi home">wabi</button>
      <nav aria-label="Main navigation">{SECTIONS.map(({ id, label, tab }) => <button key={id} className={`rail-item ${section.id === id ? 'active' : ''}`} aria-current={section.id === id ? 'page' : undefined} onClick={() => navigate(id)}><TabIcon name={tab}/>{label}{id === 'listings' && data.assessments.length > 0 && <span className="rail-count">{data.assessments.length}</span>}</button>)}</nav>
      <div className="rail-foot"><LockKeyhole size={13}/><span>{user ? 'Your scans are saved to your account' : 'Your listings stay on this device'}</span></div>
    </aside>
    <div className="main-shell">
      <NavBar/>
      <main id="main" ref={main} tabIndex="-1" key={`${page}-${selectedId || ''}`} className="page" data-page={page}>{storageError && <div className="alert" role="alert"><AlertTriangle size={17}/><span>{storageError}</span><button className="icon-button" aria-label="Dismiss message" onClick={() => setStorageError('')}><X size={16}/></button></div>}{ready && <>
        {page === 'authenticity' && <AuthenticityPage onToast={say} incoming={incoming} onIncoming={() => setIncoming(null)} records={data.assessments} navigate={navigate} openReport={openReport} onScanned={saveScan} onUpgraded={upgradeScan} hasFull={id => Boolean(dataRef.current.assessments.find(r => r.id === id)?.analysis?.details)} wallet={wallet} refreshWallet={refreshWallet} remove={removeListing} sample={sample} setSample={setSample} addPhotos={addPhotos}/>}
        {page === 'check' && <CheckPage onSave={saveAssessment} back={backTo} seed={manual}/>}
        {page === 'markers' && <MarkersPage back={backTo}/>}
        {page === 'listings' && (selected ? <Report key={selected.id} onToast={say} checkWatch={() => checkWatched({ only: selected.id, force: true })} record={selected} onSave={updateAssessment} onPatch={patchAssessment} onUpgraded={upgradeScan} wallet={wallet} refreshWallet={refreshWallet} back={backTo} origin={route.origin} onCollect={() => setModal({ type: 'watch', record: selected })} remove={id => { back(); return removeListing(id); }}/> : <ListingsPage records={data.assessments} open={openReport} add={() => { navigate('authenticity'); focusScanField(); }} remove={removeListing} refresh={() => checkWatched({ force: true })} onSave={updateAssessment} syncing={Boolean(user?.id && scanAvailable && synced !== user.id)}/>)}
        {page === 'collection' && <CollectionPage marketBusy={marketBusy} marketErrors={marketErrors} priceWatch={id => priceWatch(id).catch(() => {})} watches={data.watches} add={() => setModal({ type: 'watch' })} edit={watch => setModal({ type: 'watch', watch })} check={w => addPhotos({ model: w.model, reference: w.reference || '' })} remove={async id => { const latest = dataRef.current; if (await persist({ ...latest, watches: latest.watches.filter(w => w.id !== id) }, 'Couldn’t remove that watch. Please try again.')) say('Watch removed from your collection'); }}/>}
        {page === 'profile' && <ProfilePage erase={() => setModal('erase')} navigate={navigate} wallet={wallet} walletDown={walletDown} refreshWallet={refreshWallet}/>}
        {page === 'guide' && <Guide back={backTo} start={() => { navigate('authenticity'); focusScanField(); }}/>}
      </>}</main>
    </div>
    <TabBar label="Sections" items={SECTIONS.map(s => ({ id: s.id, label: s.label, icon: s.tab, badge: s.id === 'listings' && data.assessments.some(a => a.watch?.unseen) ? 'changes to see' : null }))} active={section.id} onSelect={navigate}/>
    <Banner message={toast} said={said} action={toastAction.current} onDismiss={() => setToast('')}/>
    {ready && onboarding && launch !== 'up' && <Onboarding signInFirst={signInFirst}
      leave={toSample => { try { localStorage.setItem(ONBOARDED_KEY, '1'); } catch {} if (page !== 'authenticity') navigate('authenticity'); if (toSample) setSample(true); else arrive('first'); }}
      done={toSample => { setOnboarding(false); if (toSample) return; if (signInFirst) setTimeout(() => setModal({ type: 'signin', from: 'scan', after: focusScanField }), 250); else focusScanField(); }}/>}
    {launch !== 'gone' && <Launch ready={ready} first={onboarding} reveal={() => { setLaunch('out'); if (!onboarding && page === 'authenticity') arrive('launch'); }} done={() => setLaunch('gone')}/>}
    {modal === 'erase' && <Alert title="Delete all data?" message={`This permanently deletes every listing, photo and collection watch from this device. It cannot be undone.${user ? ' Scans saved to your account come back the next time you open wabi signed in. To remove those too, delete your account.' : ''}`}
      confirm={{ label: 'Delete all data', onSelect: eraseData }} cancel="Keep my data" onClose={() => setModal(null)}/>}
    {modal?.type === 'watch' && <WatchModal initial={modal.watch} assessment={modal.record} close={() => setModal(null)} onSave={async saved => { const v = modal.record && listingVerdict(modal.record); const watch = v && !saved.checked ? { ...saved, checked: { score: v.score, kind: v.kind, label: v.free ? `${v.label}, free check` : v.label } } : saved; marketTried.current.delete(watch.id); const latest = dataRef.current; const next = { ...latest, watches: modal.watch ? latest.watches.map(w => w.id === watch.id ? watch : w) : [watch, ...latest.watches] }; if (await persist(next)) { setModal(null); say('Saved to your collection'); } }}/>}
    {modal?.type === 'signin' && <SignInSheet reason={modal.from} close={() => setModal(null)} done={() => { const after = modal.after; setModal(null); say('Signed in'); refreshWallet(); after?.(); }}/>}
  </div></NavBarProvider></Account.Provider>;
}

// The Check pass comes forward when the layer over it goes: it rises 12pt as the launch layer dissolves, and 24pt
// with one pass of light across it when the introduction closes. One attribute on <html> runs it, then is dropped.
function arrive(kind) {
  const root = document.documentElement; root.dataset.arrive = kind;
  clearTimeout(arrive.timer); arrive.timer = setTimeout(() => { delete root.dataset.arrive; }, 1000);
}
// A time token read from the stylesheet (Reduce Motion shortens them), for the few timers that must agree with it.
const cssMs = (name, fallback) => { const v = parseFloat(getComputedStyle(document.documentElement).getPropertyValue(name)); return Number.isFinite(v) ? v : fallback; };

// The launch layer: the picture the native launch screen and the page's first paint already show (the wordmark alone,
// the same size, in the same place), kept up until the app has its data, so all three are one frame and the tab bar
// is never seen before the app is ready. A returning launch then cross-fades straight to the app. The very first
// launch takes about a second more: a ring of sixty ticks strikes in round the wordmark, a gold hand sweeps one turn
// and lands at twelve, and the ring opens out as the welcome screen settles beneath it. A touch skips to the end.
// Under Reduce Motion the wordmark is still and the layer dissolves.
const TICKS = Array.from({ length: 60 }, (_, i) => i);
function Launch({ ready, first, reveal, done }) {
  const ring = useRef(first && !reduceMotion()).current;
  const [playing, setPlaying] = useState(false); const [struck, setStruck] = useState(!ring); const [out, setOut] = useState(false);
  const finish = useRef(done); finish.current = done;
  // The native launch image goes once this layer has been painted (two frames on); the ring starts after it has.
  useEffect(() => {
    let live = true; let second = 0;
    const one = requestAnimationFrame(() => { second = requestAnimationFrame(() => Promise.race([hideSplash(), new Promise(r => setTimeout(r, 400))]).then(() => live && setPlaying(true))); });
    return () => { live = false; cancelAnimationFrame(one); cancelAnimationFrame(second); };
  }, []);
  useEffect(() => {
    if (!ready || !struck || out) return undefined;
    setOut(true); reveal?.();
    // The dissolve ends on its own transition; the timer is only there in case that event never comes.
    const safety = setTimeout(() => finish.current(), cssMs('--t-launch-first', 400) + 300);
    return () => clearTimeout(safety);
  }, [ready, struck]); // eslint-disable-line react-hooks/exhaustive-deps
  const base = `${import.meta.env.BASE_URL}images/brand/`;
  return <div className="launch" aria-hidden="true" data-first={ring ? '' : undefined} data-play={playing ? '' : undefined} data-out={out ? '' : undefined}
    onPointerDown={() => setStruck(true)} onTransitionEnd={e => { if (out && e.target === e.currentTarget && e.propertyName === 'opacity') done(); }}>
    {ring && <svg className="launch-ring" viewBox="0 0 200 200">
      {TICKS.map(i => <g key={i} transform={`rotate(${i * 6} 100 100)`}><line className={`launch-tick${i % 5 ? '' : ' major'}`} x1="100" y1="8" x2="100" y2={i % 5 ? 13 : 17} style={{ '--i': i }}/></g>)}
      <g className="launch-hand" onAnimationEnd={() => { tap('light'); setStruck(true); }}><line x1="100" y1="5" x2="100" y2="30"/></g>
    </svg>}
    <picture><source media="(prefers-color-scheme: dark)" srcSet={`${base}wordmark-dark@3x.png`}/><img className="launch-mark" src={`${base}wordmark-light@3x.png`} alt="" width="132" height="56"/></picture>
  </div>;
}

// First launch: one sheet of two pages that swipe. The first says what wabi does; on the second you find the
// difference yourself. Skip stays at the top, and the page dots, the one pill and its line stay at the foot, while
// the pages move between them. Only the page in view is exposed to assistive technology, so there is one title at a
// time; Continue flips that at once and the scroll follows. Finishing slides the whole layer down off Check.
const WELCOME = [
  { icon: Link2, title: 'Paste any listing', body: 'eBay, Chrono24, forums, Marketplace.' },
  { icon: Search, title: 'Every photo, part by part', body: 'Dial, hands, bezel and bracelet, against sourced tells.' },
  { icon: ShieldCheck, title: 'Know what to ask', body: 'A score, why, and what to ask the seller.' },
];
function Onboarding({ leave, done, signInFirst }) {
  const [page, setPage] = useState(0); const [leaving, setLeaving] = useState(false);
  const box = useRef(); const track = useRef(); const aim = useRef({ to: null, timer: 0 }).current;
  // Focus the dialog itself, not a button, so the first frame shows no focus ring; Tab still reaches every control.
  useEffect(() => { box.current?.focus({ preventScroll: true }); }, [page]);
  // Continue names the page it is going to, and the scroll on the way there is not read as a swipe back.
  const turn = to => {
    aim.to = to; clearTimeout(aim.timer); aim.timer = setTimeout(() => { aim.to = null; }, 800);
    setPage(to); const el = track.current; el?.scrollTo({ left: to * el.clientWidth, behavior: reduceMotion() ? 'auto' : 'smooth' });
  };
  const onScroll = e => {
    const el = e.currentTarget; const at = Math.round(el.scrollLeft / Math.max(1, el.clientWidth));
    if (aim.to != null) { if (at === aim.to) aim.to = null; return; }
    if (at !== page) setPage(at);
  };
  const finish = toSample => { if (leaving) return; setLeaving(true); leave?.(toSample === true); setTimeout(() => done(toSample === true), cssMs('--t-sheet-out', 320) + 20); };
  const art = `${import.meta.env.BASE_URL}images/editorial/`;
  const off = n => (page === n ? {} : { inert: true, 'aria-hidden': 'true' });
  return <div ref={box} tabIndex={-1} className="onboarding" role="dialog" aria-modal="true" aria-label="Welcome to wabi" data-page={page} data-leaving={leaving ? '' : undefined} inert={leaving}>
    <div className="onb-frame">
      <div className="onb-track" ref={track} onScroll={onScroll}>
        <section className="onb-page welcome" {...off(0)}>
          <div className="welcome-photo" aria-hidden="true"><picture><source media="(prefers-color-scheme: dark)" srcSet={`${art}welcome-dial-night.webp`}/><img src={`${art}dial-macro.webp`} alt=""/></picture></div>
          <div className="onb-pad">
            <h1 className="welcome-title onb-rise" style={{ '--i': 0 }}>Welcome to wabi</h1>
            <ul className="welcome-list">{WELCOME.map(({ icon: Icon, title, body }, i) => <li key={title} className="onb-rise" style={{ '--i': i + 1 }}><Icon size={26} strokeWidth={1.5} aria-hidden="true"/><div><b>{title}</b><p>{body}</p></div></li>)}</ul>
          </div>
        </section>
        <section className="onb-page look" {...off(1)}>
          <div className="onb-pad onb-copy"><h1 className="onb-title">A fake can fool a photo. Not a close look.</h1><p>Drag across the dial. One side is a genuine print, the other a counterfeit.</p></div>
          <CompareCard active={page === 1 && !leaving}/>
        </section>
      </div>
      <div className="onb-top"><button type="button" className="text-button onb-skip" onClick={() => finish()}>Skip</button></div>
      <div className="onb-foot onb-rise" style={{ '--i': 4 }}>
        <div className="onb-dots" role="img" aria-label={`Page ${page + 1} of 2`}><i className={page === 0 ? 'on' : ''}/><i className={page === 1 ? 'on' : ''}/></div>
        <Button className="onb-pill" onClick={() => (page === 0 ? turn(1) : finish())}>
          <span data-on={page === 0 ? '' : undefined} aria-hidden={page === 0 ? undefined : 'true'}>Continue</span>
          <span data-on={page === 1 ? '' : undefined} aria-hidden={page === 1 ? undefined : 'true'}>Check a listing</span>
        </Button>
        <div className="onb-under"><p className="onb-line" key={page}>{page === 0 ? 'An estimate, never a certificate. Always inspect in person.' : signInFirst ? 'Add your email next and your first check is free.' : 'Your first check is free.'}</p>
          {page === 1 && <button type="button" className="text-button onb-sample" onClick={() => finish(true)}>See a sample report</button>}</div>
      </div>
    </div>
  </div>;
}

// The dial is drawn, not photographed, and its print is generic: no maker, no model. The counterfeit side differs only
// in what a close look finds: wider letter spacing, heavier print, shorter and thicker minute ticks. Both sides share
// one baseline (within two units) and one gold baton at twelve, so nothing else gives the game away. The drawing is
// taller than the card at its shortest and is cut from the bottom, so a taller card on a taller phone shows more of
// the same dial rather than a larger one.
function CompareDial({ fake, style }) {
  return <svg viewBox="0 0 350 360" preserveAspectRatio="xMidYMin slice" aria-hidden="true" style={style}>
    <rect className="cmp-ground" width="350" height="360"/>
    <circle className="cmp-dial" cx="175" cy="560" r="560"/>
    <circle className="cmp-ticks" cx="175" cy="560" r={fake ? 527 : 524} transform="rotate(-90 175 560)" strokeWidth={fake ? 10 : 16} strokeDasharray={fake ? '2.6 8.438' : '1.4 9.575'} strokeDashoffset={fake ? 1.3 : .7}/>
    <rect className="cmp-baton" x="168" y="50" width="14" height="38" rx="2"/><rect className="cmp-baton-light" x="168" y="50" width="4" height="38" rx="2"/>
    <text className="cmp-print" x={fake ? 176 : 175} y={fake ? 151 : 150} textAnchor="middle" fontSize="26" fontWeight={fake ? 760 : 560} letterSpacing={fake ? 4.05 : 2.6}>AUTOMATIC</text>
    <text className="cmp-sub" x={fake ? 176 : 175} y={fake ? 181 : 180} textAnchor="middle" fontSize="16" fontWeight={fake ? 680 : 500} letterSpacing={fake ? 1.92 : 1.28}>200m = 660ft</text>
  </svg>;
}
// What there is to find, and how far the line must have travelled to have shown it: the spacing shows across any
// stretch of the word, the weight wants most of it, and the ticks are clearest out past the print.
const FINDS = [
  { id: 'spacing', label: 'Letter spacing', found: s => s.hi - s.lo >= 20 },
  { id: 'weight', label: 'Print weight', found: s => s.hi - s.lo >= 36 },
  { id: 'ticks', label: 'Minute ticks', found: s => s.lo <= 24 || s.hi >= 76 },
];
const LINE_SWEEP = [46, 64, 36, 46];
const easeInOut = x => (x < .5 ? 2 * x * x : 1 - (2 - 2 * x) ** 2 / 2);
function CompareCard({ active }) {
  const START = LINE_SWEEP[0];
  const [pos, setPos] = useState(START); const [seen, setSeen] = useState({ lo: START, hi: START }); const [hint, setHint] = useState(false);
  const sweep = useRef({ timer: 0, raf: 0, running: false, off: false }).current; const felt = useRef({ pos: START, at: 0 }).current;
  const move = to => { setPos(to); setSeen(s => (to < s.lo || to > s.hi ? { lo: Math.min(s.lo, to), hi: Math.max(s.hi, to) } : s)); };
  // Half a second after the page arrives the line sweeps out and back once by itself, to show that it moves. The first
  // touch, key or focus on the slider calls it off for good (and puts the line back where it rests). Under Reduce
  // Motion nothing sweeps: the handle wears a "Drag" chip for two seconds instead.
  const halt = () => { clearTimeout(sweep.timer); cancelAnimationFrame(sweep.raf); if (sweep.running) { sweep.running = false; setPos(START); } };
  useEffect(() => {
    if (!active || sweep.off) return undefined;
    if (reduceMotion()) { sweep.off = true; setHint(true); const t = setTimeout(() => setHint(false), 2000); return () => clearTimeout(t); }
    sweep.timer = setTimeout(() => {
      const total = cssMs('--t-sweep', 1600); const t0 = performance.now(); sweep.running = true;
      const spans = LINE_SWEEP.slice(1).map((v, i) => Math.abs(v - LINE_SWEEP[i])); const whole = spans.reduce((a, b) => a + b, 0);
      const frame = now => {
        let p = Math.min(1, (now - t0) / total) * whole; let leg = 0;
        while (leg < spans.length - 1 && p > spans[leg]) { p -= spans[leg]; leg += 1; }
        move(LINE_SWEEP[leg] + (LINE_SWEEP[leg + 1] - LINE_SWEEP[leg]) * easeInOut(Math.min(1, p / spans[leg])));
        if (now - t0 < total) sweep.raf = requestAnimationFrame(frame); else { sweep.running = false; sweep.off = true; setPos(START); }
      };
      sweep.raf = requestAnimationFrame(frame);
    }, 500);
    return halt;
  }, [active]); // eslint-disable-line react-hooks/exhaustive-deps
  const mine = () => { sweep.off = true; halt(); setHint(false); };
  // A selection tick each time the line crosses a quarter, at most one every 80ms.
  const drag = to => {
    const now = performance.now();
    if ([25, 50, 75].some(q => (felt.pos < q) !== (to < q)) && now - felt.at > 80) { tap('select'); felt.at = now; }
    felt.pos = to; move(to);
  };
  // A finger or pointer drags the card itself, so the line sits exactly under it; the range input underneath is how
  // the keyboard and assistive technology move the same line.
  const held = useRef(false);
  const point = e => { const r = e.currentTarget.getBoundingClientRect(); drag(Math.round(Math.min(96, Math.max(4, (e.clientX - r.left) / r.width * 100)))); };
  return <>
    <div className="compare" onPointerDown={e => { if ((e.button ?? 0) !== 0) return; mine(); held.current = true; e.currentTarget.setPointerCapture?.(e.pointerId); point(e); }}
      onPointerMove={e => held.current && point(e)} onPointerUp={() => { held.current = false; }} onPointerCancel={() => { held.current = false; }}>
      <CompareDial/>
      <CompareDial fake style={{ clipPath: `inset(0 0 0 ${pos}%)` }}/>
      <span className="compare-label genuine" data-faint={pos < 15 ? '' : undefined} aria-hidden="true">Genuine</span><span className="compare-label fake" data-faint={pos > 85 ? '' : undefined} aria-hidden="true">Counterfeit</span>
      <input className="compare-range" type="range" min="4" max="96" value={Math.round(pos)} onChange={e => drag(Number(e.target.value))} onKeyDown={mine} onFocus={mine} aria-label="Drag to compare the genuine and counterfeit print"/>
      <span className="compare-line" style={{ left: `${pos}%` }} aria-hidden="true"/>
      <span className="compare-handle" style={{ left: `${pos}%` }} aria-hidden="true"><svg width="18" height="12" viewBox="0 0 18 12" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 1L1 6l4 5M13 1l4 5-4 5"/></svg>{hint && <span className="compare-hint">Drag</span>}</span>
    </div>
    <ul className="compare-finds" aria-label="What differs">{FINDS.map(f => <li key={f.id} data-found={f.found(seen) ? '' : undefined}>{f.label}</li>)}</ul>
  </>;
}
// The library size, counted when the app is built.
const LIBRARY = typeof __LIBRARY__ === 'undefined' ? { checks: 0, brands: 0 } : __LIBRARY__;
const focusScanField = () => setTimeout(() => document.getElementById('scan-url')?.focus(), 50);
// The Check tab: the pass you paste a link into, then the other way in (your own photos), what has changed on the
// listings you watch, your recent checks as a stack of passes, and two things to read. A sample report, when it is
// open, takes the tab over the way a real result does.
function AuthenticityPage({ onToast, incoming, onIncoming, records, navigate, openReport, onScanned, onUpgraded, hasFull, wallet, refreshWallet, remove, sample, setSample, addPhotos }) {
  const [claims] = useClaims();
  const markers = claims?.filter(c => c.status !== 'superseded' && c.status !== 'disputed') || [];
  const { user } = useContext(Account);
  // The sample lifts out of the ghost stack and drops back into it, as a real pass does from the real stack.
  const openSample = () => transition('lift', () => setSample(true), () => { window.scrollTo(0, 0); });
  const closeSample = () => { transition('drop', () => setSample(false), () => { window.scrollTo(0, 0); const cell = document.querySelector('.recent-ghost-cell'); if (!cell) return undefined; cell.dataset.landing = ''; return () => { delete cell.dataset.landing; }; }); focusScanField(); };
  if (sample) return <div className="home"><SampleReport close={closeSample}/></div>;
  const changed = records.filter(a => a.watch?.unseen && a.watch.history?.[0]);
  const below = <>
    <GroupedList className="home-more home-own"><GroupedRow lead={<IconTile><Camera size={18} strokeWidth={1.6}/></IconTile>} title="Add your own photos" sub="Check a watch in front of you" onClick={() => addPhotos()}/></GroupedList>
    {changed.length > 0 && <section className="home-changes" aria-label="Changes"><div className="ios-section"><h2>Changes</h2></div>
      <GroupedList>{changed.map(a => { const c = changeLine(a.watch.history[0]); return <GroupedRow key={a.id} className="change-row" lead={<PhotoTile src={coverOf(a)?.url} size={40} className="change-thumb"/>} title={a.model} sub={<span className={`change-line tone-${c.kind}`}>{c.mark}<span className="num">{c.text}</span></span>} onClick={() => openReport(a.id, 'push', 'authenticity')}/>; })}</GroupedList>
    </section>}
    <RecentPasses records={records} open={openReport} seeAll={() => navigate('listings')} remove={remove} sample={openSample}/>
    <div className="ios-section"><h2>Learn</h2></div>
    <GroupedList className="home-more">
      <GroupedRow lead={<IconTile><BookOpen size={18} strokeWidth={1.6}/></IconTile>} title="How to spot a fake" sub="Counterfeit tells by brand and model" onClick={() => navigate('markers')}/>
      <GroupedRow lead={<IconTile><InfoIcon/></IconTile>} title="How wabi works" sub="What the score can and can’t tell you" onClick={() => navigate('guide')}/>
    </GroupedList>
  </>;
  return <div className="home">
    <div className="home-title-row" data-nav-track=""><span className="ios-large" aria-hidden="true">Check</span><button type="button" className="avatar-button" aria-label="Profile" onClick={() => navigate('profile')}>{user?.email ? <span className="avatar-initial">{user.email[0].toUpperCase()}</span> : <TabIcon name="profile"/>}</button></div>
    {scanAvailable ? <ScanPanel onToast={onToast} incoming={incoming} onIncoming={onIncoming} tells={claims ? markers.filter(c => c.kind === 'tell').length : 0} markers={markers} onScanned={onScanned} onUpgraded={onUpgraded} hasFull={hasFull} openReport={openReport} wallet={wallet} refreshWallet={refreshWallet} returning={records.length > 0} addPhotos={addPhotos} below={below}/>
      : <><NavSlots title="Check"/><section className="pass check-pass"><div className="pass-top"><span className="pass-wordmark">wabi</span></div><h1 className="display home-title">Great price. Is it real?</h1><p className="home-body">Add the seller’s photos and wabi walks you through every part.</p><Button className="on-pass" onClick={() => addPhotos()}>Check a watch</Button></section>{below}</>}
  </div>;
}
// A watched listing's newest change, as a mark and a few words: "Price dropped · $6,900 to $6,400", "Listing ended".
function changeLine(c) {
  if (c.kind === 'price') { const m = /from (.+) to (.+?)\.?$/.exec(c.text || ''); return { kind: 'price', mark: c.down ? <DownMark/> : <UpMark/>, text: `Price ${c.down ? 'dropped' : 'went up'}${m ? ` · ${m[1]} to ${m[2]}` : ''}` }; }
  return { kind: 'change', mark: null, text: c.kind === 'ended' ? 'Listing ended' : WATCH_LABELS[c.kind] || 'Listing changed' };
}
// Recent checks, stacked like passes in Wallet: each shows its top strip (photo, name, reference, score) and the
// newest lies on top, whole. A press raises a pass and parts the ones above it; letting go lifts it open into its
// report from that pose. A long press offers the report, the listing itself, or removing it. With nothing checked
// yet, a ghost of the stack opens a sample report.
function RecentPasses({ records, open, seeAll, remove, sample }) {
  const [deleting, setDeleting] = useState(null);
  const recent = records.filter(r => r.scan || r.analysis).slice(0, 3);
  if (!recent.length) return <section className="recent" aria-label="Recent checks">
    <div className="ios-section"><h2>Recent</h2></div>
    <button type="button" className="recent-ghost" onClick={e => { e.currentTarget.firstElementChild.dataset.lifting = ''; sample(); }}>
      <span className="recent-ghost-cell"><img src={`${import.meta.env.BASE_URL}images/editorial/diver-top.webp`} alt="" width="64" height="64"/><span className="recent-ghost-text"><b>See what a check looks like</b><span>Open a sample report. Yours stack up here.</span></span><Chevron/></span>
    </button>
  </section>;
  return <section className="recent" aria-label="Recent checks">
    <div className="ios-section"><h2>Recent</h2>{records.length > 3 && <button type="button" className="see-all" onClick={seeAll}>See All</button>}</div>
    <ol className="pass-stack" style={{ '--n': recent.length }}>{recent.map((a, i) => <RecentPass key={a.id} a={a} top={i === 0} index={i} open={open} onRemove={() => { notify('warning'); setDeleting(a); }}/>)}</ol>
    {deleting && <DeleteListing record={deleting} onDelete={() => remove(deleting.id)} onClose={() => setDeleting(null)}/>}
  </section>;
}
function RecentPass({ a, top, index, open, onRemove }) {
  const v = listingVerdict(a); const cover = coverOf(a)?.url; const ask = parsePrice(a.price ?? ''); const source = a.scan ? siteName(a.scan.site || sourceOf(a.url)) : sourceOf(a.url);
  const strip = useRef(null);
  const lift = () => { const el = strip.current; if (!el) return; el.dataset.lifting = ''; open(a.id, 'lift', 'authenticity'); };
  const { bind, menu } = useContextMenu({ label: `${a.model}, actions`, items: [
    { label: 'Open report', icon: <FileText size={17} strokeWidth={1.6}/>, onSelect: lift },
    a.url && { label: `Open on ${siteName(sourceOf(a.url)) || 'the web'}`, icon: <ArrowUpRight size={17} strokeWidth={1.6}/>, onSelect: () => window.open(a.url, '_blank', 'noopener,noreferrer') },
    { label: 'Delete listing', icon: <Trash2 size={17} strokeWidth={1.6}/>, destructive: true, onSelect: onRemove },
  ].filter(Boolean) });
  return <li style={{ '--i': index }}><button ref={strip} type="button" className={`mini-pass${top ? ' top' : ''}`} data-pass-id={a.id} {...bind} onClick={() => { tap('soft'); lift(); }} aria-label={[a.model, v.score != null && `score ${v.score}`, v.label].filter(Boolean).join(', ')}>
    <span className="mini-pass-strip"><PhotoTile src={cover} size={40} className="mini-pass-thumb"/><span className="mini-pass-name"><b>{a.model}</b><span className="mini-pass-line" data-kind={v.kind || undefined}><VerdictMark kind={v.kind} size={8}/><span className="num">{[WORD[v.kind] || WORD.none, a.reference && `Ref. ${a.reference}`, source, ask ? money(ask) : null].filter(Boolean).join(' · ')}</span></span></span><span className="mini-pass-score" aria-hidden="true"><TickDial score={v.score} kind={v.kind} size={44}/></span></span>
    {top && <span className="mini-pass-body"><Verdict kind={v.kind}>{v.label}</Verdict><span className="mini-pass-when">{shortDate(a.scanned || a.created)}</span></span>}
  </button>{menu}</li>;
}
// Full scans the account can run now: an access code, the monthly plan's scans left this period, or pack credits.
const planLeft = w => (w?.subscription?.active ? w.subscription.scansLeft || 0 : 0);
const PLAN_HELD = ['active', 'trialing', 'past_due', 'unpaid', 'incomplete'];
const canRunFull = w => Boolean(w && (w.unlimited || w.credits > 0 || planLeft(w) > 0));
// What the pass says in its corner: the full scans the account holds, if any.
const passMeta = w => (!w ? '' : w.unlimited ? 'Unlimited scans' : planLeft(w) > 0 ? `${planLeft(w)} plan scans left` : w.credits > 0 ? count(w.credits, 'full scan') : '');
// The one line under Check listing: what the tap will do and what it will spend. With scans it runs the full report
// and names the scan it uses; without, it is today's free checks; signed out with accounts on, the first one is free.
function CostLine({ wallet: w, signInFirst }) {
  if (signInFirst) return <p className="home-note scan-quota"><b className="free-offer">Add your email to get your first check free.</b></p>;
  if (canRunFull(w)) return <p className="home-note scan-quota">Runs the full report. {w.unlimited ? 'Included with your access code.' : planLeft(w) > 0 ? <>Uses <b className="num">1 of your plan’s {planLeft(w)}</b> scans left this month.</> : <>Uses <b className="num">1 of your {w.credits}</b> full {w.credits === 1 ? 'scan' : 'scans'}.</>}</p>;
  if (!w?.freePerDay || w.freeLeft == null) return null;
  return <p className="home-note scan-quota">{w.freeLeft > 0 ? <><b className="num">{w.freeLeft} of {w.freePerDay}</b> free checks left today.</> : <>You’ve used today’s <b className="num">{w.freePerDay}</b> free checks. They reset tomorrow.</>}</p>;
}
// "2,600+ sourced tells and reference facts across 21 brands": every live claim in the library, tells and facts alike.
function libraryLine() {
  if (!LIBRARY.checks) return 'wabi’s library of sourced tells and reference facts';
  const n = LIBRARY.checks >= 1000 ? `${new Intl.NumberFormat('en-US').format(Math.floor(LIBRARY.checks / 100) * 100)}+` : LIBRARY.checks;
  return `${n} sourced tells and reference facts across ${LIBRARY.brands} brands`;
}
// The six checks the scan screen walks through, in order, under the names the report gives them. One check is 8 ticks
// (60° of the hand), so the sixth lands on 12.
const SCAN_CHECKS = CHECK_NAMES;
const TICK_MS = 125; const TICKS_PER_CHECK = 8; const SWEEP = 48; const HOLD = 4;
const clock = s => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
const BATONS = Array.from({ length: 12 }, (_, i) => i);
// The scanning screen: the pass being made. Cancel sits alone in the bar and the elapsed time rides on the pass. Inside
// the ring of sixty ticks is a dial: applied indices arrive two for each finished check, and a gold seconds hand
// beats 8 times a second but never runs ahead of the real work (cap is the last tick the current stage allows). When
// the listing's photo arrives it takes the dial's place under the hand.
// While the full report is written (seller research can take a minute or two) the pass draws itself up into a compact
// strip that stays at the top: the hand runs on like a seconds hand, the listing's photos take turns under it, the
// status says what the search is doing, and real tells for the brand rotate in below the checklist.
// Nothing here re-renders on the beat: one timer counts the ticks and writes them to the ring and the hand directly;
// React hears about it only when a check completes or one of the slow turns comes round.
const FULL_SCAN_STATUS = ['Searching the web for this seller', 'Reading their sales history', 'Looking for reviews and complaints', 'Checking how long they’ve been selling', 'Comparing the price with recent sales', 'Writing your report'];
// ahead: a full report will follow the free check, so the pass names it from the start.
function ScanScreen({ cap, elapsed, title, line, skipped = [], onCancel, onDone, full = false, ahead = false, photos = [], tells = [], note = '' }) {
  const reduce = useReducedMotion();
  const [step, setStep] = useState(0); const [struck, setStruck] = useState(false);
  const [turn, setTurn] = useState({ shot: 0, status: 0, tell: 0 });
  // Once the full report has begun the pass stays compact, through the last ticks and into the reveal.
  const [compact, setCompact] = useState(false);
  useEffect(() => { if (!full || compact) return undefined; const t = setTimeout(() => transition('compact', () => setCompact(true)), 0); return () => clearTimeout(t); }, [full]); // eslint-disable-line react-hooks/exhaustive-deps
  const ring = useRef(null); const hand = useRef(null);
  const live = useRef({}); live.current = { cap, full, reduce, onDone };
  useEffect(() => {
    const lines = ring.current.querySelectorAll('.tick-ring-ticks line');
    let tick = 0; let beat = 0; let run = 0; let lit = 0; let frame = 0; let ended = false; let last = performance.now(); let owed = 0;
    // What the eye follows is written straight to the ring and the hand, once a frame at most.
    const paint = () => {
      frame = 0; const now = live.current; const s = Math.min(SCAN_CHECKS.length, Math.floor(tick / TICKS_PER_CHECK)); const sweep = Math.min(tick, SWEEP) / SWEEP;
      const want = Math.round((now.reduce ? s / SCAN_CHECKS.length : sweep) * 60);
      for (; lit < want; lit += 1) lines[lit]?.classList.add('on');
      // Past the last check the hand keeps a seconds hand's pace (6° a second) and never winds back.
      hand.current?.style.setProperty('--hand', `${now.reduce ? s * 60 : sweep * 360 + run * .75}deg`);
    };
    const timer = setInterval(() => {
      const t = performance.now(); owed += Math.min(t - last, 2000); last = t;
      for (; owed >= TICK_MS; owed -= TICK_MS) {
        if (tick < live.current.cap) tick += 1;
        if (live.current.full) { beat += 1; if (tick >= (SCAN_CHECKS.length - 1) * TICKS_PER_CHECK) run += 1; }
      }
      setStep(Math.min(SCAN_CHECKS.length, Math.floor(tick / TICKS_PER_CHECK)));
      if (live.current.full) { const next = { shot: Math.floor(beat / 20), status: Math.floor(beat / 28), tell: Math.floor(beat / 56) }; setTurn(was => (was.shot === next.shot && was.status === next.status && was.tell === next.tell ? was : next)); }
      if (tick >= SWEEP) setStruck(true);
      if (!frame) frame = requestAnimationFrame(paint);
      // All sixty lit, a held breath, then the pass opens into the result.
      if (tick >= SWEEP + HOLD && !ended) { ended = true; paint(); live.current.onDone?.(); }
    }, TICK_MS);
    return () => { clearInterval(timer); cancelAnimationFrame(frame); };
  }, []);
  // Each check that completes is felt as a light tick.
  useEffect(() => { if (step > 0) tap(); }, [step]);
  const shots = photos.slice(0, 12); const shot = shots.length ? (full || compact ? turn.shot % shots.length : 0) : -1;
  const status = FULL_SCAN_STATUS[turn.status % FULL_SCAN_STATUS.length];
  const tell = tells.length ? tells[turn.tell % tells.length] : null;
  // The watch photo sits inside the ring once the listing is read; during the full report the photos take turns, each
  // fading in over the one before it.
  const inRing = shot >= 0 ? shots[shot] : null; const before = shot >= 0 && shots.length > 1 && compact ? shots[(shot + shots.length - 1) % shots.length] : null;
  // The strip shows three thumbnails at least, so its window follows the current one.
  const slide = Math.max(0, Math.min(shot - 1, shots.length - 3));
  // What kind of check this is and how long it has run: on the pass's top row, and on the strip row once the pass has
  // drawn up and given its wordmark row away.
  const meta = <span className="pass-meta">{full || compact || ahead ? 'Full report' : 'Free check'} · <span className="scan-elapsed num" aria-label="Elapsed time">{clock(elapsed)}</span></span>;
  // Portalled to the body so it covers the tab bar and banners.
  return createPortal(<div className="scan-screen" role="dialog" aria-modal="true" aria-label="Checking the listing" aria-busy="true" data-full={compact ? '' : undefined}>
    <div className="scan-top"><button type="button" className="scan-cancel" onClick={onCancel}>{full || compact ? 'Hide' : 'Cancel'}</button></div>
    <div className={`pass scan-pass${compact ? ' compact' : ''}`}>
      {!compact && <div className="pass-top"><span className="pass-wordmark">wabi</span>{meta}</div>}
      <div className="scan-stage">
        <div ref={ring} className={`tick-ring${struck ? ' struck' : ''}`}>
          <svg className="tick-ring-ticks" viewBox="0 0 248 248" aria-hidden="true">{TICKS.map(i => <g key={i} transform={`rotate(${i * 6} 124 124)`}><line x1="124" y1="4" x2="124" y2={i % 5 ? 15 : 19}/></g>)}</svg>
          <div className="scan-dial">
            <svg className="scan-face" viewBox="0 0 196 196" aria-hidden="true">{BATONS.map(i => <g key={i} transform={`rotate(${i * 30} 98 98)`}><rect className={i < step * 2 ? 'on' : ''} x="97" y="10" width="2" height="10" rx="1" style={{ '--d': i % 2 }}/></g>)}</svg>
            {inRing ? <span className="scan-loupe">{before && <i className="scan-before" style={{ backgroundImage: `url("${before}")` }}/>}<img src={inRing} alt="" key={inRing} referrerPolicy="no-referrer"/></span> : <span className="sr-only" role="img" aria-label="Reading the listing"/>}
            <svg className="scan-hand" viewBox="0 0 196 196" aria-hidden="true"><g ref={hand}><line x1="98" y1="116" x2="98" y2="20"/></g><circle cx="98" cy="98" r="2.5"/></svg>
          </div>
        </div>
        <div className="scan-head">
          {compact && <p className="scan-status" role="status"><span key={status}>{status}</span></p>}
          <h1><span key={title}>{title}</span></h1>
          {!compact && <p className="scan-sub num">{line}</p>}
          {note && <p className="scan-note">{note}</p>}
        </div>
      </div>
      {compact && <div className="scan-photos">
        {shots.length > 1 && <><div className="scan-strip" aria-hidden="true"><div className="scan-strip-track" style={{ '--slide': slide }}>{shots.map((src, i) => <img key={src + i} src={src} alt="" className={i === shot ? 'on' : ''} referrerPolicy="no-referrer"/>)}</div></div>
          <p className="scan-count num" aria-hidden="true">Photo {shot + 1} of {shots.length}</p></>}
        {meta}
      </div>}
    </div>
    <ol className="scan-checks" aria-label="Checks">{SCAN_CHECKS.map((label, i) => {
      // The free check doesn't price the watch or look up the seller, so those rows say so the moment they are reached:
      // they are never shown as being checked.
      const state = skipped.includes(i) && i <= step ? 'skipped' : i < step ? 'done' : i === step ? 'current' : 'waiting';
      return <li key={label} className={state} style={{ '--i': i }}><span className="scan-mark">{state === 'done' ? <CheckIcon/> : state === 'current' ? <TickSpinner size={16} progress={reduce ? 1 / 3 : undefined}/> : state === 'skipped' ? <LockKeyhole size={12} strokeWidth={1.6} aria-hidden="true"/> : null}</span><span className="scan-check-label">{label}</span><span className="scan-check-status" key={state}>{state === 'done' ? 'Done' : state === 'current' ? 'Checking' : state === 'skipped' ? 'In the full report' : ''}</span></li>;
    })}</ol>
    {compact && tell && <div className="scan-tell" key={tell.id || tell.claim}><p className="scan-tell-brand">A {tell.brand} detail, while you wait</p><p className="scan-tell-claim">{tell.claim}</p>{tell.counterfeitSign && <p className="scan-tell-fake">Fakes often: {tell.counterfeitSign}</p>}</div>}
    <p className="scan-foot">{compact ? 'The full report usually takes a minute or two. Keep wabi open.' : 'An estimate from what the listing shows. Never a certificate.'}</p>
  </div>, document.body);
}
function useReducedMotion() {
  const [reduce, setReduce] = useState(() => { try { return window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch { return false; } });
  useEffect(() => { let q; try { q = window.matchMedia('(prefers-reduced-motion: reduce)'); } catch { return; } const on = () => setReduce(q.matches); q.addEventListener?.('change', on); return () => q.removeEventListener?.('change', on); }, []);
  return reduce;
}
// The one-box scan: paste a link and press Check listing. wabi reads the listing and shows its photos, then the free
// check gives a score from the fastest model. The full report (details, seller background, photo by photo, markers)
// is paid: it shows locked until the buyer spends a scan. Both results are saved to Listings.
function ScanPanel({ onToast, incoming, onIncoming, tells, markers = [], onScanned, onUpgraded, hasFull = () => false, openReport, wallet, refreshWallet, returning = false, addPhotos, below = null }) {
  const [url, setUrl] = useState(''); const [stage, setStage] = useState('idle'); const [error, setError] = useState('');
  const [listing, setListing] = useState(null); const [mini, setMini] = useState(null); const [result, setResult] = useState(null); const [savedId, setSavedId] = useState(null);
  // The saved listing for the scan on screen. Read through a ref: a scan's callbacks are made when it starts, and the
  // listing of an earlier scan must never receive this one's report.
  const savedRef = useRef(null); const remember = id => { savedRef.current = id; setSavedId(id); };
  const [elapsed, setElapsed] = useState(0); const [unlockError, setUnlockError] = useState('');
  const { user, askSignIn } = useContext(Account); const signInFirst = authEnabled && wallet?.authEnabled && !user && !wallet?.accessCodeValid;
  const busy = ['reading', 'reviewing', 'unlocking'].includes(stage);
  // With scans on the account (or an access code), Check listing goes straight on to the full report.
  const walletRef = useRef(wallet); walletRef.current = wallet;
  const [autoNote, setAutoNote] = useState('');
  // With a full scan on the account the check goes straight on to the full report, so the pass says so from the tap.
  const [goingFull, setGoingFull] = useState(false);
  // The scanning screen stays up from Check listing until the hand has finished its turn and held at 12. It counts
  // its own ticks; cap is how far the stage the work has reached lets them go.
  const run = useRef(0); const [screen, setScreen] = useState(false);
  // The time on the pass counts from the tap for as long as the screen is up (and on, behind it, while a hidden full
  // report is still being written), so it never stops while the hand is still moving.
  const started = useRef(0); const timing = screen || busy;
  const begin = () => { started.current = Date.now(); setElapsed(0); };
  useEffect(() => { if (!timing) return undefined; const t = setInterval(() => setElapsed(Math.round((Date.now() - started.current) / 1000)), 1000); return () => clearInterval(t); }, [timing]);
  const cap = stage === 'reading' ? TICKS_PER_CHECK - 1 : stage === 'reviewing' ? 4 * TICKS_PER_CHECK - 1 : stage === 'unlocking' ? 6 * TICKS_PER_CHECK - 1 : SWEEP + HOLD;
  // Saving waits for the screen to finish its turn, and its confirmation waits for the result to finish arriving (the
  // photo, the count, the verdict), so the banner never drops across the reveal.
  const pending = useRef(null);
  useEffect(() => { if (!screen && pending.current) { const save = pending.current; pending.current = null; save({ after: revealMs() }); } }, [screen]);
  // With the screen already put away (Hide), there is nothing to wait for: the save runs at once, even if the person
  // has since left this tab.
  const screenRef = useRef(false);
  const afterScreen = save => { if (screenRef.current) pending.current = save; else save(); };
  // The Check pass (or the result's pass) becomes the scan pass, and the scan pass opens into the result: one object
  // all the way through. From a tap the change is a transition; from anywhere else it simply happens.
  function startScreen(moving) { screenRef.current = true; if (moving) transition('form', () => setScreen(true)); else setScreen(true); }
  function endScreen(kind, also) { screenRef.current = false; transition(kind, () => { setScreen(false); also?.(); }, () => { if (kind === 'reveal') window.scrollTo(0, 0); }); }
  // The free check can be cancelled. A full report that is already being paid for is never thrown away: Hide puts the
  // screen away onto the free result and lets the report finish and save; a banner says when it is ready.
  // Once the full scan has started, or its report has arrived and the hand is finishing its turn, Hide only puts the
  // screen away: the save that is waiting runs when it goes.
  const hidden = useRef(false);
  function cancel() {
    if (stage === 'unlocking') { hidden.current = true; endScreen('unform'); return; }
    if (stage === 'done') { endScreen('unform'); return; }
    run.current += 1; pending.current = null; endScreen('unform', () => setStage(mini ? 'mini' : 'idle'));
  }
  // What the field does when something lands in it, and when it is asked for something it does not have: a paste
  // brightens its edge and nudges the button; an empty or unreadable link shakes it.
  const [pasted, setPasted] = useState(0); const [shake, setShake] = useState(0);
  const landed = () => { tap(); setPasted(n => n + 1); };
  async function paste() { try { const text = (await navigator.clipboard.readText()).trim(); if (text) { setUrl(text); setError(''); landed(); } } catch { /* the field still accepts a normal paste */ } }
  // A link handed over by the browser extension is scanned straight away, once: coming back to this tab never checks it again.
  useEffect(() => { if (incoming?.url) { onIncoming?.(); setUrl(incoming.url); scan(null, incoming.url); } }, [incoming]); // eslint-disable-line react-hooks/exhaustive-deps
  // The free scan needs an account: signed out, Scan asks for an email first and then carries on with the same link.
  async function scan(e, given, signedIn = false) {
    e?.preventDefault();
    const typed = (given ?? url).trim(); const link = /^https?:\/\//i.test(typed) ? typed : `https://${typed}`;
    // Nothing to check yet: the field takes focus and says so by moving, not with an error.
    if (!typed) { setError(''); setShake(n => n + 1); tap(); document.getElementById('scan-url')?.focus(); return; }
    if (!/^https?:\/\/[^\s/]+\.[^\s/]+\S*$/i.test(link)) { setError({ text: 'Paste the full listing link, for example https://www.ebay.com/itm/…' }); setShake(n => n + 1); notify('error'); return; }
    if (signInFirst && !signedIn) { setError(''); askSignIn('scan', () => scan(null, link, true)); return; }
    tap('medium'); setError(''); setUnlockError(''); setListing(null); setMini(null); setResult(null); remember(null); begin(); setStage('reading'); setGoingFull(canRunFull(walletRef.current)); startScreen(Boolean(e));
    const id = ++run.current; let reading = true;
    try {
      const found = await fetchScanListing(link);
      if (id !== run.current) return;
      reading = false; setListing(found); setStage('reviewing');
      const review = await quickReview(found.url || link);
      if (id !== run.current) return;
      setMini(review); track('Lead');
      const w = walletRef.current;
      if (review.score.assessable !== false && canRunFull(w)) {
        setAutoNote(w.unlimited ? 'Full report included with your access code' : planLeft(w) > 0 ? `Using 1 of your plan’s ${planLeft(w)} full scans left this month` : `Using 1 of your ${count(w.credits, 'full scan')}`);
        await runFull(review.listing.url || found.url || link, id, review);
        return;
      }
      setStage('mini'); refreshWallet();
      afterScreen(async told => remember(await onScanned(recordFromMini(review), told)));
    } catch (e) {
      if (id !== run.current) return;
      // The server can still ask for sign-in (an expired session, or the wallet not loaded yet).
      if (e.signIn) { endScreen('unform', () => setStage('idle')); askSignIn('scan', () => scan(null, link, true)); return; }
      // A listing wabi could not open can still be checked from its photos, so the way there is offered with the reason.
      endScreen('unform', () => { setError({ text: e.message, photos: reading && e.status !== 429 }); setStage('error'); setShake(n => n + 1); }); notify('error');
    }
  }
  async function unlock() {
    setUnlockError(''); setAutoNote(''); begin(); startScreen(true);
    await runFull(mini.listing.url, ++run.current, mini);
  }
  // The paid scan, from Unlock or straight after the free score. A failure returns the credit (server side) and
  // leaves the free result on screen, saved as before. A report that was paid for is always saved: if the screen has
  // since moved on (Done, or another link), it is saved where it belongs and a banner offers it, and the screen is left alone.
  async function runFull(link, id, review) {
    setStage('unlocking'); hidden.current = false; const at0 = savedRef.current;
    try {
      const full = await scanListing(link);
      if (id !== run.current) {
        const record = await recordFromScan(full);
        const saved = at0 ? (await onUpgraded(at0, record)) || at0 : await onScanned(record);
        if (saved) onToast('Full report ready', { action: { label: 'Open', onClick: () => openReport(saved) } });
        refreshWallet(); return;
      }
      setResult(full); setStage('done');
      const record = await recordFromScan(full);
      afterScreen(async told => {
        const at = savedRef.current; if (at) await onUpgraded(at, record, told); else remember(await onScanned(record, told));
        if (hidden.current && savedRef.current) { const saved = savedRef.current; onToast('Full report ready', { action: { label: 'Open', onClick: () => openReport(saved) } }); }
      });
    } catch (e) {
      if (id !== run.current) { refreshWallet(); return; }
      endScreen('reveal', () => { setUnlockError(e.message); setStage('mini'); }); notify('error');
      if (!savedRef.current) remember(await onScanned(recordFromMini(review)));
    }
    refreshWallet();
  }
  const images = result?.listing.images || mini?.listing.images || listing?.images || [];
  const shown = result?.listing || mini?.listing || listing;
  return <section className="scan-panel" aria-live="polite">
    {screen && <ScanScreen cap={cap} elapsed={elapsed} title={listing?.title || mini?.listing.title || 'Reading the listing'} line={scanLine(listing || mini?.listing)} skipped={stage === 'mini' || (stage === 'reviewing') ? [4, 5] : []} onCancel={cancel} onDone={() => endScreen('reveal')}
      full={stage === 'unlocking'} ahead={goingFull} note={stage === 'unlocking' ? autoNote : ''} photos={mini?.listing.scannedImages || mini?.listing.images || listing?.images || []}
      tells={markers.filter(c => c.kind === 'tell' && c.brand && c.brand === mini?.identification?.brand)}/>}
    {!mini && !result && <><NavSlots title="Check"/><form className="pass check-pass home-form" data-compact={returning ? '' : undefined} data-pasted={pasted ? pasted % 2 : undefined} onSubmit={scan} noValidate>
      <div className="pass-top"><span className="pass-wordmark">wabi</span>{passMeta(wallet) && <span className="pass-meta">{passMeta(wallet)}</span>}</div>
      <h1 className="display home-title">Great price. Is it real?</h1>
      {!returning && <p className="home-body">Paste a listing from any marketplace. wabi checks it against {libraryLine()}.</p>}
      <Field id="scan-url" className={`pass-field${shake ? ` shake-${shake % 2}` : ''}`} label="Listing link" labelHidden type="url" inputMode="url" autoCapitalize="off" autoCorrect="off" spellCheck="false" placeholder="Paste a listing link" value={url} onChange={e => { setUrl(e.target.value); if (error) setError(''); }} onPaste={landed} disabled={busy} aria-invalid={error ? 'true' : undefined} aria-describedby={error ? 'scan-error' : undefined}
        action={url ? <button type="button" className="field-clear" onClick={() => { setUrl(''); setError(''); document.getElementById('scan-url')?.focus(); }} aria-label="Clear link" disabled={busy}><X size={17} strokeWidth={1.6} aria-hidden="true"/></button>
          : navigator.clipboard?.readText && <button type="button" className="field-paste" onClick={paste} aria-label="Paste link" disabled={busy}>Paste</button>}/>
      {error && <div className="field-error" id="scan-error" role="alert"><VerdictMark kind="fail" size={10}/><span>{error.text}</span>{error.photos && <button type="button" className="field-error-action" onClick={() => addPhotos(url.trim())}>Add photos</button>}</div>}
      <Button type="submit" className="on-pass" haptic={null} disabled={busy}>{busy ? <TickSpinner size={20} label="Reading listing"/> : 'Check listing'}</Button>
      <CostLine wallet={wallet} signInFirst={signInFirst}/>
    </form>
    <p className="scan-legal trust-line"><ShieldIcon size={14}/><span>Links go to wabi’s review service. <a href={PRIVACY_URL} target="_blank" rel="noopener noreferrer">Privacy</a> · <a href={TERMS_URL} target="_blank" rel="noopener noreferrer">Terms</a>.</span></p>
    {below}</>}
    {!screen && (mini || result) && (() => {
      // A full report still being written when this is closed is kept (runFull saves it) but no longer takes the screen.
      const reset = () => { run.current += 1; onToast(''); setUrl(''); setListing(null); setMini(null); setResult(null); remember(null); setStage('idle'); window.scrollTo(0, 0); };
      const another = () => { reset(); focusScanField(); };
      const owned = !result && savedId && hasFull(savedId);
      const model = buildReport(result ? scanFields(result) : recordFromMini(mini));
      const shots = result?.listing.scannedImages || mini?.listing.scannedImages || images;
      const assessable = Boolean(result) || mini.score.assessable !== false;
      const share = async () => { try { const how = await shareText([`${model.watch}${model.score != null ? ` · wabi score ${model.score} of 100` : ''} · ${model.verdict}`, shown?.url].filter(Boolean).join('\n')); if (how === 'copied') onToast('Copied'); } catch { onToast('Couldn’t share that. Try again.'); } };
      // The result is a presented screen: Done and its menu live in the navigation bar, so they are there at any scroll.
      const head = <ReportBar title={model.watch} onClose={reset} items={[{ label: 'Share report', icon: <Share2 size={17} strokeWidth={1.6}/>, onSelect: share }, { label: 'Open in Listings', icon: <ListChecks size={17} strokeWidth={1.6}/>, disabled: !savedId, onSelect: () => openReport(savedId) }]}/>;
      const ask = result && result.analysis.listing.currency && result.analysis.listing.currency !== 'USD' ? null : result?.analysis.listing.asking_price;
      return <ReportView onToast={onToast} model={model} images={shots} url={shown?.url} head={head} fresh onAnother={another} onOpenSaved={savedId ? () => openReport(savedId) : undefined} locked={!result} analysis={result?.analysis}
        free={result ? null : { assessable, photos: (mini.listing.scannedImages || mini.listing.images || []).length, flags: mini.redFlagCount || 0 }}
        price={result && <PricePanel value={result.analysis.value} ask={ask}/>} written={result && <ScanResult result={result} images={images}/>}
        onAskPhotos={savedId && photoRequestAvailable ? () => openReport(savedId) : undefined}>
        {!result && <LibraryNote brand={mini.identification.brand}/>}
        {result || !assessable ? undefined
          : owned ? <section className="bar-host"><p className="report-owned" role="status">You already unlocked the full report for this listing. No new scan is needed.</p><div className="report-cta"><Button onClick={() => openReport(savedId)}>Open the full report</Button></div></section>
          : <LockedReport wallet={wallet} refreshWallet={refreshWallet} onUnlock={unlock} unlocking={stage === 'unlocking'} elapsed={elapsed} error={unlockError}/>}
      </ReportView>;
    })()}
  </section>;
}
// A presented report's bar: Done on the leading side and, when there is anything in it, a More menu on the trailing.
function ReportBar({ title, onClose, items = [] }) {
  const { menu, show } = useContextMenu({ items, label: 'Report actions' });
  return <><NavSlots title={title} leading={<NavAction className="report-close" label="Close report" onClick={onClose}>Done</NavAction>}
    trailing={items.length > 0 && <NavAction label="More" onClick={e => show(e.currentTarget)}><MoreHorizontal strokeWidth={1.6}/></NavAction>}/>{menu}</>;
}
// A report with nothing behind it: the bundled sample, drawn by the real view. It says it is an example above the
// pass, saves nothing, sells nothing, and has one way on: back to the field to check a real listing.
function SampleReport({ close }) {
  return <ReportView sample model={SAMPLE.model} images={SAMPLE.images} analysis={SAMPLE.analysis} onAnother={close} head={<ReportBar title={SAMPLE.model.watch} onClose={close}/>}/>;
}
// The listing's own photo across the top of the result pass, as a Wallet pass's strip image. A tap opens the photos
// full screen. If it fails to load the pass simply starts at its band.
function PassPhoto({ src, count: n = 1, onOpen }) {
  const [state, onLoad, onError, ref] = useImageState(src);
  if (state === 'error') return null;
  return <button type="button" className="report-pass-photo" data-state={state} onClick={onOpen} aria-label={n > 1 ? `Open the listing’s ${n} photos` : 'Open the listing’s photo'}><img ref={ref} src={src} alt="The listing’s photo" referrerPolicy="no-referrer" onLoad={onLoad} onError={onError}/></button>;
}
// How far the check went, in one line of text under the checks, all counted from the scan.
function Coverage({ c }) {
  const parts = [`${c.done} of ${c.total} checks complete`, c.photos && `${count(c.photos, 'photo')} reviewed`, c.references && count(c.references, 'reference'), c.claims && count(c.claims, 'claim')].filter(Boolean);
  return <p className="coverage">{parts.join(' · ')}</p>;
}
// How long a new result takes to arrive: the pass opens, the number counts, the verdict lands.
const REVEAL_WAIT = 250;
// With Reduce Motion nothing counts, but the banner still waits a beat so the verdict is read first.
const revealMs = () => (reduceMotion() ? 1000 : REVEAL_WAIT + cssMs('--t-count', 1100) + cssMs('--t-verdict', 320));
const DISCLAIMER = 'A score is wabi’s read of the listing, not a guarantee. Confirm in person or with an authorized dealer before you pay.';
// The report, for a result that has just been made and for a saved listing alike. The pass carries the photo, the
// watch, the verdict and the score. Under it, in the order a buyer needs them: what needs a closer look, what passed,
// the price, the watch part by part, the listing's claims, its details, the full written report, where to go next,
// and the limit of all of it, once. A free check shows what it found and what the full report would open. One pill
// sits in the bottom bar, chosen by the verdict. Tapping a check, a part or a claim opens its sheet.
function ReportView({ model, images = [], head, url, onAnother, anotherLabel = 'Check another listing', onOpenSaved, locked, saved, fresh = false, sample = false, free = null, analysis, written, price, onAskPhotos, children, onToast }) {
  const [sheet, setSheet] = useState(null); const [viewer, setViewer] = useState(null);
  // Confirmations go to the app's one banner; without one (a caller that passes none) they are announced in place.
  const [ownToast, setOwnToast] = useState(''); const toast = onToast || setOwnToast;
  const askable = model.rows.map((r, i) => ({ ...r, i })).filter(r => r.ask);
  const [asked, setAsked] = useState(() => model.rows.map(r => Boolean(r.ask)));
  // A report unlocked in place brings its questions with it.
  const wasLocked = useRef(locked); const [opened, setOpened] = useState(false);
  useEffect(() => { if (wasLocked.current && !locked) { setAsked(model.rows.map(r => Boolean(r.ask))); setOpened(true); } wasLocked.current = locked; }, [locked]); // eslint-disable-line react-hooks/exhaustive-deps
  const toggle = i => setAsked(a => a.map((v, j) => (j === i ? !v : v)));
  // A new result arrives in order: the pass opens, the number counts, the verdict lands, then the rest. A saved
  // listing that is reopened simply shows.
  const reveal = fresh && !saved && !sample; const wait = reveal ? REVEAL_WAIT : 0;
  // The verdict lands with a haptic, once, as the numeral finishes counting (not when a saved listing is reopened).
  const felt = useRef(false);
  useEffect(() => {
    if (locked || saved || sample || felt.current || !model.kind) return undefined;
    felt.current = true; const t = setTimeout(() => notify(model.kind === 'pass' ? 'success' : 'warning'), reduceMotion() ? 0 : wait + cssMs('--t-count', 1100));
    return () => clearTimeout(t);
  }, [locked, saved, model.kind]); // eslint-disable-line react-hooks/exhaustive-deps
  const message = () => questionMessage(askable.filter(r => asked[r.i]).map(r => r.ask));
  async function copy() {
    const n = askable.filter(r => asked[r.i]).length;
    try { await navigator.clipboard.writeText(message()); } catch { /* the banner still confirms; the sheet text can be selected */ }
    setSheet(null); toast(n === 1 ? 'Question copied' : 'Questions copied');
  }
  async function share() { try { await navigator.share({ text: message() }); setSheet(null); } catch { /* put away without sending: the sheet stays */ } }
  const site = model.source && siteName(model.source);
  const id = analysis?.identification;
  // The listing as a short spec list: what the scan read, the asking price and where it is listed. The reference is on
  // the pass, so it is only repeated here when the pass has no room for it.
  const spec = [
    !locked && id?.production_era && { label: 'Era', value: id.production_era },
    !locked && id?.dial_variant && { label: 'Dial', value: id.dial_variant },
    !locked && (() => { const d = analysis?.details?.find(x => /box|papers|scope/i.test(x.label) && x.listed); return d && { label: 'Box and papers', value: d.listed }; })(),
    model.price && { label: 'Asking price', value: <span className="num">{money(model.price)}</span> },
    site && { label: 'Listed on', value: url ? <a className="report-link" href={url} target="_blank" rel="noopener noreferrer">{site}<ArrowOut/></a> : site },
  ].filter(Boolean);
  const { look, passed } = splitChecks(model.rows);
  const ask = askable.length > 0 && !sample ? { label: 'Ask the seller', run: () => setSheet({ type: 'questions' }) } : null;
  // The one pill: a sample goes back to the field; a flagged listing sends you on to the next one; otherwise the
  // questions, when there are any. A locked report's pill is the paywall's (it comes with the children).
  const bar = sample ? { label: 'Check a listing', run: onAnother } : locked ? null : model.kind === 'fail' && onAnother ? { label: anotherLabel, run: onAnother } : ask;
  const next = sample ? [] : [bar !== ask && !locked && ask, onOpenSaved && { label: 'Open in Listings', run: onOpenSaved }, onAnother && bar?.run !== onAnother && { label: anotherLabel, run: onAnother }].filter(Boolean);
  let n = 0; const step = () => ({ '--i': n++ });
  let m = 0;
  const checkRow = r => <li key={r.name}><button type="button" className="check-row tappable" onClick={() => { tap('select'); setSheet({ type: 'detail', i: r.i }); }} aria-label={`${r.name}: ${rowWord(r)}. Open the finding`}>
    <span className={`check-mark ${r.kind ? `tone-${r.kind}` : 'muted'}`}><VerdictMark kind={r.kind} size={12}/></span>
    <span className="check-text"><span className="check-name">{r.name}</span><span className="check-finding" style={{ '--n': m++ }}><b>{rowWord(r)}</b> · {r.finding}</span></span>
    <span className="check-chevron"><Chevron/></span></button></li>;
  return <div className="report" data-reveal={reveal ? '' : undefined} data-opened={opened ? '' : undefined} data-sample={sample ? '' : undefined} style={{ '--wait': `${wait}ms` }}>
    {head}
    {sample && <p className="sample-banner" role="note">An example. Nothing here was checked.</p>}
    <section className="pass report-pass report-id" aria-label="Result">
      {images[0] && <PassPhoto src={images[0]} count={images.length} onOpen={() => setViewer(0)}/>}
      <div className="report-pass-band">
        <div className="pass-top"><span className="pass-wordmark">wabi</span><span className="pass-meta">{sample ? 'Sample' : locked ? 'Free check' : 'Full report'}</span></div>
        <p className="report-ref" data-nav-track=""><span className="report-watch">{model.watch}</span>{model.reference && <span className="report-refno num">Ref. {model.reference}</span>}</p>
        <span className="pass-rule" aria-hidden="true"/>
        <div className="report-pass-main">
          <div className="report-verdict">
            <div className="report-verdict-line" data-kind={model.kind || undefined}>{model.kind && <VerdictMark kind={model.kind} size={12}/>}<h1>{model.verdict}</h1></div>
            {model.summary && <p className="report-summary-line">{model.summary}</p>}
          </div>
          {model.score == null ? <span className="report-dial"><PassDial score={null} kind={null} size={120}/></span>
            : <button type="button" className="report-dial" onClick={() => setSheet({ type: 'score' })} aria-label={`Score ${model.score} out of 100. How the score works`}><PassDial score={model.score} kind={model.kind} size={120} delay={wait} haptic={reveal}/></button>}
        </div>
      </div>
    </section>
    <div className="report-body">
      {locked && free && <section className="report-found" style={step()} aria-label="What the free check found">
        <div className="ios-section"><h2>What the free check found</h2></div>
        <dl className="found-list">
          {free.assessable && <div className="found-row"><dt>Identified as</dt><dd>{model.watch}{model.reference && <span className="num"> · Ref. {model.reference}</span>}</dd></div>}
          <div className="found-row"><dt>Photos read</dt><dd className="num">{free.photos}</dd></div>
          {free.assessable && <div className="found-row"><dt>Flags in the photos</dt><dd><span className={`found-flags ${free.flags ? 'tone-inspect' : 'tone-pass'}`}><VerdictMark kind={free.flags ? 'inspect' : 'pass'}/>{free.flags ? `${count(free.flags, 'thing')} to look at` : 'No flags in the photos'}</span>{free.flags > 0 && <small>Details are in the full report</small>}</dd></div>}
          <div className="found-row"><dt>Seller</dt><dd>Not checked in the free check</dd></div>
        </dl>
      </section>}
      {locked && (!free || free.assessable) && <section className="report-checks" style={step()}>
        <div className="ios-section"><h2>In the full report</h2></div>
        <ul className="check-list">{model.rows.map(r => <li key={r.name}><div className="check-row locked"><span className="check-name">{r.name}</span><span className="sr-only">, in the full report</span><span className="check-bar" aria-hidden="true"/><LockKeyhole className="check-lock" size={13} strokeWidth={1.6} aria-hidden="true"/></div></li>)}</ul>
        <p className="ios-footnote">Each check opens with the photo it came from in the full report.</p>
      </section>}
      {!locked && <section className="report-checks" style={step()}>
        <div className="ios-section"><h2>Needs a closer look</h2></div>
        {look.length ? <ul className="check-list">{look.map(checkRow)}</ul> : <p className="check-none">Nothing in the listing needs a closer look. Still inspect it in person.</p>}
        {!passed.length && model.coverage && <Coverage c={model.coverage}/>}
      </section>}
      {!locked && passed.length > 0 && <section className="report-checks" style={step()}>
        <div className="ios-section"><h2>What passed</h2></div>
        <ul className="check-list">{passed.map(checkRow)}</ul>
        {model.coverage && <Coverage c={model.coverage}/>}
      </section>}
      {children}
      {!locked && price && <section className="report-price" style={step()}><div className="ios-section"><h2>Price</h2></div>{price}</section>}
      {!locked && analysis?.components && <PartsPanel components={analysis.components} onOpen={area => { tap('select'); setSheet({ type: 'part', area }); }} style={step()}/>}
      {!locked && analysis?.details?.length > 0 && <ClaimsList details={analysis.details} onOpen={i => { tap('select'); setSheet({ type: 'claim', i }); }} style={step()}/>}
      {spec.length > 0 && <section className="report-spec" style={step()} aria-label="The listing">
        <div className="ios-section"><h2>Details</h2></div>
        <dl className="spec-list">{spec.map(r => <div key={r.label} className="spec-row"><dt>{r.label}</dt><dd>{r.value}</dd></div>)}</dl>
      </section>}
      {written && <details className="full-written" style={step()}><summary>The full written report<Chevron/></summary><div className="full-written-body"><div>{written}</div></div></details>}
      {next.length > 0 && <GroupedList className="report-next" style={step()}>{next.map(a => <GroupedRow key={a.label} title={a.label} onClick={a.run}/>)}</GroupedList>}
      {!onToast && <Banner message={ownToast} onDismiss={() => setOwnToast('')}/>}
      <p className="report-foot" style={step()}>{DISCLAIMER}</p>
    </div>
    {bar && <div className="report-cta"><Button onClick={bar.run}>{bar.label}</Button></div>}
    {sheet?.type === 'detail' && <CheckSheet row={model.rows[sheet.i]} images={images} url={url} asked={asked[sheet.i]} onToggle={() => toggle(sheet.i)} onView={setViewer} onClose={() => setSheet(null)}/>}
    {sheet?.type === 'part' && <PartSheet area={sheet.area} analysis={analysis} images={images} url={url} onView={setViewer} onClose={() => setSheet(null)}/>}
    {sheet?.type === 'claim' && <ClaimSheet claim={analysis.details[sheet.i]} onClose={() => setSheet(null)}/>}
    {sheet?.type === 'score' && <ScoreSheet onClose={() => setSheet(null)}/>}
    {sheet?.type === 'questions' && <QuestionsSheet items={askable.map(r => ({ text: r.ask, from: r.name.toLowerCase(), checked: asked[r.i], toggle: () => toggle(r.i) }))} url={url} onCopy={copy} onShare={navigator.share ? share : undefined}
      onAskPhotos={onAskPhotos && (() => { setSheet(null); onAskPhotos(); })} onClose={() => setSheet(null)}/>}
    {viewer != null && <PhotoViewer images={images} start={viewer} onClose={() => setViewer(null)}/>}
  </div>;
}
// The verdict under a sheet's title: a mark and a word, with no chip round them.
function SheetVerdict({ kind, word }) { return <span className={`sheet-verdict ${kind ? `tone-${kind}` : 'muted'}`}><VerdictMark kind={kind}/>{word || WORD[kind] || WORD.none}</span>; }
// One block of a reading sheet: a small label and what it says, as a grouped cell.
function SheetCell({ label, className = '', children }) { return <div className={`sheet-cell ${className}`}>{label && <span className="sheet-cell-label">{label}</span>}{children}</div>; }
// The listing's scanned photos as a carousel that opens on the one a finding came from. A tap opens a photo full
// screen. Only the cited photo's frame is .check-photo; where the scan located the area, a ring draws on round it.
function Evidence({ images, cited, area, url, note = '', onView }) {
  const track = useRef(null); const [at, setAt] = useState(cited - 1);
  useLayoutEffect(() => { const el = track.current; if (el) el.scrollLeft = (cited - 1) * el.clientWidth; }, [cited]);
  const onScroll = e => { const el = e.currentTarget; const i = Math.round(el.scrollLeft / Math.max(1, el.clientWidth)); if (i !== at) setAt(i); };
  return <figure className="evidence">
    <div className="evidence-track" ref={track} onScroll={onScroll} data-no-drag="">{images.map((src, i) => <div key={src + i} className={i === cited - 1 ? 'check-photo' : 'check-photo-alt'}>
      <Photo src={src} alt={`Listing photo ${i + 1}`} label={`Listing photo ${i + 1} of ${images.length}`} url={url} onOpen={() => onView(i)}>{i === cited - 1 && area && <svg className="check-circle" style={{ left: `${area.x * 100}%`, top: `${area.y * 100}%` }} width="72" height="72" viewBox="0 0 72 72" aria-hidden="true"><circle cx="36" cy="36" r="34" pathLength="1"/></svg>}</Photo>
    </div>)}</div>
    {images.length > 1 && <div className="evidence-dots" aria-hidden="true">{images.map((src, i) => <i key={src + i} className={i === at ? 'on' : ''}/>)}</div>}
    <figcaption>Listing photo {at + 1} of {images.length}{at === cited - 1 ? note : ''}</figcaption>
  </figure>;
}
// One check: what wabi saw, first, so it is in view at the medium detent; then the listing photo it came from (with the
// checked area circled when the scan located it), what genuine looks like and the seller-question toggle.
// Only the photo checks compare against a sourced reference; the other rows carry context (a caveat, the sales range,
// the seller's profile), so they get a neutral label.
const GENUINE_ROWS = new Set(CHECK_NAMES.slice(1, 4));
function CheckSheet({ row, images, url, asked, onToggle, onView, onClose }) {
  const src = row.photo && images[row.photo - 1];
  return <Sheet title={row.name} label="check" detents={['medium', 'large']} onClose={onClose} head={<SheetVerdict kind={row.kind} word={rowWord(row)}/>}>
    <SheetCell label="What wabi saw"><p>{row.finding}</p></SheetCell>
    {src && <Evidence images={images} cited={row.photo} area={row.area} url={url} note={row.area ? ' · The checked area is circled' : ''} onView={onView}/>}
    {row.genuine && <SheetCell label={row.kind && GENUINE_ROWS.has(row.name) ? 'What genuine looks like' : 'Good to know'}><p>{row.genuine}</p></SheetCell>}
    {row.ask && <Button variant="secondary" aria-pressed={asked} onClick={() => { tap('select'); onToggle(); }}>{asked && <CheckIcon/>}{asked ? 'Added to seller questions' : 'Add to seller questions'}</Button>}
  </Sheet>;
}
// One part of the watch (the movement, say): what wabi saw, the photo it was judged from, and each counterfeit tell
// from the library that was run against it, with its result and the source it comes from.
const CHECK_RESULT = { consistent: { word: WORD.pass, kind: 'pass' }, contradicts: { word: WORD.fail, kind: 'fail' }, not_visible: { word: WORD.none, kind: null } };
const PART_KIND = { consistent: 'pass', concern: 'fail', replacement_suspected: 'inspect' };
function PartSheet({ area, analysis, images, url, onView, onClose }) {
  const c = analysis.components.find(x => x.area === area);
  const checks = (analysis.knowledge_checks || []).filter(k => k.component === area);
  const photo = c?.images?.[0]; const src = photo && images[photo - 1];
  const host = u => { try { return new URL(u).hostname.replace(/^www\./, ''); } catch { return 'source'; } };
  // Titled by the row's own word; the longer name of what was looked at is its first line.
  return <Sheet title={PART_NAMES[area]} sub={CHECKS.find(x => x.id === area)?.title} label="part" detents={['medium', 'large']} onClose={onClose} head={<SheetVerdict kind={c ? PART_KIND[c.finding] : null}/>}>
    {c?.observation && <SheetCell label="What wabi saw"><p>{c.observation}</p></SheetCell>}
    {src ? <Evidence images={images} cited={photo} url={url} note=", the one this part was judged from" onView={onView}/>
      : <SheetCell><p>No listing photo shows this part clearly. Ask the seller for one before you pay.</p></SheetCell>}
    <h3 className="part-h3">Known counterfeit tells{checks.length > 0 && <span className="part-count num"> · {checks.filter(k => k.result === 'consistent').length} of {checks.length} passed</span>}</h3>
    {checks.length ? checks.map(k => { const r = CHECK_RESULT[k.result] || CHECK_RESULT.not_visible; return <SheetCell key={k.claim_id} className="tell-cell">
      <div className="tell-head"><SheetVerdict kind={r.kind} word={r.word}/>{k.weight === 'strong' && <span className="tell-weight">Strong sign</span>}</div>
      {k.observation && <p className="tell-seen">{k.observation}</p>}
      <div className="tell-block"><span className="sheet-cell-label">Genuine<span className="sr-only">:</span></span> <p>{k.claim}</p></div>
      {k.counterfeitSign && <div className="tell-block"><span className="sheet-cell-label">Fakes often<span className="sr-only">:</span></span> <p>{k.counterfeitSign}</p></div>}
      {k.sources?.length > 0 && <p className="tell-source">Source: {k.sources.slice(0, 2).map((u, i) => <a key={u} href={u} target="_blank" rel="noopener noreferrer">{i ? ', ' : ''}{host(u)}</a>)}</p>}
    </SheetCell>; }) : <SheetCell><p>wabi’s library has no specific checks for this part on this model yet. The finding above comes from the photo alone.</p></SheetCell>}
  </Sheet>;
}
// One of the listing's claims: what the listing says, and what wabi makes of it.
const CLAIM_KIND = { consistent: 'pass', questionable: 'inspect', red_flag: 'fail' };
function ClaimSheet({ claim, onClose }) {
  return <Sheet title={claim.label} label="claim" detents={['medium', 'large']} onClose={onClose} head={<SheetVerdict kind={CLAIM_KIND[claim.assessment]} word={ASSESSMENTS[claim.assessment].label}/>}>
    {claim.listed && <SheetCell label="The listing says"><p>“{claim.listed}”</p></SheetCell>}
    <SheetCell label="What wabi found"><p>{claim.note || (claim.assessment === 'consistent' ? 'The photos agree with this.' : 'The photos don’t show enough to confirm this.')}</p></SheetCell>
  </Sheet>;
}
// What the three verdicts mean, and the limit of all of them.
// A report row's word: its verdict, or why it has none.
const rowWord = r => (r.kind ? WORD[r.kind] : r.unrun ? 'Not checked' : WORD.none);
const SCORE_KEYS = [['pass', 'What the listing shows matches a genuine watch.'], ['inspect', 'Something couldn’t be confirmed from the listing. Look closer, or ask the seller.'], ['fail', 'Something in the listing doesn’t match a genuine watch.'], ['none', 'The listing’s photos don’t show this part, so it isn’t scored.']];
function ScoreSheet({ onClose }) {
  return <Sheet title="How the score works" detents={['medium', 'large']} onClose={onClose}>
    <ul className="score-keys">{SCORE_KEYS.map(([kind, text]) => <li key={kind}><span className={`part-mark ${kind === 'none' ? 'muted' : `tone-${kind}`}`}><VerdictMark kind={kind} size={12}/></span><span className="score-key-text"><b>{WORD[kind]}</b><span>{text}</span></span></li>)}</ul>
    <p className="sheet-footnote">{DISCLAIMER}</p>
  </Sheet>;
}
// The questions worth sending, as a list you tick. Copy puts them on the clipboard as one message; Share hands the
// same message to the system share sheet where there is one. Under the list, the ways on: the listing itself, and a
// request for the photos it does not show.
function QuestionsSheet({ items, url, onCopy, onShare, onAskPhotos, onClose }) {
  const n = items.filter(q => q.checked).length;
  // The actions are docked in the sheet's footer bar, one row of them, so they are in reach at either detent and the
  // list keeps the rest of the sheet. On a short phone the medium detent would show one question, so a longer list
  // opens at large there.
  const detents = items.length > 2 && window.innerHeight < 700 ? ['large', 'medium'] : ['medium', 'large'];
  return <Sheet title="Ask the seller" sub="Pick what to send. wabi copies them as one message you can paste into the listing’s chat." detents={detents} onClose={onClose}
    footer={<div className="ask-foot"><Button disabled={!n} onClick={onCopy}>{n === 0 ? 'Pick a question to copy' : n === 1 ? 'Copy 1 question' : `Copy ${n} questions`}</Button>{onShare && <Button variant="secondary" disabled={!n} onClick={onShare}>Share…</Button>}</div>}>
    <ul className="question-list">{items.map(q => <li key={q.text}><label className="question-row"><span className="question-box"><input type="checkbox" checked={q.checked} onChange={() => { tap('select'); q.toggle(); }}/><svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="M2.5 7.5l3 3 6-7" pathLength="1"/></svg></span><span className="question-copy"><span className="question-text">{q.text}</span><span className="question-from">From {q.from}</span></span></label></li>)}</ul>
    {(url || onAskPhotos) && <GroupedList className="question-more">
      {url && <GroupedRow title="Open the listing" href={url} external/>}
      {onAskPhotos && <GroupedRow title="Ask the seller for photos" sub="A private link for the views the listing doesn’t show" onClick={onAskPhotos}/>}
    </GroupedList>}
  </Sheet>;
}
// A listing photo, full screen on black. Swipe sideways between photos; pinch or double-tap to look closer; swipe
// down, tap Close or press Escape to put it away.
function PhotoViewer({ images, start = 0, onClose }) {
  const box = useRef(null); const track = useRef(null); const [at, setAt] = useState(start); const [zoomed, setZoomed] = useState(false); const [leaving, setLeaving] = useState(false);
  const g = useRef({ scale: 1, x: 0, y: 0, pts: new Map(), pinch: null, drag: null, tapped: 0 }).current;
  const close = () => { if (leaving) return; setLeaving(true); setTimeout(onClose, reduceMotion() ? 0 : cssMs('--t-quick', 300)); };
  useOverlay(box, close);
  useLayoutEffect(() => { const el = track.current; el.scrollLeft = start * el.clientWidth; box.current.querySelector('.viewer-close')?.focus({ preventScroll: true }); }, []); // eslint-disable-line react-hooks/exhaustive-deps
  const img = (i = at) => track.current?.children[i]?.querySelector('img');
  const apply = (moving, i) => { const el = img(i); if (!el) return; el.style.transition = moving ? 'transform var(--t-quick) var(--spring)' : 'none'; el.style.transform = g.scale === 1 && !g.x && !g.y ? '' : `translate(${g.x}px, ${g.y}px) scale(${g.scale})`; };
  const rest = i => { g.scale = 1; g.x = 0; g.y = 0; apply(true, i); setZoomed(false); };
  const onScroll = e => { const el = e.currentTarget; const i = Math.round(el.scrollLeft / Math.max(1, el.clientWidth)); if (i !== at) { if (g.scale !== 1) rest(at); setAt(i); } };
  const spread = () => { const [a, b] = [...g.pts.values()]; return Math.hypot(a.x - b.x, a.y - b.y); };
  const down = e => {
    g.pts.set(e.pointerId, { x: e.clientX, y: e.clientY });
    if (g.pts.size === 2) { g.pinch = { d: spread() || 1, scale: g.scale }; g.drag = null; }
    else g.drag = { x: e.clientX, y: e.clientY, ox: g.x, oy: g.y, t: performance.now(), mode: g.scale > 1 ? 'pan' : null };
  };
  const move = e => {
    if (!g.pts.has(e.pointerId)) return; g.pts.set(e.pointerId, { x: e.clientX, y: e.clientY });
    if (g.pinch && g.pts.size === 2) { g.scale = Math.min(4, Math.max(1, g.pinch.scale * spread() / g.pinch.d)); if (g.scale === 1) { g.x = 0; g.y = 0; } apply(false); setZoomed(g.scale > 1); return; }
    const d = g.drag; if (!d) return; const dx = e.clientX - d.x; const dy = e.clientY - d.y;
    if (d.mode === 'pan') { g.x = d.ox + dx; g.y = d.oy + dy; apply(false); return; }
    if (!d.mode && dy > 12 && dy > Math.abs(dx) * 1.5) { d.mode = 'down'; box.current.dataset.held = ''; }
    if (d.mode === 'down') { box.current.style.setProperty('--pull', `${Math.max(0, dy)}px`); box.current.style.setProperty('--dim', String(Math.max(.3, 1 - dy / 500))); }
  };
  const up = e => {
    const d = g.drag; g.pts.delete(e.pointerId); if (g.pts.size < 2) g.pinch = null;
    if (!d || g.pts.size) return; g.drag = null; const dy = e.clientY - d.y;
    if (d.mode === 'down') { delete box.current.dataset.held; if (dy > 110 || dy / Math.max(1, performance.now() - d.t) > .5) close(); else { box.current.style.removeProperty('--pull'); box.current.style.removeProperty('--dim'); } return; }
    if (Math.abs(e.clientX - d.x) > 8 || Math.abs(dy) > 8) return;
    // A second tap soon after the first looks closer at that point; done again, it steps back.
    const now = performance.now(); if (now - g.tapped > 300) { g.tapped = now; return; } g.tapped = 0;
    if (g.scale > 1) { rest(); return; }
    const r = img()?.getBoundingClientRect(); if (!r) return;
    g.scale = 2.5; g.x = (r.left + r.width / 2 - e.clientX) * 1.5; g.y = (r.top + r.height / 2 - e.clientY) * 1.5; apply(true); setZoomed(true);
  };
  return createPortal(<div ref={box} className="photo-viewer" role="dialog" aria-modal="true" aria-label="Listing photos" data-leaving={leaving ? '' : undefined} data-zoomed={zoomed ? '' : undefined}>
    <div className="viewer-track" ref={track} onScroll={onScroll} onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up}>
      {images.map((src, i) => <div className="viewer-slide" key={src + i}><img src={src} alt={`Listing photo ${i + 1} of ${images.length}`} referrerPolicy="no-referrer" draggable="false"/></div>)}
    </div>
    <div className="viewer-top"><span className="viewer-count num" aria-hidden="true">{at + 1} of {images.length}</span><button type="button" className="viewer-close" aria-label="Close photo" onClick={close}><CloseIcon/></button></div>
  </div>, document.body);
}
// "Ref. 126610LN · eBay listing · $9,850" under the watch name while it is checked.
function scanLine(l) {
  if (!l) return '';
  const ref = guessFromTitle(l.title || '').reference;
  const price = l.price ? ((!l.currency || l.currency.toUpperCase() === 'USD') ? money(Number(l.price)) : `${l.currency} ${Number(l.price).toLocaleString()}`) : '';
  return [ref && `Ref. ${ref}`, l.site && `${siteName(l.site)} listing`, price].filter(Boolean).join(' · ');
}
const SITE_NAMES = { 'ebay.com': 'eBay', 'chrono24.com': 'Chrono24', 'watchuseek.com': 'WatchUSeek', 'reddit.com': 'Reddit', 'facebook.com': 'Facebook', 'jomashop.com': 'Jomashop', 'bobswatches.com': 'Bob’s Watches', 'crownandcaliber.com': 'Crown & Caliber' };
function siteName(site) { const host = String(site).replace(/^www\./, '').toLowerCase(); const key = Object.keys(SITE_NAMES).find(k => host === k || host.endsWith(`.${k}`) || host.startsWith(k.split('.')[0] + '.')); return key ? SITE_NAMES[key] : site; }
const freeLine = w => (w?.freePerDay && w.freeLeft != null ? (w.freeLeft > 0 ? `${w.freeLeft} of ${w.freePerDay} free checks left today. ` : `You’ve used today’s ${w.freePerDay} free checks. They reset tomorrow. `) : '');
function recordFromMini(m) {
  const usd = (amount, currency) => (amount && (!currency || currency.toUpperCase() === 'USD') ? String(amount) : '');
  return {
    model: [m.identification.brand, m.identification.model].filter(Boolean).join(' ').slice(0, 100) || guessFromTitle(m.listing.title || '').model || 'Unidentified watch',
    reference: (m.identification.reference || guessFromTitle(m.listing.title || '').reference || '').slice(0, 40),
    year: '', price: usd(m.listing.price, m.listing.currency), url: m.listing.url,
    description: [m.listing.title, `Listed on ${m.listing.site}`].filter(Boolean).join('\n'),
    photos: {}, checks: emptyChecks(), comps: [],
    scan: { tier: 'mini', site: m.listing.site, title: m.listing.title, images: m.listing.images, scannedImages: m.listing.scannedImages, score: m.score, headline: m.headline, redFlagCount: m.redFlagCount, identification: m.identification },
  };
}
// The packs on sale, always with their price. Signed out, the button says to sign in first and the price stays
// visible; a button that cannot buy is never shown. The monthly plan comes first, then the packs, cheapest per scan
// last. Several offers show as a choice; one shows as a single line. The App Store doesn't allow outside payment for
// digital goods, so the iOS app sells nothing. pulse nudges the chosen option when the page has scrolled to it.
const PACK_CHECK = <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 7.5l3 3 6-7"/></svg>;
function PackOffer({ wallet, onBuy, busy, block = false, variant = 'primary', pulse = 0 }) {
  const { user, askSignIn } = useContext(Account);
  // The monthly plan first (unless this account already has it), then the packs, cheapest per scan last.
  // A plan Stripe may still charge (active, or a payment being retried) is never offered again: one plan per account.
  const plan = wallet.plan && !PLAN_HELD.includes(wallet.subscription?.status) ? [{ ...wallet.plan, kind: 'subscription' }] : [];
  const packs = wallet.packs?.length ? wallet.packs : wallet.price ? [{ id: undefined, credits: wallet.packCredits, ...wallet.price }] : [];
  const offers = [...plan, ...packs];
  const [chosen, setChosen] = useState(() => (plan.length ? plan[0].id : offers[Math.min(1, offers.length - 1)]?.id));
  const pick = offers.find(o => o.id === chosen) || offers[0];
  const signInFirst = authEnabled && wallet.authEnabled && !user; const cls = `button ${variant}${block ? ' block' : ''}`;
  if (isNative) return <p className="small pack-terms">Scans can’t be bought in the iOS app. Scans on your wabi account work here once you sign in.</p>;
  const each = o => new Intl.NumberFormat('en-US', { style: 'currency', currency: o.currency, minimumFractionDigits: 2 }).format(o.amount / (o.credits || o.scans));
  // Each bigger pack is anchored against the single scan: "Save 43%".
  const single = packs.find(o => o.credits === 1);
  const saving = o => (single && o.credits > 1 && o.currency === single.currency ? Math.round((1 - o.amount / o.credits / single.amount) * 100) : 0);
  const isPlan = o => o?.kind === 'subscription';
  const per = o => (o.interval === 'year' ? 'year' : 'month');
  // One tab stop for the group; the arrow keys move the choice, as in a native radio group.
  const onKey = e => {
    const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[e.key]; const at = offers.findIndex(o => o.id === pick.id);
    const next = e.key === 'Home' ? 0 : e.key === 'End' ? offers.length - 1 : step ? (at + step + offers.length) % offers.length : null;
    if (next == null) return;
    e.preventDefault(); setChosen(offers[next].id); e.currentTarget.querySelectorAll('[role=radio]')[next]?.focus();
  };
  // A plan option, two lines in a 64pt cell: what you get and its price, then its per-scan cost (with, for the plan,
  // how often the price recurs at the end of that line, under the price); the radio mark trails both. The plan's title and its price already say it
  // is monthly, so it carries no tag; a pack's saving follows its name.
  const tile = o => isPlan(o)
    ? <><span className="pack-mark" aria-hidden="true">{PACK_CHECK}</span><span className="pack-main"><span className="pack-title"><b>{count(o.scans, 'full scan')} a {per(o)}</b></span><span className="small"><span>{each(o)} each · cancel any time</span><span className="pack-per">/{per(o)}</span></span></span><span className="pack-price">{o.label}</span></>
    : <><span className="pack-mark" aria-hidden="true">{PACK_CHECK}</span><span className="pack-main"><span className="pack-title"><b>{count(o.credits, 'full scan')}</b>{saving(o) > 0 && <span className="pack-badge">Save {saving(o)}%</span>}</span><span className="small">{o.credits > 1 ? `${each(o)} each` : 'One listing'}</span></span><span className="pack-price">{o.label}</span></>;
  const terms = isPlan(pick)
    ? `${signInFirst ? 'Sign in, then Stripe checkout' : 'Stripe checkout'} · Renews every ${per(pick)} until you cancel in Profile · A failed scan’s credit comes back automatically; otherwise payments aren’t `
    : `${signInFirst ? 'Sign in, then Stripe checkout' : 'Stripe checkout'} · Credits never expire · A failed scan’s credit comes back automatically; otherwise purchases aren’t `;
  return <div className="pack-offer">
    {!pick ? <p className="small">The price isn’t available right now. Try again in a moment.</p>
      : offers.length > 1 ? <div className="pack-choice" role="radiogroup" aria-label="Choose a plan or pack" style={{ '--packs': offers.length }} onKeyDown={onKey}>{offers.map(o => <button key={o.id} type="button" role="radio" aria-checked={o.id === pick.id} tabIndex={o.id === pick.id ? 0 : -1} className={`pack-option${o.id === pick.id ? ' on' : ''}${isPlan(o) ? ' plan' : ''}`} data-pulse={o.id === pick.id && pulse ? pulse % 2 : undefined} onClick={() => { tap('select'); setChosen(o.id); }}>{tile(o)}</button>)}</div>
        : <p className="pack-line" data-pulse={pulse ? pulse % 2 : undefined}>{isPlan(pick) ? <><b>{count(pick.scans, 'full scan')} a {per(pick)}</b> for <b>{pick.label}</b>/{per(pick)}</> : <><b>{count(pick.credits, 'full scan')}</b> for <b>{pick.label}</b></>} <span>{pick.currency}</span></p>}
    {wallet.scansDown ? <p className="small form-error" role="status">Scans are paused for a few minutes, so buying is too. Try again shortly.</p>
      : signInFirst ? <button className={cls} onClick={() => askSignIn()}>Sign in to buy</button>
      : pick && <button className={cls} onClick={() => onBuy(pick)} disabled={busy}>{busy && <TickSpinner size={16}/>}{isPlan(pick) ? `Subscribe · ${pick.label}/${per(pick)}` : `Buy ${count(pick.credits, 'full scan')} · ${pick.label}`}</button>}
    {/* the last words stay with the link, so a wrapped line never starts with the separator */}
    <p className="small pack-terms">{terms}<span className="nowrap">refundable · <a href={TERMS_URL} target="_blank" rel="noopener noreferrer">Terms</a></span></p>
  </div>;
}
// What stands between a free check and the full report. There is exactly one unlock control on the screen, and it is
// in the bottom bar: with a scan on the account it unlocks; without one (on the web) it leads down to the plans, whose
// own button does the buying. In the iOS app nothing is sold and nothing leads to a purchase: the cell says what full
// reports use, and offers sign-in or the unlock.
function LockedReport({ wallet, refreshWallet, onUnlock, unlocking, elapsed, error }) {
  const { user, askSignIn } = useContext(Account);
  const needsSignIn = authEnabled && wallet?.authEnabled && !user && !wallet?.unlimited;
  const [code, setCode] = useState(''); const [codeOpen, setCodeOpen] = useState(false); const [busy, setBusy] = useState(false); const [note, setNote] = useState('');
  const canUnlock = !needsSignIn && canRunFull(wallet);
  const sells = !isNative && (needsSignIn || Boolean(wallet?.paymentsEnabled));
  const card = useRef(null); const [pulse, setPulse] = useState(0);
  async function applyCode(e) {
    e.preventDefault(); setBusy(true); setNote('');
    try { const w = await refreshWallet({ access: code.trim() }); if (w.accessCodeValid) { setAccessCode(code); setCodeOpen(false); await refreshWallet(); } else setNote('That code is not valid.'); }
    catch (err) { setNote(err.message); } finally { setBusy(false); }
  }
  async function buy(pack) { setBusy(true); setNote(''); try { await startCheckout(pack); } catch (err) { if (err.signIn) askSignIn(); else setNote(err.message); if (err.scansDown) refreshWallet(); setBusy(false); } }
  const toPlans = () => { card.current?.querySelector('.pack-offer')?.scrollIntoView({ block: 'center', behavior: reduceMotion() ? 'auto' : 'smooth' }); setPulse(n => n + 1); };
  // The card's own button buys, so the screen has one filled action: while the plans are on screen the docked bar steps
  // away, and while they are not it only leads down to them, in the secondary style.
  const [offerSeen, setOfferSeen] = useState(false);
  useEffect(() => {
    const el = card.current?.querySelector('.pack-offer'); if (!el || typeof IntersectionObserver === 'undefined') { setOfferSeen(false); return undefined; }
    const io = new IntersectionObserver(([e]) => setOfferSeen(e.isIntersecting), { threshold: 0.2 }); io.observe(el); return () => io.disconnect();
  }, [sells, canUnlock, unlocking]);
  const away = !canUnlock && offerSeen;
  const bar = canUnlock ? <Button onClick={onUnlock} disabled={unlocking}>{unlocking ? <TickSpinner size={20} label="Writing the full report"/> : <>Unlock full report{wallet.unlimited ? '' : planLeft(wallet) > 0 ? ` · ${planLeft(wallet)} left this month` : ` · 1 of ${count(wallet.credits, 'scan')}`}</>}</Button>
    : sells && !unlocking ? <Button variant="secondary" onClick={toPlans}>Get the full report</Button> : null;
  const codeEntry = !unlocking && !canUnlock && (codeOpen ? <form className="code-form" onSubmit={applyCode}><input aria-label="Access code" placeholder="Access code" value={code} onChange={e => setCode(e.target.value)} autoCapitalize="off" autoCorrect="off" data-autofocus=""/><button className="button secondary" disabled={busy || !code.trim()}>Apply</button></form> : <button type="button" className="text-button code-toggle" onClick={() => setCodeOpen(true)}>Have an access code?</button>);
  const progress = unlocking && <ScanSteps steps={[{ text: 'Checking every photo', state: 'run' }, { text: 'Checking the seller’s background', state: 'run' }, { text: 'Writing the full report', state: 'wait' }]} elapsed={elapsed}/>;
  if (isNative) return <section className="locked-report paywall bar-host" aria-label="Full report, locked">
    <div className="paywall-card native" ref={card}>
      <h2>Full report</h2><p className="paywall-native-body">Full reports use scans on your wabi account.</p>
      {progress}
      {!unlocking && needsSignIn && <Button onClick={() => askSignIn()}>Sign in</Button>}
      {!unlocking && !needsSignIn && !canUnlock && <p className="small pack-terms">Scans can’t be bought in the iOS app.</p>}
      {error && <FormError>{error}</FormError>}
      {codeEntry}{note && <FormError>{note}</FormError>}
    </div>
    {bar && <div className="report-cta">{bar}</div>}
  </section>;
  return <section className="locked-report paywall bar-host" aria-label="Full report, locked">
    <div className="paywall-card" ref={card}>
      <div className="paywall-art" aria-hidden="true"><img src={`${import.meta.env.BASE_URL}images/editorial/crown-green.webp`} alt="" loading="lazy"/></div>
      <h2>The full report</h2>
      <ul className="paywall-list">{['Every claim in the listing checked', 'The seller’s history and risk', `Each photo reviewed against ${CHECKS.length} areas`, 'Price compared with the market'].map(t => <li key={t}><span className="paywall-check"><CheckIcon size={14}/></span>{t}</li>)}</ul>
      {progress || (canUnlock ? null : sells ? <PackOffer wallet={wallet} onBuy={buy} busy={busy} block pulse={pulse}/> : <p className="small">{wallet ? 'Full scans are coming soon.' : 'Loading your scans…'}</p>)}
      {error && <FormError>{error}</FormError>}
      {codeEntry}
      {note && <FormError>{note}</FormError>}
    </div>
    {bar && <div className="report-cta" data-away={away ? '' : undefined} inert={away || undefined}>{bar}</div>}
  </section>;
}
function ScanSteps({ steps, elapsed }) {
  return <div className="scan-steps" role="status"><ul>{steps.map(s => <li key={s.text} className={s.state}>{s.state === 'done' ? <Check size={14}/> : s.state === 'run' ? <TickSpinner size={16}/> : <span className="dot"/>}{s.text}</li>)}</ul><span className="small">{elapsed}s · keep the app open</span></div>;
}
// The saved shape of a full scan without its cover photo, for showing the report straight away.
function scanFields(r) {
  const id = r.analysis.identification; const l = r.analysis.listing;
  const usd = (amount, currency) => (amount && (!currency || currency.toUpperCase() === 'USD') ? String(amount) : '');
  return {
    model: [id.brand, id.model].filter(Boolean).join(' ').slice(0, 100) || guessFromTitle(r.listing.title || '').model || 'Unidentified watch',
    reference: (id.reference_candidates[0]?.reference || l.stated_reference || '').slice(0, 40),
    price: usd(l.asking_price, l.currency) || usd(r.listing.price, r.listing.currency),
    analysis: r.analysis,
    scan: { site: r.listing.site, title: r.listing.title, images: r.listing.images, scannedImages: r.listing.scannedImages, seller: r.seller, reuse: r.reuse || null, score: r.score },
  };
}
async function recordFromScan(r) {
  const id = r.analysis.identification; const l = r.analysis.listing;
  const cover = r.cover ? { id: crypto.randomUUID(), name: 'listing.jpg', url: await resizeImage(r.cover, 1600).catch(() => r.cover) } : null;
  const photos = cover ? { cover } : {};
  const usd = (amount, currency) => (amount && (!currency || currency.toUpperCase() === 'USD') ? String(amount) : '');
  return {
    model: [id.brand, id.model].filter(Boolean).join(' ').slice(0, 100) || guessFromTitle(r.listing.title || '').model || 'Unidentified watch',
    reference: (id.reference_candidates[0]?.reference || l.stated_reference || '').slice(0, 40),
    year: l.stated_year.match(/\b(19|20)\d\d\b/)?.[0] || '',
    price: usd(l.asking_price, l.currency) || usd(r.listing.price, r.listing.currency),
    url: r.listing.url,
    description: [r.listing.title, `Listed on ${r.listing.site}`].filter(Boolean).join('\n'),
    photos, checks: emptyChecks(), comps: [],
    analysis: { ...r.analysis, photoIds: photoIds(photos) },
    scan: { site: r.listing.site, title: r.listing.title, images: r.listing.images, scannedImages: r.listing.scannedImages, seller: r.seller, reuse: r.reuse || null, score: r.score },
  };
}

// A scan kept with the account, as a saved listing on this device. Photos stay on the device that added them.
async function recordFromAccount(entry) {
  if (entry.record) {
    const { id, photos, watch, account, localOnly, ...rest } = entry.record;
    return { ...rest, url: rest.url || entry.url, photos: {}, checks: emptyChecks(), comps: [], ...(rest.analysis && { analysis: { ...rest.analysis, photoIds: '' } }) };
  }
  const record = entry.kind === 'full' ? await recordFromScan({ ...entry.raw, cover: null }) : recordFromMini(entry.raw);
  return { ...record, url: record.url || entry.url };
}
// Whether the person changed a listing's details or notes on this device (Edit listing details), which never go to the account.
const edited = r => Boolean(r.edited);
// A saved listing, for the account: only what the scan found, rebuilt from the scan itself. The person's own photos,
// notes and edits, comparables, photo requests and watch alerts stay on the device.
function forAccount(r) {
  const id = r.analysis?.identification; const seen = r.scan?.identification; const l = r.analysis?.listing;
  const usd = (amount, currency) => (amount && (!currency || String(currency).toUpperCase() === 'USD') ? String(amount) : '');
  const record = {
    model: (id ? [id.brand, id.model] : [seen?.brand, seen?.model]).filter(Boolean).join(' ').slice(0, 100) || guessFromTitle(r.scan?.title || '').model || 'Unidentified watch',
    reference: (id?.reference_candidates?.[0]?.reference || l?.stated_reference || seen?.reference || '').slice(0, 40),
    year: (l?.stated_year || '').match(/\b(19|20)\d\d\b/)?.[0] || '',
    price: usd(l?.asking_price, l?.currency),
    url: r.url,
    description: [r.scan?.title, r.scan?.site && `Listed on ${r.scan.site}`].filter(Boolean).join('\n'),
    scan: r.scan, created: r.created, scanned: r.scanned,
    ...(r.analysis?.details && { analysis: { ...r.analysis, photoIds: '' } }),
  };
  return { url: r.url, at: r.scanned || r.created, record };
}

const hostOf = url => { try { return new URL(url).hostname.replace(/^www\./, ''); } catch { return url; } };
// The written half of a full report, for anyone who wants it in words: the summary and what moved it, what to ask the
// seller for, the seller, where else the photos appear, each claim with wabi's note on it, each photo, and the
// counterfeit tells that were run. Every block is a labelled cell and every verdict is a mark and a word. The score is
// on the pass and the price has its own tile, so neither is repeated here; nor is the report's one disclaimer.
const TONE_KIND = { pos: 'pass', sand: 'inspect', red: 'fail' };
function ScanResult({ result, images }) {
  const { analysis, seller, reuse } = result;
  const scanned = result.listing.scannedImages || images;
  return <div className="written">
    <SheetCell label="Summary"><p>{analysis.overall.summary}</p>{analysis.probability_rationale && <p className="written-more">{analysis.probability_rationale}</p>}</SheetCell>
    {analysis.red_flags.length > 0 && <SheetCell label="Flagged in the listing"><ul className="written-list marked">{analysis.red_flags.map((f, i) => <li key={i}><span className="part-mark tone-fail"><VerdictMark kind="fail"/></span><span>{f}</span></li>)}</ul></SheetCell>}
    {analysis.missing_evidence.length > 0 && <SheetCell label="Ask the seller before you pay"><ul className="written-list">{analysis.missing_evidence.map((m, i) => <li key={i}><span className="written-row"><b>{m.request}</b>{m.why && <span>{m.why}</span>}</span></li>)}</ul></SheetCell>}
    <SellerNotes seller={seller}/>
    {reuse && <PhotoReuse reuse={reuse}/>}
    <ClaimNotes details={analysis.details}/>
    {analysis.photo_review.length > 0 && <SheetCell label="Photo by photo"><ul className="written-list photo-notes">{analysis.photo_review.map(p => <li key={p.image}>{scanned[p.image - 1] ? <img src={scanned[p.image - 1]} alt={`Listing photo ${p.image}`} width="44" height="44" referrerPolicy="no-referrer" loading="lazy"/> : <span className="photo-num num" aria-hidden="true">{p.image}</span>}<span className="written-row"><b>Photo {p.image} · {p.shows}</b>{p.notes && <span>{p.notes}</span>}</span></li>)}</ul></SheetCell>}
    <LibraryNote brand={analysis.identification?.brand}/>
    {analysis.knowledge_checks.length > 0 && <TellNotes checks={analysis.knowledge_checks} considered={analysis.knowledgeClaimsConsidered}/>}
  </div>;
}
// A cell's own verdict line: what it is about on the left, the mark and word on the right.
function WrittenHead({ title, sub, kind, word }) {
  return <div className="written-head"><span className="written-row"><b>{title}</b>{sub && <span>{sub}</span>}</span><SheetVerdict kind={kind} word={word}/></div>;
}
// The seller: who they are, how they read, what was found about them and where.
function SellerNotes({ seller }) {
  if (!seller) return <SheetCell label="Seller" className="seller-card"><WrittenHead title="Not checked" kind={null} word={SELLER_RISK.unknown.label}/><p>wabi couldn’t finish checking the seller. Look them up yourself before you pay.</p></SheetCell>;
  const risk = SELLER_RISK[seller.risk_level] || SELLER_RISK.unknown;
  return <SheetCell label="Seller" className="seller-card">
    <WrittenHead title={seller.name || 'Unknown seller'} sub={seller.platform} kind={TONE_KIND[risk.tone]} word={risk.label}/>
    {seller.summary && <p>{seller.summary}</p>}
    {seller.profile_facts.length > 0 && <ul className="written-list">{seller.profile_facts.map(f => <li key={f}><span>{f}</span></li>)}</ul>}
    {seller.risks.length > 0 && <ul className="written-list marked">{seller.risks.map(r => <li key={r}><span className="part-mark tone-fail"><VerdictMark kind="fail"/></span><span>{r}</span></li>)}</ul>}
    {seller.findings.length > 0 && <ul className="written-list links">{seller.findings.map(f => <li key={f.source_url + f.detail}><a href={f.source_url} target="_blank" rel="noopener noreferrer"><span className="written-row"><b>{f.detail}</b><span>{hostOf(f.source_url)}</span></span><ArrowOut/></a></li>)}</ul>}
  </SheetCell>;
}
// Seen elsewhere: other web pages showing the listing's photos. Not proof either way: dealers cross-post, scammers
// copy. The buyer is told what each case means and what to check.
function PhotoReuse({ reuse }) {
  const { checked, matches, exactMatches } = reuse;
  const title = !matches.length ? 'Not found elsewhere' : exactMatches ? `Also on ${count(exactMatches, 'other page')}` : 'Similar photos elsewhere';
  return <SheetCell label="Photos seen elsewhere" className="reuse-card">
    <WrittenHead title={title} kind={exactMatches ? 'inspect' : 'pass'}/>
    <p>{!matches.length ? `None of the ${count(checked, 'photo')} wabi checked turned up on other pages it could find. That doesn’t prove the photos are the seller’s own.`
      : exactMatches ? 'The same photos appear on these pages. If they are the same seller’s other listings, that’s normal. If the seller, the price or the date differ, the photos may be copied: ask the seller for a photo of the watch with today’s date written on paper.'
      : 'Pages with photos like these. Usually other examples of the same model, but compare them before you pay.'}</p>
    {matches.length > 0 && <ul className="written-list links reuse-list">{matches.map(m => <li key={m.url}><a href={m.url} target="_blank" rel="noopener noreferrer nofollow"><span className="written-row"><b>{m.site}</b><span>{m.title || m.url}</span><small>{m.exact ? 'Same photo' : 'Similar photo'} · photo {m.images.join(', ')}</small></span><ArrowOut/></a></li>)}</ul>}
  </SheetCell>;
}
// What the seller says, claim by claim, worst first, with wabi's note on each in full.
function ClaimNotes({ details }) {
  if (!details.length) return null;
  return <SheetCell label="What the listing claims"><ul className="written-list">{worstFirst(details, d => CLAIM_KIND[d.assessment]).map((d, i) => <li className="detail-row" key={`${d.label}${i}`}>
    <WrittenHead title={d.label} sub={d.listed && `“${d.listed}”`} kind={CLAIM_KIND[d.assessment]} word={ASSESSMENTS[d.assessment].label}/>{d.note && <p>{d.note}</p>}</li>)}</ul></SheetCell>;
}
// The counterfeit tells from the library that were run against these photos: how many could be, how they fell, and
// each one with what was seen and what a genuine watch shows.
const TELL_ORDER = ['contradicts', 'consistent', 'not_visible'];
function TellNotes({ checks, considered }) {
  const sorted = [...checks].sort((a, b) => TELL_ORDER.indexOf(a.result) - TELL_ORDER.indexOf(b.result) || (a.weight === 'strong' ? -1 : 0) - (b.weight === 'strong' ? -1 : 0));
  return <SheetCell label="Known counterfeit tells">
    <p>{checks.length} of {considered ?? checks.length} tells for this model could be checked in these photos.</p>
    <ul className="written-tally">{TELL_ORDER.map(r => { const k = CHECK_RESULT[r]; return <li key={r}><span className={`part-mark ${k.kind ? `tone-${k.kind}` : 'muted'}`}><VerdictMark kind={k.kind}/></span><b className="num">{checks.filter(c => c.result === r).length}</b>{k.word}</li>; })}</ul>
    <ul className="written-list">{sorted.map(k => { const r = CHECK_RESULT[k.result] || CHECK_RESULT.not_visible; return <li key={k.claim_id}>
      <div className="tell-head"><SheetVerdict kind={r.kind} word={r.word}/>{k.weight === 'strong' && <span className="tell-weight">Strong sign</span>}</div>
      {k.observation && <p>{k.observation}</p>}
      <p className="written-more">Genuine: {k.claim}{k.result === 'contradicts' && k.counterfeitSign ? ` Fakes often: ${k.counterfeitSign}` : ''}</p>
    </li>; })}</ul>
  </SheetCell>;
}
// A part's finding in the one vocabulary every surface uses: Pass, Inspect, Flag, Not shown.
const FINDING_LABEL = { consistent: WORD.pass, concern: WORD.fail, replacement_suspected: WORD.inspect, insufficient_evidence: WORD.none };
// The watch's parts as indices on a dial, one baton each at 45° steps: solid when it passes, hollow when it wants a
// closer look, hollow with a bar across it when it is flagged, dotted when no photo showed it. The shape carries the
// result; the tint only repeats it.
function IndexRing({ parts, size = 132 }) {
  const ok = parts.filter(p => p.finding === 'consistent').length;
  // The ring sits well down the report, so its indices draw in when it comes into view, not when the page is made.
  // Under Reduce Motion there is no drawing in to wait for, so they are simply there.
  const ring = useRef(null); const [seen, setSeen] = useState(reduceMotion);
  useEffect(() => {
    const el = ring.current; if (seen) return undefined; if (!el || !('IntersectionObserver' in window)) { setSeen(true); return undefined; }
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } }, { threshold: .6 });
    io.observe(el); return () => io.disconnect();
  }, []);
  return <svg ref={ring} data-seen={seen ? '' : undefined} className="index-ring" width={size} height={size} viewBox="0 0 132 132" role="img" aria-label={`${ok} of ${parts.length} parts pass`}>
    <circle className="index-track" cx="66" cy="66" r="50"/>
    {parts.map((p, i) => { const kind = PART_KIND[p.finding] || 'none'; return <g key={p.id} transform={`rotate(${i * 45} 66 66)`}><g className="index" style={{ '--i': i }}>
      <rect className={`seg ${kind}`} x="64" y="8" width="4" height="16" rx="2"><title>{`${p.title}: ${FINDING_LABEL[p.finding]}`}</title></rect>
      {kind === 'fail' && <line className="seg-bar" x1="60.5" y1="16" x2="71.5" y2="16"/>}
    </g></g>; })}
  </svg>;
}
// The watch, part by part: the ring of eight, how many look right, then each part as a row (worst first) that opens
// its photo and the tells it was held against.
function PartsPanel({ components, onOpen, style }) {
  const parts = CHECKS.map(c => ({ ...c, finding: components.find(x => x.area === c.id)?.finding || 'insufficient_evidence' }));
  const ok = parts.filter(p => p.finding === 'consistent').length;
  return <section className="report-dash" style={style}>
    <div className="ios-section"><h2>The watch, part by part</h2></div>
    <div className="dial-tile"><IndexRing parts={parts}/><p className="dial-figure"><b className="num" aria-hidden="true">{ok}<small>/{parts.length}</small></b><span>{ok === 1 ? 'part looks right' : 'parts look right'}</span></p></div>
    <ul className="part-list">{worstFirst(parts, p => PART_KIND[p.finding]).map(p => <li key={p.id}><button type="button" onClick={() => onOpen(p.id)} aria-label={`${PART_NAMES[p.id]}: ${FINDING_LABEL[p.finding]}. Open the checks`}><span className={`part-mark ${PART_KIND[p.finding] ? `tone-${PART_KIND[p.finding]}` : 'muted'}`}><VerdictMark kind={PART_KIND[p.finding]}/></span><span className="part-name">{PART_NAMES[p.id]}</span><span className="part-word">{FINDING_LABEL[p.finding]}</span><Chevron/></button></li>)}</ul>
  </section>;
}
// The listing's claims, one row each, worst first: what is claimed, what the listing states, and how it holds up.
function ClaimsList({ details, onOpen, style }) {
  const held = details.filter(d => d.assessment === 'consistent').length;
  return <section className="report-claims" style={style}>
    <div className="ios-section"><h2>Claims in the listing</h2><span className="section-trail num">{held} of {details.length} hold up</span></div>
    <ul className="claim-list">{worstFirst(details.map((d, i) => ({ ...d, i })), d => CLAIM_KIND[d.assessment]).map(d => <li key={`${d.label}${d.i}`}><button type="button" onClick={() => onOpen(d.i)} aria-label={`${d.label}: ${ASSESSMENTS[d.assessment].label}. Open wabi’s assessment`}><span className={`part-mark ${CLAIM_KIND[d.assessment] ? `tone-${CLAIM_KIND[d.assessment]}` : 'muted'}`}><VerdictMark kind={CLAIM_KIND[d.assessment]}/></span><span className="claim-text"><span className="part-name">{d.label}</span>{d.listed && <span className="claim-listed">“{d.listed}”</span>}</span><span className="part-word">{ASSESSMENTS[d.assessment].label}</span><Chevron/></button></li>)}</ul>
  </section>;
}
// Asking price against value: today's market range when it has been found (otherwise the AI's estimate), and the
// reference's five-year price trend with the asking price drawn across it.
function PricePanel({ value, ask, market: state }) {
  const market = state?.market; const range = market ? market : value;
  if (range.mid == null) return <div className="card dash-tile"><span className="label">Price vs. value</span><b className="tile-figure">{ask ? money(ask) : '—'}</b><p className="small">wabi couldn’t identify the watch closely enough to price it.</p></div>;
  const diff = ask ? (ask - range.mid) / range.mid : null;
  const lo = Math.min(range.low ?? range.mid, ask || Infinity) * 0.92; const hi = Math.max(range.high ?? range.mid, ask || 0) * 1.08;
  return <div className="card dash-tile price-tile"><span className="label">Asking vs. {market ? 'market value' : 'estimated value'}</span>
    <b className={`tile-figure ${diff == null ? '' : Math.abs(diff) < 0.1 ? 'pos' : diff < 0 ? 'sand' : 'neg'}`}>{diff == null ? money(range.mid) : percent(diff)}<small>{diff == null ? (market ? ' market' : ' estimated') : market ? ' vs. market' : ' vs. mid'}</small></b>
    <TickScale min={lo} max={hi} marks={[range.low != null && { value: range.low, text: compactMoney(range.low), label: 'Low' }, { value: range.mid, text: compactMoney(range.mid), label: market ? 'Market' : 'Mid' }, range.high != null && { value: range.high, text: compactMoney(range.high), label: 'High' }].filter(Boolean)} thumb={ask ? { value: ask } : null} label={`Asking ${ask ? money(ask) : 'unknown'} against ${market ? 'a market range' : 'an estimate'} of ${money(range.low ?? range.mid)} to ${money(range.high ?? range.mid)}`}/>
    <p className="small tile-foot">{!ask ? 'No asking price found.' : diff != null && diff < -0.25 ? `Asking ${money(ask)} is well below the ${market ? 'market' : 'estimated'} value. Ask the seller why.` : `Asking ${money(ask)}.`}{market ? '' : state?.busy ? ' Checking the market…' : ' The value is wabi’s estimate.'}</p>
    {market && <TrendChart market={market} ask={ask || null}/>}
    {market && <MarketSources market={market}/>}
  </div>;
}
// Choosing one evidence photo: the camera or the photo library in the app, a file chooser in the browser.
function usePhotoPick(view, onChange, onError) {
  const [busy, setBusy] = useState(false);
  async function accept(load) {
    setBusy(true);
    try {
      const source = await load();
      if (!source) return;
      onChange({ id: crypto.randomUUID(), name: source.name, url: await resizeImage(source.url) });
      onError('');
    } catch { onError('This photo couldn’t be read. Choose another.'); } finally { setBusy(false); }
  }
  function fromFile(file) {
    if (!file) return;
    const problem = checkImageFile(file);
    if (problem) { onError(problem); return; }
    accept(async () => ({ name: file.name, url: await fileToDataUrl(file) }));
  }
  const fromCamera = () => accept(async () => { const url = await takePhoto(view.title); return url && { name: `${view.id}.jpg`, url }; });
  return { busy, fromFile, fromCamera };
}
const PHOTO_TYPES = 'image/jpeg,image/png,image/webp,image/heic,image/heif';
// One evidence view as a slot on the seller's upload page.
function PhotoSlot({ view, photo, onChange, onError }) {
  const { busy, fromFile, fromCamera } = usePhotoPick(view, onChange, onError);
  return <div className="upload-preview">{photo ? <><img src={photo.url} alt={`${view.title}: uploaded evidence`}/><span className="slot-done" aria-hidden="true"><Check size={12} strokeWidth={2.4}/></span><button type="button" className="remove-photo" aria-label={`Remove ${view.title} image`} onClick={() => onChange(null)}><X size={15}/></button></> : isNative
    ? <button type="button" className="upload-target" aria-label={`Add ${view.title} photo`} onClick={fromCamera} disabled={busy}><Camera size={25} strokeWidth={1.3}/><span>{busy ? 'Preparing…' : 'Add photo'}</span></button>
    : <label className="upload-target"><ImagePlus size={25} strokeWidth={1.3}/><span>{busy ? 'Preparing…' : 'Add photo'}</span><input type="file" aria-label={`Upload ${view.title}`} accept={PHOTO_TYPES} disabled={busy} onChange={e => { fromFile(e.target.files[0]); e.target.value = ''; }}/></label>}</div>;
}
// One of the six shots (the manual check, and a listing added by hand): a square linen tile that is the whole target
// for choosing the photo, with the shot's name under it. Filled, it shows the photo with a check; on the manual check
// it says Added and offers to remove it, and on a saved listing the tile opens the photo.
function ShotTile({ view, photo, onChange, onError, onTouch, onOpen }) {
  const { busy, fromFile, fromCamera } = usePhotoPick(view, onChange, onError);
  const face = photo ? <><img src={photo.url} alt={onOpen ? '' : `${view.title}: uploaded evidence`}/><span className="shot-check" aria-hidden="true"><CheckIcon size={13}/></span></>
    : busy ? <TickSpinner size={20} label="Preparing the photo"/> : <span className="shot-plus" aria-hidden="true"><Plus size={28} strokeWidth={1.5}/></span>;
  return <li className={`shot${photo ? ' filled' : ''}`} onFocus={onTouch} onPointerDown={onTouch}>
    {photo ? (onOpen ? <button type="button" className="shot-tile" aria-label={`Open ${view.title}`} onClick={onOpen}>{face}</button> : <span className="shot-tile">{face}</span>) : isNative
      ? <button type="button" className="shot-tile" aria-label={`Add ${view.title} photo`} onClick={fromCamera} disabled={busy}>{face}</button>
      : <label className="shot-tile">{face}<input type="file" aria-label={`Upload ${view.title}`} accept={PHOTO_TYPES} disabled={busy} onChange={e => { fromFile(e.target.files[0]); e.target.value = ''; }}/></label>}
    <span className="shot-name">{view.title}</span>
    {photo && !onOpen && <span className="shot-state">Added<button type="button" className="shot-remove" aria-label={`Remove ${view.title} image`} onClick={() => onChange(null)}>Remove</button></span>}
  </li>;
}
// A form in the platform's grammar: named sections of white rows on the canvas. A row carries its label at the leading
// edge and its control fills the rest.
function FormSection({ name, note, className = '', children }) {
  return <section className={`form-section ${className}`}>{name && <h3 className="form-section-name">{name}</h3>}<div className="form-rows">{children}</div>{note && <p className="ios-footnote">{note}</p>}</section>;
}
function FormRow({ label, prefix, children }) {
  return <label className="form-row"><span className="form-row-label">{label}</span><span className="form-row-field">{prefix && <span className="form-row-prefix" aria-hidden="true">{prefix}</span>}{children}</span></label>;
}
// A money field. What it holds is the plain number, exactly as it was typed or given (so the caret never moves under
// the finger); while the field is not being edited the figure is shown over it grouped in thousands.
const plainDigits = text => String(text ?? '').replace(/[,$\s]/g, '');
const groupDigits = value => { const n = parsePrice(plainDigits(value)); return n === null ? String(value ?? '') : n.toLocaleString('en-US', { maximumFractionDigits: 2 }); };
function MoneyInput({ value, onChange, ...rest }) {
  const text = String(value ?? '');
  return <span className="money-field"><input type="text" inputMode="decimal" {...rest} value={text} onChange={e => onChange(plainDigits(e.target.value))}/>{text && <span className="money-shown num" aria-hidden="true">{groupDigits(text)}</span>}</span>;
}
// A one-line field that takes more lines when its value needs them: a watch's full name often does. It stays one
// paragraph, and Return sends the form as it does from any other row. Where the browser cannot size a field to its
// content by rule, the height is set from what it holds, again whenever the field is laid out (a sheet opening).
const sizesToContent = typeof CSS !== 'undefined' && CSS.supports?.('field-sizing', 'content');
// multiline (a note): Return starts a new line instead of sending the form.
function GrowingInput({ value, onChange, multiline = false, ...rest }) {
  const el = useRef(null);
  useLayoutEffect(() => {
    const t = el.current; if (!t || sizesToContent) return undefined;
    const fit = () => { t.style.height = 'auto'; t.style.height = `${t.scrollHeight}px`; };
    fit(); const watch = new ResizeObserver(fit); watch.observe(t); return () => watch.disconnect();
  }, [value]);
  if (multiline) return <textarea ref={el} rows="2" className="form-grow" {...rest} value={value} onChange={onChange}/>;
  return <textarea ref={el} rows="1" className="form-grow" {...rest} value={value} onChange={e => { if (/\n/.test(e.target.value)) e.target.value = e.target.value.replace(/\s*\n\s*/g, ' '); onChange(e); }} onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); e.currentTarget.form?.requestSubmit(); } }}/>;
}
// Add your own photos: one page. The listing's link (which can bring in its first photo, title and price), six shots,
// what the seller claims, and notes. Its save sits in a docked bar that says how many photos there are so far.
function CheckPage({ onSave, back, seed = {} }) {
  const [form, setForm] = useState({ model: seed.model || '', reference: seed.reference || '', year: '', price: '', url: seed.url || '', description: '' });
  // Each error sits under its own field: the link (fetching), the model (required) and the photos (unreadable files).
  const [photos, setPhotos] = useState({}); const [errors, setErrors] = useState({}); const [saving, setSaving] = useState(false);
  const setError = (key, message) => setErrors(e => ({ ...e, [key]: message }));
  const errorProps = key => (errors[key] ? { 'aria-invalid': true, 'aria-describedby': `check-err-${key}` } : {});
  const errorLine = key => errors[key] && <FormError id={`check-err-${key}`} className="field-error">{errors[key]}</FormError>;
  const set = (name, value) => { setForm(f => ({ ...f, [name]: value })); if (name === 'model' && errors.model) setError('model', ''); };
  const field = name => ({ value: form[name], onChange: e => set(name, e.target.value) });
  function setPhoto(id, photo) { setPhotos(p => { const next = { ...p }; if (photo) next[id] = photo; else delete next[id]; return next; }); }
  async function submit(e) {
    e.preventDefault();
    if (!form.model.trim()) { setError('model', 'Enter a watch model.'); notify('error'); const input = document.getElementById('check-model'); input?.scrollIntoView({ block: 'center', behavior: reduceMotion() ? 'auto' : 'smooth' }); input?.focus({ preventScroll: true }); return; }
    setSaving(true); try { await onSave({ ...form, model: form.model.trim(), photos: cover ? { ...photos, cover } : photos, checks: emptyChecks(), comps: [] }); } finally { setSaving(false); }
  }
  const [cover, setCover] = useState(null); const [fetching, setFetching] = useState(false); const [preview, setPreview] = useState(null);
  async function fetchListing() {
    setFetching(true); setError('url', '');
    try {
      const result = await fetchListingPreview(form.url.trim());
      const photo = await listingCover(result);
      const guess = guessFromTitle(result.title || '');
      setPreview(result); setCover(photo);
      if (photo && !photos.dial) setPhoto('dial', photo);
      setForm(f => ({ ...f, url: result.url || f.url, model: guess.model || f.model, reference: f.reference || guess.reference || '', price: f.price || (result.price && (!result.currency || result.currency === 'USD') ? String(result.price) : ''), description: f.description || [result.title, result.site && `Listed on ${result.site}`].filter(Boolean).join('\n') }));
      if (!photo) setError('url', 'The listing has no photo wabi could fetch. Save its first photo and add it below.');
    } catch (e) { setError('url', e.message); notify('error'); } finally { setFetching(false); }
  }
  // The capsule in the field pastes while the field is empty, and fetches once it holds a link.
  async function paste() {
    let text = ''; try { text = (await navigator.clipboard.readText()).trim(); } catch { /* no clipboard access: the field takes the focus instead */ }
    if (text) { tap('light'); set('url', text); } else document.getElementById('check-url')?.focus();
  }
  // The hint under the grid belongs to the shot that was touched last.
  const [touched, setTouched] = useState(VIEWS[0].id); const hint = VIEWS.find(v => v.id === touched);
  const supplied = Math.min(VIEWS.length, VIEWS.filter(v => photos[v.id]).length);
  const hasLink = form.url.trim() !== '';
  return <><PageHead back={back} title="Add your own photos"/>
    <form id="check-form" className="manual" onSubmit={submit} noValidate>
      <section className="manual-part">
        <h2 className="manual-head"><label htmlFor="check-url">{listingPreviewAvailable ? 'Listing link' : 'Listing URL'}</label></h2>
        <div className="link-box"><input id="check-url" type="url" inputMode="url" autoCapitalize="off" autoCorrect="off" spellCheck="false" placeholder="Paste the listing’s link" {...field('url')} {...errorProps('url')} onKeyDown={e => { if (e.key === 'Enter' && listingPreviewAvailable && hasLink) { e.preventDefault(); fetchListing(); } }}/>
          {listingPreviewAvailable && hasLink ? <button type="button" className="link-capsule" aria-label="Fetch listing" aria-busy={fetching || undefined} onClick={fetchListing} disabled={fetching}>{fetching ? <TickSpinner size={16}/> : 'Fetch'}</button>
            : !hasLink && navigator.clipboard?.readText ? <button type="button" className="link-capsule" aria-label="Paste link" onClick={paste}>Paste</button> : null}</div>
        {errorLine('url')}
        {(cover || preview) && <div className="listing-preview"><PhotoTile src={cover?.url} alt={cover ? 'First photo of the listing' : ''} size={64}/><div><b>{preview?.title || 'Listing'}</b><span className="num">{[preview?.site, preview?.price && (!preview.currency || preview.currency === 'USD' ? money(preview.price) : `${preview.currency} ${preview.price.toLocaleString()}`)].filter(Boolean).join(' · ')}</span>{cover && <small>Its first photo is also the dial photo.</small>}</div></div>}
        {!(cover || preview) && !errors.url && listingPreviewAvailable && <p className="ios-footnote">Brings in the listing’s first photo, title and price. Nothing is verified yet.</p>}
      </section>
      <section className="manual-part">
        <h2 className="manual-head">Photos</h2>
        {errorLine('photo')}
        <ol className="shots">{VIEWS.map(v => <ShotTile key={v.id} view={v} photo={photos[v.id]} onChange={p => setPhoto(v.id, p)} onError={m => setError('photo', m)} onTouch={() => setTouched(v.id)}/>)}</ol>
        <p className="shot-hint"><b>{hint.title}.</b> {hint.hint}</p>
        <p className="ios-footnote manual-privacy">{analysisAvailable ? 'Photos stay on this device until you run a review.' : 'Photos stay on this device.'}</p>
      </section>
      <section className="manual-part">
        <h2 className="manual-head">The watch</h2>
        <div className="form-rows">
          <FormRow label="Claimed model"><GrowingInput id="check-model" required maxLength={100} placeholder="Rolex Submariner" {...field('model')} {...errorProps('model')}/></FormRow>
          <FormRow label="Claimed reference"><input placeholder="116610LN" maxLength={40} autoCapitalize="characters" autoCorrect="off" {...field('reference')}/></FormRow>
          <FormRow label="Claimed year"><input placeholder="1978" type="text" inputMode="numeric" maxLength={4} {...field('year')}/></FormRow>
          <FormRow label="Asking price" prefix="$"><MoneyInput aria-label="Asking price · USD" placeholder="9,500" value={form.price} onChange={v => set('price', v)}/></FormRow>
        </div>
        {errorLine('model')}
        <p className="ios-footnote">As the seller describes it.</p>
      </section>
      <section className="manual-part">
        <h2 className="manual-head">Notes</h2>
        <div className="form-rows"><textarea className="form-notes" aria-label="Seller’s description and your notes" rows="3" placeholder="Dial, service history, replacement parts…" maxLength={10000} {...field('description')}/></div>
      </section>
    </form>
    <div className="dock-bar"><p className="dock-note" role="status">{supplied} of {VIEWS.length} photos. You can add more later.</p><Button type="submit" form="check-form" disabled={saving}><Working on={saving}>Save listing</Working></Button></div></>;
}

// Score, verdict and kind for a Listings row. Scanned listings use the report; a listing added by hand uses its photo review.
const RATING_KIND = { no_major_concerns_seen: 'pass', some_concerns: 'inspect', significant_concerns: 'fail' };
function listingVerdict(a) {
  if (a.scan) { const r = buildReport(a); return { score: r.score, kind: r.kind, label: r.verdict, free: a.scan.tier === 'mini' && Boolean(r.kind) }; }
  const kind = RATING_KIND[a.analysis?.overall.rating] || null;
  return { score: null, kind, label: kind ? VERDICTS[kind] : a.analysis ? 'Not enough to judge' : 'Not reviewed' };
}
// The one confirmation for deleting a listing, wherever it is asked for: it names the listing and shows its photo.
const listingLine = a => { const ask = parsePrice(a.price ?? ''); return [a.reference && `Ref. ${a.reference}`, ask ? money(ask) : null].filter(Boolean).join(' · '); };
function DeleteListing({ record, onDelete, onClose }) {
  return <ActionSheet title="Delete this listing?" message="This removes its photos and notes from this device, and removes it from your account if it’s saved there. Watches in your collection are kept."
    header={{ thumb: coverOf(record)?.url || <DialGlyph/>, name: record.model, line: listingLine(record) }}
    actions={[{ label: 'Delete listing', destructive: true, onSelect: onDelete }]} cancel="Keep it" onClose={onClose}/>;
}
// Rows that change place (a filter, a sort) slide to where they now belong: each has its own name for the View
// Transition, which it carries only while one of these runs.
function reflow(update) {
  if (!document.startViewTransition || reduceMotion()) { update(); return; }
  const root = document.documentElement; const run = ++navRun; root.dataset.nav = 'reflow';
  document.startViewTransition(() => flushSync(update)).finished.finally(() => { if (run === navRun) delete root.dataset.nav; });
}
// The same for a change that is saved first (a delete): the list as a whole slides to its new place once the page
// has caught up with it.
function shift(update, caughtUp) {
  if (!document.startViewTransition) return update().finally(caughtUp);
  const root = document.documentElement; const run = ++navRun; root.dataset.nav = 'shift';
  return document.startViewTransition(() => update().finally(() => flushSync(caughtUp))).finished.finally(() => { if (run === navRun) delete root.dataset.nav; });
}
const SORTS = [{ id: 'new', label: 'Newest' }, { id: 'price', label: 'Price low to high' }, { id: 'score', label: 'Score low to high' }];
const lowFirst = pick => (x, y) => (pick(x) ?? Infinity) - (pick(y) ?? Infinity);
const SORT_BY = { price: lowFirst(r => parsePrice(r.a.price ?? '') || null), score: lowFirst(r => r.v.score) };
const MinusDisc = () => <svg width="22" height="22" viewBox="0 0 22 22" aria-hidden="true"><circle cx="11" cy="11" r="11" fill="currentColor"/><path d="M6 11h10" fill="none" style={{ stroke: 'var(--canvas)' }} strokeWidth="2" strokeLinecap="round"/></svg>;
const DownMark = () => <svg className="trend-mark" width="9" height="9" viewBox="0 0 9 9" aria-hidden="true" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M4.5 1v7M1.5 5l3 3 3-3"/></svg>;
const UpMark = () => <svg className="trend-mark" width="9" height="9" viewBox="0 0 9 9" aria-hidden="true" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M4.5 8V1M1.5 4l3-3 3 3"/></svg>;
// One listing in the ledger: its photo, name, price and where it is from, the verdict in a mark and one word of the
// shared vocabulary (the row's spoken name keeps the report's own wording), and its score on a twelve-index dial. A
// free check says so in a chip, which gives its place to a change since the listing was last opened. A tap lifts the
// row into its report. It can be deleted by a swipe, from its menu (a long press or a right click), or with Edit,
// which uncovers a button for it.
function ListingRow({ a, v, editing, fresh, leaving, open, onEdit, onDelete }) {
  const listed = parsePrice(a.price ?? ''); const badge = a.watch?.unseen && watchBadge(a.watch.history?.[0]);
  // A watched listing shows the price it had when it was last read; the price it was checked at follows, struck out.
  const seen = a.watch?.last; const ask = seen?.price && (seen.currency || 'USD') === 'USD' ? seen.price : listed; const was = listed && ask !== listed ? listed : null;
  const source = a.scan ? siteName(a.scan.site || sourceOf(a.url)) : sourceOf(a.url) || 'Added by hand';
  const cover = coverOf(a)?.url; const when = shortDate(a.scanned || a.created);
  const item = useRef(null);
  const lift = () => { if (item.current) item.current.dataset.lifting = ''; open(a.id, 'lift'); };
  const { bind, menu } = useContextMenu({ label: `${a.model}, actions`, disabled: editing, items: [
    { label: 'Open report', icon: <FileText size={17} strokeWidth={1.6}/>, onSelect: lift },
    { label: 'Edit details', icon: <Pencil size={17} strokeWidth={1.6}/>, onSelect: onEdit },
    a.url && { label: `Open on ${siteName(sourceOf(a.url)) || 'the web'}`, icon: <ArrowUpRight size={17} strokeWidth={1.6}/>, onSelect: () => window.open(a.url, '_blank', 'noopener,noreferrer') },
    { label: 'Delete listing', icon: <Trash2 size={17} strokeWidth={1.6}/>, destructive: true, onSelect: onDelete },
  ].filter(Boolean) });
  return <li ref={item} className={`assessment-card${fresh ? ' is-new' : ''}${leaving ? ' is-leaving' : ''}`} data-pass-id={a.id} style={{ '--vt': `lr-${String(a.id).replace(/[^\w-]/g, '_')}` }}><div className="ledger-row">
    <button type="button" className="row-minus" inert={!editing} aria-label={`Delete listing ${a.model}`} onClick={onDelete}><MinusDisc/></button>
    <SwipeRow disabled={editing} action={{ label: 'Delete', icon: <Trash2 strokeWidth={1.6}/>, ariaLabel: `Delete ${a.model}`, onAction: onDelete }}>
      <button type="button" className="list-row" {...bind} onClick={lift} aria-label={[a.model, v.score != null && `score ${v.score}`, v.label, v.free && 'free check', ask ? money(ask) : 'no price', source, when].filter(Boolean).join(', ')}>
        <PhotoTile src={cover} size={64} className="row-thumb"/>
        <span className="lrow-main">
          <span className="lrow-name">{a.model}</span>
          <span className="lrow-line"><span className="lrow-price num">{ask ? money(ask) : 'No price'}</span>{was && <s className="lrow-was num"><span className="sr-only">was </span>{money(was)}</s>}<span className="row-source num">{[a.reference ? `Ref. ${a.reference}` : null, source, when].filter(Boolean).map((part, i) => <span key={i}> · {part}</span>)}</span></span>
          <span className="lrow-verdict"><Verdict kind={v.kind}>{WORD[v.kind] || v.label}</Verdict>{v.free && !badge && <span className="lrow-tag">Free check</span>}{badge && <span className="row-pills">{badge.label === 'Price dropped' ? <DownMark/> : badge.label === 'Price up' ? <UpMark/> : null}{badge.label}</span>}</span>
        </span>
        <span className="lrow-score"><TickDial score={v.score} kind={v.kind}/></span>
      </button>
    </SwipeRow>
  </div>{menu}</li>;
}
function ListingsPage({ records, open, add, remove, refresh, onSave, syncing = false }) {
  const [deleting, setDeleting] = useState(null); const [filter, setFilter] = useState('all'); const [sort, setSort] = useState('new');
  const [editing, setEditing] = useState(false); const [details, setDetails] = useState(null); const [leaving, setLeaving] = useState(null);
  const rows = records.map(a => ({ a, v: listingVerdict(a) }));
  const needs = rows.filter(r => r.v.kind === 'inspect' || r.v.kind === 'fail');
  // The filter only appears from three listings; below that (after a delete, say) every listing shows.
  const filtering = records.length >= 3;
  const kept = filtering && filter === 'look' ? needs : rows;
  const shown = SORT_BY[sort] ? [...kept].sort(SORT_BY[sort]) : kept;
  const summary = records.length && !filtering ? `${count(records.length, 'listing')}${needs.length ? ` · ${needs.length} ${needs.length === 1 ? 'needs' : 'need'} a look` : ''}` : '';
  // A listing that arrives while the page is open (a scan brought in from the account) fades in; the ones the page
  // opened with are simply there.
  const first = useRef(null); first.current ??= new Set(records.map(r => r.id)); const born = useRef(new Map()).current;
  const isNew = id => { if (first.current.has(id)) return false; if (!born.has(id)) born.set(id, Date.now()); return Date.now() - born.get(id) < 600; };
  useEffect(() => { if (!records.length) setEditing(false); }, [records.length]);
  const ptr = usePullToRefresh(refresh, { enabled: Boolean(refresh) && records.some(r => r.watch?.on), label: 'Checking prices' });
  const sortMenu = useContextMenu({ label: 'Sort listings', items: SORTS.map(s => ({ label: s.label, icon: sort === s.id ? <CheckIcon size={15}/> : null, onSelect: () => reflow(() => setSort(s.id)) })) });
  // The row closes up first, the rest slide into its place, then it is gone and the banner says so.
  function erase(id) {
    if (reduceMotion()) { remove(id); return; }
    // From three listings to two the filter gives its place to the count line, so the list slides up to it.
    const gone = () => Promise.resolve(remove(id)); const settled = () => setLeaving(null); const header = records.length === 3;
    setLeaving(id); setTimeout(() => (header ? shift(gone, settled) : gone().finally(settled)), cssMs('--t-collapse', 280));
  }
  // The add action stays in the bar when the list is empty, beside the empty state's own button.
  useNavBar({ title: 'Listings', leading: records.length > 0 && <NavAction strong={editing} onClick={() => setEditing(e => !e)}>{editing ? 'Done' : 'Edit'}</NavAction>,
    trailing: <>{records.length > 1 && <NavAction label="Sort listings" onClick={e => sortMenu.show(e.currentTarget)}><ArrowUpDown strokeWidth={1.6}/></NavAction>}<NavAction label="Check a new listing" onClick={add}><PlusIcon/></NavAction></> });
  return <div className="listings-page">
    <header className="screen-head">{ptr.indicator}{ptr.refreshing && <p className="ptr-note" role="status">Checking prices…</p>}<LargeTitle>Listings</LargeTitle>{summary && <p className="screen-count">{summary}</p>}</header>
    {records.length > 0 ? <>
      {filtering && <Segmented className="ledger-filter" label="Filter listings" options={[{ value: 'all', label: 'All', count: rows.length }, { value: 'look', label: 'Needs a look', count: needs.length }]} value={filter} onChange={id => reflow(() => setFilter(id))}/>}
      {shown.length ? <ul className={`listings ledger${editing ? ' editing' : ''}`}>{shown.map(({ a, v }) => <ListingRow key={a.id} a={a} v={v} editing={editing} fresh={isNew(a.id)} leaving={leaving === a.id} open={open} onEdit={() => setDetails(a.id)} onDelete={() => setDeleting(a)}/>)}</ul>
        : <EmptyState art={<span className="empty-mark tone-pass"><VerdictMark kind="pass" size={28}/></span>} title="All clear." body="Nothing needs a closer look."><button type="button" className="text-button" onClick={() => reflow(() => setFilter('all'))}>All listings</button></EmptyState>}
    </> : syncing ? <SkeletonRows className="ledger-skel" count={3} thumb={64} value label="Loading your listings"/>
      : <PageEmpty art={<EditorialArt name="loupe-dial" night="loupe-felt-night"/>} title="Your checked listings live here" body="Listings you check show up here, with their score and what to ask the seller."><Button onClick={add}>Check a listing</Button></PageEmpty>}
    {sortMenu.menu}
    {details && records.some(r => r.id === details) && <ListingModal record={records.find(r => r.id === details)} onSave={onSave} close={() => setDetails(null)}/>}
    {deleting && <DeleteListing record={deleting} onDelete={() => erase(deleting.id)} onClose={() => setDeleting(null)}/>}
  </div>;
}
const CONSENT_KEY = 'wabi-ai-consent-v1';
function hasConsent() { try { return localStorage.getItem(CONSENT_KEY) === 'yes'; } catch { return false; } }
function setConsent(value) { try { if (value) localStorage.setItem(CONSENT_KEY, 'yes'); else localStorage.removeItem(CONSENT_KEY); } catch { /* asked again next time */ } }
const photoIds = photos => Object.values(photos).map(p => p.id).sort().join(',');
// identify: the same permission asked by Identify from photos, which sends only the photos chosen.
function ConsentModal({ accept, close, identify = false }) {
  return <Modal title="Send these photos for review?" close={close}><p>wabi sends these photos and the details you entered to its review service. Nothing is kept on wabi’s servers; the review is saved only on this device.</p><ul className="consent-list"><li>{identify ? 'Nothing is sent unless you allow it.' : 'Nothing is sent unless you tap Review photos.'}</li><li>Avoid photographing documents that show your name, address or full serial numbers.</li></ul><p className="small"><a href={PRIVACY_URL} target="_blank" rel="noopener noreferrer">Privacy policy</a></p><div className="modal-actions"><button className="button secondary" onClick={close}>Not now</button><button className="button primary" onClick={accept}>{identify ? 'Allow and identify' : 'Allow and review'} <ArrowRight size={16}/></button></div></Modal>;
}
function AnalysisSummary({ analysis, stale }) {
  const rating = RATINGS[analysis.overall.rating]; const id = analysis.identification;
  const kind = RATING_KIND[analysis.overall.rating] || null;
  return <><Verdict kind={kind}>{WORD[kind] || WORD.none}</Verdict><h2>{VERDICTS[kind] || rating.label}</h2><p className="summary-id">{id.brand} {id.model}{id.reference_candidates[0] ? ` · ref. ${id.reference_candidates[0].reference}` : ''}</p><p>{analysis.overall.summary}</p><p className="small">Identification confidence: {id.confidence} · {id.production_era || 'era unclear'}{stale ? ' · Photos changed since this review; run it again.' : ''}</p></>;
}
// What a review of the buyer's own photos found, as groups: what the watch is, what stood out, and each known marker
// that could be checked.
// How the seller's claim matches the photos, as a verdict mark and its word.
const CLAIM_MATCH = { consistent: 'pass', partly_consistent: 'inspect', inconsistent: 'fail', cannot_tell: null };
function AnalysisDetails({ analysis }) {
  const id = analysis.identification;
  return <div className="ai-panel">
    <section className="detail-group">
      <div className="ios-section"><h2>What the photos suggest</h2></div>
      <dl className="spec-list">
        <div className="spec-row"><dt>Identified as</dt><dd>{[id.brand, id.model].filter(Boolean).join(' ')}{id.dial_variant ? `, ${id.dial_variant.toLowerCase()}` : ''}</dd></div>
        <div className="spec-row"><dt>Seller’s claim</dt><dd><Verdict kind={CLAIM_MATCH[id.seller_claim_match] || null}/></dd></div>
        {id.reference_candidates.map(r => <div className="spec-row" key={r.reference}><dt>Ref. {r.reference}<span className="spec-sub">{r.rationale}</span></dt></div>)}
      </dl>
      {id.notes && <p className="ios-footnote">{id.notes}</p>}
      <p className="ios-footnote">Reviewed {shortDate(analysis.analyzedAt)}, from your photos and the seller’s claims. Not a certificate of authenticity.</p>
    </section>
    <section className="detail-group">
      <div className="ios-section"><h2>Flags</h2></div>
      {analysis.red_flags.length ? <ul className="flag-list glist">{analysis.red_flags.map((f, i) => <li key={i} className="grow static"><span className="error-mark" aria-hidden="true"><VerdictMark kind="fail" size={10}/></span><span className="grow-main"><span className="grow-title">{f}</span></span></li>)}</ul> : <p className="note-cell">None seen in the supplied photos.</p>}
    </section>
    <LibraryNote brand={id.brand}/>
    {analysis.knowledge_checks && <KnowledgeChecks checks={analysis.knowledge_checks} considered={analysis.knowledgeClaimsConsidered}/>}</div>;
}
// Said plainly when the counterfeit library has nothing for the watch's brand, so no review reads as more checked than it is.
function LibraryNote({ brand }) {
  const [claims] = useClaims();
  const name = brand && (detectBrand(brand) || brand);
  if (!claims || !name || claims.some(c => c.brand === name)) return null;
  return <p className="library-note" role="note"><Info size={15}/><span>wabi’s counterfeit library for {name} is still being built, so this review leans on general watch knowledge. Have a watchmaker inspect it before you pay.</span></p>;
}
const CHECK_RESULTS = { contradicts: 'fail', consistent: 'pass', not_visible: null };
function KnowledgeChecks({ checks, considered }) {
  const order = ['contradicts', 'consistent', 'not_visible'];
  const sorted = [...checks].sort((a, b) => order.indexOf(a.result) - order.indexOf(b.result) || (a.weight === 'strong' ? -1 : 0) - (b.weight === 'strong' ? -1 : 0));
  return <section className="detail-group knowledge-checks">
    <div className="ios-section"><h2>Known tells checked</h2></div>
    <div className="glist">{sorted.map(k => <article key={k.claim_id} className={`grow static marker marker-${k.result}`}><span className="grow-main"><span className="marker-heading"><Verdict kind={CHECK_RESULTS[k.result]}>{WORD[CHECK_RESULTS[k.result]] || WORD.none}</Verdict>{k.weight === 'strong' && <span className="marker-weight">Strong sign</span>}</span><span className="grow-title marker-observation">{k.observation}</span><span className="grow-sub">Genuine: {k.claim}{k.result === 'contradicts' && k.counterfeitSign ? ` Fakes often: ${k.counterfeitSign}` : ''}</span></span></article>)}</div>
    <p className="ios-footnote">{checks.length} of {considered ?? checks.length} tells for this model could be checked in these photos.</p>
  </section>;
}
// A saved free review: its score, with the same paywall to unlock the full report for that listing.
function MiniReport({ record, wallet, refreshWallet, onUpgraded }) {
  const [unlocking, setUnlocking] = useState(false); const [error, setError] = useState(''); const [elapsed, setElapsed] = useState(0);
  useEffect(() => { if (!unlocking) return; const start = Date.now(); const t = setInterval(() => setElapsed(Math.round((Date.now() - start) / 1000)), 1000); return () => clearInterval(t); }, [unlocking]);
  const sc = record.scan;
  const mini = { identification: sc.identification || { brand: '', model: record.model, reference: record.reference }, score: sc.score, headline: sc.headline, redFlagCount: sc.redFlagCount || 0, listing: { images: sc.images, scannedImages: sc.scannedImages, url: record.url } };
  async function unlock() {
    setError(''); setElapsed(0); setUnlocking(true);
    try { const full = await scanListing(record.url); await onUpgraded(record.id, await recordFromScan(full)); notify('success'); }
    catch (e) { setError(e.message); notify('error'); } finally { setUnlocking(false); refreshWallet(); }
  }
  return <LockedReport wallet={wallet} refreshWallet={refreshWallet} onUnlock={unlock} unlocking={unlocking} elapsed={elapsed} error={error}/>;
}
// On a scanned listing the dashboard is the report; the buyer's own notes and comparable sales sit behind one row.
// Watch: wabi re-reads the listing twice a day while the app is used and notes what changed.
const WATCH_LABELS = { ended: 'Ended', photos: 'Photos changed', title: 'Title changed' };
const watchBadge = c => c && { label: c.kind === 'price' ? (c.down ? 'Price dropped' : 'Price up') : WATCH_LABELS[c.kind], tone: c.kind === 'ended' ? 'red' : c.kind === 'price' && c.down ? 'pos' : 'sand' };
// A row that does something, in a group under a listing: an icon tile, its name in the tint, and a tick spinner in
// place of the chevron while it works.
function ActionRow({ icon, title, sub, onClick, busy = false, disabled = false, tint = false, external = false }) {
  return <button type="button" className={`grow${tint ? ' tint-row' : ''}`} onClick={onClick} disabled={disabled || busy} aria-busy={busy || undefined}>{icon && <IconTile>{icon}</IconTile>}<span className="grow-main"><span className="grow-title">{title}</span>{sub && <span className="grow-sub">{sub}</span>}</span>{busy ? <TickSpinner size={16}/> : tint ? null : external ? <ArrowOut/> : <Chevron/>}</button>;
}
function WatchCard({ record, onSave, check }) {
  const w = record.watch; const [busy, setBusy] = useState(false);
  // Opening the listing counts as seeing its changes.
  useEffect(() => { if (w?.unseen) onSave({ ...record, watch: { ...w, unseen: false } }, ''); }, []); // eslint-disable-line react-hooks/exhaustive-deps
  async function run() { setBusy(true); try { await check(); } finally { setBusy(false); } }
  async function toggle() {
    tap('light');
    if (w?.on) { await onSave({ ...record, watch: { ...w, on: false } }, 'Stopped watching this listing'); return; }
    await onSave({ ...record, watch: { on: true, since: new Date().toISOString(), last: w?.last || null, history: w?.history || [], unseen: false } }, 'Watching this listing');
    run();
  }
  const time = iso => new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }).format(new Date(iso));
  return <section className="watch-card detail-group">
    <div className="ios-section"><h2>{w?.on ? 'Watching this listing' : 'Keep an eye on it'}</h2></div>
    <div className="glist">
      <div className="grow static"><span className="grow-main"><span className="grow-title" aria-hidden="true">Watch this listing</span></span><button type="button" className={`switch${w?.on ? ' on' : ''}`} aria-pressed={Boolean(w?.on)} aria-label="Watch this listing" onClick={toggle}><span className="switch-knob"/></button></div>
      {w?.on && <div className="grow static"><span className="grow-main"><span className="grow-title">Last checked</span></span><span className="grow-value num">{w.last ? time(w.last.checkedAt) : 'Checking now…'}</span></div>}
      {w?.on && <ActionRow tint title="Check now" onClick={run} busy={busy}/>}
    </div>
    <p className="ios-footnote">Price, photos or sold. Checked when you open wabi.</p>
    {w?.history?.length > 0 && <ul className="watch-history glist">{w.history.map((c, i) => <li key={`${c.at}${i}`} className="grow static"><span className="grow-main"><span className="grow-title">{c.text}</span><span className="grow-sub num">{shortDate(c.at)}</span></span></li>)}</ul>}
  </section>;
}
// Optional: when the listing's photos don't show enough, the buyer can ask the seller for specific views through a
// private link. Nothing here is needed for a check; the listing alone is always enough to scan.
const SELLER_VIEWS = ['case', 'bracelet', 'movement', 'documents'];
const viewTitle = id => VIEWS.find(v => v.id === id).title;
function sellerMessage(record, token, views) {
  return `Hi, I’m interested in your ${record.model || 'watch'}. Before I decide, could you add a few photos here? ${requestLink(token)}\n\nIt asks for: ${views.map(v => viewTitle(v).toLowerCase()).join(', ')}. It takes a couple of minutes and needs no account. Thank you!`;
}
async function shareText(text) {
  if (navigator.share) { try { await navigator.share({ text }); return 'shared'; } catch (e) { if (e?.name === 'AbortError') return ''; } }
  await navigator.clipboard.writeText(text); return 'copied';
}
function SellerPhotos({ record, onSave, review, running, error: reviewError }) {
  const req = record.sellerRequest; const [asking, setAsking] = useState(false); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [note, setNote] = useState('');
  const imported = req?.imported || [];
  async function share() { setError(''); try { const done = await shareText(sellerMessage(record, req.token, req.views)); if (done) setNote(done === 'copied' ? 'Message copied. Paste it to the seller.' : ''); } catch { setError('Couldn’t copy the message. Copy the link instead: ' + requestLink(req.token)); } }
  async function check() {
    setBusy(true); setError(''); setNote('');
    try {
      const { photos } = await fetchRequestPhotos(req);
      const fresh = photos.filter(p => !imported.includes(p.view));
      if (!fresh.length) { setNote(photos.length ? 'No new photos since the last check.' : 'Nothing from the seller yet.'); return; }
      const next = { ...record.photos };
      for (const p of fresh) next[p.view] = { id: crypto.randomUUID(), name: `From the seller · ${viewTitle(p.view)}`, url: `data:${p.mediaType};base64,${p.data}` };
      await onSave({ ...record, photos: next, sellerRequest: { ...req, imported: [...imported, ...fresh.map(p => p.view)] } }, `${count(fresh.length, 'photo')} from the seller added`);
    } catch (e) { setError(e.message); } finally { setBusy(false); }
  }
  const fromSeller = imported.map(v => record.photos[v]).filter(Boolean);
  return <section className="seller-photos detail-group">
    <div className="ios-section"><h2>Photos from the seller</h2></div>
    {fromSeller.length > 0 && <div className="seller-thumbs">{fromSeller.map(p => <img key={p.id} src={p.url} alt={p.name}/>)}</div>}
    <div className="glist">
      {req ? <><ActionRow icon={<Download size={18} strokeWidth={1.6}/>} title="Check for photos" onClick={check} busy={busy}/><ActionRow icon={<Share2 size={18} strokeWidth={1.6}/>} title="Send the message again" onClick={share}/></>
        : <ActionRow icon={<Send size={18} strokeWidth={1.6}/>} title="Ask the seller for photos" onClick={() => setAsking(true)}/>}
      {review && fromSeller.length > 0 && <ActionRow tint title={record.sellerReview ? 'Review them again' : 'Review the seller’s photos'} onClick={review} busy={running}/>}
    </div>
    <p className="ios-footnote">{req ? `Asked ${shortDate(req.createdAt)} for ${req.views.map(v => viewTitle(v).toLowerCase()).join(', ')}. The link works until ${shortDate(req.expiresAt)}.` : 'For a closer look at what listings rarely show, like the clasp, the case back or the movement. They get a private link and need no account.'}</p>
    {!review && fromSeller.length > 0 && <p className="ios-footnote">They’re in this listing’s photos. Review the photos to include them.</p>}
    {note && <p className="ios-footnote" role="status">{note}</p>}{(error || reviewError) && <FormError>{error || reviewError}</FormError>}
    {record.sellerReview && <div className="seller-review"><section className="card report-summary"><AnalysisSummary analysis={record.sellerReview} stale={record.sellerReview.photoIds !== photoIds(record.photos)}/></section><AnalysisDetails analysis={record.sellerReview}/></div>}
    {asking && <AskSellerModal record={record} close={() => setAsking(false)} onCreated={sellerRequest => onSave({ ...record, sellerRequest }, 'Photo request created')}/>}
  </section>;
}
function AskSellerModal({ record, close, onCreated }) {
  const [views, setViews] = useState(SELLER_VIEWS); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [made, setMade] = useState(null); const [note, setNote] = useState('');
  const toggle = id => setViews(v => (v.includes(id) ? v.filter(x => x !== id) : [...v, id]));
  async function create() {
    setBusy(true); setError('');
    try {
      const ordered = VIEWS.map(v => v.id).filter(id => views.includes(id));
      const r = await createPhotoRequest({ listing: { title: record.model || '', url: record.url || '', site: sourceOf(record.url || '') }, views: ordered });
      const sellerRequest = { token: r.token, key: r.key, views: ordered, createdAt: new Date().toISOString(), expiresAt: r.expiresAt, imported: [] };
      setMade(sellerRequest); await onCreated(sellerRequest);
    } catch (e) { setError(e.message); } finally { setBusy(false); }
  }
  async function share() { setError(''); try { const done = await shareText(sellerMessage(record, made.token, made.views)); if (done === 'copied') setNote('Copied. Paste it to the seller.'); } catch { setError('Couldn’t copy. Select the message and copy it.'); } }
  return <Modal title="Ask the seller for photos" close={close}>
    {!made ? <><p>Choose what to ask for. The seller gets a private link to upload them; only you can see what they send, and the link stops working after two weeks.</p>
      <fieldset className="view-picks"><legend className="sr-only">Photos to ask for</legend>{VIEWS.map(v => <label key={v.id} className="view-pick"><input type="checkbox" checked={views.includes(v.id)} onChange={() => toggle(v.id)}/><span><b>{v.title}</b><small>{v.hint}</small></span></label>)}</fieldset>
      <div className="modal-actions"><button className="button primary" onClick={create} disabled={busy || !views.length}>{busy ? <TickSpinner size={16}/> : <Send size={15}/>}Create the link</button></div></>
      : <><p>Send this to the seller through the marketplace’s messages. When they’ve uploaded, tap Check for photos on this listing.</p>
      <textarea className="seller-message" readOnly rows="7" value={sellerMessage(record, made.token, made.views)} onFocus={e => e.target.select()} aria-label="Message to the seller"/>
      <div className="modal-actions"><button className="button primary" onClick={share}><Share2 size={15}/>Share or copy the message</button><button className="button secondary" onClick={close}>Done</button></div>{note && <p className="small" role="status">{note}</p>}</>}
    {error && <FormError>{error}</FormError>}
  </Modal>;
}
// What the seller sees: the listing name, the views the buyer asked for, and an upload slot for each.
function SellerUpload({ token }) {
  const [req, setReq] = useState(null); const [error, setError] = useState(''); const [busy, setBusy] = useState(''); const [sent, setSent] = useState({});
  useEffect(() => { let live = true; getPhotoRequest(token || '').then(r => live && setReq(r)).catch(e => live && setError(e.message)); return () => { live = false; }; }, [token]);
  async function add(view, photo) {
    if (!photo) return;
    setBusy(view); setError('');
    try { setReq(await uploadRequestPhoto(token, view, photo.url)); setSent(s => ({ ...s, [view]: photo })); } catch (e) { setError(e.message); } finally { setBusy(''); }
  }
  const done = req && req.views.every(v => req.received.includes(v));
  return <div className="send-shell"><span className="wordmark">wabi</span>
    {!req && !error && <p className="small" role="status">Loading the request…</p>}
    {!req && error && <><h1>This link isn’t working</h1><p>{error}</p></>}
    {req && <><h1>A buyer asked for a few photos</h1><p className="send-lead">{req.listing.title ? <>Of your <b>{req.listing.title}</b>{req.listing.site ? ` on ${req.listing.site}` : ''}. </> : null}Photos go only to the buyer who sent this link and are deleted on {shortDate(req.expiresAt)}. No account needed.</p>
      <div className="upload-grid">{req.views.map(id => { const v = VIEWS.find(x => x.id === id); const got = req.received.includes(id); return <div className={`upload-card${got ? ' sent' : ''}`} key={id}><PhotoSlot view={v} photo={sent[id] || null} onChange={p => add(id, p)} onError={setError}/><b>{v.title}{got && <span className="sent-mark"><Check size={13}/> Sent</span>}</b><p>{busy === id ? 'Uploading…' : v.hint}</p></div>; })}</div>
      {error && <FormError>{error}</FormError>}
      {done && <p className="send-done" role="status"><CheckCircle2 size={17}/> All sent. Thank you. The buyer can see them now.</p>}</>}
    <p className="small send-foot">wabi helps buyers check pre-owned watches. <a href={PRIVACY_URL} target="_blank" rel="noopener noreferrer">Privacy</a></p>
  </div>;
}
// The hand-made assessment (your own checks, comparable sales, next steps). A scanned listing already has the full
// report, so it isn't shown there; listings you add yourself still use it.
// The buyer's own read of one area, and wabi's finding for it: each a mark and its own words.
// The owner's own observation of a part, in the report's words.
const OWN_CHECK = { unknown: { kind: null, word: WORD.none }, consistent: { kind: 'pass', word: WORD.pass }, replacement: { kind: 'inspect', word: WORD.inspect }, concern: { kind: 'fail', word: WORD.fail } };
const FINDING_KIND = { consistent: 'pass', concern: 'fail', replacement_suspected: 'inspect' };
function NextStep({ icon, title, sub }) {
  return <div className="grow static next-step"><IconTile>{icon}</IconTile><span className="grow-main"><span className="grow-title">{title}</span><span className="grow-sub">{sub}</span></span></div>;
}
function NotesWrap({ scan, children }) {
  return scan ? null : children;
}
function Report({ onToast, record, onSave, onPatch, back, origin, onCollect, onUpgraded, wallet, refreshWallet, checkWatch, remove }) {
  const { askSignIn } = useContext(Account);
  const [tab, setTab] = useState('evidence'); const [checks, setChecks] = useState(record.checks); const [comps, setComps] = useState(record.comps); const [image, setImage] = useState(null); const [saving, setSaving] = useState(false);
  const [running, setRunning] = useState(false); const [analysisError, setAnalysisError] = useState(''); const [askConsent, setAskConsent] = useState(false); const [photoError, setPhotoError] = useState('');
  const analysis = record.analysis; const stale = analysis && analysis.photoIds !== photoIds(record.photos);
  const range = estimateRange(comps); const concerns = Object.values(checks).filter(c => c.status === 'concern').length;
  const aiFinding = id => analysis?.components.find(c => c.area === id);
  const s = spread(record); const marketState = useMarket(record, onPatch); const [editing, setEditing] = useState(false);
  const [fetchingCover, setFetchingCover] = useState(false); const [coverError, setCoverError] = useState(''); const [deleting, setDeleting] = useState(false);
  async function fetchCover() {
    setFetchingCover(true); setCoverError('');
    try { const cover = await listingCover(await fetchListingPreview(record.url)); if (cover) onSave({ ...record, photos: { ...record.photos, cover } }, 'Listing photo added'); else setCoverError('No listing photo was found for this link.'); }
    catch (e) { setCoverError(e.message); } finally { setFetchingCover(false); }
  }
  async function save() { setSaving(true); try { await onSave({ ...record, checks, comps }, 'Review notes saved'); } finally { setSaving(false); } }
  async function run() {
    if (!hasConsent()) { setAskConsent('run'); return; }
    setRunning(true); setAnalysisError('');
    try { const result = await requestAnalysis(record); await onPatch(record.id, { analysis: { ...result, photoIds: photoIds(record.photos) } }, 'Review saved to this listing'); refreshWallet?.(); }
    catch (e) { if (e.signIn) askSignIn(); setAnalysisError(e.message); notify('error'); } finally { setRunning(false); }
  }
  // A scanned listing keeps its scan; a review of the seller's extra photos is saved beside it.
  async function reviewSeller() {
    if (!hasConsent()) { setAskConsent('seller'); return; }
    setRunning(true); setAnalysisError('');
    try { const result = await requestAnalysis(record); await onPatch(record.id, { sellerReview: { ...result, photoIds: photoIds(record.photos) } }, 'Review of the seller’s photos saved'); refreshWallet?.(); }
    catch (e) { if (e.signIn) askSignIn(); setAnalysisError(e.message); notify('error'); } finally { setRunning(false); }
  }
  function addPhoto(view, photo) { const photos = { ...record.photos }; if (photo) photos[view] = photo; else delete photos[view]; onSave({ ...record, photos }, photo ? 'Photo added' : 'Photo removed'); }
  // A listing added by hand is reviewed from its photos: the one action in its bottom bar, with what a review sends
  // said above it.
  const reviewable = analysisAvailable && !record.scan; const noPhotos = !Object.keys(record.photos).length;
  const reviewBar = reviewable && <div className="dock-bar"><p className="dock-note" role={running ? 'status' : undefined}>{running ? 'Usually under a minute. Keep the app open.' : noPhotos ? 'Add a photo to review this watch.' : 'Sends these photos and the details you entered to wabi’s review service. Nothing is kept on its servers.'}</p>
    <Button onClick={run} disabled={running || noPhotos}><Working on={running}>{analysis ? 'Review photos again' : 'Review photos'}{wallet && !wallet.unlimited && wallet.paywall ? ' · 1 scan' : ''}</Working></Button></div>;
  const ask = parsePrice(record.price ?? ''); const val = analysis?.value;
  const compact = n => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', notation: 'compact', maximumFractionDigits: 1 }).format(n);
  const scale = val?.mid ? { min: Math.min(val.low ?? val.mid, ask || Infinity) * 0.92, max: Math.max(val.high ?? val.mid, ask || 0) * 1.08 } : null;
  const scanned = Boolean(record.scan);
  // What can be done with the listing as a whole sits behind the bar's ellipsis; editing it has its own symbol.
  const report = scanned ? buildReport(record, marketState?.market) : null;
  async function share() {
    const text = [`${[report.watch, report.reference && `Ref. ${report.reference}`].filter(Boolean).join(', ')}: wabi score ${report.score}, ${report.verdict}.`, report.summary, record.url, 'An estimate, not a certificate.'].filter(Boolean).join(' ');
    try { if (await shareText(text) === 'copied') onToast('Report copied'); } catch { onToast('Couldn’t share the report. Try again.'); }
  }
  const more = useContextMenu({ label: 'Listing actions', items: [
    report?.score != null && { label: 'Share report', icon: <Share2 size={17} strokeWidth={1.6}/>, onSelect: share },
    record.url && { label: `Open on ${siteName(sourceOf(record.url)) || 'the web'}`, icon: <ArrowUpRight size={17} strokeWidth={1.6}/>, onSelect: () => window.open(record.url, '_blank', 'noopener,noreferrer') },
    { label: 'Add to collection', icon: <Plus size={17} strokeWidth={1.6}/>, onSelect: onCollect },
    { label: 'Delete listing', icon: <Trash2 size={17} strokeWidth={1.6}/>, destructive: true, onSelect: () => setDeleting(true) },
  ].filter(Boolean) });
  // The way back names the tab the listing was opened from. From Listings it keeps the name it has always had.
  const bar = <NavSlots leading={<NavBack label={back.label} ariaLabel={origin === 'listings' ? 'All listings' : undefined} onClick={back.onClick}/>} title={record.model}
    trailing={<><NavAction label="Edit listing details" onClick={() => setEditing(true)}><Pencil strokeWidth={1.6}/></NavAction><NavAction label="More" onClick={e => more.show(e.currentTarget)}><MoreHorizontal strokeWidth={1.6}/></NavAction></>}/>;
  return <>{bar}{!scanned && <><section className="photo-hero">{coverOf(record) ? <img src={coverOf(record).url} alt="The listed watch"/> : <span className="photo-empty"><Camera size={22} strokeWidth={1.5} aria-hidden="true"/>No listing photo yet</span>}{record.url && !record.photos.cover && listingPreviewAvailable && !(record.scan && !record.scan.images?.length) && <button className="photo-fetch" onClick={fetchCover} disabled={fetchingCover}>{fetchingCover ? <TickSpinner size={16}/> : <Link2 size={14}/>} {fetchingCover ? 'Fetching…' : 'Use listing photo'}</button>}{coverError && <p className="photo-fetch-error" role="alert">{coverError}</p>}</section>
    <header className="report-head"><div className="report-head-row" data-nav-track=""><h1>{record.model}</h1></div><p className="report-head-sub">Ref. {record.reference || 'not specified'}{record.year ? ` · ${record.year}` : ''} · Saved {shortDate(record.created)}</p></header></>}
    {more.menu}{editing && <ListingModal record={record} onSave={onSave} close={() => setEditing(false)}/>}
    {deleting && <DeleteListing record={record} onDelete={() => remove(record.id)} onClose={() => setDeleting(false)}/>}
    {scanned && <ReportView onToast={onToast} model={report} images={record.scan.scannedImages || record.scan.images || []} url={record.url} saved locked={!analysis?.details} analysis={analysis?.details ? analysis : undefined}
      free={analysis?.details ? null : { assessable: record.scan.score?.assessable !== false, photos: (record.scan.scannedImages || record.scan.images || []).length, flags: record.scan.redFlagCount || 0 }}
      price={analysis?.details && <PricePanel value={analysis.value} market={marketState} ask={parsePrice(record.price ?? '') || (analysis.listing.currency && analysis.listing.currency !== 'USD' ? null : analysis.listing.asking_price)}/>}
      written={analysis?.details && <ScanResult result={{ analysis, seller: record.scan.seller, reuse: record.scan.reuse, score: record.scan.score, listing: { scannedImages: record.scan.scannedImages || record.scan.images } }} images={record.scan.images}/>}
      onAskPhotos={photoRequestAvailable ? () => document.querySelector('.seller-photos')?.scrollIntoView({ block: 'start', behavior: reduceMotion() ? 'auto' : 'smooth' }) : undefined}>
      {record.scan.tier === 'mini' && record.scan.score?.assessable !== false && <MiniReport record={record} wallet={wallet} refreshWallet={refreshWallet} onUpgraded={onUpgraded}/>}
    </ReportView>}
    {scanned && !analysis?.details && <MarketCard record={record} state={marketState} onEdit={() => setEditing(true)}/>}
    {!scanned && <>
    <section className="card report-summary">{analysis ? <AnalysisSummary analysis={analysis} stale={stale}/> : analysisAvailable ? <><Verdict kind={null}>Not reviewed</Verdict><h2>Review this watch</h2><p>wabi will identify the reference, check the photos for counterfeit tells, list what to ask the seller and estimate the value. It takes about a minute.</p></> : <><Verdict kind={null}>Not reviewed</Verdict><h2>Review not available</h2><p>Record your own observations below.</p></>}
      {analysisError && <FormError>{analysisError}</FormError>}{coverError && <FormError>{coverError}</FormError>}</section>
    <section className="detail-group own-photos">
      <div className="ios-section"><h2>Photos <span className="head-count num">{VIEWS.filter(v => record.photos[v.id]).length} of {VIEWS.length}</span></h2></div>
      <ol className="shots">{VIEWS.map(v => <ShotTile key={v.id} view={v} photo={record.photos[v.id]} onChange={p => addPhoto(v.id, p)} onError={setPhotoError} onOpen={() => setImage({ ...record.photos[v.id], title: v.title })}/>)}</ol>
      {photoError && <FormError>{photoError}</FormError>}
    </section>
    <section className="detail-group">
      <div className="ios-section"><h2>Details</h2></div>
      <dl className="report-stats spec-list">
        <div className="spec-row"><dt>Asking</dt><dd className="num">{ask ? money(ask) : 'Not given'}</dd></div>
        <div className="spec-row"><dt>Estimate{s !== null && <span className="spec-sub num">{percent(s)} asking vs. estimate</span>}</dt><dd className="num">{val?.mid ? money(val.mid) : 'Not estimated yet'}</dd></div>
        <div className="spec-row"><dt>{analysis ? 'Flags' : 'Your concerns'}</dt><dd className="num">{analysis ? analysis.red_flags.length : concerns}</dd></div>
        <div className="spec-row"><dt>Photo coverage</dt><dd className="num">{evidenceCoverage(record.photos)}%</dd></div>
      </dl>
      {scale && <div className="card scale-card"><div className="scale-head"><span className="label">Asking price on the value range</span><b className={s <= 0 ? 'pos' : 'neg'}>{ask ? `${percent(s)} vs. mid` : 'No asking price'}</b></div><TickScale min={scale.min} max={scale.max} marks={[val.low != null && { value: val.low, text: compact(val.low), label: 'Low' }, { value: val.mid, text: compact(val.mid), label: 'Mid' }, val.high != null && { value: val.high, text: compact(val.high), label: 'High' }].filter(Boolean)} thumb={ask ? { value: ask } : null} label={`Asking ${ask ? money(ask) : 'unknown'} against a range of ${money(val.low ?? val.mid)} to ${money(val.high ?? val.mid)}`}/></div>}
    </section>
    <MarketCard record={record} state={marketState} onEdit={() => setEditing(true)}/>
    </>}
    {record.url && listingPreviewAvailable && <WatchCard record={record} onSave={onSave} check={checkWatch}/>}
    {photoRequestAvailable && <SellerPhotos record={record} onSave={onSave} review={record.scan && analysisAvailable ? reviewSeller : null} running={running} error={record.scan ? analysisError : ''}/>}
    <section className="detail-group"><div className="ios-section"><h2>After you buy</h2></div><div className="glist"><ActionRow icon={<TabIcon name="collection"/>} title="Add to collection" onClick={onCollect}/></div></section>
    <NotesWrap scan={scanned}>
    <Segmented tabs className="listing-tabs" label="Listing sections" options={[{ value: 'evidence', label: 'Evidence' }, { value: 'value', label: 'Value estimate' }, { value: 'next', label: 'Next steps' }].map(t => ({ ...t, id: `tab-${t.value}`, controls: t.value === tab ? `panel-${t.value}` : undefined }))} value={tab} onChange={setTab}/>
    <section role="tabpanel" id={`panel-${tab}`} aria-labelledby={`tab-${tab}`} className="tab-panel">
    {tab === 'evidence' && <>{analysis && <AnalysisDetails analysis={analysis}/>}
      <section className="detail-group">
        <div className="ios-section"><h2>The watch, part by part</h2></div>
        <div className="glist review-list">
          {CHECKS.map(c => { const ai = aiFinding(c.id); const mine = OWN_CHECK[checks[c.id].status]; return <details className="review-check" key={c.id} open={checks[c.id].status !== 'unknown' || (ai && ai.finding !== 'consistent') || undefined}>
            <summary><span className="grow-title">{PART_NAMES[c.id]}</span><Verdict kind={mine.kind}>{mine.word}</Verdict><Chevron/></summary>
            <div className="review-body"><p>{c.question}</p>
              {ai && <div className={`ai-finding ${ai.finding}`}><Verdict kind={FINDING_KIND[ai.finding] || null}>{FINDING_LABEL[ai.finding]}</Verdict><p>{ai.observation}</p></div>}
              <div className="form-rows review-own">
                <label className="form-row review-select"><span className="form-row-label">Your observation</span><span className="form-row-field"><select value={checks[c.id].status} onChange={e => setChecks({ ...checks, [c.id]: { ...checks[c.id], status: e.target.value } })}><option value="unknown">Not shown</option><option value="consistent">Looks right</option><option value="concern">Concern or inconsistency</option><option value="replacement">Replacement part</option></select></span></label>
                <label className="form-row review-note"><span className="form-row-label">Notes</span><span className="form-row-field"><GrowingInput multiline value={checks[c.id].note} onChange={e => setChecks({ ...checks, [c.id]: { ...checks[c.id], note: e.target.value } })} placeholder="The specific detail and your source…"/></span></label>
              </div>
              <small>{c.request}</small></div>
          </details>; })}
          <ActionRow tint title="Save review notes" onClick={save} busy={saving} disabled={checks === record.checks}/>
        </div>
        <p className="ios-footnote">{analysis ? 'Findings appear under each area. Your own observations are recorded separately.' : 'Your observations only. “Looks right” is not an expert finding.'}</p>
      </section>
      <section className="detail-group">
        <div className="ios-section"><h2>Listing notes</h2></div>
        <p className="note-cell preserve-text">{record.description || 'No seller description recorded.'}</p>
        {record.url && <ul className="source-rows"><li><a className="source-row" href={record.url} target="_blank" rel="noopener noreferrer"><span className="source-main"><span className="source-title">Open original listing</span></span><ArrowOut/></a></li></ul>}
      </section></>}
    {tab === 'value' && <div className="valuation">
      {analysis && <section className="detail-group ai-value"><div className="ios-section"><h2>Estimated range</h2></div>{analysis.value.mid !== null ? <div className="valuation-range">{['low', 'mid', 'high'].map(level => <div key={level}><span>{level}</span><b className="num">{analysis.value[level] === null ? 'None' : money(analysis.value[level])}</b></div>)}</div> : <p className="ios-footnote">The identification was too uncertain to price.</p>}<p className="ios-footnote">{analysis.value.basis}</p></section>}
      <section className="detail-group">
        <div className="ios-section"><h2>Completed sales</h2></div>
        <div className="valuation-range">{['low', 'mid', 'high'].map(level => <div key={level}><span>{level === 'mid' ? 'Median sale' : `${level} sale`}</span><b className="num">{range ? money(range[level]) : 'None yet'}</b></div>)}</div>
        <p className="ios-footnote">{range ? `Based on ${range.count} sales you confirmed. Low and high are the minimum and maximum; this is not an appraisal.` : 'Add three confirmed completed sales with source and date to calculate a range. Asking prices are not sold prices.'} wabi does not verify these or adjust for originality, condition, fees, or exchange rates.</p>
        <div className="comps-list">{comps.map((comp, i) => { const edit = patch => setComps(comps.map(c => (c.id === comp.id ? { ...c, ...patch } : c))); return <div className="comp-row form-section" key={comp.id}>
          <div className="comp-title"><h3 className="form-section-name">Sale {i + 1}</h3><button type="button" className="past-remove" aria-label={`Remove comparable ${i + 1}`} onClick={() => setComps(comps.filter(c => c.id !== comp.id))}>Remove</button></div>
          <div className="form-rows">
            <FormRow label="Sold price" prefix="$"><MoneyInput aria-label="Sold price · USD" value={comp.price} onChange={v => edit({ price: v })}/></FormRow>
            <FormRow label="Sale date"><input type="date" max={todayISO()} value={comp.date} onChange={e => edit({ date: e.target.value })}/></FormRow>
            <FormRow label="Source"><input placeholder="Auction result or documented sale" value={comp.source} onChange={e => edit({ source: e.target.value })}/></FormRow>
            <label className="form-row check-row"><span className="check-row-text">I checked that this is a completed sale of a comparable watch.</span><input type="checkbox" className="switch-box" checked={comp.confirmed} onChange={e => edit({ confirmed: e.target.checked })}/></label>
          </div></div>; })}</div>
        <div className="glist comp-actions"><ActionRow tint title="Add comparable sale" onClick={() => setComps([...comps, { id: crypto.randomUUID(), price: '', date: '', source: '', confirmed: false }])}/><ActionRow tint title="Save valuation research" onClick={save} busy={saving} disabled={comps === record.comps}/></div>
      </section></div>}
    {tab === 'next' && <section className="detail-group">
      <div className="ios-section"><h2>Before you buy</h2></div>
      <div className="glist next-steps">
        {analysis?.red_flags.map((f, i) => <NextStep key={`flag${i}`} icon={<Flag size={18} strokeWidth={1.6}/>} title="Resolve a flag" sub={f}/>)}
        {analysis?.missing_evidence.map((m, i) => <NextStep key={`miss${i}`} icon={<Camera size={18} strokeWidth={1.6}/>} title={m.request} sub={m.why}/>)}
        {!analysis && VIEWS.filter(v => !record.photos[v.id]).map(v => <NextStep key={v.id} icon={<Camera size={18} strokeWidth={1.6}/>} title={`Request ${v.title.toLowerCase()}`} sub={v.hint}/>)}
        {Object.entries(checks).filter(([, c]) => c.status === 'concern' || c.status === 'replacement').map(([id, c]) => <NextStep key={id} icon={<Flag size={18} strokeWidth={1.6}/>} title={`Clarify the ${PART_NAMES[id].toLowerCase()}`} sub={c.note || 'Ask for documented details and an independent opinion.'}/>)}
        <NextStep icon={<ShieldCheck size={18} strokeWidth={1.6}/>} title="Arrange an independent watchmaker inspection" sub="Have them check the movement, the condition and any replaced parts. Agree on inspection and returns before you pay."/>
        <NextStep icon={<LockKeyhole size={18} strokeWidth={1.6}/>} title="Check the seller and payment protections" sub="Confirm who the seller is and get the return terms in writing. Pay with a method that offers buyer protection."/>
      </div>
      <p className="ios-footnote">Work through these with the seller, in order.</p>
    </section>}
    </section></NotesWrap>{image && <Modal title={image.title} close={() => setImage(null)}><img className="expanded-image" src={image.url} alt={image.title}/><div className="modal-actions"><button className="button danger" onClick={() => { const view = VIEWS.find(v => v.title === image.title); addPhoto(view.id, null); setImage(null); }}><Trash2 size={15}/> Remove photo</button></div></Modal>}{askConsent && <ConsentModal close={() => setAskConsent(false)} accept={() => { const next = askConsent === 'seller' ? reviewSeller : run; setConsent(true); setAskConsent(false); setTimeout(next, 0); }}/>}{reviewBar}</>;
}

const todayISO = () => new Date().toISOString().slice(0, 10);
const compactMoney = n => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', notation: 'compact', maximumFractionDigits: 1 }).format(n);

// Market value. The brand comes from the model text; with none named, a Rolex is assumed.
function marketQuery({ model = '', reference = '', year = '' }) {
  const brand = detectBrand(model) || 'Rolex';
  return { brand, model: model.replace(new RegExp(brand, 'i'), '').trim() || model.trim(), reference: reference.trim(), year: String(year || '').match(/\b(19|20)\d\d\b/)?.[0] || '' };
}
const queryKey = q => [q.brand, q.model, q.reference].join('|').toLowerCase();
const canPrice = r => scanAvailable && Boolean((r.reference || '').trim() || ((r.model || '').trim() && r.model.trim() !== 'Unidentified watch'));
// Re-checked every few days; the server answers from its weekly shared cache, so this is cheap.
const MARKET_FORMAT = 4; // bumped when the stored market data gains fields, so older copies are re-checked once
const marketFresh = (m, q) => Boolean(m && m.v === MARKET_FORMAT && m.query === queryKey(q) && (Date.now() - new Date(m.checked).getTime()) / 864e5 < 3);
const asMarket = (m, q) => ({ low: m.low, mid: m.mid, high: m.high, retail: m.retail ?? null, change1y: m.change_1y_pct ?? null, identified: m.identified || '', basis: m.basis || '', sources: m.sources || [], history: m.history || [], recent: m.recent || [], log: m.log || [], asOf: m.asOf || todayISO(), checked: todayISO(), query: queryKey(q), v: MARKET_FORMAT });
// The price trend: dated prices from sources (a month when the source gives one), wabi's own log of market checks
// for this reference, and today's market price. Time is in fractional years.
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const yearsOf = iso => Number(iso.slice(0, 4)) + (Number(iso.slice(5, 7)) - 0.5) / 12;
// The one-year view: every dated listing and sale as a dot, with a line through each month's median. The five-year
// view: one sourced price per year. Both include wabi's own market checks and end at today's market price.
function trendSeries(market, span) {
  if (!market?.mid) return { line: [], scatter: [] };
  const now = yearsOf(market.asOf); const nowPoint = { t: now, price: market.mid, label: 'Now' };
  const sourced = (market.history || []).map(h => ({ t: h.year + ((h.month ?? 6.5) - 0.5) / 12, price: h.price, label: h.month ? `${MONTHS[h.month - 1]} ’${String(h.year).slice(2)}` : String(h.year), source_url: h.source_url, note: h.note }));
  const logged = (market.log || []).map(p => ({ t: yearsOf(p.date), price: p.mid, label: shortDate(p.date), note: 'wabi market price' }));
  const before = p => p.t < now - 1 / 24;
  if (span === '5Y') return { line: [...[...sourced, ...logged].filter(p => before(p) && p.t >= now - 5.5).sort((a, b) => a.t - b.t), nowPoint], scatter: [] };
  const dots = (market.recent || []).map(r => ({ t: Number(r.date.slice(0, 4)) + (Number(r.date.slice(5, 7)) - 1 + Number(r.date.slice(8, 10)) / 31) / 12, price: r.price, kind: r.kind, label: shortDate(r.date), month: r.date.slice(0, 7), source_url: r.source_url, note: r.note }));
  const inYear = [...dots, ...[...sourced, ...logged].map(p => ({ ...p, month: `${Math.floor(p.t)}-${String(Math.min(12, Math.floor((p.t % 1) * 12) + 1)).padStart(2, '0')}` }))].filter(p => before(p) && p.t >= now - 1.05);
  const months = Object.entries(inYear.reduce((m, p) => ({ ...m, [p.month]: [...(m[p.month] || []), p] }), {})).sort(([a], [b]) => a.localeCompare(b));
  const median = ps => { const v = ps.map(p => p.price).sort((a, b) => a - b); return v.length % 2 ? v[(v.length - 1) / 2] : Math.round((v[v.length / 2 - 1] + v[v.length / 2]) / 2); };
  const line = months.map(([m, ps]) => ({ t: Number(m.slice(0, 4)) + (Number(m.slice(5, 7)) - 0.5) / 12, price: median(ps), label: `${MONTHS[Number(m.slice(5, 7)) - 1]} ’${m.slice(2, 4)}`, note: `median of ${count(ps.length, 'price')}` }));
  return { line: [...line, nowPoint], scatter: dots.filter(p => before(p) && p.t >= now - 1.05) };
}
// The trend chart with a 1Y / 5Y switch; each view needs enough real points to draw a line.
function TrendChart({ market, ask }) {
  const views = { '1Y': trendSeries(market, '1Y'), '5Y': trendSeries(market, '5Y') };
  const usable = { '1Y': views['1Y'].line.length >= 2, '5Y': views['5Y'].line.length >= 3 && views['5Y'].line[0].t < views['5Y'].line.at(-1).t - 1.5 };
  const [span, setSpan] = useState(usable['1Y'] ? '1Y' : '5Y');
  if (!usable['1Y'] && !usable['5Y']) return <p className="small trend-empty">The price trend for this reference fills in over the coming weeks.</p>;
  const { line: points, scatter } = views[span];
  const W = 320, H = 140, padX = 14, top = 14, bottom = 24;
  const values = [...points, ...scatter].map(p => p.price).concat(ask ? [ask] : []);
  const lo = Math.min(...values) * 0.97, hi = Math.max(...values) * 1.03;
  const x0 = Math.min(...[...points, ...scatter].map(p => p.t)), xs = points.at(-1).t - x0 || 1;
  const x = t => padX + (t - x0) / xs * (W - padX * 2), y = v => top + (1 - (v - lo) / (hi - lo || 1)) * (H - top - bottom);
  const first = points[0], last = points.at(-1); const change = (last.price - first.price) / first.price;
  const line = points.map(p => `${x(p.t).toFixed(1)},${y(p.price).toFixed(1)}`).join(' ');
  const axis = span === '5Y' ? points.filter(p => p.source_url || p === last) : [first, last];
  const listed = [...scatter, ...(span === '5Y' ? points.filter(p => p !== last) : [])].sort((a, b) => b.t - a.t);
  return <figure className={`trend-chart ${change < 0 ? 'down' : ''}`}>
    <figcaption><span className="label">Price trend</span><span className={`trend ${change >= 0 ? 'pos' : 'neg'}`}>{change >= 0 ? '▲' : '▼'} {Math.abs(change * 100).toFixed(1)}% <small>since {first.label}</small></span></figcaption>
    {usable['1Y'] && usable['5Y'] && <div className="trend-span"><Segmented label="Trend range" options={['1Y', '5Y']} value={span} onChange={setSpan}/></div>}
    <svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={`Typical price ${points.map(p => `${p.label} ${money(p.price)}`).join(', ')}${scatter.length ? `, from ${count(scatter.length, 'dated price')}` : ''}${ask ? `; asking ${money(ask)}` : ''}`}>
      <polygon className="trend-fill" points={`${x(first.t)},${H - bottom} ${line} ${x(last.t)},${H - bottom}`}/>
      {scatter.map((p, i) => <circle key={`s${i}`} className={`trend-obs ${p.kind}`} cx={x(p.t)} cy={y(p.price)} r="2.6"><title>{`${p.label}: ${money(p.price)} ${p.kind}${p.note ? ` · ${p.note}` : ''}`}</title></circle>)}
      {ask ? <><line className="trend-ask" x1={padX} x2={W - padX} y1={y(ask)} y2={y(ask)}/><text className="trend-ask-label" x={W - padX} y={y(ask) - 5} textAnchor="end">Asking {compactMoney(ask)}</text></> : null}
      <polyline className="trend-line" points={line}/>
      {points.map((p, i) => <circle key={i} className={`trend-dot ${p === last ? 'now' : ''}`} cx={x(p.t)} cy={y(p.price)} r={p === last ? 4.5 : 3}><title>{`${p.label}: ${money(p.price)}${p.note ? ` · ${p.note}` : ''}`}</title></circle>)}
      {axis.map((p, i) => <text key={i} className="trend-year" x={x(p.t)} y={H - 6} textAnchor={p === first ? 'start' : p === last ? 'end' : 'middle'}>{p.label}</text>)}
    </svg>
    {span === '1Y' && scatter.length > 0 && <p className="trend-legend"><span><i className="dot sold"/>Sold</span><span><i className="dot asking"/>Asking</span><span><i className="dot line"/>Monthly median</span></p>}
    <details className="price-points"><summary>{span === '1Y' && scatter.length ? count(scatter.length, 'recent price') : 'Price points'}</summary><ul>{listed.map((p, i) => <li key={i}>{p.source_url ? <a href={p.source_url} target="_blank" rel="noopener noreferrer">{p.label} · {money(p.price)}{p.kind ? ` · ${p.kind}` : ''}<ExternalLink size={12}/></a> : <b>{p.label} · {money(p.price)}</b>}{p.note && <span>{p.note}</span>}</li>)}</ul></details>
  </figure>;
}
const MARKET_SOURCE = 'Market estimate';
// A market check becomes the watch's dated valuation (one per day), so profit and the chart follow the market.
function withMarket(w, market) {
  const entry = { amount: market.mid, low: market.low, high: market.high, date: market.asOf, source: MARKET_SOURCE };
  return { ...w, market, valuations: [...w.valuations.filter(v => !(v.source === MARKET_SOURCE && v.date === entry.date)), entry].sort((x, y) => x.date.localeCompare(y.date)) };
}

// Where a price sits in the market: the low–high range as a bar, the typical price as a dot, and your price
// (what you paid, or what the seller asks) as a green marker.
function RangeBar({ low, mid, high, mark, markLabel }) {
  const lo = Math.min(low, mark ?? low) * 0.97, hi = Math.max(high, mark ?? high) * 1.03;
  const pos = v => `${((v - lo) / (hi - lo || 1)) * 100}%`;
  return <div className="range-bar" role="img" aria-label={`Market range ${money(low)} to ${money(high)}, typical ${money(mid)}${mark ? `; ${markLabel.toLowerCase()} ${money(mark)}` : ''}`}>
    <div className="range-track"><span className="range-span" style={{ left: pos(low), width: `calc(${pos(high)} - ${pos(low)})` }}/><span className="range-mid" style={{ left: pos(mid) }}/>{mark ? <span className="range-mark" style={{ left: pos(mark) }}><i>{markLabel}</i></span> : null}</div>
    <div className="range-labels"><span><b>{compactMoney(low)}</b>Low</span><span><b>{compactMoney(mid)}</b>Market</span><span><b>{compactMoney(high)}</b>High</span></div>
  </div>;
}
const Trend = ({ pct }) => pct == null ? null : <span className={`trend ${pct >= 0 ? 'pos' : 'neg'}`}>{pct >= 0 ? '▲' : '▼'} {Math.abs(pct).toFixed(1)}% <small>1Y</small></span>;
// Where a market price came from: each source a row that opens it, and under them when the price was last checked.
function MarketSources({ market }) {
  return <div className="market-sources">
    {market.sources.length > 0 && <ul className="source-rows">{market.sources.map(src => <li key={src.url}><a className="source-row" href={src.url} target="_blank" rel="noopener noreferrer"><span className="source-main"><span className="source-title">{src.title || new URL(src.url).hostname}</span>{src.note && <span className="source-sub">{src.note}</span>}</span><ArrowOut/></a></li>)}</ul>}
    <p className="source-foot">Updated {shortDate(market.asOf)}.{market.retail ? ` Retail price today: ${money(market.retail)}.` : ''}</p>
  </div>;
}
// The market card on a report: what the same reference sells for, and where the asking price sits in that range.
// A report's market data: loaded when the report opens if missing or a few days old, and saved on the listing.
// The chart draws at once from the listing's saved copy or the local price database; a stale copy is refreshed in
// the background while it stays on screen.
function useMarket(record, onPatch) {
  const q = marketQuery(record); const key = queryKey(q); const local = cachedPrice(key);
  const own = record.market?.query === key ? record.market : null;
  const market = own && (!local || own.checked >= local.checked) ? own : local?.query === key ? local : own;
  const [busy, setBusy] = useState(false); const [error, setError] = useState('');
  async function load() {
    setBusy(true); setError('');
    try { await onPatch(record.id, { market: await savePrice(key, asMarket(await marketValue(q), q)) }, null); } catch (e) { console.warn('market value not loaded:', e.message); setError(e.message); } finally { setBusy(false); }
  }
  useEffect(() => {
    if (!canPrice(record)) return;
    if (marketFresh(local, q)) { if (!marketFresh(record.market, q)) onPatch(record.id, { market: local }, null); }
    else if (!marketFresh(record.market, q)) load();
  }, [record.id]);
  return { market, busy, error, load };
}
function MarketCard({ record, state, onEdit }) {
  const { market, busy, error, load } = state;
  if (!scanAvailable) return null;
  if (!canPrice(record)) return <section className="card dash-tile market-card"><span className="label">Market value</span><p className="small">No model or reference was given, so this watch can’t be matched to a market price yet.</p><button type="button" className="text-button" onClick={onEdit}>Add a model or reference</button></section>;
  const ask = parsePrice(record.price ?? '');
  const gap = market && ask ? (ask - market.mid) / market.mid : null;
  if (error && !market && !busy) return <section className="market-card" aria-label="Market value"><ErrorCell quiet retry={load}>The market value couldn’t be loaded.</ErrorCell></section>;
  return <section className="card dash-tile market-card" aria-busy={busy}>
    <div className="market-head"><div><span className="label">Market value</span>{market ? <b className="tile-figure num">{money(market.mid)}</b> : busy ? <Skeleton width={128} height={28} className="market-skel"/> : null}<p className="small">{market ? `${money(market.low)} – ${money(market.high)}${market.identified ? ` · ${market.identified}` : ''}` : busy ? 'Checking the market…' : 'Not checked yet.'}</p></div><Trend pct={market?.change1y}/></div>
    {market && <RangeBar low={market.low} mid={market.mid} high={market.high} mark={ask || null} markLabel="Asking"/>}
    {gap !== null && <p className={`market-verdict ${gap <= 0 ? 'pos' : 'neg'}`}>Asking {money(ask)} is {percent(Math.abs(gap)).replace(/^[+−]/, '')} {gap <= 0 ? 'below' : 'above'} the market price{ask < market.low ? ', under the usual low. Check why.' : ask > market.high ? ', over the usual high.' : '.'}</p>}
    {market && <TrendChart market={market} ask={ask || null}/>}
    {market && <MarketSources market={market}/>}
    {!busy && market && <button type="button" className="text-button" onClick={load}>{error ? 'Try again' : 'Check again'}</button>}
  </section>;
}
// Value over time, open on the canvas: market value as a solid line, what you paid as a dashed step that rises when a
// watch is bought, gridlines on round values with their labels at the trailing edge, and the same numbers as a table
// for screen readers. The market line starts at the first dated valuation and runs through real readings only (a
// dot each, joined by straight segments); before it there is only what was paid. A drag along the chart reads each
// month, as do the arrow keys.
const CHART_H = 200;
// Three gridlines on round values inside the range: the smallest step from 250, 500, 1,000, 2,500, 5,000… that leaves
// no more than three multiples of it in view, so each label is exactly the value of the line it sits on.
function niceTicks(lo, hi) {
  for (let base = 1; base < 1e9; base *= 10) for (const m of [1, 2.5, 5]) {
    const step = base * m; if (step < 250) continue;
    const first = Math.ceil(lo / step) * step; const n = Math.floor((hi - first) / step) + 1;
    if (n <= 3) return n < 1 ? [(lo + hi) / 2] : Array.from({ length: n }, (_, i) => first + (n - 1 - i) * step);
  }
  return [(lo + hi) / 2];
}
const READINGS = ['No readings', 'One reading', 'Two readings'];
function ValueChart({ series, note, onScrub }) {
  const [span, setSpan] = useState('1y'); const [hover, setHover] = useState(null);
  // What is drawn follows the chosen range a moment later, so the old line can fade before the new one draws.
  const [drawn, setDrawn] = useState(span); const [redrawn, setRedrawn] = useState(false);
  useEffect(() => { if (drawn === span) return undefined; const t = setTimeout(() => { setDrawn(span); setRedrawn(true); }, reduceMotion() ? 0 : cssMs('--t-chart-out', 120)); return () => clearTimeout(t); }, [span, drawn]);
  // The plot is drawn at its real size, so strokes, dots and dashes are the sizes they say.
  const area = useRef(null); const [W, setW] = useState(318);
  useLayoutEffect(() => { const el = area.current; if (!el) return undefined; const fit = () => setW(el.clientWidth || 318); fit(); const watch = new ResizeObserver(fit); watch.observe(el); return () => watch.disconnect(); }, [series.length < 2]); // eslint-disable-line react-hooks/exhaustive-deps
  const pts = monthsInRange(series, drawn); const listed = monthsInRange(series, span);
  const on = hover != null && hover >= 0 && hover < pts.length;
  useEffect(() => { const first = pts.findIndex(p => p.read); onScrub?.(on ? { ...pts[hover], valued: first !== -1 && hover >= first } : null); }, [on, hover, drawn]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => () => onScrub?.(null), []); // eslint-disable-line react-hooks/exhaustive-deps
  const drag = useRef(null);
  // The line that rides the crosshair is centred on it, and stops at the chart's edges whatever its length.
  const tip = useRef(null);
  useLayoutEffect(() => { const t = tip.current; if (!t) return; const half = t.offsetWidth / 2; t.style.left = `${Math.max(half, Math.min(Number(t.dataset.at), t.parentElement.clientWidth + 44 - half))}px`; });
  const readings = series.filter(p => p.read).length;
  const sparse = readings < 3 && <p className="vc-sparse">{READINGS[readings]} so far. The line fills in each time wabi checks the market.</p>;
  if (pts.length < 2) return <section className="value-chart-card" aria-label="Value over time"><p className="vc-summary">The chart starts once a watch has a purchase date or a dated valuation.</p>{note && <p className="vc-note">{note}</p>}</section>;
  const from = pts.findIndex(p => p.read); const valued = from === -1 ? [] : pts.map((p, i) => ({ ...p, i })).filter(p => p.i >= from && (p.read || p.i === pts.length - 1));
  let lo = Math.min(...pts.flatMap((p, i) => (from !== -1 && i >= from ? [p.value, p.paid] : [p.paid]))); let hi = Math.max(...pts.flatMap((p, i) => (from !== -1 && i >= from ? [p.value, p.paid] : [p.paid])));
  const pad = (hi - lo) * 0.12 || 200; lo -= pad; hi += pad;
  const ticks = niceTicks(lo, hi);
  const top = 14, bottom = 10, inset = 4;
  const x = i => inset + (i / (pts.length - 1)) * (W - inset * 2);
  const y = v => top + (1 - (v - lo) / (hi - lo)) * (CHART_H - top - bottom);
  const valueD = valued.map((p, n) => `${n ? 'L' : 'M'}${x(p.i).toFixed(1)} ${y(p.value).toFixed(1)}`).join(' ');
  const paidD = pts.map((p, i) => { if (!i) return `M${x(0).toFixed(1)} ${y(p.paid).toFixed(1)}`; const prev = pts[i - 1].paid; return `L${x(i).toFixed(1)} ${y(prev).toFixed(1)}${prev !== p.paid ? ` L${x(i).toFixed(1)} ${y(p.paid).toFixed(1)}` : ''}`; }).join(' ');
  const k = v => (v < 1000 ? `$${Math.round(v)}` : `$${(v / 1000).toFixed(2).replace(/\.?0+$/, '')}k`);
  const hp = on ? pts[hover] : pts.at(-1); const hx = x(on ? hover : pts.length - 1); const read = on && from !== -1 && hover >= from;
  const pick = i => { const next = Math.max(0, Math.min(pts.length - 1, i)); setHover(h => { if (h !== next && drag.current?.on) tap('select'); return next; }); };
  const at = e => { const r = e.currentTarget.getBoundingClientRect(); return Math.round(((e.clientX - r.left - inset) / (r.width - inset * 2)) * (pts.length - 1)); };
  const purchases = series.reduce((n, p, i) => n + (i && p.paid > series[i - 1].paid ? 1 : 0), series[0]?.paid > 0 ? 1 : 0);
  function onKey(e) {
    const cur = on ? hover : pts.length - 1;
    if (e.key === 'ArrowLeft') { e.preventDefault(); pick(cur - 1); } else if (e.key === 'ArrowRight') { e.preventDefault(); pick(cur + 1); }
    else if (e.key === 'Home') { e.preventDefault(); pick(0); } else if (e.key === 'End') { e.preventDefault(); pick(pts.length - 1); } else if (e.key === 'Escape') setHover(null);
  }
  // A pointer reads the month under it as it moves. A finger first has to travel 8pt along the chart, so a scroll
  // that starts on it is still a scroll; from there the chart keeps the touch until it lifts.
  const touch = {
    onPointerDown: e => { drag.current = e.pointerType === 'mouse' ? null : { x: e.clientX, y: e.clientY, on: false }; },
    onPointerMove: e => {
      if (e.pointerType === 'mouse') { pick(at(e)); return; }
      const d = drag.current; if (!d) return;
      if (!d.on) { const dx = Math.abs(e.clientX - d.x); const dy = Math.abs(e.clientY - d.y); if (dy > 8 && dy >= dx) { drag.current = null; return; } if (dx < 8) return; d.on = true; e.currentTarget.setPointerCapture?.(e.pointerId); }
      pick(at(e));
    },
    onPointerUp: e => { if (e.pointerType !== 'mouse') { drag.current = null; setHover(null); } },
    onPointerCancel: () => { drag.current = null; setHover(null); },
    onPointerLeave: e => { if (e.pointerType === 'mouse') setHover(null); },
  };
  const gain = hp.value - hp.paid; const end = valued.at(-1);
  return <section className="value-chart-card" aria-label="Value over time">
    <div className="vc-plot"><div className="vc-area" ref={area}>
      <svg className={`vc-svg${drawn !== span ? ' leaving' : ''}${redrawn ? ' again' : ''}`} key={drawn} width={W} height={CHART_H} viewBox={`0 0 ${W} ${CHART_H}`} aria-hidden="true">
        {ticks.map((t, i) => <line key={i} className="vc-grid" x1="0" x2={W} y1={Math.round(y(t)) + .5} y2={Math.round(y(t)) + .5}/>)}
        <defs><linearGradient id="vc-fade" x1="0" y1="0" x2="0" y2="1"><stop className="vc-fade-top" offset="0"/><stop className="vc-fade-floor" offset="1"/></linearGradient></defs>
        {readings >= 3 && valued.length > 1 && <path className="vc-fill" fill="url(#vc-fade)" d={`${valueD} L${x(end.i).toFixed(1)} ${CHART_H} L${x(valued[0].i).toFixed(1)} ${CHART_H} Z`}/>}
        <path className="vc-paid" d={paidD}/>
        {valued.length > 1 && <path className="vc-line" d={valueD} pathLength="1"/>}
        {valued.filter(p => p.read).map(p => <circle key={p.key} className={`vc-read${p === end ? ' end' : ''}`} cx={x(p.i)} cy={y(p.value)} r="3"/>)}
        {on && <line className="vc-cross" x1={Math.round(hx) + .5} x2={Math.round(hx) + .5} y1="0" y2={CHART_H}/>}
        {on && <circle className="vc-at paid" cx={hx} cy={y(hp.paid)} r="3.5"/>}
        {read && <circle className="vc-at value" cx={hx} cy={y(hp.value)} r="4.5"/>}
      </svg>
      {/* a slider over the months: its value text is the month being read, so a screen reader says each one as it moves */}
      <div className="vc-hit" role="slider" tabIndex="0" aria-label={`Collection value, ${pts[0].month} to ${pts.at(-1).month}`} aria-valuemin={0} aria-valuemax={pts.length - 1} aria-valuenow={on ? hover : pts.length - 1}
        aria-valuetext={`${hp.month}: ${on ? (read ? `market ${money(hp.value)}, ` : '') : `${money(hp.value)}, `}paid ${money(hp.paid)}`} {...touch} onKeyDown={onKey} onBlur={() => setHover(null)}/>
      {on && <div className="vc-tip" ref={tip} data-at={hx} aria-hidden="true"><span>Paid <span className="num">{money(hp.paid)}</span></span>{read && <span>{gain >= 0 ? 'Gain' : 'Change'} <b className={`num${gain >= 0 ? ' pos' : ''}`}>{signed(gain)}</b></span>}</div>}
    </div>{ticks.map((t, i) => <span key={i} className="vc-tick num" style={{ top: `${y(t)}px` }} aria-hidden="true">{k(t)}</span>)}</div>
    <div className="vc-ends num" aria-hidden="true"><span>{pts[0].short}</span><span>{pts.at(-1).short}</span></div>
    <p className="vc-legend"><span><svg width="16" height="4" viewBox="0 0 16 4" aria-hidden="true"><line className="key-value" x1="1" y1="2" x2="15" y2="2"/></svg>Market value</span><span><svg width="16" height="4" viewBox="0 0 16 4" aria-hidden="true"><line className="key-paid" x1="1" y1="2" x2="15" y2="2"/></svg>What you paid</span></p>
    <Segmented className="vc-range" label="Time range" options={SPANS.map(r => ({ value: r.id, label: r.label }))} value={span} onChange={id => { setSpan(id); setHover(null); }}/>
    {readings >= 2 && <p className="vc-summary">{keepAmounts(rangeSummary(listed, span, purchases))}</p>}
    {sparse}
    {note && <p className="vc-note">{note}</p>}
    <table className="sr-only"><caption>Collection value and amount paid by month</caption><thead><tr><th scope="col">Month</th><th scope="col">Market value</th><th scope="col">Paid</th></tr></thead><tbody>{listed.map(p => <tr key={p.key}><th scope="row">{p.month}</th><td>{money(p.value)}</td><td>{money(p.paid)}</td></tr>)}</tbody></table>
  </section>;
}
const longDate = iso => new Intl.DateTimeFormat('en-US', { month: 'long', year: 'numeric' }).format(new Date(`${iso}T12:00:00`));
// Signed amounts in a sentence never break between the sign and the figure.
const keepAmounts = text => text.split(/([+−]?\$[\d,]+)/).map((part, i) => (i % 2 ? <span key={i} className="nowrap">{part}</span> : part));
// The collection's total counts up once, the first time it is seen; after that it simply changes.
let totalSeen = false;
function useTotal(target) {
  const [shown, setShown] = useState(totalSeen || reduceMotion() ? null : 0); const begun = useRef(false);
  useEffect(() => {
    if (shown === null || !target) return undefined;
    // A total that changes while it is still counting (a market price arriving) simply lands.
    if (begun.current) { setShown(null); return undefined; }
    begun.current = true; totalSeen = true; let start = 0; const span = cssMs('--t-total', 600); let frame = 0;
    const step = now => { const p = Math.min(1, (now - start) / span); if (p >= 1) { setShown(null); return; } setShown(Math.round(target * (1 - (1 - p) ** 3))); frame = requestAnimationFrame(step); };
    // A total that arrives as a sheet leaves (the first watch saved) counts once the page is back in front of it.
    const wait = document.body.classList.contains('has-sheet') ? cssMs('--t-sheet-out', 320) : 0;
    const t = setTimeout(() => { start = performance.now(); frame = requestAnimationFrame(step); }, wait);
    return () => { clearTimeout(t); cancelAnimationFrame(frame); };
  }, [target]); // eslint-disable-line react-hooks/exhaustive-deps
  return shown === null ? target : shown;
}
// One watch in the collection: its row, and under it (opened by the row) its details as grouped rows.
function HoldingRow({ w, value, pl, isOpen, toggle, busy, error, leaving, edit, price, check, onRemove }) {
  const band = w.market; const photo = w.photo ? w.photo.url || w.photo : null; const brand = detectBrand(w.model);
  // The brand is not said twice: a name that begins with it is followed by the reference alone.
  const line = [brand && !w.model.trim().toLowerCase().startsWith(brand.toLowerCase()) ? brand : null, w.reference && `Ref. ${w.reference}`].filter(Boolean).join(' · ') || (brand ? '' : 'Reference not given');
  const failed = Boolean(error) && !busy;
  return <li className={`coll-row${leaving ? ' is-leaving' : ''}`}><div className="coll-fold">
    <SwipeRow action={{ label: 'Remove', icon: <Trash2 strokeWidth={1.6}/>, ariaLabel: `Remove ${w.model}`, onAction: onRemove }}>
      <button type="button" className="holding-toggle" aria-expanded={isOpen} onClick={toggle}>
        <span className={`hold-thumb${photo ? '' : ' drawn'}`}>{photo ? <img src={photo} alt="" width="48" height="48"/> : <DialGlyph/>}</span>
        <span className="lrow-main"><span className="hold-name">{w.model}</span>{line && <span className="hold-ref num">{line}</span>}</span>
        <span className="hold-end"><span className="hold-value num">{money(value)}</span>{pl !== null && <span className={`holding-delta num ${pl >= 0 ? 'pos' : 'neg'}`}>{pl >= 0 ? <UpMark/> : <DownMark/>}{signed(pl)}{w.purchasePrice ? <span className="sr-only">, {percent(pl / w.purchasePrice)}</span> : null}</span>}</span>
        <Chevron/>
      </button>
    </SwipeRow>
    <div className={`hold-wrap${isOpen ? ' open' : ''}`} inert={!isOpen}><div className="holding-detail">
      <h3 className="form-section-name">Details</h3>
      <dl className="spec-list">
        <div className="spec-row"><dt>You paid</dt><dd className="num">{w.purchasePrice != null ? money(w.purchasePrice) : 'Not recorded'}</dd></div>
        <div className="spec-row"><dt>Bought</dt><dd>{w.purchaseDate ? longDate(w.purchaseDate) : 'Not recorded'}</dd></div>
        <div className="spec-row"><dt>Recent sales</dt><dd className="num">{band?.low != null && band?.high != null ? `${money(band.low)} to ${money(band.high)}` : busy ? 'Checking…' : canPrice(w) && !failed ? <button type="button" className="spec-action" onClick={price}>Check market</button> : 'Not found yet'}</dd></div>
        <div className="spec-row"><dt>wabi score</dt><dd>{w.checked?.score != null ? `${w.checked.score}, ${w.checked.label.toLowerCase()}` : w.checked?.label || 'Not checked'}</dd></div>
      </dl>
      {failed && !busy && <ErrorCell quiet retry={price}>Recent sales couldn’t be loaded.</ErrorCell>}
      {w.market && <>{w.market.sources.length > 0 && <h3 className="form-section-name">Sources</h3>}<MarketSources market={w.market}/></>}
      {(w.purchasePrice != null || w.valuations.length > 0) && <><h3 className="form-section-name">Valuation history</h3><ul className="holding-history spec-list" aria-label="Valuation history">{w.purchasePrice != null && <li className="spec-row"><span>Bought{w.purchaseDate ? ` ${shortDate(w.purchaseDate)}` : ''}</span><span className="num">{money(w.purchasePrice)}</span></li>}{w.valuations.slice().reverse().map((v, i) => <li key={i} className="spec-row"><span>{shortDate(v.date)}{v.source === MARKET_SOURCE && v.low != null ? `, market ${compactMoney(v.low)} to ${compactMoney(v.high)}` : v.source && v.source !== 'Owner-entered estimate' ? `, ${v.source}` : ''}</span><span className="num">{money(v.amount)}</span></li>)}</ul></>}
      {w.notes && <><h3 className="form-section-name">Notes</h3><p className="holding-notes preserve-text">{w.notes}</p></>}
      {photo && <img className="holding-photo" src={photo} alt={w.model}/>}
      <div className="glist hold-actions">
        {w.checked?.score == null && !w.checked?.label && <ActionRow tint title="Check it with your own photos" onClick={check}/>}
        {canPrice(w) && band && <ActionRow tint title={failed ? 'Try the market again' : 'Check market again'} onClick={price} busy={busy}/>}
        <ActionRow tint title="Edit & update value" onClick={edit}/>
        <button type="button" className="grow ink-row" onClick={onRemove}><span className="grow-main"><span className="grow-title">Remove from collection</span></span></button>
      </div>
    </div></div>
  </div></li>;
}
function CollectionPage({ watches, add, edit, remove, check, marketBusy = [], marketErrors = {}, priceWatch }) {
  const [deleting, setDeleting] = useState(null); const [open, setOpen] = useState(null); const [scrub, setScrub] = useState(null); const [leaving, setLeaving] = useState(null);
  // As on Listings: the row closes up first, then it is gone and the total changes.
  function erase(id) {
    if (reduceMotion()) { remove(id); return; }
    setLeaving(id); setTimeout(() => Promise.resolve(remove(id)).finally(() => setLeaving(null)), cssMs('--t-collapse', 280));
  }
  const total = watches.reduce((n, w) => n + currentValue(w), 0);
  const costed = watches.filter(w => w.purchasePrice != null);
  const profit = costed.reduce((n, w) => n + currentValue(w) - w.purchasePrice, 0);
  const series = monthlySeries(watches);
  const holdings = watches.map(w => ({ w, value: currentValue(w), pl: w.purchasePrice != null ? currentValue(w) - w.purchasePrice : null })).sort((a, b) => b.value - a.value);
  const figure = useTotal(total);
  const ptr = usePullToRefresh(async () => { for (const w of watches) { try { await priceWatch(w.id); } catch { break; } } }, { enabled: watches.some(canPrice), label: 'Checking market prices' });
  useNavBar({ title: 'Collection', trailing: <NavAction label="Add a watch" onClick={add}><PlusIcon/></NavAction> });
  return <div className={`collection-page ${watches.length ? '' : 'is-empty'}`}>
    <header className="screen-head">{ptr.indicator}<LargeTitle>Collection</LargeTitle></header>
    {watches.length ? <>
      <div className="coll-summary" data-scrub={scrub ? '' : undefined}>
        <span className="portfolio-label">{scrub ? (scrub.valued ? scrub.month : `Paid by ${scrub.month}`) : `Estimated value · ${count(watches.length, 'watch', 'watches')}`}</span>
        <span className="portfolio-total">{money(scrub ? (scrub.valued ? scrub.value : scrub.paid) : figure)}</span>
        {costed.length > 0 && (Math.round(profit) === 0 ? <span className="portfolio-gain num even">Same as you paid</span>
          : <span className={`portfolio-gain num ${profit > 0 ? 'pos' : 'neg'}`}>{profit > 0 ? <UpMark/> : <DownMark/>}{signed(profit)} since you bought {costed.length === 1 ? 'it' : 'them'}</span>)}
        {marketBusy.length > 0 && <span className="portfolio-note" role="status">Checking market prices…</span>}
      </div>
      <ValueChart series={series} note="Estimates from recent sales, not appraisals." onScrub={setScrub}/>
      <div className="ios-section"><h2>Your watches <span className="head-count num">{watches.length}</span></h2></div>
      <ul className="holdings">{holdings.map(({ w, value, pl }) => <HoldingRow key={w.id} w={w} value={value} pl={pl} isOpen={open === w.id} toggle={() => { tap('select'); setOpen(open === w.id ? null : w.id); }} busy={marketBusy.includes(w.id)} error={marketErrors[w.id]} leaving={leaving === w.id} edit={() => edit(w)} price={() => priceWatch(w.id)} check={() => check(w)} onRemove={() => setDeleting(w)}/>)}</ul>
    </> : <PageEmpty art={<EditorialArt name="empty-tray-day" night="empty-tray-night"/>} title="Your watch box is empty" body="Add a watch you own to see what the market says it’s worth against what you paid.">
      <Button onClick={add}>Add a watch</Button>
    </PageEmpty>}
    {deleting && <ActionSheet title="Remove this watch?" message={`This deletes ${deleting.model} and its valuation history from your collection. Saved listings are kept.`}
      header={{ thumb: deleting.photo ? deleting.photo.url || deleting.photo : <DialGlyph/>, name: deleting.model, line: [deleting.reference && `Ref. ${deleting.reference}`, money(currentValue(deleting))].filter(Boolean).join(' · ') }}
      actions={[{ label: 'Remove watch', destructive: true, onSelect: () => erase(deleting.id) }]} cancel="Keep it" onClose={() => setDeleting(null)}/>}
  </div>;
}
// Find the reference from the owner's own photos: up to three (dial, side, case back), then pick a candidate. It is
// the last row of the form's first section; what it finds are rows under it.
const CONFIDENCE = { high: 'Likely', medium: 'Possible', low: 'Less likely' };
function IdentifyFromPhoto({ onPick }) {
  const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [result, setResult] = useState(null); const [photo, setPhoto] = useState(null);
  // The photos wait here while the person is asked, once, whether they may be sent (as for a photo review).
  const [asking, setAsking] = useState(null);
  async function choose(files) {
    const list = [...(files || [])].slice(0, 3); if (!list.length) return;
    if (!hasConsent()) { setAsking(list); return; }
    setBusy(true); setError(''); setResult(null);
    try {
      for (const f of list) { const problem = checkImageFile(f); if (problem) throw new Error(problem); }
      const images = await Promise.all(list.map(async f => resizeImage(await fileToDataUrl(f), 1400, 0.8)));
      setPhoto(images[0]);
      setResult(await identifyFromPhotos(images));
    } catch (e) { setError(e.message); } finally { setBusy(false); }
  }
  return <>
    {asking && <ConsentModal identify close={() => setAsking(null)} accept={() => { const list = asking; setConsent(true); setAsking(null); choose(list); }}/>}
    {!result && <label className={`form-row identify-row${busy ? ' busy' : ''}`}><input type="file" accept="image/*" multiple aria-label="Identify the watch from photos" disabled={busy || !scanAvailable} onChange={e => { choose([...e.target.files]); e.target.value = ''; }}/><IconTile><Focus size={18} strokeWidth={1.6}/></IconTile><span className="grow-main"><span className="grow-title">{busy ? 'Looking at your photos…' : 'Identify from photos'}</span><span className="grow-sub">{busy ? 'Usually under half a minute.' : 'Dial, side and case back'}</span></span>{busy ? <TickSpinner size={16}/> : <Chevron/>}</label>}
    {error && <FormError className="identify-error">{error}</FormError>}
    {result && <div className="identify-result">
      <p className="identify-found">{[result.brand, result.model].filter(Boolean).join(' ') || 'No watch found'}</p>
      {result.candidates.map(c => <button type="button" key={c.reference} className="grow" onClick={() => onPick({ model: [result.brand, c.name || result.model].filter(Boolean).join(' '), reference: c.reference, photo })}><span className="grow-main"><span className="grow-title">Ref. {c.reference} · {c.name}</span><span className="grow-sub">{c.years}{c.why ? ` · ${c.why}` : ''}</span></span><span className="grow-value">{CONFIDENCE[c.confidence] || c.confidence}</span></button>)}
      {result.how_to_confirm && <p className="identify-how">{result.how_to_confirm}</p>}
      <button type="button" className="grow tint-row" onClick={() => { setResult(null); setPhoto(null); }}><span className="grow-main"><span className="grow-title">Try other photos</span></span></button>
    </div>}
  </>;
}

// Add a watch to the collection, or edit any part of one: model, reference, photo, purchase, notes and past
// valuations. Changing the model or reference re-prices it against the market. Opened from a listing, it starts with
// what was asked as the price paid, today.
function WatchModal({ initial, assessment, onSave, close }) {
  const aiMid = assessment?.analysis?.value.mid ?? null; const asked = assessment ? parsePrice(assessment.price ?? '') : null;
  const [form, setForm] = useState({ model: initial?.model || assessment?.model || '', reference: initial?.reference || assessment?.reference || '', purchasePrice: initial?.purchasePrice ?? (asked ?? ''), purchaseDate: initial?.purchaseDate || (assessment ? todayISO() : ''), notes: initial?.notes || '', amount: '', valueDate: todayISO(), source: 'Owner-entered estimate' });
  const [photo, setPhoto] = useState(initial?.photo || assessment?.photos.dial || assessment?.photos.cover || null);
  const [valuations, setValuations] = useState(initial?.valuations || []);
  const [error, setError] = useState(''); const [saving, setSaving] = useState(false); const [choosing, setChoosing] = useState(false);
  const set = (key, value) => setForm(f => ({ ...f, [key]: value, ...(key === 'amount' ? { source: 'Owner-entered estimate' } : {}) }));
  const field = key => ({ value: form[key], onChange: e => set(key, e.target.value) });
  async function acceptPhoto(load) {
    try { const got = await load(); if (!got) return; setPhoto({ id: crypto.randomUUID(), name: got.name, url: await resizeImage(got.url) }); setError(''); } catch { setError('This photo couldn’t be read. Choose another.'); }
  }
  function pickPhoto(file) {
    if (!file) return; const problem = checkImageFile(file); if (problem) { setError(problem); return; }
    acceptPhoto(async () => ({ name: file.name, url: await fileToDataUrl(file) }));
  }
  const fromDevice = source => acceptPhoto(async () => { const url = await takePhoto('Watch photo', source); return url && { name: 'watch.jpg', url }; });
  async function submit(e) {
    e.preventDefault(); if (!form.model.trim()) return;
    if (form.amount !== '' && (parsePrice(form.amount) === null || !form.valueDate)) { setError('Enter a valid valuation and date.'); notify('error'); return; }
    setSaving(true);
    try {
      const model = form.model.trim(), reference = form.reference.trim();
      const same = initial && initial.model === model && (initial.reference || '') === reference;
      await onSave({ ...(same ? initial : {}), id: initial?.id || crypto.randomUUID(), model, reference, purchasePrice: parsePrice(form.purchasePrice), purchaseDate: form.purchaseDate, notes: form.notes, photo, market: same ? initial.market : undefined, valuations: [...valuations.filter(v => same || v.source !== MARKET_SOURCE), ...(form.amount !== '' ? [{ amount: parsePrice(form.amount), date: form.valueDate, source: form.source }] : [])].sort((a, b) => a.date.localeCompare(b.date)) });
    } finally { setSaving(false); }
  }
  const src = photo ? photo.url || photo : null;
  const face = src ? <img src={src} alt="" width="88" height="88"/> : <Camera size={28} strokeWidth={1.4} aria-hidden="true"/>;
  return <Modal title={initial ? 'Edit watch' : 'Add to collection'} close={close} detents={['large']} className="form-sheet"><form onSubmit={submit}>
    <div className="watch-photo-field">{isNative
      ? <button type="button" className="photo-well" aria-label={photo ? 'Edit the watch photo' : 'Add a watch photo'} onClick={() => setChoosing(true)}><span className="photo-well-face">{face}</span><span className="photo-well-word">{photo ? 'Edit' : 'Add photo'}</span></button>
      : <label className="photo-well"><input type="file" accept="image/*" aria-label="Watch photo" onChange={e => { pickPhoto(e.target.files?.[0]); e.target.value = ''; }}/><span className="photo-well-face">{face}</span><span className="photo-well-word">{photo ? 'Edit' : 'Add photo'}</span></label>}
      {photo && !isNative && <button type="button" className="photo-well-remove" onClick={() => setPhoto(null)}>Remove</button>}</div>
    <FormSection name="Watch">
      <FormRow label="Watch model"><GrowingInput required maxLength={100} placeholder="Omega Speedmaster" {...field('model')}/></FormRow>
      <FormRow label="Reference"><input maxLength={40} placeholder="1601" autoCapitalize="characters" autoCorrect="off" {...field('reference')}/></FormRow>
      <IdentifyFromPhoto onPick={c => { setForm(f => ({ ...f, model: c.model, reference: c.reference })); if (!photo && c.photo) setPhoto({ id: crypto.randomUUID(), name: 'watch.jpg', url: c.photo }); }}/>
    </FormSection>
    <FormSection name="Purchase">
      <FormRow label="Purchase price" prefix="$"><MoneyInput aria-label="Purchase price · USD" placeholder="Optional" value={form.purchasePrice} onChange={v => set('purchasePrice', v)}/></FormRow>
      <FormRow label="Purchase date"><input type="date" max={todayISO()} {...field('purchaseDate')}/></FormRow>
    </FormSection>
    <FormSection name="Notes"><textarea className="form-notes" aria-label="Notes and service history" rows="3" maxLength={10000} placeholder="Where it came from, service history, what makes it yours…" {...field('notes')}/></FormSection>
    <FormSection name="Valuation" note="Valuations are estimates, not appraisals.">
      <FormRow label="New valuation" prefix="$"><MoneyInput aria-label="New valuation · USD" placeholder="Optional" value={form.amount} onChange={v => set('amount', v)}/></FormRow>
      <FormRow label="Valuation date"><input type="date" required={form.amount !== ''} max={todayISO()} {...field('valueDate')}/></FormRow>
      {aiMid !== null && <button type="button" className="grow tint-row use-ai" onClick={() => setForm({ ...form, amount: String(aiMid), source: 'Estimate' })}><span className="grow-main"><span className="grow-title">Use the estimated value ({money(aiMid)})</span></span></button>}
    </FormSection>
    {valuations.length > 0 && <FormSection name="Past valuations">{valuations.map((v, i) => <div key={`${v.date}${i}`} className="form-row past-row"><span className="grow-main"><span className="grow-title num">{money(v.amount)}</span><span className="grow-sub">{shortDate(v.date)} · {v.source === MARKET_SOURCE ? 'Market' : v.source || 'Estimate'}</span></span><button type="button" className="past-remove" aria-label={`Remove the ${shortDate(v.date)} valuation`} onClick={() => setValuations(valuations.filter((_, j) => j !== i))}>Remove</button></div>)}</FormSection>}
    {error && <FormError>{error}</FormError>}
    <SheetFooter><Button type="submit" disabled={saving}><Working on={saving}>{initial ? 'Save changes' : 'Save to collection'}</Working></Button></SheetFooter></form>
    {choosing && <ActionSheet title="Watch photo" actions={[{ label: 'Take Photo', onSelect: () => { fromDevice('camera'); } }, { label: 'Choose from Library', onSelect: () => { fromDevice('photos'); } }, ...(photo ? [{ label: 'Remove Photo', destructive: true, onSelect: () => setPhoto(null) }] : [])]} onClose={() => setChoosing(false)}/>}
  </Modal>;
}

// Edit what was recorded about a listing: model, reference, year, price, link and notes.
function ListingModal({ record, onSave, close }) {
  const [form, setForm] = useState({ model: record.model, reference: record.reference || '', year: record.year || '', price: record.price || '', url: record.url || '', description: record.description || '' });
  const [saving, setSaving] = useState(false);
  const set = (key, value) => setForm(f => ({ ...f, [key]: value }));
  const field = key => ({ value: form[key], onChange: e => set(key, e.target.value) });
  async function submit(e) { e.preventDefault(); if (!form.model.trim()) return; setSaving(true); try { await onSave({ ...record, ...form, edited: true, model: form.model.trim(), reference: form.reference.trim(), price: form.price === '' ? '' : String(parsePrice(String(form.price)) ?? '') }, 'Listing details updated'); close(); } finally { setSaving(false); } }
  return <Modal title="Edit listing details" close={close} detents={['large']} className="form-sheet"><form onSubmit={submit}>
    <FormSection name="Listing">
      <FormRow label="Watch model"><GrowingInput required maxLength={100} {...field('model')}/></FormRow>
      <FormRow label="Reference"><input maxLength={40} autoCapitalize="characters" autoCorrect="off" {...field('reference')}/></FormRow>
      <FormRow label="Year"><input type="text" maxLength={20} inputMode="numeric" {...field('year')}/></FormRow>
      <FormRow label="Asking price" prefix="$"><MoneyInput aria-label="Asking price · USD" value={form.price} onChange={v => set('price', v)}/></FormRow>
      <IdentifyFromPhoto onPick={c => setForm(f => ({ ...f, model: c.model, reference: c.reference }))}/>
    </FormSection>
    <FormSection name="Link"><FormRow label="Listing link"><input type="url" inputMode="url" autoCapitalize="off" autoCorrect="off" placeholder="https://" {...field('url')}/></FormRow></FormSection>
    <FormSection name="Seller description and notes"><textarea className="form-notes" aria-label="Seller description and notes" rows="4" maxLength={20000} {...field('description')}/></FormSection>
    <SheetFooter><Button type="submit" disabled={saving}><Working on={saving}>Save details</Working></Button></SheetFooter></form></Modal>;
}

// Full-scan credits: balance, buying a pack through Stripe Checkout, and an access code for unlimited scans.
// The browser extension is built but not launched: its Profile section shows only in a build with VITE_EXTENSION=on.
const extensionOn = import.meta.env.VITE_EXTENSION === 'on';
// The browser extension is for paying customers: once signed in with a pack bought, a key connects it to the account.
function ExtensionSection({ wallet }) {
  const { user, askSignIn } = useContext(Account); const [key, setKey] = useState(''); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [copied, setCopied] = useState(false);
  async function make() { setBusy(true); setError(''); try { setKey((await extensionKey()).key); } catch (e) { setError(e.message); } finally { setBusy(false); } }
  async function copy() { try { await navigator.clipboard.writeText(key); setCopied(true); } catch { setError('Couldn’t copy. Select the key and copy it.'); } }
  const status = !user ? 'Not connected' : !wallet?.paid ? 'Comes with a scan pack' : key ? 'Key ready' : 'Ready to connect';
  const end = !user ? <button type="button" className="text-button" onClick={() => askSignIn('profile')}>Sign in<span className="sr-only"> to connect it</span></button>
    : wallet?.paid && !key ? <button type="button" className="text-button" onClick={make} disabled={busy}>{busy ? <TickSpinner size={16}/> : null}Get<span className="sr-only"> a connection</span> key</button> : null;
  return <section className="settings-group extension-section" aria-labelledby="set-extension"><h2 id="set-extension" className="settings-label">Browser extension</h2>
    <GroupedList><GroupedRow lead={<IconTile><Puzzle size={18} strokeWidth={1.5}/></IconTile>} title="wabi in your browser" sub={status} end={end}/>
      {key && <div className="key-row"><input readOnly value={key} aria-label="Extension connection key" onFocus={e => e.target.select()}/><button className="button secondary" onClick={copy}><Copy size={15}/>{copied ? 'Copied' : 'Copy'}</button></div>}</GroupedList>
    <p className="settings-caption">{!user ? 'Get wabi’s score right on eBay and Chrono24 listings while you browse. The extension comes with the monthly plan or any scan pack.'
      : !wallet?.paid ? 'Start the monthly plan or buy a scan pack above, then connect the extension here.'
      : key ? 'Click the wabi icon in your browser’s toolbar and paste this key. A new key replaces this one.' : 'Get a key, then paste it into the extension from your browser’s toolbar.'}</p>
    {error && <FormError>{error}</FormError>}
  </section>;
}
// Something that could not be loaded: one cell with a mark, what happened in a sentence, and a way to try again.
// A field's or an action's error, the sign-in pattern: the cross, then one sentence in Footnote.
function FormError({ children, id, className = '' }) {
  return <p className={`form-error ${className}`} id={id} role="alert"><VerdictMark kind="fail" size={10}/><span>{children}</span></p>;
}
// quiet: a load that started on its own (a market price) is announced politely, not as an alert.
function ErrorCell({ children, retry, busy = false, quiet = false }) {
  return <div className="glist error-cell" role={quiet ? 'status' : 'alert'}><div className="grow static"><span className="error-mark" aria-hidden="true"><VerdictMark kind="fail" size={10}/></span><span className="grow-main"><span className="grow-title">{children}</span></span>{retry && <button type="button" className="text-button" onClick={retry} disabled={busy}>Try again</button>}</div></div>;
}
// A row that opens in place: its chevron turns down and what it holds unfolds under it, inside the same cell.
function FoldRow({ icon, title, value, open, onToggle, children }) {
  const id = useId();
  return <><button type="button" className="grow fold-row" aria-expanded={open} aria-controls={id} onClick={() => { tap('select'); onToggle(!open); }}>{icon && <IconTile>{icon}</IconTile>}<span className="grow-main"><span className="grow-title">{title}</span></span>{value && <span className="grow-value">{value}</span>}<Chevron/></button>
    <div className="fold" id={id} data-open={open ? '' : undefined}><div className="fold-in">{children}</div></div></>;
}
// A long email keeps both ends: the name gives way in the middle first, down to its first few characters (a short
// name is never cut), and only then does the domain start to give way at its own end.
function MidTrunc({ text }) {
  const at = text.lastIndexOf('@'); const cut = at > 0 && text.length - at <= 22 ? at : Math.max(0, text.length - 12);
  return <span className="mid-trunc" data-long={cut > 6 ? '' : undefined}><span>{text.slice(0, cut)}</span><span>{text.slice(cut)}</span></span>;
}

// Full scans on Profile. The balance is a quiet tile (a green card always means a check): the count in the serif, a
// twelve-index dial for how much of the month's plan is left (its lit indices say how much, the words inside say of
// how many; the count itself is printed once, beside it), and one line saying where the scans come from. Under it
// the plan and the way to manage it. The iOS app sells nothing and links to no payment page, so it only shows the plan.
const HOURS = Array.from({ length: 12 }, (_, i) => i);
const planDate = sub => (sub?.renews ? new Date(sub.renews).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : null);
function ScanBalance({ wallet }) {
  const sub = wallet.subscription; const plan = planLeft(wallet); const total = wallet.credits + plan; const date = planDate(sub);
  const lit = sub?.active && sub.scans > 0 ? Math.max(0, Math.min(12, Math.round(sub.scansLeft / sub.scans * 12))) : null;
  const from = wallet.unlimited ? [] : [plan > 0 && `${plan} from your plan`, plan > 0 && wallet.credits > 0 && `${wallet.credits} from packs`, sub?.active && date && (sub.cancelAtPeriodEnd ? `Ends ${date}` : `Renews ${date}`)].filter(Boolean);
  return <div className="scan-balance">
    <p className="balance-figure"><b className="figure">{wallet.unlimited ? '∞' : total}</b><span>{wallet.unlimited ? 'Unlimited full scans' : `full scan${total === 1 ? '' : 's'} left`}</span></p>
    {lit !== null && <svg className="tick-dial high usage-dial" width="56" height="56" viewBox="0 0 48 48" aria-hidden="true">{HOURS.map(i => <line key={i} className={i < lit ? 'lit' : ''} x1="24" y1="2" x2="24" y2="7" transform={`rotate(${i * 30} 24 24)`}/>)}<text x="24" y="27.6" textAnchor="middle">of {sub.scans}</text></svg>}
    {from.length > 0 && <p className="balance-line num">{from.join(' · ')}</p>}
  </div>;
}
function PlanStatus({ sub, onError, unpaid = false }) {
  const [busy, setBusy] = useState(false); const date = planDate(sub);
  async function manage() { setBusy(true); try { await openBillingPortal(); } catch (e) { onError(e.message); setBusy(false); } }
  const paused = 'Your last payment didn’t go through, so the plan’s scans are paused.';
  const when = date && (sub.cancelAtPeriodEnd ? `Ends ${date}. It won’t renew.` : `Renews ${date}`);
  return <GroupedList className="plan-status">
    {unpaid ? (isNative ? <GroupedRow lead={<IconTile><CreditCard/></IconTile>} title="Monthly plan" sub={`${paused} Update your card on the web, in Profile.`}/>
      : <ActionRow icon={<CreditCard/>} title="Update card" sub={`${paused} Update your card to keep your plan.`} onClick={manage} busy={busy} external/>)
      : <><GroupedRow lead={<IconTile><CalendarDays/></IconTile>} title="Monthly plan" sub={<span className="num">{sub.scansLeft} of {sub.scans} full scans left this month</span>} end={isNative && when ? <span className="grow-value">{when}</span> : null}/>
        {!isNative && <ActionRow icon={<SlidersHorizontal/>} title="Manage plan" sub={when} onClick={manage} busy={busy} external/>}</>}
  </GroupedList>;
}
function ScansSection({ wallet, down, refreshWallet }) {
  const [note, setNote] = useState(''); const [busy, setBusy] = useState(false);
  const sub = wallet?.subscription; const held = !sub?.active && PLAN_HELD.includes(sub?.status);
  const again = async () => { setBusy(true); await refreshWallet(); setBusy(false); };
  return <section className="settings-group" aria-labelledby="set-scans"><h2 id="set-scans" className="settings-label">Full scans</h2>
    {!wallet ? (down ? <ErrorCell retry={again} busy={busy}>Your scans couldn’t be loaded.</ErrorCell> : <div className="scan-balance" role="progressbar" aria-label="Loading your scans" aria-busy="true"><p className="balance-figure"><Skeleton width={44} height={40} radius={8}/><Skeleton width={112} height={14}/></p></div>) : <>
      <ScanBalance wallet={wallet}/>
      {(sub?.active || held) && <PlanStatus sub={sub} onError={setNote} unpaid={held}/>}
      <p className="settings-caption">{!sub?.active && sub?.status && !held ? 'Your monthly plan has ended. Pack scans you bought still work. ' : ''}{freeLine(wallet)}A full scan checks every claim, the seller and each photo.</p>
      {note && <FormError className="settings-caption">{note}</FormError>}
    </>}
  </section>;
}
// What is on sale (on the web only), then the access code: a row that opens in place to what a code does, its field
// and Save code. The App Store doesn't allow outside payment for digital goods, so the iOS app shows one line instead.
function OfferSection({ wallet, refreshWallet }) {
  const { user } = useContext(Account);
  const [code, setCode] = useState(accessCode()); const [open, setOpen] = useState(false); const [busy, setBusy] = useState(''); const [note, setNote] = useState('');
  async function apply(e) {
    e.preventDefault(); setBusy('code'); setNote('');
    try {
      if (!code.trim()) {
        if (!accessCode()) setNote('Enter an access code first.');
        else { setAccessCode(''); await refreshWallet({ access: '' }); setNote('Access code removed.'); }
      } else {
        const w = await refreshWallet({ access: code.trim() });
        if (w.accessCodeValid) { setAccessCode(code); await refreshWallet(); setNote('Access code saved. Checks and full scans are unlimited on this device.'); }
        else { setNote('That code is not valid.'); notify('error'); }
      }
    } catch (err) { setNote(err.message); } finally { setBusy(''); }
  }
  async function buy(pack) { setBusy('buy'); setNote(''); try { await startCheckout(pack); } catch (err) { setNote(err.message); if (err.scansDown) refreshWallet(); setBusy(''); } }
  const sells = Boolean(wallet?.paymentsEnabled && !wallet.unlimited);
  return <section className="settings-group offer-group" aria-labelledby={sells && !isNative ? 'set-offer' : undefined} aria-label={sells && !isNative ? undefined : 'Access code'}>
    {sells && !isNative && <h2 id="set-offer" className="settings-label">More scans</h2>}
    {sells && <PackOffer wallet={wallet} onBuy={buy} busy={busy === 'buy'} variant={authEnabled && !user ? 'secondary' : 'primary'}/>}
    <GroupedList className="code-group"><FoldRow icon={<KeyRound/>} title="Have an access code?" value={wallet?.accessCodeValid ? 'Saved' : null} open={open} onToggle={setOpen}>
      <p className="fold-note">An access code gives unlimited free checks and full scans on this device, with no sign-in needed. wabi gives them to testers and reviewers; you don’t need one to buy scans.</p>
      <form className="form-rows code-entry" onSubmit={apply}>
        <label className="form-row"><span className="form-row-label">Access code</span><span className="form-row-field"><input value={code} onChange={e => setCode(e.target.value)} placeholder="Type or paste it" autoCapitalize="off" autoCorrect="off" spellCheck={false} enterKeyHint="done"/></span></label>
        <button className="grow tint-row" disabled={busy === 'code'} aria-busy={busy === 'code' || undefined}><span className="grow-main"><span className="grow-title">Save code</span></span>{busy === 'code' && <TickSpinner size={16}/>}</button>
      </form>
    </FoldRow></GroupedList>
    {note && <p className="settings-caption" role="status">{note}</p>}
  </section>;
}
// The top of Profile: who is signed in, or a way to sign in. Until sign-in is set up it says so, rather than hiding.
function AccountSection({ refreshWallet }) {
  const { user, askSignIn } = useContext(Account);
  const [confirming, setConfirming] = useState(false); const [leaving, setLeaving] = useState(false); const [error, setError] = useState('');
  // (resolving false keeps the alert open, with the reason under its message)
  async function remove() {
    setError('');
    try { await deleteAccount(); await signOut().catch(() => {}); refreshWallet(); return true; }
    catch (e) { setError(e.message); notify('error'); return false; }
  }
  if (user) return <><section className="card profile-card" aria-label="Account">
    <div className="grow static account-row"><span className="account-disc" aria-hidden="true">{(user.email || '?')[0].toUpperCase()}</span><span className="grow-main"><span className="grow-title account-name"><MidTrunc text={user.email || 'Signed in'}/></span><span className="grow-sub">Scans saved to your account</span></span></div>
    <button type="button" className="grow tint-row" disabled={leaving} aria-busy={leaving || undefined} onClick={async () => { setLeaving(true); try { await signOut(); refreshWallet(); } finally { setLeaving(false); } }}><span className="grow-main"><span className="grow-title">Sign out</span></span>{leaving && <TickSpinner size={16}/>}</button>
    <button type="button" className="grow ink-row" onClick={() => { setError(''); setConfirming(true); }}><span className="grow-main"><span className="grow-title">Delete account</span></span></button></section>
    {confirming && <Alert title="Delete your account?" message="This deletes your wabi account, the scans saved to it and any full scans left on it, for good, and cancels a monthly plan. Unused scans aren’t refunded. Listings and photos saved on this device stay until you delete them in Profile."
      confirm={{ label: 'Delete account', onSelect: remove }} cancel="Keep my account" error={error} onClose={() => setConfirming(false)}/>}</>;
  return <section className="card profile-card signed-out" aria-label="Account"><div className="account-row"><span className="account-disc" aria-hidden="true"><UserRound size={22} strokeWidth={1.6}/></span>
    <span className="grow-main"><span className="grow-title account-name">Sign in to wabi</span><span className="grow-sub">{authEnabled ? 'Unlock full reports and keep your scans on any device.' : 'Accounts open soon. Your listings stay on this device.'}</span></span></div>
    <Button onClick={() => askSignIn('profile')} disabled={!authEnabled}>Sign in</Button></section>;
}
// A button's label while it works: the label gives way to the tick spinner (then to a check that draws itself, where
// there is a success to show) but stays the button's name, so it can still be found and read.
function Working({ on, done, children }) {
  if (!on) return children;
  return <>{done ? <svg className="drawn-check" width="20" height="20" viewBox="0 0 20 20" aria-hidden="true"><path d="M4.5 10.5l3.8 3.8 7.4-8.6" pathLength="1"/></svg> : <TickSpinner size={20}/>}<span className="sr-only">{children}</span></>;
}
// One step of a sheet that moves to the next. Each step has a side it comes from and goes back to (the first step the
// leading side, the second the trailing one); when a step is replaced, a lifeless copy of it leaves to its side while
// the new one arrives. Under Reduce Motion the steps simply change.
function SlideStep({ side, enter, className = '', children }) {
  const ref = useRef();
  useLayoutEffect(() => {
    const el = ref.current;
    return () => {
      const home = el.parentNode; if (!home || reduceMotion()) return;
      const ghost = el.cloneNode(true);
      for (const n of [ghost, ...ghost.querySelectorAll('*')]) for (const a of ['id', 'for', 'name', 'role', 'aria-label', 'aria-labelledby', 'aria-describedby', 'data-enter']) n.removeAttribute(a);
      ghost.inert = true; ghost.setAttribute('aria-hidden', 'true'); ghost.classList.add('is-leaving');
      home.appendChild(ghost); setTimeout(() => ghost.remove(), cssMs('--t-step', 320) + 40);
    };
  }, []);
  return <div ref={ref} className={`slide-step ${className}`} data-side={side} data-enter={enter ? '' : undefined}>{children}</div>;
}

// The box the steps sit in moves between their heights instead of jumping: whenever the step in it comes out a
// different height (the other step, or an answer that changes what is offered), the box travels from the height it
// shows now to the new one, cut to its own edges on the way, and the sheet's top edge travels with it.
function useEasedHeight(ref) {
  const last = useRef(null);
  useLayoutEffect(() => {
    const el = ref.current; const step = el?.querySelector(':scope > .slide-step:not(.is-leaving)'); if (!step) return;
    const now = step.offsetHeight; const was = last.current; last.current = now;
    if (was == null || was === now || reduceMotion()) return;
    // (in flight it has a height of its own to start from; at rest it was as tall as the step it held)
    const from = el.style.height ? el.getBoundingClientRect().height : was;
    el.style.transition = 'none'; el.style.height = `${from}px`; el.dataset.moving = ''; el.getBoundingClientRect();
    el.style.transition = ''; el.style.height = `${now}px`;
    if (Math.abs(from - now) < .5) { el.style.height = ''; delete el.dataset.moving; }
  });
  return { onTransitionEnd: e => { const el = ref.current; if (e.target === el && e.propertyName === 'height') { el.style.height = ''; delete el.dataset.moving; } } };
}

const AppleMark = () => <svg width="17" height="17" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M16.37 12.6c-.02-2.3 1.88-3.4 1.96-3.46-1.07-1.56-2.73-1.77-3.32-1.8-1.41-.14-2.76.83-3.48.83-.72 0-1.82-.81-3-.79-1.54.02-2.97.9-3.76 2.28-1.6 2.78-.41 6.9 1.15 9.16.76 1.1 1.67 2.34 2.86 2.3 1.15-.05 1.58-.74 2.97-.74 1.38 0 1.77.74 2.98.72 1.23-.02 2.01-1.12 2.76-2.23.87-1.28 1.23-2.52 1.25-2.58-.03-.01-2.4-.92-2.42-3.66zM14.1 5.86c.63-.77 1.06-1.83.94-2.89-.91.04-2.01.61-2.67 1.37-.58.67-1.1 1.76-.96 2.8 1.02.08 2.06-.52 2.69-1.28z"/></svg>;
const GoogleMark = () => <svg width="17" height="17" viewBox="0 0 24 24" aria-hidden="true"><path fill="#4285F4" d="M22.5 12.24c0-.78-.07-1.53-.2-2.24H12v4.24h5.9a5.05 5.05 0 0 1-2.19 3.31v2.75h3.54c2.08-1.91 3.25-4.73 3.25-8.06z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.54-2.75c-.98.66-2.24 1.05-3.74 1.05-2.87 0-5.3-1.94-6.17-4.55H2.17v2.84A11 11 0 0 0 12 23z"/><path fill="#FBBC05" d="M5.83 14.09a6.6 6.6 0 0 1 0-4.18V7.07H2.17a11 11 0 0 0 0 9.86l3.66-2.84z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.07.56 4.21 1.65l3.15-3.15A10.96 10.96 0 0 0 12 1 11 11 0 0 0 2.17 7.07l3.66 2.84C6.7 7.32 9.13 5.38 12 5.38z"/></svg>;

// Sign-in: Apple or Google on the web, or a six-digit code by email anywhere.
// reason: 'profile' (from Profile), 'scan' (before the free check) or anything else (unlocking a full report).
// The code step: six cells drawn under one real field, so the keyboard's one-time-code suggestion and a paste both
// fill it. The sixth digit sends it after a beat (long enough to see it land); a wrong code shakes the cells and
// clears them; the right one rings them in the tint, draws a check and closes the sheet.
const EMAIL_SHAPE = /^\S+@\S+\.\S+$/;
const RESEND_AFTER = 30; const CODE_BEAT = 240; const DONE_HOLD = 520;
const countdown = s => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
function SignInSheet({ reason, close, done }) {
  const fromProfile = reason === 'profile'; const forScan = reason === 'scan';
  const [email, setEmail] = useState(''); const [code, setCode] = useState(''); const [sent, setSent] = useState(false);
  // Which button is at work ('apple', 'google', 'email', 'code' or 'resend'): it shows the spinner and the rest wait.
  const [busy, setBusy] = useState(''); const [error, setError] = useState('');
  const [social, setSocial] = useState(knownProviders); const [resend, setResend] = useState({ at: 0, left: 0 });
  const [shake, setShake] = useState(0); const [signedIn, setSignedIn] = useState(false);
  const emailRef = useRef(); const codeRef = useRef(); const typed = useRef(''); const beat = useRef(0); const moved = useRef(false);
  const steps = useRef(); const eased = useEasedHeight(steps);
  const ids = useId(); const emailId = `${ids}email`; const codeId = `${ids}code`; const errorId = `${ids}error`;
  const valid = EMAIL_SHAPE.test(email.trim());
  useEffect(() => { let live = true; enabledProviders().then(s => live && setSocial(s)); return () => { live = false; clearTimeout(beat.current); }; }, []);
  // With Apple or Google on offer the keyboard stays down until the email field is chosen; with email alone it is the
  // only way in, so the field is ready to type in.
  useEffect(() => { if (social && !social.apple && !social.google && !sent) emailRef.current?.focus({ preventScroll: true }); }, [social]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => { if (sent) codeRef.current?.focus({ preventScroll: true }); }, [sent]);
  // The wait before another code can be asked for, counted against the clock (so time spent in Mail counts too).
  const left = resend.left;
  useEffect(() => {
    if (!sent || !resend.at) return undefined;
    const tick = () => setResend(r => { const now = Math.max(0, Math.ceil((r.at - Date.now()) / 1000)); return now === r.left ? r : { ...r, left: now }; });
    const t = setInterval(tick, 250); document.addEventListener('visibilitychange', tick);
    return () => { clearInterval(t); document.removeEventListener('visibilitychange', tick); };
  }, [sent, resend.at]);
  const fail = message => { setError(message); notify('error'); };
  const run = async (key, fn) => { if (busy) return; setBusy(key); setError(''); try { await fn(); } catch (e) { fail(e.message); } finally { setBusy(''); } };
  const mail = async () => { try { await sendCode(email.trim()); } catch (err) { reportSignInFailure(`email: ${err.message}`); throw err; } setResend({ at: Date.now() + RESEND_AFTER * 1000, left: RESEND_AFTER }); };
  const send = e => { e.preventDefault(); if (!valid) { fail('Enter your email address.'); emailRef.current?.focus(); return; } run('email', async () => { await mail(); moved.current = true; setSent(true); }); };
  const verify = e => {
    e?.preventDefault(); clearTimeout(beat.current);
    if (typed.current.length !== 6) { codeRef.current?.focus(); return; }
    run('code', async () => {
      try { await verifyCode(email.trim(), typed.current); } catch (err) { typed.current = ''; setCode(''); setShake(n => n + 1); codeRef.current?.focus(); throw err; }
      setSignedIn(true); notify('success');
      await new Promise(r => setTimeout(r, reduceMotion() ? 0 : DONE_HOLD));
      done();
    });
  };
  const type = value => {
    const next = value.replace(/\D/g, '').slice(0, 6); typed.current = next; setCode(next); clearTimeout(beat.current);
    if (next && error) setError('');
    if (next.length === 6) beat.current = setTimeout(() => verify(), CODE_BEAT);
  };
  const back = () => { clearTimeout(beat.current); typed.current = ''; setCode(''); setError(''); setSent(false); };
  // While one button works the others step back and cannot be pressed.
  const wait = key => (busy && busy !== key ? { inert: true, 'data-waiting': '' } : {});
  // An error has its own line, kept under the field or the cells whether or not there is one, so nothing else moves
  // when it appears.
  const problem = <div className="signin-slot">{error && <FormError id={errorId} className="signin-error">{error}</FormError>}</div>;
  // Until the answer is in (the app asks at start, so this is rare) the two buttons' places are held for them.
  const pending = social === null; const offered = pending || social.apple || social.google;
  return <Modal className="signin-sheet" title={sent ? 'Check your email' : fromProfile ? 'Sign in to wabi' : forScan ? 'Get your free check' : 'Sign in to unlock'} close={close}>
    <div className="signin-steps" ref={steps} {...eased}>
      {!sent ? <SlideStep key="email" side="lead" enter={moved.current}>
        <p className="signin-lede">{fromProfile ? 'Keep your full scans with your account and use them on any device.' : forScan ? 'Your first check is free. Sign in so it stays with you on any device.' : 'See the full report: every claim, the seller and each photo. Your scans follow you to any device.'}</p>
        {pending && <div className="signin-social" aria-hidden="true"><Skeleton height={50} radius={999}/><Skeleton height={50} radius={999}/></div>}
        {!pending && offered && <div className="signin-social">
          {social.apple && <Button variant="apple" haptic="light" {...wait('apple')} onClick={() => run('apple', () => signInWith('apple'))}><Working on={busy === 'apple'}><AppleMark/>Continue with Apple</Working></Button>}
          {social.google && <Button variant="google" haptic="light" {...wait('google')} onClick={() => run('google', () => signInWith('google'))}><Working on={busy === 'google'}><GoogleMark/>Continue with Google</Working></Button>}
        </div>}
        <form className="signin-form" onSubmit={send} noValidate>
          {offered && <h3 className="signin-or">Or use your email</h3>}
          <div className="signin-field" {...wait('email')}><label className="sr-only" htmlFor={emailId}>Email</label>
            <input id={emailId} ref={emailRef} type="email" autoComplete="email" inputMode="email" autoCapitalize="off" autoCorrect="off" spellCheck={false} enterKeyHint="send" value={email} onChange={e => { setEmail(e.target.value); if (error) setError(''); }} placeholder="you@example.com" aria-invalid={error ? 'true' : undefined} aria-describedby={error ? errorId : undefined}/>
            {email && <button type="button" className="signin-clear" aria-label="Clear" onClick={() => { setEmail(''); setError(''); emailRef.current?.focus(); }}><svg width="17" height="17" viewBox="0 0 17 17" aria-hidden="true"><circle cx="8.5" cy="8.5" r="8.5" fill="currentColor"/><path d="M5.7 5.7l5.6 5.6M11.3 5.7l-5.6 5.6" stroke="var(--fill)" strokeWidth="1.6" strokeLinecap="round"/></svg></button>}
          </div>
          {problem}
          <Button type="submit" variant={valid ? 'primary' : 'secondary'} haptic="light" className="signin-send" {...wait('email')}><Working on={busy === 'email'}>Email me a code</Working></Button>
        </form>
      </SlideStep> : <SlideStep key="code" side="trail" enter>
        <form className="signin-form" onSubmit={verify} noValidate>
          <p className="signin-lede">We sent an email to <b>{email.trim()}</b>. Enter the 6-digit code, or tap the link in the email to sign in.</p>
          <div className="code-cells" data-shake={shake ? (shake % 2 ? 'a' : 'b') : undefined} data-done={signedIn ? '' : undefined}><label className="sr-only" htmlFor={codeId}>Code</label>
            <input id={codeId} ref={codeRef} className="code-input" type="text" inputMode="numeric" pattern="[0-9]*" autoComplete="one-time-code" value={code} onChange={e => type(e.target.value)} aria-invalid={error ? 'true' : undefined} aria-describedby={error ? errorId : undefined}/>
            <div className="code-row" aria-hidden="true">{[0, 1, 2, 3, 4, 5].map(i => <span key={i} className={`code-cell${i === Math.min(code.length, 5) ? ' at' : ''}`}>{code[i] || ''}</span>)}</div>
          </div>
          {problem}
          <p className="signin-resend num">{left > 0 ? <>Resend code in {countdown(left)}</> : <button type="button" className="text-button" {...wait('resend')} onClick={() => run('resend', mail)}>{busy === 'resend' ? 'Sending…' : 'Resend code'}</button>}</p>
          <Button type="submit" variant={code.length === 6 || busy === 'code' ? 'primary' : 'secondary'} haptic="light" {...wait('code')}><Working on={busy === 'code'} done={signedIn}>Sign in</Working></Button>
          {isNative && <Button variant="secondary" {...wait('mail')} onClick={openMail}>Open Mail</Button>}
          <button type="button" className="text-button signin-other" {...wait('other')} onClick={back}>Use a different email</button>
        </form>
      </SlideStep>}
    </div>
    <p className="signin-foot">By continuing you agree to the <a href={TERMS_URL} target="_blank" rel="noopener noreferrer">terms of use</a> and the <a href={PRIVACY_URL} target="_blank" rel="noopener noreferrer">privacy policy</a>. Your scans are saved to your account; photos you add stay on this device.</p>
  </Modal>;
}

// Saved cards. They are kept by Stripe, never by wabi, so this only lists brand, last four digits and expiry. Every
// brand's tile is the same ink card with its name on it. Remove asks once, in the same action sheet as a listing or a watch. On a narrow phone the
// word "ending" is drawn as two dots, so the brand is never cut to make room for it.
const CARD_SHORT = { amex: 'Amex', mastercard: 'MC' };
const CARD_BRANDS = { visa: 'Visa', mastercard: 'Mastercard', amex: 'Amex', discover: 'Discover', diners: 'Diners Club', jcb: 'JCB', unionpay: 'UnionPay' };
function PaymentMethodsSection({ wallet }) {
  const { user, askSignIn } = useContext(Account);
  const signInFirst = authEnabled && wallet.authEnabled && !user;
  const [methods, setMethods] = useState(null); const [failed, setFailed] = useState(false); const [note, setNote] = useState(''); const [busy, setBusy] = useState(false); const [confirming, setConfirming] = useState(null);
  const load = () => paymentMethods().then(r => { setMethods(Array.isArray(r?.methods) ? r.methods : []); setFailed(false); });
  useEffect(() => { setMethods(null); setNote(''); setFailed(false); if (signInFirst) return undefined; let live = true; load().catch(e => { if (live) { console.warn('saved cards not loaded:', e.message); setFailed(true); } }); return () => { live = false; }; }, [user?.id, signInFirst]); // eslint-disable-line react-hooks/exhaustive-deps
  // Add a card opens the in-app sheet; the list is read again once a card is saved.
  const [adding, setAdding] = useState(false);
  function add() { setNote(''); tap(); setAdding(true); }
  const reload = async () => { setBusy(true); try { await load(); } catch (e) { console.warn('saved cards not loaded:', e.message); setFailed(true); } finally { setBusy(false); } };
  async function remove(id) { setBusy(true); setNote(''); tap('rigid'); try { const r = await removePaymentMethod(id); setMethods(Array.isArray(r?.methods) ? r.methods : []); setConfirming(null); } catch (e) { setNote(e.message); notify('error'); } finally { setBusy(false); } }
  const brand = m => CARD_BRANDS[m.brand] || 'Card';
  const cardIcon = <IconTile><CreditCard/></IconTile>;
  return <section className="settings-group payment-methods" aria-labelledby="set-payment"><h2 id="set-payment" className="settings-label">Payment methods</h2>
    {signInFirst ? <><GroupedList><GroupedRow lead={cardIcon} title="Saved cards" sub="Signed out" end={<button type="button" className="text-button" onClick={() => askSignIn()}>Sign in</button>}/></GroupedList><p className="settings-caption">Sign in to save a card for faster checkout.</p></>
      : failed && !methods ? <ErrorCell retry={reload} busy={busy}>Your saved cards couldn’t be loaded.</ErrorCell> : <>
        {methods === null ? <SkeletonRows count={2} thumb={30} label="Loading saved cards"/> : <GroupedList className="card-list">
          {methods.length === 0 && <GroupedRow lead={cardIcon} title="Saved cards" sub="No saved cards" end={null}/>}
          {methods.map(m => <div key={m.id} className="grow static saved-card">
            <span className="card-tile" aria-hidden="true"><b>{CARD_SHORT[m.brand] || brand(m).split(' ')[0]}</b></span>
            <span className="grow-main"><span className="grow-title card-name num">{brand(m)} <span className="card-ending">ending </span><span className="card-dots" aria-hidden="true"/>{m.last4}</span>
              <span className="grow-sub num">Expires {String(m.expMonth).padStart(2, '0')}/{String(m.expYear).slice(-2)}</span></span>
            <button type="button" className="text-button" disabled={busy} onClick={() => { tap('select'); setConfirming(m.id); }} aria-label={`Remove ${brand(m)} ending ${m.last4}`}>Remove</button>
          </div>)}
          {!isNative && <button type="button" className="grow tint-row add-card-row" onClick={add} disabled={busy}><IconTile><Plus/></IconTile><span className="grow-main"><span className="grow-title">Add a card</span></span></button>}
        </GroupedList>}
        <p className="settings-caption">{isNative ? 'Cards saved to your wabi account show here. ' : ''}Cards are stored by Stripe. wabi never sees or keeps your card number.</p></>}
    {confirming && (m => m && <ActionSheet title="Remove this card?"
      header={{ thumb: <span className="card-tile"><b>{CARD_SHORT[m.brand] || brand(m).split(' ')[0]}</b></span>, name: `${brand(m)} ending ${m.last4}`, line: `Expires ${String(m.expMonth).padStart(2, '0')}/${String(m.expYear).slice(-2)}` }}
      actions={[{ label: 'Remove card', destructive: true, onSelect: () => remove(m.id) }]} cancel="Keep it" onClose={() => setConfirming(null)}/>)(methods?.find(x => x.id === confirming))}
    {adding && <AddCardSheet email={user?.email} onClose={() => setAdding(false)} onAdded={() => { load().catch(e => setNote(e.message)); }}/>}
    {note && <FormError className="settings-caption">{note}</FormError>}
  </section>;
}
// The permission asked before photos you add yourself are sent for review. It is given in context, by the consent
// dialog the review shows, so all Profile can do is say where it stands and take it back: a state and one action,
// not a switch that would promise to turn it on.
function PermissionSection() {
  const [allowed, setAllowed] = useState(hasConsent);
  return <section className="settings-group" aria-labelledby="set-permission"><h2 id="set-permission" className="settings-label">Privacy</h2>
    <GroupedList><GroupedRow lead={<IconTile><Camera/></IconTile>} title="Photo review" end={<span className="grow-value">{allowed ? 'Allowed' : 'Off'}</span>}/>
      {allowed && <button type="button" className="grow tint-row" onClick={() => { tap(); setConsent(false); setAllowed(false); }}><span className="grow-main"><span className="grow-title">Withdraw permission</span></span></button>}</GroupedList>
    <p className="settings-caption">{allowed ? 'You’ve allowed wabi to send the photos you add yourself, and the details you enter, to its review service when you tap Review photos.'
      : 'wabi asks before it sends photos you add yourself for review. You haven’t allowed this yet, or you’ve withdrawn it. Nothing is sent until you allow it.'}</p>
  </section>;
}
// Profile is a Settings screen: flat grouped cells, one after another, and one centred footer. The first time it is
// shown its groups rise into place one after another; after that it is simply there.
let profileShown = false;
function ProfilePage({ erase, navigate, wallet, walletDown, refreshWallet }) {
  const tile = Icon => <IconTile><Icon/></IconTile>;
  const [rise] = useState(() => { const first = !profileShown; profileShown = true; return first; });
  const [credits, setCredits] = useState(false);
  return <><PageHead title="Profile"/><div className="profile" data-rise={rise ? '' : undefined}>
    <div className="profile-col">
      <AccountSection refreshWallet={refreshWallet}/>
      {scanAvailable && <ScansSection wallet={wallet} down={walletDown} refreshWallet={refreshWallet}/>}
    </div>
    <div className="profile-col">
      {scanAvailable && <OfferSection wallet={wallet} refreshWallet={refreshWallet}/>}
      {scanAvailable && authEnabled && extensionOn && <ExtensionSection wallet={wallet}/>}
      {scanAvailable && wallet?.paymentsEnabled && <PaymentMethodsSection wallet={wallet}/>}
      {analysisAvailable && <PermissionSection/>}
      <section className="settings-group" aria-labelledby="set-about"><h2 id="set-about" className="settings-label">About</h2>
        <GroupedList>
          <GroupedRow lead={tile(Info)} title="How wabi works" onClick={() => navigate('guide')}/>
          <GroupedRow lead={tile(BookOpen)} title="How to spot a fake" onClick={() => navigate('markers')}/>
          <GroupedRow lead={tile(LockKeyhole)} title="Privacy policy" href={PRIVACY_URL} external/>
          <GroupedRow lead={tile(FileText)} title="Terms of use" href={TERMS_URL} external/>
          <GroupedRow lead={tile(LifeBuoy)} title="Support" href={SUPPORT_URL} external/>
          <FoldRow icon={<ImageIcon/>} title="Photo credits" open={credits} onToggle={setCredits}>{PHOTO_CREDITS.map(line => <p key={line} className="fold-note">{line}</p>)}</FoldRow>
        </GroupedList></section>
      <section className="settings-group" aria-labelledby="set-data"><h2 id="set-data" className="settings-label">Data</h2>
        <GroupedList><button type="button" className="grow ink-row" onClick={erase}><span className="grow-main"><span className="grow-title">Delete all data</span></span></button></GroupedList>
        <p className="settings-caption">Removes listings, photos and your collection from this device.</p></section>
    </div>
    <footer className="profile-foot"><span className="wordmark-inline" aria-hidden="true">wabi</span><p>Version {APP_VERSION}</p><p>Estimates are not appraisals or certificates of authenticity.</p><p>Independent. Not affiliated with, or endorsed by, any watch brand.</p></footer>
  </div></>;
}
// How wabi works: a reading page pushed from the tab it was opened from. Five things to know as numbered cells, what
// happens to your data as a group of its own, and one way on at the end (no bar floating over the text).
const GUIDE = [
  { title: 'Start with the reference', text: 'The model name in a listing is only a claim. The reference and year decide which details the watch should have.' },
  { title: 'Genuine and original are different', text: 'A real watch can have a service dial, a newer bracelet or relumed hands. We flag each part separately, because each one changes the value.' },
  { title: 'A score, and what holds it back', text: 'Every scan gives a score from the listing’s photos, details and seller. Few photos, a failed tell or a risky seller keep the score down. It is never a certificate.' },
  { title: 'Price from the market', text: 'You see a low, typical and high price for the reference, plus any completed sales you add.' },
  { title: 'Finish with a watchmaker', text: 'Only someone holding the watch can check the movement and the parts photos can’t show.' },
  { title: 'What is kept, and where', text: 'Your photos and your collection stay on this device. What goes to your account, and what is sent for review, is set out below.' },
];
const GUIDE_DATA = [
  { title: 'On this device', text: 'Photos you add and your collection. They are not in your account.' },
  { title: 'In your account', text: 'When you’re signed in, the listings you scan, so they show on any device you sign in on.' },
  { title: 'Sent for review', text: 'A listing’s link, so wabi can score it. Photos you add yourself are sent only once you allow it.' },
];
function Guide({ back, start }) {
  return <><PageHead back={back} title="How wabi works" sub="Six things to know before you trust a listing."/><div className="guide">
    <EditorialArt name="bench-tools" night className="guide-art"/>
    <ol className="glist guide-points">{GUIDE.map((p, i) => <li key={p.title} style={{ '--n': i }}><span className="guide-num" aria-hidden="true">{i + 1}</span><div><h2>{p.title}</h2><p>{p.text}</p></div></li>)}</ol>
    <section className="settings-group" aria-labelledby="guide-data" style={{ '--n': GUIDE.length }}><h2 id="guide-data" className="settings-label">Your data</h2>
      <GroupedList>{GUIDE_DATA.map(d => <GroupedRow key={d.title} title={d.title} sub={d.text}/>)}</GroupedList>
      <p className="settings-caption">Delete your saved data any time from Profile.</p></section>
    <Button className="guide-start" onClick={start} style={{ '--n': GUIDE.length + 1 }}>Start a check</Button>
  </div></>;
}

const COMPONENT_TITLES = Object.fromEntries(CHECKS.map(c => [c.id, c.title]));
// The area of the watch in one word: the heading tells are grouped under.
const COMPONENT_AREAS = { identity: 'Reference', dial: 'Dial', hands: 'Hands', case: 'Case', bezel: 'Bezel', bracelet: 'Bracelet', movement: 'Movement', provenance: 'Provenance' };
// What you can see in a photo comes first; the paperwork last.
const PART_ORDER = ['dial', 'hands', 'case', 'bezel', 'bracelet', 'movement', 'identity', 'provenance'];
const partRank = c => { const i = PART_ORDER.indexOf(c.component); return i === -1 ? PART_ORDER.length : i; };
// How much a tell counts, as a mark and a word (never a colour): a strong sign, a tell, or a plain fact about the reference.
// What kind of claim a card holds, as a label: not a verdict, so it carries no verdict mark.
const strengthOf = c => (c.weight === 'strong' ? 'Strong sign' : c.kind === 'tell' ? 'Tell' : 'Fact');
function claimScope(c) {
  return [c.family || `${c.brand}, all models`, c.references.includes('*') ? null : c.references.join(', '), c.period && `${c.period.fromYear ?? '…'}–${c.period.toYear ?? 'today'}`, c.variant].filter(Boolean).join(' · ');
}
// One tell: its strength, the claim, the watches it applies to, and (opening in place) what fakes get wrong and how to
// check it in a photo. A claim with more to open is held to three lines until it is opened.
function TellCard({ c }) {
  const [open, setOpen] = useState(false); const id = useId(); const word = strengthOf(c); const more = Boolean(c.counterfeitSign || c.photoCheck);
  return <article className={`source-card${more ? ' has-more' : ''}${open ? ' open' : ''}`}>
    <p className="tell-kind">{word}</p>
    <h3>{c.claim}</h3>
    <p className="subtle">{claimScope(c)}</p>
    {more && <><button type="button" className="tell-more" aria-expanded={open} aria-controls={id} onClick={() => { tap('select'); setOpen(!open); }}>{c.counterfeitSign ? 'What fakes get wrong' : 'How to check in photos'}<Chevron/></button>
      <div className="fold" id={id} data-open={open ? '' : undefined}><div className="fold-in">{c.counterfeitSign && <p><b>Fakes often:</b> {c.counterfeitSign}</p>}{c.photoCheck && <p><b>Check in photos:</b> {c.photoCheck}</p>}</div></div></>}
  </article>;
}
// A row of 32pt pills that scrolls sideways; the chosen one is filled with ink and brought into view. A pill may carry
// a count after its name, and the row may end in a quiet line saying what else there is.
function PillRow({ label, options, value, onChange, soon = [], hint }) {
  const row = useRef();
  useEffect(() => {
    const el = row.current; const on = el?.querySelector('[aria-pressed=true]'); if (!on || el.scrollWidth <= el.clientWidth) return;
    const lead = parseFloat(getComputedStyle(el).paddingLeft) || 0;
    el.scrollTo({ left: Math.max(0, on.getBoundingClientRect().left - el.getBoundingClientRect().left + el.scrollLeft - lead), behavior: reduceMotion() ? 'auto' : 'smooth' });
  }, [value]);
  return <div className="pill-group"><span className="pill-label" aria-hidden="true">{label}</span>
    <div className="pill-row" role="group" aria-label={label} ref={row}>{options.map(o => <button key={o.value} type="button" className="pill" aria-pressed={value === o.value} onClick={() => { tap('select'); onChange(o.value); }}><span>{o.label}{o.count != null && <i className="num">{o.count.toLocaleString('en-US')}</i>}</span></button>)}
      {soon.map(b => <span key={b} className="pill soon" aria-label={`${b}, coming soon`}><span>{b} · soon</span></span>)}
      {hint && <span className="pill-hint">{hint}</span>}</div></div>;
}
// The library is read by brand, then model family, then the part of the watch. With every part on show each part gives
// its five strongest tells and a row that opens the rest; with one part chosen its tells load twenty at a time.
const TELL_PAGE = 20; const TELL_PREVIEW = 5; const FAMILY_TOP = 12;
function MarkersPage({ back }) {
  const [claims, error, retry] = useClaims(); const [query, setQuery] = useState(''); const [brand, setBrand] = useState('all'); const [family, setFamily] = useState('all'); const [part, setPart] = useState('all'); const [limit, setLimit] = useState(TELL_PAGE);
  const [searching, setSearching] = useState(false); const [keyed, setKeyed] = useState(false); const input = useRef(); const more = useRef(); const parts = useRef(); const pressed = useRef(false); const jump = useRef(false);
  const live = (claims || []).filter(c => c.status !== 'superseded');
  const brands = [...new Set(live.map(c => c.brand))];
  // Brands queued in the research backlog but with no claims yet are shown as coming, so the library reads as growing, not missing.
  const coming = coverage.brands.filter(b => !brands.includes(b.brand)).map(b => b.brand);
  const all = live.filter(c => brand === 'all' || c.brand === brand);
  const scope = c => c.family || 'Brand-wide';
  const perFamily = {}; for (const c of all) perFamily[scope(c)] = (perFamily[scope(c)] || 0) + 1;
  const everyFamily = Object.keys(perFamily).sort();
  // Every brand at once has a hundred families, too many for one row: the dozen with the most to read are offered (and
  // whichever is chosen), and the row says that a brand shows its own.
  const families = brand !== 'all' ? everyFamily : [...everyFamily].sort((a, b) => perFamily[b] - perFamily[a]).slice(0, FAMILY_TOP).concat(family !== 'all' && perFamily[family] ? [family] : []).filter((f, i, list) => list.indexOf(f) === i);
  const references = new Set(all.flatMap(c => c.references.filter(r => r !== '*')));
  const q = query.trim().toLowerCase();
  const matching = all.filter(c => (family === 'all' || scope(c) === family) && (!q || `${c.claim} ${c.counterfeitSign || ''} ${c.references.join(' ')} ${c.family || ''} ${c.variant || ''} ${COMPONENT_TITLES[c.component]}`.toLowerCase().includes(q)))
    .sort((a, b) => partRank(a) - partRank(b) || (b.kind === 'tell') - (a.kind === 'tell') || (b.weight === 'strong') - (a.weight === 'strong'));
  const totals = {}; for (const c of matching) totals[c.component] = (totals[c.component] || 0) + 1;
  const present = [...new Set(matching.map(c => c.component))];
  const filtered = part === 'all' ? matching : matching.filter(c => c.component === part);
  const pickBrand = b => { setBrand(b); setFamily('all'); setLimit(TELL_PAGE); };
  const pickPart = (p, top = false) => { jump.current = top; setPart(p); setLimit(TELL_PAGE); };
  // Every part: a short read of each (a part with one more than that is shown whole). One part: its page so far.
  const groups = part === 'all' ? present.map(p => { const items = matching.filter(c => c.component === p); const shown = items.length > TELL_PREVIEW + 1 ? items.slice(0, TELL_PREVIEW) : items; return { part: p, items: shown, rest: items.length - shown.length }; })
    : filtered.length ? [{ part, items: filtered.slice(0, limit), rest: 0 }] : [];
  const rest = part === 'all' ? 0 : filtered.length - limit;
  useEffect(() => {
    if (rest <= 0 || !more.current || !('IntersectionObserver' in window)) return undefined;
    const io = new IntersectionObserver(es => { if (es.some(e => e.isIntersecting)) setLimit(l => l + TELL_PAGE); }, { rootMargin: '600px 0px' });
    io.observe(more.current); return () => io.disconnect();
  }, [rest > 0, limit]); // eslint-disable-line react-hooks/exhaustive-deps
  // "Show all" on a part leaves you at the top of that part's list, not wherever its sixth cell used to be.
  useLayoutEffect(() => { if (!jump.current) return; jump.current = false; parts.current?.scrollIntoView({ block: 'start', behavior: reduceMotion() ? 'auto' : 'smooth' }); }, [part]);
  const n = k => all.filter(c => c.kind === k).length; const area = p => COMPONENT_AREAS[p] || COMPONENT_TITLES[p] || 'Other';
  const reset = () => { setQuery(''); setPart('all'); pickBrand('all'); };
  return <><PageHead back={back} title="How to spot a fake"/><div className="tells">
    <div className="tells-head"><EditorialArt name="bench-tools" night className="tells-thumb"/>
      {claims ? <p className="tells-counts num"><span><b>{n('tell').toLocaleString('en-US')}</b> counterfeit {n('tell') === 1 ? 'tell' : 'tells'}</span><span><b>{n('spec').toLocaleString('en-US')}</b> reference {n('spec') === 1 ? 'fact' : 'facts'}</span><span><b>{everyFamily.length.toLocaleString('en-US')}</b> model {everyFamily.length === 1 ? 'family' : 'families'}<span className="tells-refs"> · {tally(references.size, 'reference')}</span></span></p>
        : <p className="tells-counts" aria-hidden="true"><Skeleton width="70%" height={12}/><Skeleton width="60%" height={12}/><Skeleton width="80%" height={12}/></p>}</div>
    {/* (the field shows a ring only when focus came from the keyboard: a tap already shows the caret and Cancel) */}
    <div className="tells-search"><div className="search-box" data-keyed={keyed ? '' : undefined} onPointerDown={() => { pressed.current = true; }}><Search size={17} strokeWidth={1.8} aria-hidden="true"/>
      <input ref={input} type="text" inputMode="search" enterKeyHint="search" autoCapitalize="off" autoCorrect="off" spellCheck={false} aria-label="Search the knowledge base" placeholder="Search tells, parts or references" value={query} onChange={e => { setQuery(e.target.value); setLimit(TELL_PAGE); }} onFocus={() => { setSearching(true); setKeyed(!pressed.current); pressed.current = false; }} onBlur={() => { setSearching(false); setKeyed(false); pressed.current = false; }}/>
      {query && <button type="button" className="search-clear" aria-label="Clear search" onMouseDown={e => e.preventDefault()} onClick={() => { setQuery(''); setLimit(TELL_PAGE); input.current?.focus(); }}><svg width="17" height="17" viewBox="0 0 17 17" aria-hidden="true"><circle cx="8.5" cy="8.5" r="8.5" fill="currentColor"/><path d="M5.7 5.7l5.6 5.6M11.3 5.7l-5.6 5.6" stroke="var(--canvas)" strokeWidth="1.6" strokeLinecap="round"/></svg></button>}</div>
      {searching && <button type="button" className="text-button search-cancel" onMouseDown={e => e.preventDefault()} onClick={() => { setQuery(''); setLimit(TELL_PAGE); input.current?.blur(); }}>Cancel</button>}</div>
    {error && <ErrorCell retry={retry}>{error}</ErrorCell>}
    {(brands.length > 1 || coming.length > 0) && <PillRow label="Brand" value={brand} onChange={pickBrand} soon={coming} options={['all', ...brands].map(b => ({ value: b, label: b === 'all' ? 'All brands' : b }))}/>}
    {claims && <PillRow label="Model family" value={family} onChange={f => { setFamily(f); setLimit(TELL_PAGE); }} options={['all', ...families].map(f => ({ value: f, label: f === 'all' ? 'All' : f }))}
      hint={brand === 'all' && everyFamily.length > families.length ? `Choose a brand to see all ${everyFamily.length}` : null}/>}
    {claims && <div className="tells-parts" ref={parts}><PillRow label="Part" value={part} onChange={pickPart} options={[{ value: 'all', label: 'All parts' }, ...[...new Set([...present, ...(part === 'all' ? [] : [part])])].sort((a, b) => partRank({ component: a }) - partRank({ component: b })).map(p => ({ value: p, label: area(p), count: totals[p] || 0 }))]}/></div>}
    <p className={`tells-status num${claims && !filtered.length ? ' sr-only' : ''}`} role="status">{claims ? `${tally(filtered.length, 'tell or fact', 'tells and facts')}${family === 'Brand-wide' ? ' that apply to every model of the brand' : ''}` : ''}</p>
    {!claims && !error && <SkeletonRows count={3} label="Loading tells"/>}
    {groups.map(g => <section key={g.part} className="tell-group" aria-labelledby={`tells-${g.part}`}><h2 id={`tells-${g.part}`} className="settings-label">{area(g.part)}<span className="num">{totals[g.part].toLocaleString('en-US')}</span></h2>
      <div className="glist tell-list">{g.items.map(c => <TellCard key={c.id} c={c}/>)}
        {g.rest > 0 && <button type="button" className="grow tint-row tell-all" onClick={() => { tap('select'); pickPart(g.part, true); }}><span className="grow-main"><span className="grow-title num">Show all {totals[g.part].toLocaleString('en-US')}</span></span><Chevron/></button>}</div></section>)}
    {claims && filtered.length === 0 && <PageEmpty className="tells-empty" title={q ? 'Nothing matches that search.' : 'Nothing matches these filters.'} body={q ? 'Try a part, a reference or fewer filters.' : 'Try another part or model family.'}><Button onClick={reset}>Clear filters</Button></PageEmpty>}
    {rest > 0 && <div ref={more} className="tells-more"><SkeletonRows count={3} label="Loading more tells"/></div>}
  </div></>;
}
// A dialog: the kit's sheet in a native <dialog>, so it springs in, drags by its grabber and slides out like every
// other sheet, while the browser gives it the top layer and keeps focus inside. Forms pass detents to open tall.
function Modal({ title, children, close, detents, className }) {
  return <ModalSheet title={title} close={close} detents={detents} className={className}>{children}</ModalSheet>;
}

createRoot(document.getElementById('root')).render(<App/>);
