import React, { useEffect, useRef, useState } from 'react' import { createPortal } from 'react-dom' import { useTranslation } from '../i18n' import Navbar from '../components/Layout/Navbar' import CustomSelect from '../components/shared/CustomSelect' import EmptyState from '../components/shared/EmptyState' import { Globe, MapPin, Briefcase, Calendar, Flag, PanelLeftOpen, PanelLeftClose, X, Star, Plus, Trash2, Search, Check, ArrowLeft, ChevronRight, Footprints, type LucideIcon } from 'lucide-react' import type { TranslationFn } from '../types' import { Tooltip } from '../components/shared/Tooltip' import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../components/shared/DialogShell' import { EditorField, GRID_2 } from '../components/shared/dialogParts' import DawarichAtlasSidePanel from '../components/Dawarich/DawarichAtlasSidePanel' import CountryFlag from '../components/shared/CountryFlag' import { A2_TO_A3, countryCodeToFlag, visitedRegionCount, type AtlasCountry, type AtlasStats, type AtlasData, type CountryDetail } from './atlas/atlasModel' import { useAtlas } from './atlas/useAtlas' import { bucketMonthTarget, useAtlasCountryActions, type AtlasCountryActionsOptions } from './atlas/useAtlasCountryActions' import AtlasCountrySearch from './atlas/AtlasCountrySearch' import AtlasLayerToggle from './atlas/AtlasLayerToggle' import HelpAnchor from '../components/Help/HelpAnchor' import AtlasCountryPlaces from '../components/Atlas/AtlasCountryPlaces' import { AtlasTourActivityPane } from '../components/Atlas/tourActivity/AtlasTourActivityPane' import { useAddonStore } from '../store/addonStore' import { getIntlLanguage } from '@trek/shared' // Fixed ids rather than useId: the page body stays free of hooks, and there is only one atlas. const COUNTRY_DIALOG_TITLE = 'atlas-country-dialog-title' const BUCKET_MONTH_ID = 'atlas-bucket-month' const BUCKET_YEAR_ID = 'atlas-bucket-year' /** The footer's destructive answer, filled like ConfirmDialog's. */ const DANGER_BUTTON = 'inline-flex items-center gap-1.5 rounded-[10px] bg-danger px-4 py-2 font-medium text-white hover:opacity-90' // theme-lint-disable: white on the danger fill, as ConfirmDialog draws it export default function AtlasPage(): React.ReactElement { // ViewportRoute in App.tsx picks the branch now, so the phone screen is a // chunk of its own instead of a dead limb in this one. return ( <> ) } function AtlasPageDesktop(): React.ReactElement { // Page = wiring container: the whole interactive globe (map lifecycle, atlas + // bucket data, mark/unmark flows, country search) lives in useAtlas. The page // only wires that state into JSX and its presentational SidebarContent helper. const { t, language, navigate, resolveName, dark, loading, mapRef, regionTooltipRef, panelRef, glareRef, borderGlareRef, handlePanelMouseMove, handlePanelMouseLeave, data, setData, stats, countries, selectedCountry, countryDetail, showPlanned, togglePlanned, loadCountryDetail, handleUnmarkCountry, select_country_from_search, visitedRegions, setVisitedRegions, regionsVisited, placesOpen, setPlacesOpen, atlas_country_search, set_atlas_country_search, atlas_country_results, set_atlas_country_results, atlas_country_open, set_atlas_country_open, atlas_country_options, atlas_place_results, atlas_places_loading, search_places, select_place_from_search, confirmAction, setConfirmAction, executeConfirmAction, bucketMonth, setBucketMonth, bucketYear, setBucketYear, bucketList, setBucketList, bucketTab, setBucketTab, showBucketAdd, setShowBucketAdd, bucketForm, setBucketForm, handleAddBucketItem, handleDeleteBucketItem, handleClearBucketVisit, handleBucketPoiSearch, handleSelectBucketPoi, bucketSearchResults, setBucketSearchResults, bucketPoiMonth, setBucketPoiMonth, bucketPoiYear, setBucketPoiYear, bucketSearching, bucketSearch, setBucketSearch, reloadAfterDawarich, } = useAtlas() // Solid surfaces when the user disabled transparency (read at render — the // attribute is already set by applyAppearance before navigating here). const noTransparency = typeof document !== 'undefined' && document.documentElement.hasAttribute('data-no-transparency') if (loading) { return (
) } // The glass both bottom panels are cut from. One object, because two panels // side by side that differ by a blur radius look like a mistake. const glassPanel: React.CSSProperties = { background: noTransparency ? (dark ? '#15151c' : '#ffffff') : (dark ? 'rgba(10,10,15,0.55)' : 'rgba(255,255,255,0.2)'), backdropFilter: 'blur(24px) saturate(180%)', WebkitBackdropFilter: 'blur(24px) saturate(180%)', border: '1px solid ' + (dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)'), borderRadius: 20, boxShadow: dark ? '0 8px 32px rgba(0,0,0,0.3)' : '0 8px 32px rgba(0,0,0,0.08)', } return (
{/* Map */}
{/* Region tooltip (custom, always on top, ref-controlled to avoid re-renders) */}
{placesOpen && selectedCountry && countryDetail && ( setPlacesOpen(false)} labelledBy="atlas-places-title" width="detail" header={( } tint={NEUTRAL_TINT} labelId="atlas-places-title" onClose={() => setPlacesOpen(false)} title={resolveName(selectedCountry)} sub={`${countryDetail.places.length} ${t('atlas.places', { count: countryDetail.places.length })}`} /> )} > navigate(`/trips/${id}`)} /> )} {/* Mobile: Bottom bar */}
{/* Countries highlighted */}

{stats.totalCountries}

{t('atlas.countries', { count: stats.totalCountries })}

{[[regionsVisited, t('atlas.regions', { count: regionsVisited })], [stats.totalTrips, t('atlas.trips', { count: stats.totalTrips })], [stats.totalPlaces, t('atlas.places', { count: stats.totalPlaces })], [stats.totalCities || 0, t('atlas.cities', { count: stats.totalCities || 0 })], [stats.totalDays, t('atlas.days', { count: stats.totalDays })]].map(([v, l], i) => (

{v}

{l}

))}
{/* Desktop Panels — bottom center, glass effect. Three columns so the Atlas panel stays exactly centred over the map however wide its neighbour is: Dawarich sits in the left column, right-aligned against the middle one, and stretches to its height. */}
{/* Liquid glass glare effect */}
{/* Border glow that follows cursor */}
setPlacesOpen(true)} onCountryClick={loadCountryDetail} onTripClick={(id) => navigate(`/trips/${id}`)} onUnmarkCountry={handleUnmarkCountry} bucketList={bucketList} bucketTab={bucketTab} setBucketTab={setBucketTab} showBucketAdd={showBucketAdd} setShowBucketAdd={setShowBucketAdd} bucketForm={bucketForm} setBucketForm={setBucketForm} onAddBucket={handleAddBucketItem} onDeleteBucket={handleDeleteBucketItem} onClearBucketVisit={handleClearBucketVisit} onSearchBucket={handleBucketPoiSearch} onSelectBucketPoi={handleSelectBucketPoi} bucketSearchResults={bucketSearchResults} setBucketSearchResults={setBucketSearchResults} bucketPoiMonth={bucketPoiMonth} setBucketPoiMonth={setBucketPoiMonth} bucketPoiYear={bucketPoiYear} setBucketPoiYear={setBucketPoiYear} bucketSearching={bucketSearching} bucketSearch={bucketSearch} setBucketSearch={setBucketSearch} t={t} dark={dark} />
{/* Country action popup: the flag and the name at the head, what can be done with the country below. A region names its country under its own name. */}
) } type CountryActionDialogProps = AtlasCountryActionsOptions & Pick, 'language' | 'executeConfirmAction' | 'bucketMonth' | 'setBucketMonth' | 'bucketYear' | 'setBucketYear'> /** The country action popup over useAtlasCountryActions, the logic it shares with the phone sheet. */ function CountryActionDialog(props: CountryActionDialogProps): React.ReactElement | null { const { t, language, confirmAction, setConfirmAction, executeConfirmAction, bucketMonth, setBucketMonth, bucketYear, setBucketYear } = props const { onWishlist, markCountry, markRegion, unmarkRegion, addBucket, removeBucket } = useAtlasCountryActions(props) const addBucketForMonth = () => addBucket(bucketMonthTarget(bucketMonth, bucketYear), () => { setBucketMonth(0); setBucketYear(0) }) if (!confirmAction) return null return ( setConfirmAction(null)} labelledBy={COUNTRY_DIALOG_TITLE} width="narrow" header={( {confirmAction.code.length === 2 ? ( {confirmAction.code} ) : ( {countryCodeToFlag(confirmAction.code)} )} )} // The two removals take the danger wash ConfirmDialog asks its destructive questions in. tint={confirmAction.type === 'unmark' || confirmAction.type === 'unmark-region' ? 'var(--danger-soft)' : NEUTRAL_TINT} labelId={COUNTRY_DIALOG_TITLE} onClose={() => setConfirmAction(null)} title={confirmAction.name} sub={confirmAction.countryName || undefined} /> )} footer={( {confirmAction.type === 'bucket' && ( setConfirmAction({ ...confirmAction, type: confirmAction.regionCode ? 'choose-region' : 'choose' })} icon={}> {t('common.back')} )} {confirmAction.type !== 'bucket' && ( setConfirmAction(null)}>{t('common.cancel')} )} {confirmAction.type === 'mark' && ( {t('atlas.markVisited')} )} {confirmAction.type === 'unmark' && ( )} {confirmAction.type === 'unmark-region' && ( )} {confirmAction.type === 'bucket' && ( } onClick={addBucketForMonth}> {t('atlas.addToBucket')} )} )} > {confirmAction.type === 'choose' && (
setConfirmAction({ ...confirmAction, type: 'bucket' })} /> {onWishlist && ( )}
)} {confirmAction.type === 'choose-region' && (
markRegion()} /> setConfirmAction({ ...confirmAction, type: 'bucket' })} />
)} {confirmAction.type === 'unmark' && (

{t('atlas.confirmUnmark')}

)} {confirmAction.type === 'unmark-region' && (

{t('atlas.confirmUnmarkRegion')}

)} {confirmAction.type === 'mark' && (

{t('atlas.confirmMark')}

)} {confirmAction.type === 'bucket' && ( <>

{t('atlas.bucketWhen')}

setBucketMonth(Number(v))} placeholder={t('atlas.month')} options={[ { value: '0', label: t('common.none') }, ...Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1), label: new Date(2000, i).toLocaleString(getIntlLanguage(language), { month: 'long' }) })), ]} size="sm" /> setBucketYear(Number(v))} placeholder={t('atlas.year')} options={[ { value: '0', label: t('common.none') }, ...Array.from({ length: 20 }, (_, i) => ({ value: String(new Date().getFullYear() + i), label: String(new Date().getFullYear() + i) })), ]} size="sm" />
)}
) } /** One answer of the country dialog, built like an export row: icon tile, what it does, and what that means. */ function CountryChoice({ icon: Icon, tone = 'text-content-secondary', title, hint, onClick }: { icon: LucideIcon /** The icon's colour class. */ tone?: string title: string hint: string onClick: () => void }): React.ReactElement { return ( ) } interface SidebarContentProps { data: AtlasData | null stats: AtlasStats /** Regions visited over every country, and in the country picked (#1639). */ regionsVisited: number countryRegions: number /** Opens the list of the picked country's places (#2174). */ onOpenPlaces: () => void countries: AtlasCountry[] selectedCountry: string | null countryDetail: CountryDetail | null resolveName: (code: string) => string onCountryClick: (code: string) => void onTripClick: (id: number) => void onUnmarkCountry?: (code: string) => void bucketList: any[] /** The panel's tab: the travel numbers, the bucket list, or the user's own tours (STA-02, with the Tours addon). */ bucketTab: 'stats' | 'bucket' | 'tours' setBucketTab: (tab: 'stats' | 'bucket' | 'tours') => void showBucketAdd: boolean setShowBucketAdd: (v: boolean) => void bucketForm: { name: string; notes: string; lat: string; lng: string; target_date: string } setBucketForm: (f: { name: string; notes: string; lat: string; lng: string; target_date: string }) => void onAddBucket: () => Promise onDeleteBucket: (id: number) => Promise onClearBucketVisit: (id: number) => void | Promise onSearchBucket: () => Promise onSelectBucketPoi: (result: any) => void bucketSearchResults: any[] setBucketSearchResults: (v: string[]) => void bucketPoiMonth: number setBucketPoiMonth: (v: number) => void bucketPoiYear: number setBucketPoiYear: (v: number) => void bucketSearching: boolean bucketSearch: string setBucketSearch: (v: string) => void t: TranslationFn dark: boolean } function SidebarContent({ data, stats, regionsVisited, countryRegions, onOpenPlaces, countries, selectedCountry, countryDetail, resolveName, onTripClick, onUnmarkCountry, bucketList, bucketTab, setBucketTab, showBucketAdd, setShowBucketAdd, bucketForm, setBucketForm, onAddBucket, onDeleteBucket, onClearBucketVisit, onSearchBucket, onSelectBucketPoi, bucketSearchResults, setBucketSearchResults, bucketPoiMonth, setBucketPoiMonth, bucketPoiYear, setBucketPoiYear, bucketSearching, bucketSearch, setBucketSearch, t, dark }: SidebarContentProps): React.ReactElement { const { language } = useTranslation() const toursEnabled = useAddonStore(s => s.isEnabled('tours')) const statsContentRef = useRef(null) const bucketSearchRowRef = useRef(null) const [statsWidth, setStatsWidth] = useState(undefined) useEffect(() => { const el = statsContentRef.current if (!el || typeof ResizeObserver === 'undefined') return const ro = new ResizeObserver(() => setStatsWidth(el.offsetWidth)) ro.observe(el) return () => ro.disconnect() }, []) const bg = (o) => dark ? `rgba(255,255,255,${o})` : `rgba(0,0,0,${o})` const tp = dark ? '#f1f5f9' : '#0f172a' const tm = dark ? '#94a3b8' : '#64748b' const tf = dark ? '#475569' : '#94a3b8' const accent = '#818cf8' const { mostVisited, continents, lastTrip, nextTrip, streak, firstYear, tripsThisYear } = data || {} const contEntries = continents ? Object.entries(continents).sort((a, b) => b[1] - a[1]) : [] const maxCont = contEntries.length > 0 ? contEntries[0][1] : 1 const CL = { 'Europe': t('atlas.europe'), 'Asia': t('atlas.asia'), 'North America': t('atlas.northAmerica'), 'South America': t('atlas.southAmerica'), 'Africa': t('atlas.africa'), 'Oceania': t('atlas.oceania'), 'Antarctica': t('atlas.antarctica') } const contColors = ['#818cf8', '#f472b6', '#34d399', '#fbbf24', '#fb923c', '#22d3ee'] // Tab switcher const tabBar = (
{[ { id: 'stats', label: t('atlas.statsTab'), icon: Globe }, { id: 'bucket', label: t('atlas.bucketTab'), icon: Star }, ...(toursEnabled ? [{ id: 'tours', label: t('tours.mode.tours'), icon: Footprints }] : []), ].map(tab => ( ))}
) if (countries.length === 0 && !lastTrip && bucketTab === 'stats') { return ( <> {tabBar} ) } const thisYear = new Date().getFullYear() const divider = `2px solid ${bg(0.08)}` // Bucket list content const bucketContent = ( <>
{bucketList.map(item => (
{(() => { const code = item.country_code?.length === 2 ? item.country_code : (Object.entries(A2_TO_A3).find(([, v]) => v === item.country_code)?.[0] || '') return code ? ( {code} ) : })()} {item.name} {item.target_date && (() => { const [y, m] = item.target_date.split('-') const label = m ? new Date(Number(y), Number(m) - 1).toLocaleString(getIntlLanguage(language), { month: 'short', year: 'numeric' }) : y return {label} })()} {!item.target_date && item.notes && {item.notes}} {/* Reached (#2279). A tick rather than removing the entry: a wish that came true is the part of the list worth keeping, and the source is named so a recording-derived tick is not mistaken for a manual one. */} {item.visited_at && ( {/* A tick that came from a recording can be taken back here: the wishlist is curated by hand, and a suggestion nobody can undo is not a suggestion. A tick somebody set themselves is text. */} {item.visited_source === 'dawarich' ? ( ) : ( {new Date(item.visited_at).toLocaleDateString(getIntlLanguage(language))} )} )}
))} {bucketList.length === 0 && !showBucketAdd && (
{t('atlas.bucketEmptyHint')}
)}
{showBucketAdd ? (
{/* Search or manual name */}
{ const v = e.target.value; if (bucketForm.name) setBucketForm({ ...bucketForm, name: v }); else setBucketSearch(v) }} onKeyDown={e => { if (e.key === 'Enter' && !bucketForm.name) void onSearchBucket(); else if (e.key === 'Enter') void onAddBucket(); if (e.key === 'Escape') setShowBucketAdd(false) }} placeholder={t('atlas.bucketNamePlaceholder')} autoFocus className="border border-edge text-content bg-surface-input" style={{ flex: 1, padding: '6px 10px', borderRadius: 8, fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' }} /> {!bucketForm.name && ( )} {bucketForm.name && ( )}
{/* Portalled to the body: the panel that hosts this form clips its overflow, which used to swallow the top of the list (#1899). */} {bucketSearchResults.length > 0 && createPortal(
{ const rect = bucketSearchRowRef.current?.getBoundingClientRect() if (!rect) return { left: 0, top: 0, width: 240, maxHeight: 160 } const above = rect.top - 12 const below = window.innerHeight - rect.bottom - 12 const openUp = above >= below return { left: rect.left, width: rect.width, // Never taller than the room on that side, so the list scrolls // instead of running off the edge of the viewport. maxHeight: Math.min(160, openUp ? above : below), ...(openUp ? { bottom: window.innerHeight - rect.top + 4 } : { top: rect.bottom + 4 }), } })(), zIndex: 99999, borderRadius: 8, boxShadow: '0 4px 12px rgba(0,0,0,0.12)', overflowY: 'auto', }}> {bucketSearchResults.slice(0, 6).map((r, i) => ( ))}
, document.body )}
{/* Selected place indicator */} {bucketForm.lat && bucketForm.lng && (
{Number(bucketForm.lat).toFixed(4)}, {Number(bucketForm.lng).toFixed(4)}
)} {/* Month / Year with CustomSelect */}
setBucketPoiMonth(Number(v))} placeholder={t('atlas.month')} size="sm" options={[{ value: '0', label: '—' }, ...Array.from({ length: 12 }, (_, i) => ({ value: String(i + 1), label: new Date(2000, i).toLocaleString(getIntlLanguage(language), { month: 'short' }) }))]} />
setBucketPoiYear(Number(v))} placeholder={t('atlas.year')} size="sm" options={[{ value: '0', label: '—' }, ...Array.from({ length: 20 }, (_, i) => ({ value: String(new Date().getFullYear() + i), label: String(new Date().getFullYear() + i) }))]} />
) : (
)} ) return ( <> {tabBar} {/* Every tab always rendered so the widest one sets the panel width */}
{/* ═══ SECTION 1: Numbers ═══ */} {/* Countries hero */}
{stats.totalCountries} {t('atlas.countries', { count: stats.totalCountries })}
{(stats.totalCountriesPlanned || 0) > 0 && ( +{stats.totalCountriesPlanned} {t('atlas.planned')} )}
{/* Other stats */} {[[regionsVisited, t('atlas.regions', { count: regionsVisited })], [stats.totalTrips, t('atlas.trips', { count: stats.totalTrips })], [stats.totalPlaces, t('atlas.places', { count: stats.totalPlaces })], [stats.totalCities || 0, t('atlas.cities', { count: stats.totalCities || 0 })], [stats.totalDays, t('atlas.days', { count: stats.totalDays })]].map(([v, l], i) => (
{v} {l}
))} {/* ═══ DIVIDER ═══ */}
{/* ═══ SECTION 2: Continents ═══ */}
{/* Antarctica only joins the row once someone has actually been — CONTINENT_MAP has always known AQ, but a permanent zero column would be dead space for everyone else. */} {['Europe', 'Asia', 'North America', 'South America', 'Africa', 'Oceania', ...((continents?.['Antarctica'] || 0) > 0 ? ['Antarctica'] : [])].map((cont) => { const count = continents?.[cont] || 0 const active = count > 0 return (
{count} {CL[cont]}
) })}
{/* ═══ DIVIDER ═══ */}
{/* ═══ SECTION 3: Highlights & Streaks ═══ */}
{/* Streak */} {streak > 0 && (
{streak} {t('atlas.yearsInRow', { count: streak })}
)} {/* This year */} {tripsThisYear > 0 && (
{tripsThisYear} {t('atlas.tripsIn', { count: tripsThisYear })} {thisYear}
)}
{/* ═══ Country detail overlay ═══ */} {selectedCountry && countryDetail && ( <>
{/* Twemoji where the platform has no flag glyphs: Windows draws the emoji as two letters. */} {/^[A-Za-z]{2}$/.test(selectedCountry) ? : {countryCodeToFlag(selectedCountry)}}

{resolveName(selectedCountry)} {countryDetail.status && countryDetail.status !== 'visited' && ( {t('atlas.planned')} )}

{/* Counts as quiet badges, the regions among them once any is visited (#1639). */}
{countryDetail.places.length > 0 && ( )} {[ [countryDetail.trips.length, t('atlas.tripsLabel', { count: countryDetail.trips.length })], ...(countryRegions > 0 ? [[countryRegions, t('atlas.regions', { count: countryRegions })] as const] : []), ].map(([n, label]) => ( {n} {label} ))}
{countryDetail.trips.slice(0, 3).map(trip => ( ))} {countryDetail.manually_marked && onUnmarkCountry && ( )}
)}
{bucketContent}
{/* STA-02: the user's own tours, read only once the tab is first shown. */} {toursEnabled && (
)}
) }