import { useState, useEffect, useRef, useMemo, type ReactNode } from 'react' import { useParams } from 'react-router' import { X, Trash2, ChevronUp, ChevronDown, CalendarDays } from 'lucide-react' import ConfirmDialog from '../shared/ConfirmDialog' import CustomSelect from '../shared/CustomSelect' import { BookingCodeInput } from '../shared/BookingCode' import CustomTimePicker from '../shared/CustomTimePicker' import { Tooltip } from '../shared/Tooltip' import AirportSelect from './AirportSelect' import LocationSelect from './LocationSelect' import { toLocationPicks } from './locationPicks' import { useTranslation } from '../../i18n' import { useToast } from '../shared/Toast' import { useTripStore } from '../../store/tripStore' import { useAddonStore } from '../../store/addonStore' import type { Day, Place, Accommodation, Reservation, TripFile, AssignmentsMap } from '../../types' import { BookingNotesFilesCosts } from './BookingNotesFilesCosts' import { TravelerPicker } from './TravelerPicker' import type { TripMember } from '../Budget/BudgetPanelMemberChips' import type { BookingExpenseRequest } from './BookingCostsSection.types' import type { BookingReviewDraft } from './parsedItemToDraft' import TransitSearchPanel from './TransitSearchPanel' import type { TransitPrefill } from './transitLeg' import { BookingDialogHeader, StatusPill } from './bookings/BookingDialogShell' import { DialogShell, DialogSection, DialogFooter, FooterSpacer, DialogButton, DeleteButton } from '../shared/DialogShell' import { INPUT, READONLY_BOX, GRID_2, GRID_3, PANEL, SEARCH_ON_PANEL, EditorField, Segmented, PillSelect, AddRowButton } from '../shared/dialogParts' import { fs, Eyebrow, type StatusTone } from './bookings/bookingParts' import { deleteBodyKey, typeInfo } from './bookings/bookingsModel' import { EMPTY_TRANSPORT_FIELDS, TRANSPORT_TYPE_OPTIONS as TYPE_OPTIONS, emptyCarStop, emptyStationWaypoint, emptyWaypoint, transportDayOptions, type StationWaypointForm, type WaypointForm, } from './transportEndpoints' import { useTransportForm } from './useTransportForm' import { expenseRequestAfterSave, pendingImportExpense, travelerIdsOf, filesNeedConnection, type BookingSaveSteps } from './bookingFormModel' import { useBookingExpenseIntent } from './useBookingExpenseIntent' import { useBookingFileAttach } from './useBookingFileAttach' import { useBookingFollowUp } from './useBookingFollowUp' const defaultForm = { ...EMPTY_TRANSPORT_FIELDS, url: '', meta_airline: '', meta_flight_number: '', meta_train_number: '', meta_platform: '', meta_seat: '', } interface TransportModalProps { isOpen: boolean onClose: () => void onSave: (data: Record & { title: string }, steps?: BookingSaveSteps) => Promise reservation: Reservation | null days: Day[] selectedDayId: number | null files?: TripFile[] onFileUpload?: (fd: FormData) => Promise onFileDelete?: (fileId: number) => Promise /** Deletes the reservation being edited. Omit to hide the delete action (create mode, or no permission). */ onDelete?: () => void | Promise onOpenExpense?: (req: BookingExpenseRequest) => void // Pre-fill a brand-new transport booking from a parsed import item (review- // before-save); like `reservation` for the form but stays in create mode. prefill?: BookingReviewDraft | null /** Data for the Automated (public transit) mode's quick picks. */ places?: Place[] /** Day→assignments map, used to scope the quick picks to the chosen day (#1460). */ assignments?: AssignmentsMap accommodations?: Accommodation[] /** Open directly in the Automated public-transit mode (day-header tram button, "change route"). */ initialAutomated?: boolean /** Transit search needs real dates to depart on, so the Automated mode is hidden on a dateless trip. */ tripHasDates?: boolean /** Pre-seed the transit search — used by "change route" and by per-leg planning. */ transitPrefill?: TransitPrefill | null /** Trip members + guests, for the traveler picker (#1517). */ tripMembers?: TripMember[] } export function TransportModal({ isOpen, onClose, onSave, reservation, days, selectedDayId, files = [], onFileUpload, onFileDelete, onDelete, onOpenExpense, prefill = null, places = [], assignments = {}, accommodations = [], initialAutomated = false, transitPrefill = null, tripHasDates = true, tripMembers = [] }: TransportModalProps) { const { t, locale } = useTranslation() const toast = useToast() // The trip's places, offered by every location field of the manual tab (#2468). const locationPicks = useMemo(() => toLocationPicks(places), [places]) const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget')) const budgetItems = useTripStore(s => s.budgetItems) const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem) const { id: tripId } = useParams<{ id: string }>() // Set right before submitting when the user clicked "create/edit expense", so // the post-save handler knows to open the Costs editor for the saved booking. const expense = useBookingExpenseIntent(() => handleSubmit(), { remove: item => deleteBudgetItem(Number(tripId), item.id), onError: () => toast.error(t('common.unknownError')), }) const { form, set, stationRoute, automated, setAutomated, fromPick, setFromPick, toPick, setToPick, waypoints, setWaypoints, trainWaypoints, setTrainWaypoints, carStops, setCarStops, moveCarStop, pendingFiles, setPendingFiles, travelerIds, setTravelerIds, toggleTraveler, isSaving, setIsSaving, seed, payload, writesFlightLegs, writesTrainLegs, } = useTransportForm(defaultForm) const [showDeleteConfirm, setShowDeleteConfirm] = useState(false) const attach = useBookingFileAttach({ reservation, files, setPendingFiles }) const followUp = useBookingFollowUp({ session: isOpen ? (reservation ?? prefill ?? 'new') : null, tripId, original: reservation, travelerIds, pendingFiles, setPendingFiles, upload: onFileUpload, t, }) const fileInputRef = useRef(null) useEffect(() => { // A try that stored the booking and failed on its files keeps the form as the // user left it; the costs that save reloaded must not reseed it. if (!isOpen || followUp.holdsSaved()) return setTravelerIds(travelerIdsOf(reservation)) // Edit uses the saved `reservation`; a review-import populates from `prefill`. // Either way the init reads the same fields — `reservation` still decides // edit-vs-create at submit time. const src = (reservation ?? prefill) as Reservation | null setAutomated(initialAutomated) // On a review-import, seed the booking's Files with the parsed source document. setPendingFiles(!reservation && prefill?._sourceFiles ? prefill._sourceFiles : []) // An import whose type could not be read opens as 'transport_other', not // 'flight': it has to arrive as something the user corrects, and a wrong flight // looks right enough to be saved unnoticed (#2076). seed(src, days, { isEdit: !!reservation, fallbackType: 'transport_other', dayId: selectedDayId ?? '', stopDaysFromEndpoints: false, extraFields: (s, meta) => ({ url: s.url || '', meta_airline: meta.airline || '', meta_flight_number: meta.flight_number || '', meta_train_number: meta.train_number || '', meta_platform: meta.platform || '', meta_seat: meta.seat || '', }), }) }, [isOpen, reservation, prefill, selectedDayId, budgetItems]) const handleSubmit = async (e?: React.FormEvent) => { e?.preventDefault() if (!form.title.trim()) return if (filesNeedConnection(pendingFiles, !!onFileUpload)) { toast.error(t('reservations.filesNeedConnection')); return } await saveTransport() } const saveTransport = async () => { setIsSaving(true) try { const saved = await onSave(payload(days, { reservation, prefill, budgetEnabled: isBudgetEnabled, anchorOnStations: false, url: form.url, }), followUp.steps(form.title)) // The user asked to create/edit the linked expense — open the Costs editor // for the now-saved booking. Gated on saved?.id so a failed save doesn't. const expenseRequest = expenseRequestAfterSave(expense.take(), saved, form, days) if (expenseRequest && onOpenExpense) onOpenExpense(expenseRequest) } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } finally { setIsSaving(false) } } // On an import review (not yet saved), preview the parsed price as the cost that will be // linked: the same entry the save sends, so the two cannot name different currencies. const pendingExpense = pendingImportExpense(reservation, prefill, form.type) const dayOptions = transportDayOptions(days, t, locale) const titleId = 'transport-editor-title' // The head band takes the colour of the card the booking will sit on. const tone: StatusTone = automated || form.type === 'transit' ? 'transit' : form.status const isCar = form.type === 'car' const routeNames = (form.type === 'flight' ? waypoints.map(w => w.airport?.iata) : stationRoute ? trainWaypoints.map(w => w.location?.name) : [fromPick.location?.name, ...(isCar ? carStops.map(s => s.location?.name) : []), toPick.location?.name] ).filter(Boolean) const shownType = typeInfo(form.type) const dayField = (label: string, value: string | number, onChange: (value: string | number) => void) => ( ) const timeField = (label: string, value: string, onChange: (value: string) => void) => ( ) const zoneField = (label: string, tz: string) => (
{tz || ' '}
) // Manual vs Automated creation (#1065), only while creating: a journey is // edited again through "change route" with the switch hidden. A trip without // dates has no day to depart on, so it gets the manual form alone. The switch // sits in the head band, which stays put while the body swaps modes. const modeSwitch = !reservation && tripHasDates && ( setAutomated(mode === 'automated')} options={[ { value: 'manual', label: t('transport.modeManual') }, { value: 'automated', label: t('transport.modeAutomated') }, ]} /> ) // Until there is a title, the line under it says the field is required: // Add stays greyed out without one, and a disabled button cannot say why. let headerSub: string | undefined if (automated) headerSub = t('transit.searchHint') else if (!form.title.trim()) headerSub = `${t('reservations.titleLabel')} *` else if (routeNames.length >= 2) headerSub = routeNames.join(' → ') const header = ( set('title', value), label: t('reservations.titleLabel'), placeholder: t('reservations.titlePlaceholder'), required: true, }} sub={headerSub} subWraps={automated} pills={( <> {/* The search runs against one day; it heads the band next to the mode switch. */} {automated && ( set('start_day_id', value === '' ? '' : Number(value))} options={dayOptions.map(o => ({ value: String(o.value), label: o.label, hint: 'badge' in o ? o.badge : undefined, icon: }))} /> )} {!automated && ( set('status', form.status === 'confirmed' ? 'pending' : 'confirmed')} /> )} {!automated && ( set('type', value)} options={TYPE_OPTIONS.map(o => ({ value: o.value, label: t(o.labelKey), icon: }))} fallback={{ label: t(shownType.chipKey), icon: }} /> )} {modeSwitch} )} /> ) const footer = ( {!automated && reservation?.id && onDelete && setShowDeleteConfirm(true)} />} {t('common.cancel')} {!automated && ( handleSubmit()} disabled={isSaving || !form.title.trim()}> {isSaving ? t('common.saving') : reservation ? t('common.update') : t('common.add')} )} ) const transitSearch = () => { const transitDay = days.find(d => d.id === Number(form.start_day_id)) if (!transitDay) return

{t('transit.pickDay')}

// Quick picks offer the chosen day's itinerary, not the whole trip (#1460). const dayPlaces = (assignments[String(transitDay.id)] || []) .slice().sort((a, b) => a.order_index - b.order_index) .map(a => places.find(p => p.id === a.place_id)) .filter((p): p is Place => p != null) return ( onSave(payload as Record & { title: string })} initialFrom={transitPrefill?.from ?? null} initialTo={transitPrefill?.to ?? null} initialTime={transitPrefill?.time ?? null} walk={transitPrefill?.walk ?? null} /> ) } const roleLabel = (i: number, count: number) => i === 0 ? t(form.type === 'cruise' ? 'reservations.cruise.embark' : 'reservations.meta.from') : i === count - 1 ? t(form.type === 'cruise' ? 'reservations.cruise.disembark' : 'reservations.meta.to') : t(form.type === 'cruise' ? 'reservations.cruise.port' : 'reservations.layover.stop') // Flight route: ordered airports (origin, stops, destination) on one rail. const flightRoute = () => (
    {waypoints.map((wp, i) => { const isFirst = i === 0 const isLast = i === waypoints.length - 1 const updateWp = (patch: Partial) => setWaypoints(prev => prev.map((w, j) => (j === i ? { ...w, ...patch } : w))) return (
    setWaypoints(prev => prev.filter((_, j) => j !== i)) : undefined}>
    updateWp({ airport: a || null })} />
    {!isFirst && (
    {dayField(t('reservations.arrivalDate'), wp.arrDayId, v => updateWp({ arrDayId: v }))} {timeField(t('reservations.arrivalTime'), wp.arrTime, v => updateWp({ arrTime: v }))} {wp.airport && zoneField(t('reservations.meta.arrivalTimezone'), wp.airport.tz)}
    )} {!isLast && ( <>
    {dayField(t('reservations.departureDate'), wp.depDayId, v => updateWp({ depDayId: v }))} {timeField(t('reservations.departureTime'), wp.depTime, v => updateWp({ depTime: v }))} {wp.airport && zoneField(t('reservations.meta.departureTimezone'), wp.airport.tz)}
    updateWp({ airline: e.target.value })} placeholder="Lufthansa" className={INPUT} /> updateWp({ flight_number: e.target.value })} placeholder="LH 123" className={INPUT} /> updateWp({ seat: e.target.value })} placeholder="12A" className={INPUT} /> {writesFlightLegs && ( updateWp({ confirmation_number: e.target.value })} placeholder={t('reservations.confirmationPlaceholder')} className={INPUT} /> )}
    )}
    {!isLast && (
    setWaypoints(prev => [...prev.slice(0, i + 1), emptyWaypoint(prev[i]?.depDayId || ''), ...prev.slice(i + 1)])}> {t('reservations.layover.addStop')}
    )}
    ) })}
) // Train route: ordered stations on the same rail, per-leg train fields. const trainRoute = () => (
    {trainWaypoints.map((wp, i) => { const isFirst = i === 0 const isLast = i === trainWaypoints.length - 1 const updateWp = (patch: Partial) => setTrainWaypoints(prev => prev.map((w, j) => (j === i ? { ...w, ...patch } : w))) return (
    setTrainWaypoints(prev => prev.filter((_, j) => j !== i)) : undefined}>
    updateWp({ location: l || null })} places={locationPicks} />
    {!isFirst && (
    {dayField(t('reservations.arrivalDate'), wp.arrDayId, v => updateWp({ arrDayId: v }))} {timeField(t('reservations.arrivalTime'), wp.arrTime, v => updateWp({ arrTime: v }))}
    )} {!isLast && ( <>
    {dayField(t('reservations.departureDate'), wp.depDayId, v => updateWp({ depDayId: v }))} {timeField(t('reservations.departureTime'), wp.depTime, v => updateWp({ depTime: v }))}
    {/* A cruise's ports carry only their times: number, platform and seat are a train's. */} {form.type === 'train' &&
    updateWp({ train_number: e.target.value })} placeholder="ICE 123" className={INPUT} /> updateWp({ platform: e.target.value })} placeholder="12" className={INPUT} /> updateWp({ seat: e.target.value })} placeholder="42A" className={INPUT} /> {writesTrainLegs && ( updateWp({ confirmation_number: e.target.value })} placeholder={t('reservations.confirmationPlaceholder')} className={INPUT} /> )}
    } )}
    {!isLast && (
    setTrainWaypoints(prev => [...prev.slice(0, i + 1), emptyStationWaypoint(prev[i]?.depDayId || ''), ...prev.slice(i + 1)])}> {t(form.type === 'cruise' ? 'reservations.cruise.addPort' : 'reservations.layover.addStop')}
    )}
    ) })}
) // Every other type: one From and one To, the day and time rows under them. const plainRoute = () => (
setFromPick({ location: l || undefined })} places={locationPicks} />
setToPick({ location: l || undefined })} places={locationPicks} />
{/* Stops along the drive, cars only (#1797). The rental frame above stays the pick-up and return; these are the places in between, in order. */} {isCar && (
{t('roadtrip.stops.label')}
{carStops.map((stop, i) => (
{/* The order of the stops IS the route (sequence is the index at save time), and the row has no room left to drag by, hence buttons. */} {carStops.length > 1 && (
moveCarStop(i, -1)} disabled={i === 0} shape="h-[18px] w-6 rounded-md"> moveCarStop(i, 1)} disabled={i === carStops.length - 1} shape="h-[18px] w-6 rounded-md">
)}
setCarStops(prev => prev.map((s, j) => (j === i ? { ...s, location: l || null } : s)))} places={locationPicks} />
setCarStops(prev => prev.map((s, j) => (j === i ? { ...s, time: v } : s)))} />
setCarStops(prev => prev.filter((_, j) => j !== i))} danger>
))} setCarStops(prev => [...prev, emptyCarStop()])}>{t('reservations.layover.addStop')}
)}
{dayField(isCar ? t('reservations.pickupDate') : t('reservations.date'), form.start_day_id, value => set('start_day_id', value))} {timeField(isCar ? t('reservations.pickupTime') : t('reservations.startTime'), form.departure_time, v => set('departure_time', v))}
{dayField(isCar ? t('reservations.returnDate') : t('reservations.endDate'), form.end_day_id, value => set('end_day_id', value))} {timeField(isCar ? t('reservations.returnTime') : t('reservations.endTime'), form.arrival_time, v => set('arrival_time', v))}
) return ( {automated ? ( /* Automated: public transit search (#1065) for the day picked in the head band. */ transitSearch() ) : ( <> {/* Travelers: trip members and guests on this booking (#1517) */} {form.type === 'flight' ? flightRoute() : stationRoute ? trainRoute() : plainRoute()} set('confirmation_number', e.target.value)} placeholder={t('reservations.confirmationPlaceholder')} className={INPUT} /> )} setShowDeleteConfirm(false)} title={t('reservations.confirm.deleteTitle')} message={t(deleteBodyKey(reservation?.id, budgetItems), { name: reservation?.title ?? '' })} confirmLabel={t('common.delete')} cancelLabel={t('common.cancel')} onConfirm={async () => { setShowDeleteConfirm(false) await onDelete?.() onClose() }} /> ) } const GRID_4 = 'grid grid-cols-4 items-start gap-3 max-sm:grid-cols-1' /** One stop on the route: a dot on the line from origin to destination, its fields beside it. */ function RailStop({ first, last, children }: { first: boolean; last: boolean; children: ReactNode }) { return (
  • {!first &&
  • ) } /** The role of a stop over its place field, and the remove action an intermediate stop has. */ function StopHead({ label, onRemove, children }: { label: string; onRemove?: () => void; children: ReactNode }) { const { t } = useTranslation() return (
    {label} {onRemove && ( )}
    {children}
    ) } /** A small icon button inside a route, named by its tooltip. */ function IconAction({ label, onClick, disabled, danger = false, shape = 'h-6 w-6 rounded-full', children }: { label: string onClick: () => void disabled?: boolean danger?: boolean shape?: string children: ReactNode }) { return ( ) }