import { useEffect, useRef, useState } from 'react' import Markdown from 'react-markdown' import remarkGfm from 'remark-gfm' import remarkBreaks from 'remark-breaks' import { ArrowRight, ArrowRightLeft, Bold, Clock, Code, Footprints, Heading2, Italic, Link2, List, ListChecks, MoveRight, Pencil, RefreshCw, Strikethrough, TramFront, Trash2 } from 'lucide-react' import Modal from '../shared/Modal' import ConfirmDialog from '../shared/ConfirmDialog' import { useTranslation } from '../../i18n' import { useSettingsStore } from '../../store/settingsStore' import { splitReservationDateTime, formatTime } from '../../utils/formatters' import { TransitTitle, TransitMetaBadges, TransitWalkDivider, fmtTransitDuration } from './transitDisplay' import type { Reservation } from '../../types' /** * The journey view for an automated public-transit entry (#1065): a roomy modal * around the stop-by-stop itinerary. The title renames inline right in the * header, notes get the full width with markdown support, and "Change route" * re-enters the transit search pre-seeded with this journey's route. */ interface TransitLegMeta { mode?: string line?: string | null line_color?: string | null line_text_color?: string | null headsign?: string | null agency?: string | null duration?: number stops?: number from?: { name?: string; time?: string | null; track?: string | null } to?: { name?: string; time?: string | null; track?: string | null } } interface TransitJourneyModalProps { reservation: Reservation onClose: () => void /** Partial field update — endpoints + itinerary stay untouched. */ onSave: (fields: { title: string; notes: string | null }) => Promise onDelete: () => Promise onChangeRoute: () => void canEdit: boolean } export default function TransitJourneyModal({ reservation, onClose, onSave, onDelete, onChangeRoute, canEdit }: TransitJourneyModalProps) { const { t, locale } = useTranslation() const isMobile = typeof window !== 'undefined' && window.innerWidth < 768 const timeFormat = useSettingsStore(st => st.settings.time_format) || '24h' const res = reservation const meta = typeof res.metadata === 'string' ? (() => { try { return JSON.parse(res.metadata || '{}') } catch { return {} } })() : (res.metadata || {}) const transit = meta.transit && Array.isArray(meta.transit.legs) ? meta.transit : null const [title, setTitle] = useState(res.title || '') const [editingTitle, setEditingTitle] = useState(false) const [notes, setNotes] = useState(res.notes || '') // Existing notes open rendered; the write tab is for editing. const [notesTab, setNotesTab] = useState<'write' | 'preview'>(() => (res.notes ? 'preview' : 'write')) const [saving, setSaving] = useState(false) const [confirmDelete, setConfirmDelete] = useState(false) const titleInputRef = useRef(null) const notesRef = useRef(null) // Markdown toolbar: wrap the selection / prefix the current lines, then // restore focus and a sensible cursor. const applyMd = (action: { wrap?: [string, string]; linePrefix?: string }) => { const el = notesRef.current if (!el) return const start = el.selectionStart ?? 0 const end = el.selectionEnd ?? 0 const value = notes let next = value let selStart = start let selEnd = end if (action.wrap) { const [pre, post] = action.wrap const selected = value.slice(start, end) next = value.slice(0, start) + pre + selected + post + value.slice(end) selStart = start + pre.length selEnd = selStart + selected.length } else if (action.linePrefix) { const prefix = action.linePrefix const lineStart = value.lastIndexOf('\n', start - 1) + 1 const block = value.slice(lineStart, end) const prefixed = block.split('\n').map(l => prefix + l).join('\n') next = value.slice(0, lineStart) + prefixed + value.slice(end) selStart = start + prefix.length selEnd = end + (prefixed.length - block.length) } setNotes(next) requestAnimationFrame(() => { el.focus() el.setSelectionRange(selStart, selEnd) }) } const MD_TOOLS: { Icon: typeof Bold; label: string; action: { wrap?: [string, string]; linePrefix?: string } }[] = [ { Icon: Bold, label: 'Bold', action: { wrap: ['**', '**'] } }, { Icon: Italic, label: 'Italic', action: { wrap: ['*', '*'] } }, { Icon: Strikethrough, label: 'Strikethrough', action: { wrap: ['~~', '~~'] } }, { Icon: Heading2, label: 'Heading', action: { linePrefix: '## ' } }, { Icon: List, label: 'List', action: { linePrefix: '- ' } }, { Icon: ListChecks, label: 'Checklist', action: { linePrefix: '- [ ] ' } }, { Icon: Link2, label: 'Link', action: { wrap: ['[', '](https://)'] } }, { Icon: Code, label: 'Code', action: { wrap: ['`', '`'] } }, ] useEffect(() => { setTitle(res.title || '') setNotes(res.notes || '') setEditingTitle(false) setNotesTab(res.notes ? 'preview' : 'write') }, [res.id]) useEffect(() => { if (editingTitle) titleInputRef.current?.focus() }, [editingTitle]) const dirty = title !== (res.title || '') || notes !== (res.notes || '') const save = async () => { if (!title.trim()) return setSaving(true) try { await onSave({ title: title.trim(), notes: notes.trim() || null }) onClose() } finally { setSaving(false) } } const { date, time } = splitReservationDateTime(res.reservation_time) const { time: endTime } = splitReservationDateTime(res.reservation_end_time) const dateStr = date ? new Date(date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'long', day: 'numeric', month: 'long', timeZone: 'UTC' }) : '' const statTiles = transit ? [ { Icon: Clock, value: transit.duration > 0 ? fmtTransitDuration(transit.duration, t) : '—', label: t('transit.durationLabel') }, { Icon: ArrowRightLeft, value: String(transit.transfers ?? 0), label: t('transit.transfersLabel') }, { Icon: Footprints, value: transit.walk_seconds > 59 ? t('transit.min', { count: Math.round(transit.walk_seconds / 60) }) : '—', label: t('transit.walkLabel') }, ] : [] return ( {canEdit && ( )}
{canEdit && ( )} {canEdit ? ( ) : ( )}
} >
{/* header: icon + inline-renamable title + date/time */}
{editingTitle ? ( setTitle(e.target.value)} onBlur={() => setEditingTitle(false)} onKeyDown={e => { if (e.key === 'Enter') setEditingTitle(false); if (e.key === 'Escape') { setTitle(res.title || ''); setEditingTitle(false) } }} className="text-content" aria-label={t('reservations.titleLabel')} style={{ width: '100%', border: 'none', outline: 'none', background: 'transparent', padding: 0, fontFamily: 'inherit', fontSize: 'calc(17px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.015em', borderBottom: '1.5px solid var(--text-primary)' }} /> ) : (
{canEdit && ( )}
)}
{[dateStr, time ? `${formatTime(time, locale, timeFormat)}${endTime ? ` – ${formatTime(endTime, locale, timeFormat)}` : ''}` : ''].filter(Boolean).join(' · ')}
{transit && ( <> {/* journey stats — three full-width tiles; iconless and flat on mobile */}
{statTiles.map(({ Icon, value, label }, i) => ( isMobile ? (
{value}
{label}
) : (
{value}
{label}
) ))}
{/* stop-by-stop itinerary */}
{t('transit.itinerary')}
{(transit.legs as TransitLegMeta[]).map((leg, i) => { if (leg.mode === 'WALK') return const mins = leg.duration ? Math.round(leg.duration / 60) : null if (isMobile) { // The wide from → to line plus the chip row doesn't fit a // phone: each leg becomes a depart / ride / arrive rail in // the line's color, meta as one quiet text line. const color = leg.line_color || 'var(--text-muted)' const metaLine = [ mins ? t('transit.min', { count: mins }) : null, leg.stops ? t('transit.stops', { count: leg.stops }) : null, leg.agency || null, ].filter(Boolean).join(' · ') // Names wrap instead of clipping; the platform gets its // own quiet line below so it never pushes the name out. const stopName = (stop: TransitLegMeta['from']) => (
{stop?.name}
{stop?.track && (
{t('transit.platform', { track: stop.track })}
)}
) const timeCell = (time?: string | null) => (
{time || ''}
) return (
{timeCell(leg.from?.time)}
{stopName(leg.from)}
{leg.line || leg.mode} {leg.headsign && ( {leg.headsign} )}
{metaLine && (
{metaLine}
)}
{timeCell(leg.to?.time)}
{stopName(leg.to)}
) } return (
{leg.from?.time || ''}
{leg.line || leg.mode}
{leg.from?.name} {leg.from?.track && ({t('transit.platform', { track: leg.from.track })})} {leg.to?.name}
) })}
)} {/* notes — full width, markdown */}
{canEdit && (
{notesTab === 'write' && (
{MD_TOOLS.map(({ Icon, label, action }) => ( ))}
)}
{([['write', t('common.edit')], ['preview', t('common.preview')]] as const).map(([tab, label]) => ( ))}
)}
{canEdit && notesTab === 'write' ? (