import type { DawarichAtlasSuggestions, DawarichBucketScan } from '@trek/shared'; import { DAWARICH_BUCKET_MATCH_MIN_MINUTES, DAWARICH_BUCKET_MATCH_RADIUS_M } from '@trek/shared'; import { Building2, CalendarDays, Check, Globe2, Hourglass, Info, Loader2, MapPin, RefreshCw, Star, } from 'lucide-react'; import React, { useId, useState } from 'react'; import { dawarichApi } from '../../api/dawarich'; import { useTranslation } from '../../i18n'; import MSheet from '../../mobile/components/MSheet'; import { FormSheetHeader } from '../../mobile/screens/trip/sheets/PlSheetChrome'; import { useIsPhone } from '../../mobile/useIsPhone'; import { DawarichOfflineError, dawarichRepo } from '../../repo/dawarichRepo'; import { isEffectivelyOffline } from '../../sync/networkMode'; import DawarichIcon from '../shared/DawarichIcon'; import { DialogFooter, DialogHeader, DialogShell, NEUTRAL_TINT } from '../shared/DialogShell'; import { Skeleton } from '../shared/Skeleton'; import { SlidingTabs } from '../shared/SlidingTabs'; import { useToast } from '../shared/Toast'; import { cityLine, countryLabel, countryWindow, formatDistance, newCountries, orderedMatches, } from './dawarichAtlasModel'; import DawarichBadge from './DawarichBadge'; import { formatDuration } from './dawarichSuggestionModel'; type Tab = 'wishes' | 'countries'; /** * Everything Dawarich can answer about the Atlas, in a room of its own. * * It used to be a card wedged under the wishlist, which made two different * questions — "which wishes did I actually reach?" and "which countries was I * in?" — look like one paragraph of small print. Both are offers that need * reading before they are accepted, and reading needs space, so they get a * dialog with a tab each, one selection model and one confirm button. * * Nothing here runs on its own. The Atlas is curated — it carries tombstones * precisely so a country somebody removed stays removed — and a background job * that ticked countries off would be fighting its owner. */ export default function DawarichAtlasDialog({ isOpen, initialTab = 'wishes', onClose, onChanged, }: { isOpen: boolean; /** Which question was asked to open it — the panel has a button per tab. */ initialTab?: Tab; onClose: () => void; /** Called after something was written, so the Atlas can re-read itself. */ onChanged?: () => void; }): React.ReactElement { const { t, locale } = useTranslation(); const toast = useToast(); const phone = useIsPhone(); const labelId = useId(); const [tab, setTab] = useState(initialTab); const [scan, setScan] = useState(null); const [scanning, setScanning] = useState(false); const [picked, setPicked] = useState>(new Set()); const [countries, setCountries] = useState(null); const [loadingCountries, setLoadingCountries] = useState(false); const [pickedCountries, setPickedCountries] = useState>(new Set()); // One write at a time: the button stays on screen while the request is in // flight, and a second press would send the same confirmation twice. const [writing, setWriting] = useState(false); const matches = orderedMatches(scan?.matches ?? []); const openMatches = matches.filter((match) => !match.alreadyVisited); const offered = newCountries(countries?.countries ?? []); const runScan = async (): Promise => { setScanning(true); try { const result = await dawarichRepo.bucketScan(); setScan(result); // Everything with a match and not already ticked starts selected: the // common case is "yes, all of those", and unticking the odd one is less // work than ticking twenty. setPicked(new Set(result.matches.filter((m) => m.match && !m.alreadyVisited).map((m) => m.itemId))); } catch (err) { toast.error(failureText(err, t)); } finally { setScanning(false); } }; const loadCountries = async (): Promise => { setLoadingCountries(true); try { const { from, to } = countryWindow(new Date()); const result = await dawarichRepo.atlasSuggestions(from, to); setCountries(result); setPickedCountries(new Set(newCountries(result.countries).map((c) => c.countryCode))); } catch (err) { toast.error(failureText(err, t)); } finally { setLoadingCountries(false); } }; const confirmWishes = async (): Promise => { if (picked.size === 0 || writing) return; // Writes are online-only: the reads are gated in the repo, and firing a // confirmation into a dead connection would hang to a timeout and then // report a server error for something the server never saw. if (isEffectivelyOffline()) { toast.error(t('dawarich.error.offline')); return; } setWriting(true); try { // Ticked off on the day each wish was reached, not on today. The dialog is // holding that date for every row it is about to write, so it says it; // grouping by date keeps that to one request per day rather than per wish. const byDate = new Map(); for (const m of matches) { if (!picked.has(m.itemId) || !m.match) continue; const bucket = byDate.get(m.match.at); if (bucket) bucket.push(m.itemId); else byDate.set(m.match.at, [m.itemId]); } const results = await Promise.all([...byDate].map(([at, ids]) => dawarichApi.confirmBucketVisits(ids, at))); const result = { updated: results.reduce((sum, r) => sum + r.updated, 0) }; toast.success(t('dawarich.bucket.confirmed', { count: result.updated })); // Marked in place rather than rescanned: the scan costs one upstream // request per wish, and the reader already knows what they just ticked. setScan((prev) => prev === null ? prev : { ...prev, matches: prev.matches.map((m) => (picked.has(m.itemId) ? { ...m, alreadyVisited: true } : m)) } ); setPicked(new Set()); onChanged?.(); } catch (err) { toast.error(failureText(err, t)); } finally { setWriting(false); } }; const confirmCountries = async (): Promise => { if (pickedCountries.size === 0 || writing) return; if (isEffectivelyOffline()) { toast.error(t('dawarich.error.offline')); return; } setWriting(true); try { const result = await dawarichApi.acceptAtlasCountries([...pickedCountries]); toast.success(t('dawarich.atlas.accepted', { count: result.marked })); setCountries((prev) => prev === null ? prev : { ...prev, countries: prev.countries.map((c) => pickedCountries.has(c.countryCode) ? { ...c, alreadyVisited: true } : c ), } ); setPickedCountries(new Set()); onChanged?.(); } catch (err) { toast.error(failureText(err, t)); } finally { setWriting(false); } }; const toggle = (set: Set, value: T): Set => { const next = new Set(set); if (next.has(value)) next.delete(value); else next.add(value); return next; }; const busy = tab === 'wishes' ? scanning : loadingCountries; const loaded = tab === 'wishes' ? scan !== null : countries !== null; const selected = tab === 'wishes' ? picked.size : pickedCountries.size; // Nothing was found, so there is nothing to confirm — the empty state says so // in a sentence, and a greyed-out "Add 0 countries" underneath it only asks to // be understood. const anything = tab === 'wishes' ? matches.length > 0 : offered.length > 0; // The same two questions in both shells — only the frame differs. const body = (
tabs={[ { id: 'wishes', label: t('dawarich.atlas.tab.wishes'), icon: Star, count: openMatches.length || undefined }, { id: 'countries', label: t('dawarich.atlas.tab.countries'), icon: Globe2, count: offered.length || undefined, }, ]} activeTab={tab} onChange={setTab} size="sm" fullWidth /> {tab === 'wishes' ? (
{ void runScan(); }} empty={matches.length === 0} emptyLabel={t('dawarich.bucket.noMatches')} notes={[ scan && scan.skippedWithoutCoordinates > 0 ? t('dawarich.bucket.skipped', { count: scan.skippedWithoutCoordinates }) : null, scan?.truncated ? t('dawarich.bucket.truncated') : null, t('dawarich.bucket.rule', { meters: DAWARICH_BUCKET_MATCH_RADIUS_M, minutes: DAWARICH_BUCKET_MATCH_MIN_MINUTES, }), ]} > {matches.map((match) => ( setPicked((prev) => toggle(prev, match.itemId))} leading={ } > {match.alreadyVisited ? ( {t('dawarich.bucket.alreadyVisited')} ) : ( <> {formatDistance(match.match!.distanceMeters, t)} {formatDuration(match.match!.minutes, t)} {new Date(match.match!.at).toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', })} )} ))}
) : (
{ void loadCountries(); }} empty={offered.length === 0} emptyLabel={t('dawarich.atlas.empty')} notes={[ countries && countries.unresolved.length > 0 ? t('dawarich.atlas.unresolved', { names: countries.unresolved.join(', ') }) : null, countries ? t('dawarich.atlas.window') : null, ]} > {offered.map((country) => ( setPickedCountries((prev) => toggle(prev, country.countryCode))} leading={ // The Atlas page draws its countries with the same flags, and a // list of country names without them looks like a spreadsheet. } > {country.cities.length > 0 && ( <> {country.cities.length === 1 ? t('dawarich.atlas.citiesOne') : t('dawarich.atlas.cities', { count: country.cities.length })} {cityLine(country.cities)} )} ))}
)}
); // Rendered or not, rather than `hidden`: the attribute loses to the display // utility on the class list, so the button stayed on screen greyed out. const confirmButton = !loaded || !anything ? null : ( ); const againButton = loaded ? ( ) : null; // The phone shell has its own sheet, its own rounding and its own pill // buttons, and every other panel on it uses them. if (phone) { return (
} title={t('dawarich.title')} subtitle={t('dawarich.atlas.dialogSubtitle')} onClose={onClose} closeLabel={t('common.close')} />
{body}
{selected > 0 ? t('dawarich.selected', { count: selected }) : ''} {againButton} {confirmButton}
); } return ( } tint={NEUTRAL_TINT} labelId={labelId} onClose={onClose} title={t('dawarich.title')} sub={t('dawarich.atlas.dialogSubtitle')} /> } // Before the first answer the pitch carries its own button, so there is no bar to show. footer={ againButton || confirmButton ? ( {selected > 0 ? t('dawarich.selected', { count: selected }) : ''} {againButton} {confirmButton} ) : undefined } > {body} ); } /** * One half of the dialog: the pitch before anything has been asked, the wait * while it is being asked, and the answer. * * Both halves behave identically, which is the point — the two questions are * different, the shape of answering them is not. */ function Section({ icon: Icon, title, description, action, busyLabel, busy, loaded, onRun, empty, emptyLabel, notes, children, }: { icon: React.ComponentType<{ className?: string }>; title: string; description: string; action: string; busyLabel: string; busy: boolean; loaded: boolean; onRun: () => void; empty: boolean; emptyLabel: string; notes: (string | null)[]; children: React.ReactNode; }): React.ReactElement { if (busy) { return (

{busyLabel}

{[0, 1, 2].map((i) => (
))}
); } if (!loaded) { return (

{title}

{description}

); } return (
{empty ? (
{emptyLabel}
) : (
{children}
)} {notes.filter(Boolean).length > 0 && (
{notes.filter(Boolean).map((note) => (

{note}

))}
)}
); } /** * A selectable answer: what it is on the left, why it is being offered * underneath, and a tick that says whether it will be applied. * * The whole row is the control — a 16px checkbox is a hard target on a phone, * and there is nothing else in the row to click. */ function Row({ name, checked, disabled = false, onToggle, leading, children, }: { name: string; checked: boolean; disabled?: boolean; onToggle: () => void; leading: React.ReactNode; children: React.ReactNode; }): React.ReactElement { return ( ); } /** * What to tell the reader when a question could not be asked. * * Being offline is not an error the server reported — nothing was sent — and * "something went wrong" for a plane journey is the kind of message that sends * somebody looking for a bug in their Dawarich instance. */ function failureText(err: unknown, t: (key: string) => string): string { if (err instanceof DawarichOfflineError) return t('dawarich.error.offline'); return errorText(err) ?? t('dawarich.error.unknown'); } /** The server's `{ error }` envelope, when there is one. */ function errorText(err: unknown): string | null { const data = (err as { response?: { data?: { error?: unknown } } })?.response?.data; return typeof data?.error === 'string' ? data.error : null; }