import ChargingInfo from '../Roadtrip/ChargingInfo' import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react' import { avatarSrc } from '../../utils/avatarSrc' import { safeHttpUrl } from '../../utils/safeUrl' import { openFile } from '../../utils/fileDownload' import Markdown from 'react-markdown' import remarkGfm from 'remark-gfm' import remarkBreaks from 'remark-breaks' import { markdownLinkComponents } from '../shared/markdownLink' import { X, Clock, MapPin, ExternalLink, Phone, Banknote, Edit2, Trash2, Plus, Minus, ChevronDown, ChevronUp, FileText, Upload, File, FileImage, Star, Navigation, Map as MapIcon, Users, Mountain, TrendingUp, Bookmark, BookmarkCheck, Copy, Route, StickyNote } from 'lucide-react' import PlaceAvatar from '../shared/PlaceAvatar' import PlaceAvatarUpload from '../shared/PlaceAvatarUpload' import PlaceRating from '../shared/StarRating' import TrackColorPicker from '../shared/TrackColorPicker' import { resolveTrackColor, inheritedTrackColor } from '../Map/trackColors' import { filesForPlace } from '../../utils/placeFiles' import GuestBadge from '../shared/GuestBadge' import StatusBadge from '../Collections/StatusBadge' import { mapsApi, pluginsApi } from '../../api/client' import { collectionsApi } from '../../api/collections' import { useSettingsStore } from '../../store/settingsStore' import { useAddonStore } from '../../store/addonStore' import { useSaveToCollectionStore } from '../../store/saveToCollectionStore' import { getCategoryIcon } from '../shared/categoryIcons' import DawarichIcon from '../shared/DawarichIcon' import { Tooltip } from '../shared/Tooltip' import { useToast } from '../shared/Toast' import { useTranslation, translateApiError } from '../../i18n' import { usePluginStore } from '../../store/pluginStore' import PluginFrame from '../Plugins/PluginFrame' import type { Place, Category, Day, Assignment, Reservation, TripFile, AssignmentsMap } from '../../types' import type { CollectionStatus } from '@trek/shared' import { splitReservationDateTime, formatTime, formatMoney } from '../../utils/formatters' import { useTripStore } from '../../store/tripStore' import { formatDistance, formatElevation } from '../../utils/units' import { getNavigationTargets, openNavigationTarget } from './placeNavigation' import { TRANSPORT_TYPES, getAssignmentReservations } from '../../utils/dayMerge' import { NavigationMenu } from '../shared/NavigationMenu' import { resolveOpenNow, resolvePlaceTimeZone, placeWeekdayIndex } from './placeOpenState' import { convertHoursLine } from './placeHoursFormat' import type { EndDayControlProps } from '../Roadtrip/EndDayControl' import VisitControls, { type RoadtripStayControl } from '../Roadtrip/VisitControls' const detailsCache = new Map() function getSessionCache(key) { try { const raw = sessionStorage.getItem(key) return raw ? JSON.parse(raw) : undefined } catch { return undefined } } function setSessionCache(key, value) { try { sessionStorage.setItem(key, JSON.stringify(value)) } catch {} } const creditCache = new Map() /** * Names whoever made the picture shown in the avatar. * * Only cached provider photos carry a credit, and their proxy URL embeds the * cache key. Anything else (an uploaded image, a legacy remote URL) renders * nothing. Commons pictures are largely CC BY-SA, so this is an obligation * rather than a nicety — the picker credits them while choosing, this keeps the * credit visible afterwards. */ function PhotoCredit({ imageUrl }) { const [credit, setCredit] = useState(null) const key = useMemo(() => { const match = /^\/api\/maps\/place-photo\/(.+)\/bytes$/.exec(imageUrl || '') return match ? decodeURIComponent(match[1]) : null }, [imageUrl]) useEffect(() => { if (!key) { setCredit(null); return } if (creditCache.has(key)) { setCredit(creditCache.get(key)); return } let alive = true mapsApi.placePhotoCredit(key).then(data => { creditCache.set(key, data.credit) if (alive) setCredit(data.credit) }).catch(() => {}) return () => { alive = false } }, [key]) if (!credit) return null return ( {credit} ) } function usePlaceDetails(googlePlaceId, osmId, language) { const [details, setDetails] = useState(null) const detailId = googlePlaceId || osmId const cacheKey = `gdetails_${detailId}_${language}` useEffect(() => { if (!detailId) { setDetails(null); return } if (detailsCache.has(cacheKey)) { setDetails(detailsCache.get(cacheKey)); return } const cached = getSessionCache(cacheKey) if (cached) { detailsCache.set(cacheKey, cached); setDetails(cached); return } mapsApi.details(detailId, language).then(data => { detailsCache.set(cacheKey, data.place) setSessionCache(cacheKey, data.place) setDetails(data.place) }).catch(() => {}) }, [detailId, language]) return details } function getWeekdayIndex(dateStr, timeZone) { // weekdayDescriptions[0] = Monday … [6] = Sunday if (!dateStr) return placeWeekdayIndex(new Date(), timeZone) const jsDay = new Date(dateStr + 'T12:00:00').getDay() return jsDay === 0 ? 6 : jsDay - 1 } function formatFileSize(bytes) { if (!bytes) return '' if (bytes < 1024) return `${bytes} B` if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB` return `${(bytes / 1024 / 1024).toFixed(1)} MB` } interface TripMember { id: number username: string avatar?: string | null avatar_url?: string | null is_guest?: boolean } interface PlaceInspectorProps { roadtripActive?: boolean roadtripEndDay?: EndDayControlProps roadtripStay?: RoadtripStayControl place: Place | null categories: Category[] /** 'trip' (default) keeps every existing trip-planner behaviour byte-identical; * 'collection' hides the day/reservation/file sub-panels and swaps the footer * for the saved-place actions (copy to trip, status, remove from list). */ mode?: 'trip' | 'collection' // ── Trip-only props (optional so the collection detail panel can omit them) ── days?: Day[] selectedDayId?: number | null selectedAssignmentId?: number | null assignments?: AssignmentsMap reservations?: Reservation[] /** Editors for the linked booking, each omitted when the user lacks that right — * a transport needs day_edit, anything else reservation_edit. Both absent leaves * the strip the read-only summary it has always been (#2012). */ onEditTransport?: (reservation: Reservation) => void onEditReservation?: (reservation: Reservation) => void onClose: () => void onEdit?: () => void onDelete?: () => void onAssignToDay?: (placeId: number, dayId?: number) => void onRemoveAssignment?: (dayId: number, assignmentId: number) => void files?: TripFile[] onFileUpload?: (fd: FormData) => Promise tripMembers?: TripMember[] onSetParticipants?: (assignmentId: number, dayId: number, participantIds: number[]) => void onUpdatePlace?: (placeId: number, data: Partial) => void /** Upload a custom thumbnail (#1136); enables the click-to-change avatar in trip mode. */ onUploadImage?: (placeId: number, file: File) => Promise /** Cast/clear the current user's star vote (#1435); enables the rating row. */ onRate?: (placeId: number, rating: number | null) => Promise | void leftWidth?: number rightWidth?: number // ── Collection-mode props ── collectionStatus?: CollectionStatus onCopyToTrip?: () => void onSetStatus?: (status: CollectionStatus) => void onRemoveFromList?: () => void } export default function PlaceInspector({ place, categories, mode = 'trip', days = [], selectedDayId = null, selectedAssignmentId = null, assignments = {}, reservations = [], onEditTransport, onEditReservation, onClose, onEdit, onDelete, onAssignToDay, onRemoveAssignment, files = [], onFileUpload, tripMembers = [], onSetParticipants, onUpdatePlace, onUploadImage, onRate, leftWidth = 0, rightWidth = 0, collectionStatus, onCopyToTrip, onSetStatus, onRemoveFromList, roadtripEndDay, roadtripStay, roadtripActive, }: PlaceInspectorProps) { // Plugins that declared a place-detail slot mount at the bottom of this panel, // scoped to the open place (trip mode only). Inline-filter like the other sites. const placeDetailPlugins = usePluginStore((s) => s.plugins).filter((p) => p.type === 'widget' && p.slot === 'place-detail') // Extra native rows contributed by placeDetailProvider plugins (#1429). Fail-safe: // any provider error/timeout is dropped server-side, so this only ever adds rows. const [providerDetails, setProviderDetails] = useState }>>([]) const [navOpen, setNavOpen] = useState(false) const navBtnRef = useRef(null) const placeIdForDetails = mode === 'trip' ? place?.id : undefined useEffect(() => { if (placeIdForDetails == null) { setProviderDetails([]); return } let cancelled = false pluginsApi.placeDetails(placeIdForDetails) .then((d) => { if (!cancelled) setProviderDetails((d.providers || []).filter((p) => Array.isArray(p.items) && p.items.length > 0)) }) .catch(() => { if (!cancelled) setProviderDetails([]) }) return () => { cancelled = true } }, [placeIdForDetails]) const { t, locale, language } = useTranslation() // Currency-less prices mean "the trip's currency"; null in collection mode (EUR fallback below). const tripCurrency = useTripStore(s => s.trip?.currency) const toast = useToast() const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h' const distanceUnit = useSettingsStore(s => s.settings.distance_unit) || 'metric' const collectionsEnabled = useAddonStore(s => s.isEnabled('collections')) const openSavePicker = useSaveToCollectionStore(s => s.open) const saveVersion = useSaveToCollectionStore(s => s.version) const [savedInCollection, setSavedInCollection] = useState(false) const [hoursExpanded, setHoursExpanded] = useState(false) const [filesExpanded, setFilesExpanded] = useState(false) const [isUploading, setIsUploading] = useState(false) const [editingName, setEditingName] = useState(false) const [nameValue, setNameValue] = useState('') const nameInputRef = useRef(null) const fileInputRef = useRef(null) const googleDetails = usePlaceDetails(place?.google_place_id, place?.osm_id, language) // Library-wide "is this place already saved anywhere I can see?" indicator for // the trip-planner footer bookmark. Re-checks when the place changes or after // the save picker reports a change (saveVersion bump). const showSaveToCollection = mode === 'trip' && collectionsEnabled useEffect(() => { if (!showSaveToCollection || !place) { setSavedInCollection(false); return } let cancelled = false collectionsApi.membership({ google_place_id: place.google_place_id ?? undefined, google_ftid: place.google_ftid ?? undefined, name: place.name, lat: place.lat ?? undefined, lng: place.lng ?? undefined, }).then(m => { if (!cancelled) setSavedInCollection(m.saved) }).catch(() => { if (!cancelled) setSavedInCollection(false) }) return () => { cancelled = true } // Re-check on place identity + after the picker reports a change; the other // place fields are read at fire-time only, like the existing detail caches. // eslint-disable-next-line react-hooks/exhaustive-deps }, [showSaveToCollection, place?.id, saveVersion]) const handleSaveToCollection = useCallback(() => { if (!place) return openSavePicker({ name: place.name, source_trip_id: place.trip_id ?? null, source_place_id: place.id, description: place.description ?? null, lat: place.lat ?? null, lng: place.lng ?? null, address: place.address ?? null, category_id: place.category_id ?? null, price: place.price ?? null, currency: place.currency ?? null, notes: place.notes ?? null, image_url: place.image_url ?? null, google_place_id: place.google_place_id ?? null, google_ftid: place.google_ftid ?? null, osm_id: place.osm_id ?? null, website: place.website ?? null, phone: place.phone ?? null, }) }, [place, openSavePicker]) // Sits above the `if (!place)` bail-out below: a hook after an early return is // only reached while a place is selected, so deselecting one mid-session // changes the hook count and React tears the tree down. const placeId = place?.id const handleFileUpload = useCallback(async (e) => { const selectedFiles = Array.from((e.target as HTMLInputElement).files || []) if (!selectedFiles.length || !onFileUpload || !placeId) return setIsUploading(true) try { for (const file of selectedFiles) { const fd = new FormData() fd.append('file', file) fd.append('place_id', String(placeId)) await onFileUpload(fd) } setFilesExpanded(true) } catch (err: unknown) { console.error('Upload failed', err) toast.error(translateApiError(t, err, 'files.uploadError')) } finally { setIsUploading(false) if (fileInputRef.current) fileInputRef.current.value = '' } }, [onFileUpload, placeId, toast, t]) const startNameEdit = () => { if (!onUpdatePlace) return setNameValue(place.name || '') setEditingName(true) setTimeout(() => nameInputRef.current?.focus(), 0) } const commitNameEdit = () => { if (!editingName) return const trimmed = nameValue.trim() setEditingName(false) if (!trimmed || trimmed === place.name) return onUpdatePlace(place.id, { name: trimmed }) } const handleNameKeyDown = (e) => { if (e.key === 'Enter') { e.preventDefault(); commitNameEdit() } if (e.key === 'Escape') setEditingName(false) } if (!place) return null const category = categories?.find(c => c.id === place.category_id) const dayAssignments = selectedDayId ? (assignments[String(selectedDayId)] || []) : [] const assignmentInDay = selectedDayId ? ((selectedAssignmentId ? dayAssignments.find(a => a.id === selectedAssignmentId) : null) ?? dayAssignments.find(a => a.place?.id === place.id)) : null /** This stop belongs to a booked night rather than to the traveller. */ const bookedNight = assignmentInDay?.accommodation_id != null // The weekday lines are display text; the ring is computed from the structured // periods next to them, in the place's own timezone. open_now stays the fallback. const openingHours = googleDetails?.opening_hours || null const detailLat = place.lat ?? googleDetails?.lat const detailLng = place.lng ?? googleDetails?.lng const placeTimeZone = resolvePlaceTimeZone(detailLat, detailLng) const openNow = resolveOpenNow( { periods: googleDetails?.opening_periods, specialDays: googleDetails?.opening_special_days }, detailLat, detailLng, googleDetails?.open_now, ) // Allow-listed rather than passed straight through: window.open runs a // javascript: URL in this origin, and the stored value predates the check the // server does on the way in now. const websiteUrl = safeHttpUrl(place.website) ?? safeHttpUrl(googleDetails?.website) // Prefer the place's stored ftid; if it has none yet, use the one just fetched from Google. const navigationTargets = getNavigationTargets( place ? { ...place, google_ftid: place.google_ftid || googleDetails?.google_ftid || null } : null, googleDetails?.google_maps_url, ) const selectedDay = days?.find(d => d.id === selectedDayId) const weekdayIndex = getWeekdayIndex(selectedDay?.date, placeTimeZone) // Its own files plus the ones on the bookings that hang on it (#2217). const placeFiles = filesForPlace(files, place.id, reservations, selectedAssignmentId != null ? [selectedAssignmentId] : []) return (
{/* Header */} {/* Content — scrollable */}
{/* Info-Chips — hidden on mobile, shown on desktop */}
{googleDetails?.rating && (() => { const shortReview = (googleDetails.reviews || []).find(r => r.text && r.text.length > 5) return ( } text={<> {googleDetails.rating.toFixed(1)} {googleDetails.rating_count ? ({googleDetails.rating_count.toLocaleString(locale)}) : ''} {shortReview && · „{shortReview.text}"} } color="var(--text-secondary)" bg="var(--bg-hover)" /> ) })()} {place.price > 0 && ( } text={formatMoney(Number(place.price) || 0, place.currency || tripCurrency || 'EUR', locale)} color="#059669" bg="#ecfdf5" /> )}
{/* Collaborative rating (#1435) — every member's own vote, shown as the average. */} {mode === 'trip' && onRate && (
onRate(place.id, rating)} />
)} {/* Telefon */} {(place.phone || googleDetails?.phone) && ( )} {/* Description / Summary */} {roadtripActive && place.stop_type === 'charging' && } {(roadtripEndDay || roadtripStay) && } {(place.description || googleDetails?.summary) && (
{place.description || googleDetails?.summary || ''}
)} {/* Notes */} {place.notes && (
{place.notes}
)} {/* Day-specific assignment note (#2163) — written via MCP/API or the edit form; distinct from the pool-wide place.notes above, so it carries an eyebrow saying which day-scope it belongs to. */} {assignmentInDay?.notes && (
{t('places.assignmentNotes')}
{assignmentInDay.notes}
)} {/* Reservation + Participants — trip-only (collections have no days) */} {mode === 'trip' && ( )} {/* Opening hours + Files — side by side on desktop only if both exist */} {/* Extra native rows from placeDetailProvider plugins (#1429). */} {mode === 'trip' && providerDetails.length > 0 && (
{providerDetails.flatMap((p) => p.items.map((it, i) => (
{it.label} {it.url ? {it.value ?? '↗'} : {it.value}}
)))}
)} {/* Place-detail plugin slots (#1429): sandboxed, scoped to this place. */} {mode === 'trip' && placeDetailPlugins.length > 0 && (
{placeDetailPlugins.map((p) => { const tid = (place as { trip_id?: number | string }).trip_id return (
) })}
)}
{/* Footer actions */}
{/* Collection mode — copy to trip + per-place status */} {mode === 'collection' && onCopyToTrip && ( } label={{t('collections.copyToTrip')}} /> )} {mode === 'collection' && collectionStatus && onSetStatus && ( )} {/* Trip mode — day assignment. A stop a lodging booking put there is not offered either way. Taking it off the day would leave the booking behind with nothing on the drive and no way back short of saving it again, and putting a second one beside it is the duplicate the stop exists to prevent. The booking is removed where it is made: in the day's overnight block, or by turning the night back into a pause in road trip mode. */} {mode === 'trip' && !!selectedDayId && !bookedNight && ( assignmentInDay ? ( onRemoveAssignment?.(selectedDayId, assignmentInDay.id)} variant="ghost" icon={} label={{t('inspector.removeFromDay')}} /> ) : ( onAssignToDay?.(place.id)} variant="primary" icon={} label={t('inspector.addToDay')} /> ) )} {/* Save to Collection — trip mode, independent of the Google Maps link */} {showSaveToCollection && ( : } label={{savedInCollection ? t('inspector.savedToCollection') : t('inspector.saveToCollection')}} /> )} {navigationTargets.length > 0 && ( <> {/* One target left (a place without coordinates) opens straight away, exactly as this button always did. */} { if (navigationTargets.length === 1) openNavigationTarget(navigationTargets[0]) else setNavOpen(o => !o) }} variant="ghost" icon={} label={ {navigationTargets.length === 1 ? navigationTargets[0].label : t('inspector.navigation')} } /> {navOpen && ( setNavOpen(false)} /> )} )} {websiteUrl && ( window.open(websiteUrl, '_blank', 'noopener,noreferrer')} variant="ghost" icon={} label={{t('inspector.website')}} /> )}
{mode === 'trip' && onEdit && ( } label={{t('common.edit')}} /> )} {mode === 'collection' ? (onRemoveFromList && ( } label={{t('collections.removeFromList')}} /> )) : (onDelete && ( } label={{t('common.delete')}} /> ))}
) } interface ChipProps { icon: React.ReactNode text: React.ReactNode color?: string bg?: string } function Chip({ icon, text, color = 'var(--text-secondary)', bg = 'var(--bg-hover)' }: ChipProps) { return (
{icon} {text}
) } interface ActionButtonProps { onClick: () => void variant: 'primary' | 'ghost' | 'danger' icon: React.ReactNode label: React.ReactNode /** For callers that anchor a popup to the button. React 19 passes it through. */ ref?: React.Ref } export function ActionButton({ onClick, variant, icon, label, ref }: ActionButtonProps) { const base = { primary: { background: 'var(--accent)', color: 'var(--accent-text)', border: 'none', hoverBg: 'var(--text-secondary)' }, ghost: { background: 'var(--bg-hover)', color: 'var(--text-secondary)', border: 'none', hoverBg: 'var(--bg-tertiary)' }, danger: { background: 'rgba(239,68,68,0.08)', color: '#dc2626', border: 'none', hoverBg: 'rgba(239,68,68,0.16)' }, } const s = base[variant] || base.ghost return ( ) } interface ParticipantsBoxProps { tripMembers: TripMember[] participantIds: number[] allJoined: boolean onSetParticipants: (assignmentId: number, dayId: number, participantIds: number[]) => void selectedAssignmentId: number | null selectedDayId: number | null t: (key: string) => string } function ParticipantsBox({ tripMembers, participantIds, allJoined, onSetParticipants, selectedAssignmentId, selectedDayId, t }: ParticipantsBoxProps) { const [showAdd, setShowAdd] = React.useState(false) const [hoveredId, setHoveredId] = React.useState(null) // Active participants: if allJoined, show all members; otherwise show only those in participantIds const activeMembers = allJoined ? tripMembers : tripMembers.filter(m => participantIds.includes(m.id)) const availableToAdd = allJoined ? [] : tripMembers.filter(m => !participantIds.includes(m.id)) const handleRemove = (userId) => { if (!onSetParticipants) return let newIds if (allJoined) { newIds = tripMembers.filter(m => m.id !== userId).map(m => m.id) } else { newIds = participantIds.filter(id => id !== userId) } if (newIds.length === tripMembers.length) newIds = [] onSetParticipants(selectedAssignmentId, selectedDayId, newIds) } const handleAdd = (userId) => { if (!onSetParticipants) return const newIds = [...participantIds, userId] if (newIds.length === tripMembers.length) { onSetParticipants(selectedAssignmentId, selectedDayId, []) } else { onSetParticipants(selectedAssignmentId, selectedDayId, newIds) } setShowAdd(false) } return (
{t('inspector.participants')}
{activeMembers.map(member => { const isHovered = hoveredId === member.id const canRemove = activeMembers.length > 1 return ( ) })} {/* Add button */} {availableToAdd.length > 0 && (
{showAdd && (
{availableToAdd.map(member => ( ))}
)}
)}
) } function PlaceInspectorHeader({ openNow, place, category, t, editingName, nameInputRef, nameValue, setNameValue, commitNameEdit, handleNameKeyDown, startNameEdit, onUpdatePlace, onUploadImage, locale, timeFormat, onClose }: any) { return (
{/* Avatar with open/closed ring + tag */}
{onUploadImage ? onUploadImage(place.id, file)} onRemove={() => onUpdatePlace(place.id, { image_url: null })} /> : }
{openNow === null && } {openNow !== null && ( {openNow ? t('inspector.opened') : t('inspector.closed')} )}
{editingName ? ( setNameValue(e.target.value)} onBlur={commitNameEdit} onKeyDown={handleNameKeyDown} className="text-content bg-surface-secondary" style={{ fontWeight: 600, fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', lineHeight: '1.3', border: '1px solid var(--border-primary)', borderRadius: 6, padding: '1px 6px', fontFamily: 'inherit', outline: 'none', width: '100%' }} /> ) : ( {place.name} )} {/* Where the place came from, when it did not come from somebody typing it: a stay accepted out of their own recordings. The mark alone — the name beside it is already the place's name, and a word here would only repeat the tooltip. */} {place.source === 'dawarich' && ( )} {category && (() => { const CatIcon = getCategoryIcon(category.icon) return ( {category.name} ) })()}
{place.address && (
{place.address}
)} {place.place_time && (
{formatTime(place.place_time, locale, timeFormat)}{place.end_time ? ` – ${formatTime(place.end_time, locale, timeFormat)}` : ''}
)} {place.lat && place.lng && (
{Number(place.lat).toFixed(6)}, {Number(place.lng).toFixed(6)}
)}
) } function PlaceReservationParticipants({ selectedAssignmentId, reservations, assignments, selectedDayId, tripMembers, locale, timeFormat, t, onSetParticipants, onEditTransport, onEditReservation }: any) { return ( <> {(() => { const linked = getAssignmentReservations(reservations, selectedAssignmentId) const assignment = selectedAssignmentId ? (assignments[String(selectedDayId)] || []).find(a => a.id === selectedAssignmentId) : null const currentParticipants = assignment?.participants || [] const participantIds = currentParticipants.map(p => p.user_id) const allJoined = currentParticipants.length === 0 const showParticipants = selectedAssignmentId && tripMembers.length > 1 if (linked.length === 0 && !showParticipants) return null return (
0 && showParticipants ? 'grid-cols-1 sm:grid-cols-2' : 'grid-cols-1'} gap-2`}> {/* Bookings pinned to this stop; several can share one (#2201) */} {linked.length > 0 && (
{linked.map(res => { const confirmed = res.status === 'confirmed' // The strip summarised the booking but went nowhere, so its // attachments and fields had no route from the map (#2012). // A transport has its own form; picking by type is what the day // sidebar does, and an absent handler means this user may not // open this one, so the strip stays inert rather than lying. const editor = TRANSPORT_TYPES.has(res.type) ? onEditTransport : onEditReservation const open = editor ? () => editor(res) : undefined return (
{ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open() } } : undefined} title={open ? t('inspector.editRes') : undefined} style={{ borderRadius: 12, overflow: 'hidden', border: `1px solid ${confirmed ? 'rgba(22,163,74,0.2)' : 'rgba(217,119,6,0.2)'}`, cursor: open ? 'pointer' : undefined, textAlign: 'left' }} >
{confirmed ? t('reservations.confirmed') : t('reservations.pending')} {res.title}
{(() => { const { date, time: startTime } = splitReservationDateTime(res.reservation_time) const { time: endTime } = splitReservationDateTime(res.reservation_end_time) return ( <> {date && (
{t('reservations.date')}
{new Date(date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' })}
)} {(startTime || endTime) && (
{t('reservations.time')}
{startTime ? formatTime(startTime, locale, timeFormat) : ''} {endTime ? ` – ${formatTime(endTime, locale, timeFormat)}` : ''}
)} ) })()} {res.confirmation_number && (
{t('reservations.confirmationCode')}
{res.confirmation_number}
)}
{res.notes &&
{res.notes}
} {(() => { const meta = typeof res.metadata === 'string' ? JSON.parse(res.metadata || '{}') : (res.metadata || {}) if (!meta || Object.keys(meta).length === 0) return null const parts: string[] = [] if (meta.airline && meta.flight_number) parts.push(`${meta.airline} ${meta.flight_number}`) else if (meta.flight_number) parts.push(meta.flight_number) if (meta.departure_airport && meta.arrival_airport) parts.push(`${meta.departure_airport} → ${meta.arrival_airport}`) if (meta.train_number) parts.push(meta.train_number) if (meta.platform) parts.push(`Gl. ${meta.platform}`) if (meta.check_in_time) parts.push(`Check-in ${meta.check_in_time}`) if (meta.check_out_time) parts.push(`Check-out ${meta.check_out_time}`) if (parts.length === 0) return null return
{parts.join(' · ')}
})()}
) })}
)} {/* Participants */} {showParticipants && ( )}
) })()} ) } /** * Track colour row (#776) — only for places that carry GPX geometry. Sits next * to the stats block rather than inside it: that block bails out on unparsable * geometry, and the colour control has no business disappearing with it. */ function TrackColorRow({ place, trackColor, onUpdatePlace, t }: any) { const [open, setOpen] = useState(false) return (
{open && (
onUpdatePlace?.(place.id, { route_color: color })} />
)}
) } function PlaceExtras({ openingHours, weekdayIndex, hoursExpanded, setHoursExpanded, timeFormat, t, place, placeFiles, onFileUpload, filesExpanded, setFilesExpanded, fileInputRef, handleFileUpload, isUploading, distanceUnit, onUpdatePlace }: any) { const trackColor = resolveTrackColor(place) return (
0 ? 'sm:grid-cols-2' : ''} gap-2`}> {openingHours && openingHours.length > 0 && (
{hoursExpanded && (
{openingHours.map((line, i) => (
{convertHoursLine(line, timeFormat)}
))}
)}
)} {place.route_geometry && ( )} {/* GPX Track stats */} {place.route_geometry && (() => { try { const pts: number[][] = JSON.parse(place.route_geometry) if (!pts || pts.length < 2) return null const hasEle = pts[0].length >= 3 // Haversine distance const toRad = (d: number) => d * Math.PI / 180 let totalDist = 0 for (let i = 1; i < pts.length; i++) { const [lat1, lng1] = pts[i - 1], [lat2, lng2] = pts[i] const dLat = toRad(lat2 - lat1), dLng = toRad(lng2 - lng1) const a = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) ** 2 totalDist += 6371000 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) } const distKm = totalDist / 1000 // Elevation stats let minEle = Infinity, maxEle = -Infinity, totalUp = 0, totalDown = 0 if (hasEle) { for (let i = 0; i < pts.length; i++) { const e = pts[i][2] if (e < minEle) minEle = e if (e > maxEle) maxEle = e if (i > 0) { const diff = e - pts[i - 1][2] if (diff > 0) totalUp += diff; else totalDown += Math.abs(diff) } } } // Elevation profile SVG const chartW = 280, chartH = 60 const elevations = hasEle ? pts.map(p => p[2]) : [] let pathD = '' if (elevations.length > 1) { const step = Math.max(1, Math.floor(elevations.length / chartW)) const sampled = elevations.filter((_, i) => i % step === 0) const eMin = Math.min(...sampled), eMax = Math.max(...sampled) const range = eMax - eMin || 1 pathD = sampled.map((e, i) => { const x = (i / (sampled.length - 1)) * chartW const y = chartH - ((e - eMin) / range) * (chartH - 4) - 2 return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}` }).join(' ') } return (
{t('inspector.trackStats')}
{formatDistance(distKm, distanceUnit)}
{hasEle && ( <>
{formatElevation(maxEle, distanceUnit)}
{formatElevation(minEle, distanceUnit)}
↑{formatElevation(totalUp, distanceUnit)}  ↓{formatElevation(totalDown, distanceUnit)}
)}
{pathD && ( )}
) } catch { return null } })()} {/* Files section */} {(placeFiles.length > 0 || onFileUpload) && (
{onFileUpload && ( )}
{filesExpanded && placeFiles.length > 0 && (
{placeFiles.map(f => ( ))}
)}
)}
) }