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. */}
)}
{/* 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 ? (
)
}
/** 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 })}}
{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')}
)}
>