import React, { useEffect, useRef, useId, type ReactNode } from 'react' import { X, CloudRain, Wind, Droplets, Sunrise, Sunset, Hotel, Calendar, MapPin, LogIn, LogOut, Pencil, ChevronsDown, ChevronsUp, ArrowRight, Check, Moon, type LucideIcon } from 'lucide-react' import type { WeatherResult } from '@trek/shared' import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions' import { usePluginStore } from '../../store/pluginStore' import PluginFrame from '../Plugins/PluginFrame' import { useCanDo } from '../../store/permissionsStore' import { useTripStore } from '../../store/tripStore' import CustomSelect from '../shared/CustomSelect' import CustomTimePicker from '../shared/CustomTimePicker' import { BlurredCode, BookingCodeInput } from '../shared/BookingCode' import { Tooltip } from '../shared/Tooltip' import { useSettingsStore } from '../../store/settingsStore' import { dayHeadingParts } from '../../utils/dayLabel' import { stayDayTimes } from './stayDayTimes' import { useToast } from '../shared/Toast' import { getLocaleForLanguage, useTranslation } from '../../i18n' import type { Day, Place, Category, Reservation, AssignmentsMap, Accommodation } from '../../types' import { formatClockTime, splitReservationDateTime } from '../../utils/formatters' import { useDayDetail, useDayRename, type HotelDayRange, type HotelForm, type HotelPickerMode } from './useDayDetail' import { dayBookings, stayDayLabel, toDisplayTemp } from './dayDetailModel' import { pinnedAwayIn } from '../../utils/dayMerge' import { stayDayOptions, stayFormFrom, stayPlaceChoices, stayRangeFromEnd, stayRangeFromStart } from './stayFormModel' import { DialogShell, DialogHeader, DialogSection, DialogFooter, DialogButton, FooterSpacer, NEUTRAL_TINT, PILL, fs } from '../shared/DialogShell' import { INPUT, PANEL, EditorField, AddRowButton, PillSelect } from '../shared/dialogParts' import { BOX, Eyebrow, Field, RoundAction, TypeTile, toneOf, toneColor, toneTint } from './bookings/bookingParts' import { SoftPill, TimePill, tintOf } from './planParts' import { typeInfo } from './bookings/bookingsModel' import { weatherIconFor } from '../Weather/weatherIcons' import { centredMapCard } from '../Map/centredMapCard' function WIcon({ main, size = 14 }: { main: string; size?: number }) { const Icon = weatherIconFor(main) return } /** What the server said when it refused a write, or the generic line. */ function apiErrorMessage(err: unknown): string | undefined { return (err as { response?: { data?: { error?: string } } })?.response?.data?.error } interface DayDetailPanelProps { day: Day days: Day[] places: Place[] categories?: Category[] tripId: number assignments: AssignmentsMap reservations?: Reservation[] lat: number | null lng: number | null onClose: () => void onAccommodationChange: () => void leftWidth?: number rightWidth?: number collapsed?: boolean onToggleCollapse?: () => void mobile?: boolean /** Rename the day from here — the sidebar pencil moved to the transit search (#1065). */ onUpdateDayTitle?: (dayId: number, title: string) => void /** Name of the place the day's weather is anchored to — captioned above the forecast (#2167). */ weatherPlaceName?: string | null /** Open the stay editor for a new accommodation as soon as the panel is up (the day's "+"). */ openStayPicker?: boolean /** Called once the stay editor is open, so the request is not taken twice. */ onStayPickerOpened?: () => void /** Shows a booking's detail. Given, the day's bookings and a stay's booking open it on a click. */ onOpenBooking?: (reservation: Reservation) => void } /** * The card a selected day opens over the map: its name and date in a tinted * head band that folds the card away, then the weather, the bookings of the * day and where the night is spent, each under its own label. */ export default function DayDetailPanel({ day, days, places, categories = [], tripId, assignments, reservations = [], lat, lng, onClose, onAccommodationChange, leftWidth = 0, rightWidth = 0, collapsed: collapsedProp = false, onToggleCollapse, mobile = false, onUpdateDayTitle, weatherPlaceName = null, openStayPicker = false, onStayPickerOpened, onOpenBooking }: DayDetailPanelProps) { const { t, language } = useTranslation() const can = useCanDo() const toast = useToast() const tripObj = useTripStore((s) => s.trip) const canEditDays = can('day_edit', tripObj) const isFahrenheit = useSettingsStore(s => s.settings.temperature_unit) === 'fahrenheit' const is12h = useSettingsStore(s => s.settings.time_format) === '12h' const dateFirst = useSettingsStore(s => s.settings.day_date_first === true) const collapsed = collapsedProp const toggleCollapse = () => onToggleCollapse?.() // Inline day rename (#1065) — took over from the sidebar's pencil, which the // transit search button replaced. const { editingTitle, setEditingTitle, titleDraft, setTitleDraft, titleInputRef, startRename: openRename, commitRename } = useDayRename(title => { if (day && onUpdateDayTitle) onUpdateDayTitle(day.id, title) }) const startRename = (e: React.MouseEvent) => { e.stopPropagation() openRename(day?.title || '') } const { weather, loading, accommodation, setAccommodation, dayAccommodations, showHotelPicker, setShowHotelPicker, hotelDayRange, setHotelDayRange, hotelCategoryFilter, setHotelCategoryFilter, hotelForm, setHotelForm, handleSelectPlace, handleSaveAccommodation, handleUpdateAccommodation, handleRemoveAccommodation, } = useDayDetail(day, days, tripId, lat, lng, language, onAccommodationChange) // The day's "+" asked for a new stay: open the editor once and hand the request back. useEffect(() => { if (!openStayPicker) return if (canEditDays) setShowHotelPicker(true) onStayPickerOpened?.() }, [openStayPicker, canEditDays, setShowHotelPicker, onStayPickerOpened]) // Plugin-contributed columns/actions for the day view, keyed by day id (#plugins). // day can be null (panel closed) and hooks must run before the early return, so guard it. const dayContributions = usePluginViewContributions('day', tripId)(day?.id ?? -1) // Plugins that declared a day-detail slot mount at the bottom of this panel, // scoped to the open day. Inline-filter like the place-detail site. const dayDetailPlugins = usePluginStore((s) => s.plugins).filter((p) => p.type === 'widget' && p.slot === 'day-detail') // Publish the panel's live height as a root CSS var so the map's mobile GPS // button can sit just above the panel instead of being hidden behind it (#1348). // The card grows/shrinks (collapse, content, ≤60vh), so track it live. const cardRef = useRef(null) useEffect(() => { const el = cardRef.current if (!el) return const root = document.documentElement const publish = () => root.style.setProperty('--day-panel-h', `${el.offsetHeight}px`) publish() let ro: ResizeObserver | undefined if (typeof ResizeObserver !== 'undefined') { ro = new ResizeObserver(publish) ro.observe(el) } return () => { ro?.disconnect() root.style.setProperty('--day-panel-h', '0px') } }, []) if (!day) return null const formattedDate = day.date ? new Date(day.date + 'T00:00:00Z').toLocaleDateString( getLocaleForLanguage(language), { weekday: 'long', day: 'numeric', month: 'long', timeZone: 'UTC' } ) : null const heading = dayHeadingParts(day.title || t('planner.dayN', { n: (days.indexOf(day) + 1) || '?' }), formattedDate, dateFirst) // The title input takes the place and size of the line it edits: the heading, or the line under it. const titleInput = (lead: boolean) => ( setTitleDraft(e.target.value)} onClick={e => e.stopPropagation()} onBlur={commitRename} onKeyDown={e => { if (e.key === 'Enter') commitRename(); if (e.key === 'Escape') setEditingTitle(false) }} placeholder={t('planner.dayN', { n: (days.indexOf(day) + 1) || '?' })} className={`w-full border-0 border-b-[1.5px] border-content bg-transparent p-0 text-content outline-none placeholder:text-content-faint ${lead ? 'font-bold' : 'font-geist'}`} style={lead ? fs(17, 'subtitle') : fs(12.5)} /> ) const renamePencil = canEditDays && onUpdateDayTitle && ( ) const showError = (err: unknown) => toast.error(apiErrorMessage(err) || t('common.unknownError')) // Saving the picker: a new stay or the one being edited. Both say what went // wrong when the write fails, otherwise the picker just sits there with the // Save button doing nothing; it stays open so nothing typed is lost. const saveHotelPicker = async () => { try { if (showHotelPicker === 'edit' && accommodation) await handleUpdateAccommodation() else await handleSaveAccommodation() } catch (err: unknown) { showError(err) } } const editAccommodation = (acc: Accommodation) => { setAccommodation(acc) setHotelForm(stayFormFrom(acc, null)) setHotelDayRange({ start: acc.start_day_id, end: acc.end_day_id }) setShowHotelPicker('edit') } const removeAccommodation = (acc: Accommodation) => { handleRemoveAccommodation(acc).catch(showError) } const mapCard = centredMapCard(leftWidth, rightWidth, { extent: '100vw', clearPill: !mobile }) return (
{/* Head band. Clicking it folds the card, but that is a mouse shortcut for the chevron button, a real button with a name that does the same thing. So the band declares itself presentational instead of becoming a second, unlabelled tab stop wrapped around the rename input and the buttons. */}
toggleCollapse()} className={`flex flex-none cursor-pointer items-center gap-3 px-4 ${collapsed ? 'py-2.5' : 'border-b border-edge-faint py-3.5'}`} style={{ background: NEUTRAL_TINT }}>
{editingTitle && (collapsed || heading.nameFirst) ? ( titleInput(true) ) : collapsed ? (
{heading.primary} {heading.secondary && {heading.secondary}}
) : (
{heading.primary} {heading.nameFirst && renamePencil}
)} {/* With the date first the name is this line, so its pencil and its input are here too (#2921). */} {!collapsed && heading.secondary && ( editingTitle && !heading.nameFirst ? (
{titleInput(false)}
) : (
{heading.secondary} {!heading.nameFirst && renamePencil}
) )}
toggleCollapse()}> {collapsed ? : }
{/* The body stays mounted while folded, so the weather and the picker keep their state. */}
{!!(day.date && lat && lng) && ( )} {dayContributions.length > 0 && }
{dayAccommodations.map(acc => ( r.accommodation_id === acc.id)} canEdit={canEditDays} onEdit={() => editAccommodation(acc)} onRemove={() => removeAccommodation(acc)} onOpenBooking={onOpenBooking} /> ))} {canEditDays && ( setShowHotelPicker(true)}>{t('day.addAccommodation')} )}
{/* Day-detail plugin slots: sandboxed, scoped to this day. */} {dayDetailPlugins.length > 0 && (
{dayDetailPlugins.map((p) => (
))}
)}
setShowHotelPicker(false)} onSave={() => { void saveHotelPicker() }} days={days} categories={categories} places={places} hotelDayRange={hotelDayRange} setHotelDayRange={setHotelDayRange} hotelForm={hotelForm} setHotelForm={setHotelForm} hotelCategoryFilter={hotelCategoryFilter} setHotelCategoryFilter={setHotelCategoryFilter} onSelectPlace={handleSelectPlace} />
) } /** A round button on the head band. It keeps its click from folding the card. */ function HeadButton({ label, onClick, expanded, children }: { label: string; onClick: () => void; expanded?: boolean; children: ReactNode }) { return ( ) } /** A weather fact as a pill: the icon and the value, the label in its tooltip and for screen readers. */ function WeatherChip({ icon: Icon, label, value }: { icon: LucideIcon; label: string; value: string }) { return ( }> {label}: {value} ) } function DayWeather({ weather, loading, isFahrenheit, placeName }: { weather: WeatherResult | null; loading: boolean; isFahrenheit: boolean; placeName: string | null }) { const { t } = useTranslation() if (loading) { return (
) } if (!weather) return

{t('day.noWeather')}

const unit = isFahrenheit ? '°F' : '°C' const hours = (weather.hourly || []).filter((_, i) => i % 2 === 0) return (
{/* Which place the forecast is for — on a roadtrip "the day's weather" is ambiguous without it (#2167). */} {placeName && {t('day.weatherFor', { name: placeName })}}
{weather.type === 'climate' ? 'Ø ' : ''}{toDisplayTemp(weather.temp, isFahrenheit)}{unit} {weather.temp_max != null && ( {toDisplayTemp(weather.temp_min, isFahrenheit)}° / {toDisplayTemp(weather.temp_max, isFahrenheit)}° )} {weather.description && {weather.description}}
{weather.precipitation_probability_max != null && ( )} {(weather.precipitation_sum ?? 0) > 0 && ( )} {weather.wind_max != null && ( )} {weather.sunrise && } {weather.sunset && }
{hours.length > 0 && (
{t('day.hourlyForecast')}
{hours.map(h => (
50 ? 'bg-info-soft' : ''}`}> {String(h.hour).padStart(2, '0')} {toDisplayTemp(h.temp, isFahrenheit)}° {h.precipitation_probability > 0 && ( {h.precipitation_probability}% )}
))}
)} {weather.type === 'climate' &&

{t('day.climateHint')}

}
) } /** A row or box that opens a booking: the hover lift and focus ring of the inspector's booking cards. */ const OPENS_BOOKING = 'w-full cursor-pointer text-start transition-shadow hover:shadow-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[color:var(--text-primary)]' /** The bookings of the day, hotels aside (they have their own block). With `onOpen` each row opens its booking. */ function DayReservations({ day, days, assignments, reservations, is12h, onOpen }: { day: Day; days: Day[]; assignments: AssignmentsMap; reservations: Reservation[]; is12h: boolean; onOpen?: (r: Reservation) => void }) { const { t } = useTranslation() const dayAssignments = assignments[String(day.id)] || [] const dayReservations = dayBookings(day.id, dayAssignments, reservations, pinnedAwayIn(assignments, days)) if (dayReservations.length === 0) return null return (
    {dayReservations.map(r => { const linkedAssignment = dayAssignments.find(a => a.id === r.assignment_id) const tone = toneOf(r) const status = tone === 'transit' ? null : tone === 'confirmed' ? t('reservations.confirmed') : t('reservations.pending') const { time: startTime } = splitReservationDateTime(r.reservation_time) const { time: endTime } = splitReservationDateTime(r.reservation_end_time) const row = 'flex min-w-0 items-center gap-2.5 rounded-[10px] border border-edge-faint px-2 py-1.5' const content = ( <> {r.title} {linkedAssignment?.place && {linkedAssignment.place.name}} {(startTime || endTime) && ( {startTime ? formatClockTime(startTime, is12h) : ''} {endTime ? ` – ${formatClockTime(endTime, is12h)}` : ''} )} {status && ( )} ) if (!onOpen) return
  • {content}
  • return (
  • ) })}
) } function AccommodationCard({ acc, day, linked, canEdit, onEdit, onRemove, onOpenBooking }: { acc: Accommodation day: Day linked: Reservation | undefined canEdit: boolean onEdit: () => void onRemove: () => void /** Given, the stay's booking box opens that booking. */ onOpenBooking?: (reservation: Reservation) => void }) { const { t, locale } = useTranslation() const is12h = useSettingsStore(s => s.settings.time_format) === '12h' const fmtTime = (v: string) => { if (v.includes('T')) return new Date(v).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hour12: is12h }) return formatClockTime(v, is12h) } const isCheckInDay = acc.start_day_id === day.id const isCheckOutDay = acc.end_day_id === day.id const dayLabel = stayDayLabel(acc, day.id, t) const leaving = isCheckOutDay && !isCheckInDay const tint = isCheckInDay ? tintOf('var(--success)') : isCheckOutDay ? tintOf('var(--danger)') : NEUTRAL_TINT const cells: { label: string; value: ReactNode }[] = [] const times = stayDayTimes(acc, day.id) if (times.checkIn && acc.check_in) cells.push({ label: t('day.checkIn'), value: `${fmtTime(acc.check_in)}${acc.check_in_end ? ` – ${fmtTime(acc.check_in_end)}` : ''}` }) if (times.checkOut && acc.check_out) cells.push({ label: t('day.checkOut'), value: fmtTime(acc.check_out) }) if (acc.confirmation) cells.push({ label: t('day.confirmation'), value: {acc.confirmation} }) const confirmed = linked?.status === 'confirmed' return (
{acc.place_image ? : }
{acc.place_name}
{acc.place_address &&
{acc.place_address}
}
{dayLabel && ( : }> {dayLabel} )} {canEdit && } {canEdit && }
{(cells.length > 0 || linked) && (
{cells.length > 0 && (
{cells.map(c => {c.value})}
)} {linked && (
{t('places.formReservation')} {(() => { const box = `${BOX} flex min-w-0 items-center gap-2 px-2.5 py-1.5` // A box that opens the booking is a button itself, so the code in it is // no second button and stays out of the button's name; the booking it // opens shows the code and reveals it. const content = ( <> {linked.title} {confirmed ? t('reservations.confirmed') : t('reservations.pending')} {linked.confirmation_number && ( #{linked.confirmation_number} )} ) if (!onOpenBooking) return
{content}
return ( ) })()}
)}
)}
) } interface HotelPickerModalProps { mode: HotelPickerMode onClose: () => void onSave: () => void days: Day[] categories: Category[] places: Place[] hotelDayRange: HotelDayRange setHotelDayRange: React.Dispatch> hotelForm: HotelForm setHotelForm: React.Dispatch> hotelCategoryFilter: number | '' setHotelCategoryFilter: (id: number | '') => void onSelectPlace: (placeId: number) => void } /** The stay editor: which days, the times, the code, and the place to sleep at. */ function HotelPickerModal({ mode, onClose, onSave, days, categories, places, hotelDayRange, setHotelDayRange, hotelForm, setHotelForm, hotelCategoryFilter, setHotelCategoryFilter, onSelectPlace }: HotelPickerModalProps) { const { t, locale } = useTranslation() const titleId = useId() const codeId = useId() const startId = useId() const endId = useId() if (!mode) return null const dayLabel = (d: Day, i: number) => d.title || t('planner.dayN', { n: i + 1 }) const dayOptions = stayDayOptions(days, t, locale) const position = (id: number | undefined) => days.findIndex(d => d.id === id) const allDays = hotelDayRange.start === days[0]?.id && hotelDayRange.end === days[days.length - 1]?.id const filtered = stayPlaceChoices(places, hotelForm.place_id, hotelCategoryFilter || null) const setTime = (field: 'check_in' | 'check_in_end' | 'check_out') => (v: string) => setHotelForm(f => ({ ...f, [field]: v })) const picked = places.find(p => p.id === hotelForm.place_id) ?? null const startAt = position(hotelDayRange.start) const endAt = position(hotelDayRange.end) const nights = startAt >= 0 && endAt > startAt ? endAt - startAt : 0 const categoryOptions = [ { value: '', label: t('places.allCategories') }, ...categories.map(c => ({ value: String(c.id), label: c.name, icon: , })), ] return ( } tint={tintOf(typeInfo('hotel').color, 11)} labelId={titleId} onClose={onClose} eyebrow={mode === 'edit' ? t('day.editAccommodation') : t('day.addAccommodation')} // The stay is named by where it sleeps; until one is picked the title asks for it. title={picked ? picked.name : {t('reservations.meta.pickHotel')}} sub={picked?.address || undefined} pills={startAt >= 0 ? ( <> {dayLabel(days[startAt], startAt)} {endAt > startAt && <>{dayLabel(days[endAt], endAt)}} {/* The moon says "nights"; the word stays in the tooltip, since "5 Nights" has no plural rule behind it. */} {nights > 0 && ( {nights} )} ) : undefined} /> )} footer={( {t('common.cancel')} {t('common.save')} )} >
{ const id = Number(v); setHotelDayRange(prev => stayRangeFromStart(days, prev, id)) }} options={dayOptions} size="sm" /> { const id = Number(v); setHotelDayRange(prev => stayRangeFromEnd(days, prev, id)) }} options={dayOptions} size="sm" /> setHotelDayRange({ start: days[0]?.id, end: days[days.length - 1]?.id })}> {t('day.allDays')}
setHotelForm(f => ({ ...f, confirmation: e.target.value }))} placeholder="ABC-12345" className={INPUT} />
0 ? ( value={hotelCategoryFilter ? String(hotelCategoryFilter) : ''} options={categoryOptions} onChange={v => setHotelCategoryFilter(v ? Number(v) : '')} label={t('places.formCategory')} quiet /> ) : undefined}> {filtered.length === 0 ? (

{t('day.noPlacesForHotel')}

) : (
{filtered.map(p => { const on = hotelForm.place_id === p.id const cat = categories.find(c => c.id === p.category_id) return ( ) })}
)}
) }