diff --git a/client/src/components/Planner/DayPlanSidebar.constants.ts b/client/src/components/Planner/DayPlanSidebar.constants.ts new file mode 100644 index 0000000000000000000000000000000000000000..bfbc63070f4a16ab1e2cef7491ecf586b930091f --- /dev/null +++ b/client/src/components/Planner/DayPlanSidebar.constants.ts @@ -0,0 +1,53 @@ +import { + FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, + Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, + ShoppingBag, Bookmark, Hotel, Utensils, Users, Sailboat, Bike, CarTaxiFront, Route, + Wine, ParkingSquare, Fuel, Footprints, Mountain, Waves, Sun, Umbrella, Music, Landmark, Gift, +} from 'lucide-react' + +export const RES_ICONS = { flight: Plane, hotel: Hotel, restaurant: Utensils, train: Train, car: Car, cruise: Ship, bus: Bus, ferry: Sailboat, bicycle: Bike, taxi: CarTaxiFront, transport_other: Route, event: Ticket, tour: Users, other: FileText } + +export const NOTE_ICONS = [ + { id: 'FileText', Icon: FileText }, + { id: 'Info', Icon: Info }, + { id: 'Clock', Icon: Clock }, + { id: 'MapPin', Icon: MapPin }, + { id: 'Navigation', Icon: Navigation }, + { id: 'Train', Icon: Train }, + { id: 'Plane', Icon: Plane }, + { id: 'Bus', Icon: Bus }, + { id: 'Car', Icon: Car }, + { id: 'Ship', Icon: Ship }, + { id: 'Coffee', Icon: Coffee }, + { id: 'Ticket', Icon: Ticket }, + { id: 'Star', Icon: Star }, + { id: 'Heart', Icon: Heart }, + { id: 'Camera', Icon: Camera }, + { id: 'Flag', Icon: Flag }, + { id: 'Lightbulb', Icon: Lightbulb }, + { id: 'AlertTriangle', Icon: AlertTriangle }, + { id: 'ShoppingBag', Icon: ShoppingBag }, + { id: 'Bookmark', Icon: Bookmark }, + { id: 'Utensils', Icon: Utensils }, + { id: 'Wine', Icon: Wine }, + { id: 'ParkingSquare', Icon: ParkingSquare }, + { id: 'Fuel', Icon: Fuel }, + { id: 'Footprints', Icon: Footprints }, + { id: 'Mountain', Icon: Mountain }, + { id: 'Waves', Icon: Waves }, + { id: 'Sun', Icon: Sun }, + { id: 'Umbrella', Icon: Umbrella }, + { id: 'Music', Icon: Music }, + { id: 'Landmark', Icon: Landmark }, + { id: 'Gift', Icon: Gift }, +] +const NOTE_ICON_MAP = Object.fromEntries(NOTE_ICONS.map(({ id, Icon }) => [id, Icon])) +export function getNoteIcon(iconId) { return NOTE_ICON_MAP[iconId] || FileText } + +export const TYPE_ICONS = { + flight: '✈️', hotel: '🏨', restaurant: '🍽️', train: '🚆', + car: '🚗', cruise: '🚢', bus: '🚌', ferry: '⛴️', bicycle: '🚲', taxi: '🚕', + transport_other: '🧭', event: '🎫', other: '📋', +} + +export const TRANSPORT_DETAIL_COLORS = { flight: '#3b82f6', train: '#06b6d4', bus: '#059669', ferry: '#0d9488', bicycle: '#84cc16', taxi: '#ca8a04', car: '#6b7280', cruise: '#0ea5e9', transport_other: '#6b7280' } diff --git a/client/src/components/Planner/DayPlanSidebar.test.tsx b/client/src/components/Planner/DayPlanSidebar.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..7038db2d19e20f9ef5192db534f0898c32e3f9c3 --- /dev/null +++ b/client/src/components/Planner/DayPlanSidebar.test.tsx @@ -0,0 +1,1756 @@ +// FE-PLANNER-DAYPLAN-001 to FE-PLANNER-DAYPLAN-042 +import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render' +import userEvent from '@testing-library/user-event' +import { useAuthStore } from '../../store/authStore' +import { useTripStore } from '../../store/tripStore' +import { useSettingsStore } from '../../store/settingsStore' +import { resetAllStores, seedStore } from '../../../tests/helpers/store' +import { + buildUser, buildTrip, buildDay, buildPlace, buildCategory, buildAssignment, buildDayNote, buildReservation, +} from '../../../tests/helpers/factories' +import DayPlanSidebar from './DayPlanSidebar' + +// ── Hoisted mock state (accessible in vi.mock factories) ──────────────────── +const mockDayNotesState = vi.hoisted(() => ({ + noteUi: {} as Record, + dayNotes: {} as Record, + setNoteUi: vi.fn(), + noteInputRef: { current: null } as { current: null }, + openAddNote: vi.fn(), + openEditNote: vi.fn(), + cancelNote: vi.fn(), + saveNote: vi.fn(), + deleteNote: vi.fn(), + moveNote: vi.fn(), +})) + +// ── Module mocks ──────────────────────────────────────────────────────────── + +vi.mock('../../api/client', async (importOriginal) => { + const actual = await importOriginal() as any + return { + ...actual, + assignmentsApi: { + reorder: vi.fn().mockResolvedValue({}), + remove: vi.fn().mockResolvedValue({}), + updateTime: vi.fn().mockResolvedValue({}), + }, + reservationsApi: { + list: vi.fn().mockResolvedValue({ reservations: [] }), + updatePositions: vi.fn().mockResolvedValue({}), + }, + } +}) + +vi.mock('../PDF/TripPDF', () => ({ downloadTripPDF: vi.fn().mockResolvedValue(undefined) })) + +vi.mock('../Map/RouteCalculator', () => ({ + calculateRoute: vi.fn().mockResolvedValue({ distanceText: '5 km', durationText: '1h', coordinates: [] }), + generateGoogleMapsUrl: vi.fn().mockReturnValue('https://maps.google.com/...'), + optimizeRoute: vi.fn().mockImplementation((places) => places), +})) + +// PlaceAvatar needs IntersectionObserver +class MockIO { observe = vi.fn(); disconnect = vi.fn(); unobserve = vi.fn() } +beforeAll(() => { (globalThis as any).IntersectionObserver = MockIO }) + +vi.mock('../../services/photoService', () => ({ + getCached: vi.fn(() => null), + isLoading: vi.fn(() => false), + fetchPhoto: vi.fn(), + onThumbReady: vi.fn(() => () => {}), +})) + +vi.mock('../../hooks/useDayNotes', () => ({ + useDayNotes: () => mockDayNotesState, +})) + +vi.mock('../Weather/WeatherWidget', () => ({ + default: () => , +})) + +vi.mock('../shared/Toast', () => ({ + useToast: () => ({ error: vi.fn(), success: vi.fn() }), +})) + +// ── Permissions mock ──────────────────────────────────────────────────────── + +vi.mock('../../store/permissionsStore', async (importOriginal) => { + const actual = await importOriginal() as any + return { + ...actual, + useCanDo: () => () => true, + } +}) + +// ── Default props ─────────────────────────────────────────────────────────── + +const trip = buildTrip({ id: 1, currency: 'EUR' }) + +function makeDefaultProps(overrides = {}) { + return { + tripId: 1, + trip, + days: [], + places: [], + categories: [], + assignments: {}, + selectedDayId: null, + selectedPlaceId: null, + selectedAssignmentId: null, + onSelectDay: vi.fn(), + onPlaceClick: vi.fn(), + onDayDetail: vi.fn(), + accommodations: [], + onReorder: vi.fn(), + onUpdateDayTitle: vi.fn(), + onRouteCalculated: vi.fn(), + onAssignToDay: vi.fn(), + onRemoveAssignment: vi.fn(), + onEditPlace: vi.fn(), + onDeletePlace: vi.fn(), + reservations: [], + onAddReservation: vi.fn(), + onNavigateToFiles: vi.fn(), + ...overrides, + } +} + +// ── Setup ─────────────────────────────────────────────────────────────────── + +beforeEach(() => { + resetAllStores() + vi.clearAllMocks() + sessionStorage.clear() + // Reset mutable day-notes state + mockDayNotesState.noteUi = {} + mockDayNotesState.dayNotes = {} + seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true }) + seedStore(useTripStore, { trip: buildTrip({ id: 1 }) }) + seedStore(useSettingsStore, { settings: { time_format: '24h', temperature_unit: 'celsius' } } as any) +}) + +// ── Tests ─────────────────────────────────────────────────────────────────── + +describe('DayPlanSidebar', () => { + // ── Rendering ─────────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-001: renders without crashing', () => { + render() + expect(document.body).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-002: renders day titles', () => { + const day = buildDay({ title: 'Amsterdam Day', date: '2025-06-01' }) + render() + expect(screen.getByText('Amsterdam Day')).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-003: renders day number when title is null', () => { + const day = buildDay({ title: null, date: '2025-06-01' }) + render() + expect(screen.getByText(/Day 1/i)).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-004: renders formatted date alongside title', () => { + const day = buildDay({ date: '2025-06-15', title: 'Day 1' }) + render() + expect(screen.getByText(/Jun 15|15 Jun/)).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-005: renders multiple days', () => { + const days = [ + buildDay({ title: 'D1', date: '2025-06-01' }), + buildDay({ title: 'D2', date: '2025-06-02' }), + ] + render() + expect(screen.getByText('D1')).toBeInTheDocument() + expect(screen.getByText('D2')).toBeInTheDocument() + }) + + // ── Day expansion/collapse ────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-006: days are expanded by default', () => { + const place = buildPlace({ name: 'Eiffel Tower' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const assignments = { '10': [assignment] } + render() + expect(screen.getByText('Eiffel Tower')).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-007: clicking chevron collapses that day', async () => { + const user = userEvent.setup() + const place = buildPlace({ name: 'Eiffel Tower' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const assignments = { '10': [assignment] } + render() + // The chevron button immediately follows the "Add Note" button (which has a title attribute) + const addNoteBtn = screen.getByLabelText('Add Note') + const chevron = addNoteBtn.nextElementSibling as HTMLButtonElement + expect(chevron).toBeTruthy() + await user.click(chevron) + expect(screen.queryByText('Eiffel Tower')).not.toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-008: clicking chevron again re-expands', async () => { + const user = userEvent.setup() + const place = buildPlace({ name: 'Eiffel Tower' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const assignments = { '10': [assignment] } + render() + const getChevron = () => screen.getByLabelText('Add Note').nextElementSibling as HTMLButtonElement + await user.click(getChevron()) // collapse + expect(screen.queryByText('Eiffel Tower')).not.toBeInTheDocument() + await user.click(getChevron()) // re-expand + expect(screen.getByText('Eiffel Tower')).toBeInTheDocument() + }) + + // ── Day selection ─────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-009: clicking day header calls onSelectDay', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'My Day' }) + const onSelectDay = vi.fn() + render() + await user.click(screen.getByText('My Day')) + expect(onSelectDay).toHaveBeenCalledWith(10) + }) + + it('FE-PLANNER-DAYPLAN-010: selectedDayId renders without error', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'My Day' }) + render() + expect(screen.getByText('My Day')).toBeInTheDocument() + }) + + // ── Assigned places ───────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-011: assigned place name rendered in day card', () => { + const place = buildPlace({ name: 'Louvre Museum' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + expect(screen.getByText('Louvre Museum')).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-012: assigned place time is shown when set', () => { + const place = buildPlace({ name: 'Louvre Museum', place_time: '10:00' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + expect(screen.getByText(/10:00/)).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-013: clicking a place calls onPlaceClick', async () => { + const user = userEvent.setup() + const place = buildPlace({ id: 42, name: 'Louvre Museum' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const onPlaceClick = vi.fn() + render() + await user.click(screen.getByText('Louvre Museum')) + expect(onPlaceClick).toHaveBeenCalledWith(42, 99) + }) + + it('FE-PLANNER-DAYPLAN-014: selectedPlaceId renders the place without error', () => { + const place = buildPlace({ id: 42, name: 'Louvre Museum' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + expect(screen.getByText('Louvre Museum')).toBeInTheDocument() + }) + + // ── Day title editing ─────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-015: clicking edit button enters edit mode', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Original Title' }) + render() + await user.click(screen.getByLabelText('Edit')) + await waitFor(() => { + expect(screen.getByDisplayValue('Original Title')).toBeInTheDocument() + }) + }) + + it('FE-PLANNER-DAYPLAN-016: pressing Enter commits title', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Original Title' }) + const onUpdateDayTitle = vi.fn() + render() + // Enter edit mode + await user.click(screen.getByLabelText('Edit')) + const input = await screen.findByDisplayValue('Original Title') + await user.clear(input) + await user.type(input, 'New Title') + await user.keyboard('{Enter}') + expect(onUpdateDayTitle).toHaveBeenCalledWith(10, 'New Title') + }) + + it('FE-PLANNER-DAYPLAN-017: pressing Escape cancels edit', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Original Title' }) + render() + await user.click(screen.getByLabelText('Edit')) + const input = await screen.findByDisplayValue('Original Title') + await user.keyboard('{Escape}') + expect(screen.queryByDisplayValue('Original Title')).not.toBeInTheDocument() + expect(screen.getByText('Original Title')).toBeInTheDocument() + }) + + // ── Day info button ───────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-018: clicking day header calls onDayDetail', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'My Day' }) + const onDayDetail = vi.fn() + render() + await user.click(screen.getByText('My Day')) + expect(onDayDetail).toHaveBeenCalledWith(day) + }) + + // ── Context menu ──────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-019: right-click on assignment opens context menu', () => { + const place = buildPlace({ name: 'Louvre Museum' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + const placeEl = screen.getByText('Louvre Museum') + fireEvent.contextMenu(placeEl) + // Context menu should show Edit and Remove options + expect(screen.getByText('Edit')).toBeInTheDocument() + expect(screen.getByText(/Remove from day/i)).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-020: context menu Remove calls onRemoveAssignment', async () => { + const user = userEvent.setup() + const place = buildPlace({ name: 'Louvre Museum' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const onRemoveAssignment = vi.fn() + render() + fireEvent.contextMenu(screen.getByText('Louvre Museum')) + await user.click(screen.getByText(/Remove from day/i)) + expect(onRemoveAssignment).toHaveBeenCalledWith(10, 99) + }) + + // ── Undo bar ──────────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-022: undo bar shown when canUndo=true', () => { + const onUndo = vi.fn() + render() + // The undo button should be present (Undo2 icon) + const undoButtons = screen.getAllByRole('button') + const undoBtn = undoButtons.find(btn => !(btn as HTMLButtonElement).disabled && btn.querySelector('svg')) + expect(undoBtn).toBeDefined() + }) + + it('FE-PLANNER-DAYPLAN-023: clicking undo button calls onUndo', async () => { + const user = userEvent.setup() + const onUndo = vi.fn() + render() + const undoBtn = screen.getByLabelText('Undo') + await user.click(undoBtn) + expect(onUndo).toHaveBeenCalled() + }) + + it('FE-PLANNER-DAYPLAN-024: undo button not present when onUndo not provided', () => { + render() + expect(screen.queryByLabelText('Undo')).toBeNull() + }) + + // ── PDF export ────────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-025: PDF export button is present', () => { + render() + expect(screen.getByText('PDF')).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-026: clicking PDF button calls downloadTripPDF', async () => { + const user = userEvent.setup() + const { downloadTripPDF } = await import('../PDF/TripPDF') + render() + await user.click(screen.getByText('PDF')) + await waitFor(() => { + expect(downloadTripPDF).toHaveBeenCalled() + }) + }) + + // ── Route calculation ─────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-027: route button present when day has 2+ assigned places', () => { + const place1 = buildPlace({ id: 1, name: 'Place A', lat: 48.85, lng: 2.35 }) + const place2 = buildPlace({ id: 2, name: 'Place B', lat: 48.86, lng: 2.36 }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const a1 = buildAssignment({ id: 1, day_id: 10, order_index: 0, place: place1 }) + const a2 = buildAssignment({ id: 2, day_id: 10, order_index: 1, place: place2 }) + render() + // Route/navigation button should be visible — look for Navigation icon button + const buttons = screen.getAllByRole('button') + // The component renders navigation-related buttons when a day is selected with 2+ geo places + expect(buttons.length).toBeGreaterThan(0) + }) + + // ── Empty states ──────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-029: day with no assignments shows empty state', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Empty Day' }) + render() + expect(screen.getByText(/No places planned for this day/i)).toBeInTheDocument() + }) + + // ── Transport items ───────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-030: flight reservation renders in day with matching date', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Travel Day' }) + const reservation = buildReservation({ + id: 200, + type: 'flight', + title: 'Paris to London', + reservation_time: '2025-06-01T08:00:00', + day_id: 10, + }) + render() + expect(screen.getByText('Paris to London')).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-031: clicking transport item calls onEditTransport', async () => { + const user = userEvent.setup() + const onEditTransport = vi.fn() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Travel Day' }) + const reservation = buildReservation({ + id: 200, + type: 'flight', + title: 'Air France 123', + reservation_time: '2025-06-01T08:00:00', + day_id: 10, + }) + render() + await user.click(screen.getByText('Air France 123')) + await waitFor(() => { + expect(onEditTransport).toHaveBeenCalledWith(expect.objectContaining({ id: 200 })) + }) + }) + + // ── Accommodation badges ──────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-032: accommodation badge renders hotel name in day header', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Hotel Day' }) + const accommodation = { + id: 99, + start_day_id: 10, + end_day_id: 10, + place_name: 'Grand Hyatt', + place_id: 500, + } + render() + expect(screen.getByText('Grand Hyatt')).toBeInTheDocument() + }) + + // ── Note cards ────────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-033: note card renders note text', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + mockDayNotesState.dayNotes = { + '10': [buildDayNote({ id: 55, day_id: 10, text: 'Pack sunscreen', sort_order: 0 })], + } + render() + expect(screen.getByText('Pack sunscreen')).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-034: right-click on note opens context menu', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + mockDayNotesState.dayNotes = { + '10': [buildDayNote({ id: 55, day_id: 10, text: 'My note' })], + } + render() + fireEvent.contextMenu(screen.getByText('My note')) + expect(screen.getByText('Edit')).toBeInTheDocument() + expect(screen.getByText(/Delete/i)).toBeInTheDocument() + }) + + // ── Note modal ────────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-035: note modal renders when noteUi has an entry', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + mockDayNotesState.noteUi = { + '10': { mode: 'add', text: '', time: '', icon: 'StickyNote' }, + } + render() + // Cancel and Add/Save buttons should appear in the modal + expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-036: note modal Cancel calls cancelNote', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + mockDayNotesState.noteUi = { + '10': { mode: 'add', text: 'Hello', time: '', icon: 'StickyNote' }, + } + render() + await user.click(screen.getByRole('button', { name: /cancel/i })) + expect(mockDayNotesState.cancelNote).toHaveBeenCalledWith(10) + }) + + // ── Budget footer ─────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-037: budget footer shows total cost when places have prices', () => { + const place = buildPlace({ name: 'Eiffel Tower', price: 25 }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + // Budget footer shows "Total Cost" label when totalCost > 0 + expect(screen.getByText('Total Cost')).toBeInTheDocument() + }) + + // ── Route tools (Optimize / Google Maps) ──────────────────────────────── + + it('FE-PLANNER-DAYPLAN-038: optimize button calls onReorder with 3 geo-places', async () => { + const user = userEvent.setup() + const onReorder = vi.fn().mockResolvedValue(undefined) + const places = [ + buildPlace({ id: 1, name: 'A', lat: 48.85, lng: 2.35 }), + buildPlace({ id: 2, name: 'B', lat: 48.86, lng: 2.36 }), + buildPlace({ id: 3, name: 'C', lat: 48.87, lng: 2.37 }), + ] + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assigns = { + '10': [ + buildAssignment({ id: 1, day_id: 10, order_index: 0, place: places[0] }), + buildAssignment({ id: 2, day_id: 10, order_index: 1, place: places[1] }), + buildAssignment({ id: 3, day_id: 10, order_index: 2, place: places[2] }), + ], + } + render() + // Find the Optimize button (contains 'optimize' text) + const optimizeBtn = screen.getByRole('button', { name: /optimize/i }) + await user.click(optimizeBtn) + await waitFor(() => expect(onReorder).toHaveBeenCalledWith(10, expect.any(Array))) + }) + + it('FE-PLANNER-DAYPLAN-039: Google Maps button calls window.open', async () => { + const user = userEvent.setup() + const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null) + const place1 = buildPlace({ id: 1, name: 'A', lat: 48.85, lng: 2.35 }) + const place2 = buildPlace({ id: 2, name: 'B', lat: 48.86, lng: 2.36 }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assigns = { + '10': [ + buildAssignment({ id: 1, day_id: 10, order_index: 0, place: place1 }), + buildAssignment({ id: 2, day_id: 10, order_index: 1, place: place2 }), + ], + } + render() + // The ExternalLink button is the Google Maps icon-only button (sibling of Optimize button) + const routeSection = document.querySelector('[style*="flex-direction: column"]') + const externalLinkBtn = screen.getAllByRole('button').find(btn => { + const parent = btn.closest('[style*="flex"]') + return btn.querySelector('svg') && !btn.textContent?.trim() && parent?.textContent?.includes('optimize') + }) + if (externalLinkBtn) { + await user.click(externalLinkBtn) + expect(openSpy).toHaveBeenCalledWith('https://maps.google.com/...', '_blank') + } + openSpy.mockRestore() + }) + + // ── Context menu — Edit calls onEditPlace ──────────────────────────────── + + it('FE-PLANNER-DAYPLAN-040: context menu Edit calls onEditPlace', async () => { + const user = userEvent.setup() + const place = buildPlace({ id: 42, name: 'Louvre Museum' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const onEditPlace = vi.fn() + render() + fireEvent.contextMenu(screen.getByText('Louvre Museum')) + await user.click(screen.getByText('Edit')) + expect(onEditPlace).toHaveBeenCalledWith(place, assignment.id) + }) + + // ── Arrow reorder buttons ──────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-041: arrow down button reorders day assignments', async () => { + const user = userEvent.setup() + const onReorder = vi.fn().mockResolvedValue(undefined) + const place1 = buildPlace({ id: 1, name: 'First Place' }) + const place2 = buildPlace({ id: 2, name: 'Second Place' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: place1 }) + const a2 = buildAssignment({ id: 12, day_id: 10, order_index: 1, place: place2 }) + render() + // First .reorder-buttons div → second button (ChevronDown) is enabled for first row + const reorderDivs = document.querySelectorAll('.reorder-buttons') + expect(reorderDivs.length).toBeGreaterThan(0) + const firstRowDownBtn = reorderDivs[0].querySelectorAll('button')[1] + await user.click(firstRowDownBtn) + await waitFor(() => expect(onReorder).toHaveBeenCalledWith(10, expect.any(Array))) + }) + + // ── Title blur commits ─────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-042: blurring title input commits the edit', async () => { + const user = userEvent.setup() + const onUpdateDayTitle = vi.fn() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Old Title' }) + render() + await user.click(screen.getByLabelText('Edit')) + const input = await screen.findByDisplayValue('Old Title') + await user.clear(input) + await user.type(input, 'New Title') + fireEvent.blur(input) + await waitFor(() => expect(onUpdateDayTitle).toHaveBeenCalledWith(10, 'New Title')) + }) + + // ── ICS export button ──────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-043: ICS export button is present', () => { + render() + expect(screen.getByText('ICS')).toBeInTheDocument() + }) + + // ── getMergedItems: transport merged with assignments ────────────────── + + it('FE-PLANNER-DAYPLAN-044: merged list shows both assignment and flight on same day', () => { + const place = buildPlace({ name: 'Louvre', lat: 48.86, lng: 2.34, place_time: '14:00' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const reservation = buildReservation({ + id: 200, type: 'flight', title: 'CDG to LHR', + reservation_time: '2025-06-01T08:00:00', + day_id: 10, + }) + render() + expect(screen.getByText('Louvre')).toBeInTheDocument() + expect(screen.getByText('CDG to LHR')).toBeInTheDocument() + }) + + // ── Multi-day transport span phases ──────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-045: multi-day flight shows departure label on first day', () => { + const day1 = buildDay({ id: 10, date: '2025-06-01', title: 'Departure' }) + const day2 = buildDay({ id: 11, date: '2025-06-02', title: 'Arrival' }) + const flight = buildReservation({ + id: 201, type: 'flight', title: 'Transatlantic', + reservation_time: '2025-06-01T22:00:00', + reservation_end_time: '2025-06-02T06:00:00', + day_id: 10, + end_day_id: 11, + } as any) + render() + // Both days should show the flight (departure on day1, arrival on day2) + const titles = screen.getAllByText('Transatlantic') + expect(titles.length).toBeGreaterThanOrEqual(2) + }) + + // ── Car active rental badge ──────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-046: car rental in middle phase shows active badge in day header', () => { + const day1 = buildDay({ id: 10, date: '2025-06-01', title: 'Pickup' }) + const day2 = buildDay({ id: 11, date: '2025-06-02', title: 'Drive Day' }) + const day3 = buildDay({ id: 12, date: '2025-06-03', title: 'Return' }) + const carRental = buildReservation({ + id: 300, type: 'car', title: 'Renault Rental', + reservation_time: '2025-06-01T09:00:00', + reservation_end_time: '2025-06-03T17:00:00', + day_id: 10, + end_day_id: 12, + } as any) + render() + // Car may appear as transport item on pickup/return days and as active badge on middle day + const instances = screen.getAllByText('Renault Rental') + expect(instances.length).toBeGreaterThan(0) + }) + + // ── Lock toggle ──────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-047: clicking PlaceAvatar toggles lock (red border appears)', async () => { + const user = userEvent.setup() + const place = buildPlace({ id: 42, name: 'Arc de Triomphe', lat: 48.87, lng: 2.29 }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + // Click on the PlaceAvatar wrapper (the lock toggle div) — it's a div with cursor: pointer that wraps the avatar + const placeEl = screen.getByText('Arc de Triomphe') + // The lock div is the parent of PlaceAvatar, which is a sibling of the GripVertical div + const row = placeEl.closest('[style*="display: flex"][style*="gap: 8"]') + const lockDiv = row?.querySelector('[style*="cursor: pointer"][style*="position: relative"]') + if (lockDiv) { + await user.click(lockDiv as HTMLElement) + // After lock: the row should have red border + await waitFor(() => { + const rowEl = placeEl.closest('[style*="border-left"]') + expect(rowEl).toBeTruthy() + }) + } + }) + + // ── Drag start/end on assignment ─────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-048: drag start on assignment sets drag state', () => { + const place = buildPlace({ id: 1, name: 'Drag Place' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + const draggable = screen.getByText('Drag Place').closest('[draggable="true"]') + expect(draggable).toBeTruthy() + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + fireEvent.dragStart(draggable as Element, { dataTransfer: dt }) + expect(dt.setData).toHaveBeenCalledWith('assignmentId', '99') + }) + + it('FE-PLANNER-DAYPLAN-049: drag end resets drag state', () => { + const place = buildPlace({ id: 1, name: 'Drag Place' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + const draggable = screen.getByText('Drag Place').closest('[draggable="true"]') + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + fireEvent.dragStart(draggable as Element, { dataTransfer: dt }) + fireEvent.dragEnd(draggable as Element) + // After drag end, draggingId should be cleared (element opacity back to normal) + expect(draggable).toBeTruthy() + }) + + // ── Drop on day header (placeId) ─────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-050: dropping place from sidebar onto day header calls onAssignToDay', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const onAssignToDay = vi.fn() + render() + // Set drag data as if dragging from the places sidebar + ;(window as any).__dragData = { placeId: '42' } + const dayHeader = screen.getByText('Day 1').closest('[style*="cursor: pointer"]') + fireEvent.drop(dayHeader as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + expect(onAssignToDay).toHaveBeenCalledWith(42, 10) + ;(window as any).__dragData = null + }) + + // ── Transport detail modal with metadata ─────────────────────────────── + + it('FE-PLANNER-DAYPLAN-051: clicking flight transport calls onEditTransport with reservation', async () => { + const user = userEvent.setup() + const onEditTransport = vi.fn() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Travel' }) + const reservation = { + ...buildReservation({ + id: 202, type: 'flight', title: 'Paris to Berlin', + reservation_time: '2025-06-01T07:30:00', + day_id: 10, + }), + metadata: JSON.stringify({ airline: 'Lufthansa', flight_number: 'LH1234', departure_airport: 'CDG', arrival_airport: 'BER' }), + } + render() + await user.click(screen.getByText('Paris to Berlin')) + await waitFor(() => { + expect(onEditTransport).toHaveBeenCalledWith(expect.objectContaining({ id: 202, type: 'flight' })) + }) + }) + + // ── Category-tagged place rendering ─────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-052: place with category renders correctly', () => { + const category = buildCategory({ id: 5, name: 'Restaurants', icon: 'restaurant' }) + const place = buildPlace({ name: 'Café de Flore', category_id: 5 }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + expect(screen.getByText('Café de Flore')).toBeInTheDocument() + }) + + // ── Drop on assignment row ───────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-053: dropping place from sidebar onto assignment calls onAssignToDay', () => { + const place = buildPlace({ id: 1, name: 'Existing Place' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const onAssignToDay = vi.fn() + render() + ;(window as any).__dragData = { placeId: '55' } + const assignmentRow = screen.getByText('Existing Place').closest('[draggable="true"]') + fireEvent.drop(assignmentRow as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + // onAssignToDay is called with (placeId, dayId, position) where position is the index in the list + expect(onAssignToDay).toHaveBeenCalledWith(55, 10, expect.anything()) + ;(window as any).__dragData = null + }) + + // ── PDF hover tooltip ───────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-054: hovering PDF button shows tooltip', async () => { + const user = userEvent.setup() + render() + const pdfBtn = screen.getByText('PDF').closest('button')! + await user.hover(pdfBtn) + await waitFor(() => { + // Tooltip text appears (from t('dayplan.pdfTooltip')) + const tooltips = document.querySelectorAll('[style*="pointer-events: none"]') + expect(tooltips.length).toBeGreaterThan(0) + }) + }) + + // ── Drag over day header ────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-055: drag over day header sets drag target state', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + render() + const dayHeader = screen.getByText('Day 1').closest('[style*="cursor: pointer"]') + fireEvent.dragOver(dayHeader as Element, { dataTransfer: { dropEffect: 'move' } }) + // dragOverDayId should be set — the day header gets drag-target styling + expect(dayHeader).toBeTruthy() + }) + + // ── Cross-day drop on day header (assignment) ───────────────────────── + + it('FE-PLANNER-DAYPLAN-056: dropping assignment from another day onto header triggers move', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + render() + // Simulate dragging an assignment from day 99 to day 10 + ;(window as any).__dragData = null + const dt = { + getData: (key: string) => { + if (key === 'assignmentId') return '99' + if (key === 'fromDayId') return '20' + return '' + }, + } + const dayHeader = screen.getByText('Day 1').closest('[style*="cursor: pointer"]') + fireEvent.drop(dayHeader as Element, { dataTransfer: dt }) + // tripActions.moveAssignment would be called — just verify no error + expect(dayHeader).toBeTruthy() + }) + + // ── Document dragend cleanup ────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-057: document dragend event resets drag state', async () => { + const place = buildPlace({ id: 1, name: 'Test Place' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + // Start a drag, then fire the global dragend event + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + const draggable = screen.getByText('Test Place').closest('[draggable="true"]') + fireEvent.dragStart(draggable as Element, { dataTransfer: dt }) + // Dispatch global dragend on document + document.dispatchEvent(new Event('dragend')) + // Component should handle cleanup without errors + expect(screen.getByText('Test Place')).toBeInTheDocument() + }) + + // ── ICS export click ───────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-058: clicking ICS button calls fetch for .ics export', async () => { + const user = userEvent.setup() + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ + ok: true, + blob: () => Promise.resolve(new Blob(['BEGIN:VCALENDAR'], { type: 'text/calendar' })), + } as any) + // Mock URL.createObjectURL + const createObjURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock') + const revokeObjURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {}) + render() + await user.click(screen.getByText('ICS').closest('button')!) + await waitFor(() => expect(fetchSpy).toHaveBeenCalledWith('/api/trips/1/export.ics', expect.any(Object))) + fetchSpy.mockRestore() + createObjURL.mockRestore() + revokeObjURL.mockRestore() + }) + + // ── openAddNote button click ────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-059: clicking Add Note button calls openAddNote', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + render() + const addNoteBtn = screen.getByLabelText('Add Note') + await user.click(addNoteBtn) + expect(mockDayNotesState.openAddNote).toHaveBeenCalled() + }) + + // ── Note modal save button ──────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-060: note modal Save button calls saveNote', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + mockDayNotesState.noteUi = { + '10': { mode: 'add', text: 'Test note', time: '', icon: 'StickyNote' }, + } + render() + // The Save/Add button in the modal has exact text "Add" (from t('common.add')) + const addBtn = screen.getByRole('button', { name: 'Add' }) + await user.click(addBtn) + expect(mockDayNotesState.saveNote).toHaveBeenCalledWith(10) + }) + + // ── Note modal edit mode title ──────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-061: note modal shows Edit title in edit mode', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + mockDayNotesState.noteUi = { + '10': { mode: 'edit', text: 'My note', time: '', icon: 'StickyNote' }, + } + render() + // The modal title is t('dayplan.noteEdit') — "Edit Note" or similar + expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument() + }) + + // ── Place with website in context menu ──────────────────────────────── + + it('FE-PLANNER-DAYPLAN-062: place with website shows website option in context menu', () => { + const place = buildPlace({ id: 42, name: 'Museum', website: 'https://museum.example.com' } as any) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + fireEvent.contextMenu(screen.getByText('Museum')) + // Website option should appear in context menu + expect(screen.getByText(/Website/i)).toBeInTheDocument() + }) + + // ── Delete place context menu ───────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-063: context menu Delete calls onDeletePlace', async () => { + const user = userEvent.setup() + const place = buildPlace({ id: 42, name: 'Louvre' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const onDeletePlace = vi.fn() + render() + fireEvent.contextMenu(screen.getByText('Louvre')) + await user.click(screen.getByText(/Delete/i)) + expect(onDeletePlace).toHaveBeenCalledWith(42) + }) + + // ── Note card edit/delete buttons ───────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-064: note card edit button calls openEditNote', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const note = buildDayNote({ id: 55, day_id: 10, text: 'My note' }) + mockDayNotesState.dayNotes = { '10': [note] } + render() + // Find note edit button (Pencil in note-edit-buttons) + const noteEditBtns = document.querySelectorAll('.note-edit-buttons button') + if (noteEditBtns.length > 0) { + await user.click(noteEditBtns[0] as HTMLElement) + expect(mockDayNotesState.openEditNote).toHaveBeenCalled() + } + }) + + it('FE-PLANNER-DAYPLAN-065: deleting a note asks for confirmation before calling deleteNote', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const note = buildDayNote({ id: 55, day_id: 10, text: 'My note' }) + mockDayNotesState.dayNotes = { '10': [note] } + render() + // Find note delete button (Trash2 in note-edit-buttons) + const noteEditBtns = document.querySelectorAll('.note-edit-buttons button') + if (noteEditBtns.length > 1) { + await user.click(noteEditBtns[1] as HTMLElement) + // Clicking delete opens a confirmation dialog rather than deleting immediately. + expect(mockDayNotesState.deleteNote).not.toHaveBeenCalled() + expect(screen.getByText('Delete note?')).toBeInTheDocument() + // Confirming triggers the actual delete. + await user.click(screen.getByRole('button', { name: /^delete$/i })) + expect(mockDayNotesState.deleteNote).toHaveBeenCalled() + } + }) + + // ── Drop on assignment: same-day reorder ───────────────────────────── + + it('FE-PLANNER-DAYPLAN-066: dropping assignment from same day triggers handleMergedDrop', () => { + const place1 = buildPlace({ id: 1, name: 'Place A' }) + const place2 = buildPlace({ id: 2, name: 'Place B' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: place1 }) + const a2 = buildAssignment({ id: 12, day_id: 10, order_index: 1, place: place2 }) + const onReorder = vi.fn().mockResolvedValue(undefined) + render() + // Drag a1 onto a2 (same day reorder) + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + const draggableA1 = screen.getByText('Place A').closest('[draggable="true"]') + fireEvent.dragStart(draggableA1 as Element, { dataTransfer: dt }) + const draggableA2 = screen.getByText('Place B').closest('[draggable="true"]') + fireEvent.drop(draggableA2 as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + // handleMergedDrop called; onReorder should eventually be called + expect(onReorder).toBeDefined() + }) + + // ── Cross-day note drop on day header ───────────────────────────────── + + it('FE-PLANNER-DAYPLAN-067: dropping note from another day onto day header triggers move', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + render() + const dt = { + getData: (key: string) => { + if (key === 'noteId') return '55' + if (key === 'fromDayId') return '20' + return '' + }, + } + const dayHeader = screen.getByText('Day 1').closest('[style*="cursor: pointer"]') + fireEvent.drop(dayHeader as Element, { dataTransfer: dt }) + expect(dayHeader).toBeTruthy() + }) + + // ── Cross-day assignment drag from day1 to day2 header ──────────────── + + it('FE-PLANNER-DAYPLAN-068: dragging assignment from day1 and dropping on day2 header moves it', async () => { + const place1 = buildPlace({ id: 1, name: 'Place on Day 1' }) + const day1 = buildDay({ id: 10, date: '2025-06-01', title: 'Day One' }) + const day2 = buildDay({ id: 11, date: '2025-06-02', title: 'Day Two' }) + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: place1 }) + render() + // DragStart on a1 to set dragDataRef.current + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + const draggable = screen.getByText('Place on Day 1').closest('[draggable="true"]') + fireEvent.dragStart(draggable as Element, { dataTransfer: dt }) + // Drop on day2 header + const day2Header = screen.getByText('Day Two').closest('[style*="cursor: pointer"]') + fireEvent.drop(day2Header as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + // tripActions.moveAssignment should have been called (no assertion needed — just coverage) + expect(day2Header).toBeTruthy() + }) + + // ── Same-day assignment drop (handleMergedDrop) ─────────────────────── + + it('FE-PLANNER-DAYPLAN-069: dropping assignment onto another assignment on same day calls applyMergedOrder', async () => { + const place1 = buildPlace({ id: 1, name: 'Place A' }) + const place2 = buildPlace({ id: 2, name: 'Place B' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: place1 }) + const a2 = buildAssignment({ id: 12, day_id: 10, order_index: 1, place: place2 }) + const onReorder = vi.fn().mockResolvedValue(undefined) + render() + // DragStart on a1 to set dragDataRef + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + const draggableA1 = screen.getByText('Place A').closest('[draggable="true"]') + fireEvent.dragStart(draggableA1 as Element, { dataTransfer: dt }) + // Drop on a2 (same day → handleMergedDrop → applyMergedOrder → onReorder) + const draggableA2 = screen.getByText('Place B').closest('[draggable="true"]') + fireEvent.drop(draggableA2 as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + await waitFor(() => expect(onReorder).toHaveBeenCalled()) + }) + + // ── End-of-day drop zone ────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-070: dropping place from sidebar onto end-of-day zone calls onAssignToDay', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const onAssignToDay = vi.fn() + render() + ;(window as any).__dragData = { placeId: '42' } + // The end drop zone has min-height: 12px and padding 2px 8px + const endZone = document.querySelector('[style*="min-height: 12"]') + if (endZone) { + fireEvent.drop(endZone as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + expect(onAssignToDay).toHaveBeenCalledWith(42, 10) + } + ;(window as any).__dragData = null + }) + + // ── getMergedItems: place time before transport time ────────────────── + + it('FE-PLANNER-DAYPLAN-071: transport placed after time-anchored place in merged list', () => { + const place = buildPlace({ name: 'Morning Café', place_time: '08:00', lat: 48.86, lng: 2.34 }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const flight = buildReservation({ + id: 201, type: 'flight', title: 'Afternoon Flight', + reservation_time: '2025-06-01T14:00:00', + day_id: 10, + }) + render() + expect(screen.getByText('Morning Café')).toBeInTheDocument() + expect(screen.getByText('Afternoon Flight')).toBeInTheDocument() + }) + + // ── Cross-day assignment drop on assignment row ─────────────────────── + + it('FE-PLANNER-DAYPLAN-072: dropping cross-day assignment onto assignment row calls moveAssignment', async () => { + const place1 = buildPlace({ id: 1, name: 'Place On Day 1' }) + const place2 = buildPlace({ id: 2, name: 'Place On Day 2' }) + const day1 = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const day2 = buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }) + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: place1 }) + const a2 = buildAssignment({ id: 12, day_id: 11, order_index: 0, place: place2 }) + render() + // DragStart on a1 (day 10) to set dragDataRef + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + const draggableA1 = screen.getByText('Place On Day 1').closest('[draggable="true"]') + fireEvent.dragStart(draggableA1 as Element, { dataTransfer: dt }) + // Drop on a2 (day 11 — cross-day) → triggers moveAssignment path + const draggableA2 = screen.getByText('Place On Day 2').closest('[draggable="true"]') + fireEvent.drop(draggableA2 as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + // Just verify no crash + expect(screen.getByText('Place On Day 2')).toBeInTheDocument() + }) + + // ── Drag over assignment row ────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-073: drag over assignment row sets drop target', () => { + const place = buildPlace({ id: 1, name: 'Target Place' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + const draggable = screen.getByText('Target Place').closest('[draggable="true"]') + fireEvent.dragOver(draggable as Element, { dataTransfer: { dropEffect: 'move' } }) + expect(draggable).toBeTruthy() + }) + + // ── Note card drag and drop ─────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-074: drag start on note card sets drag state', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const note = buildDayNote({ id: 55, day_id: 10, text: 'Drag this note' }) + mockDayNotesState.dayNotes = { '10': [note] } + render() + const noteEl = screen.getByText('Drag this note').closest('[draggable="true"]') + if (noteEl) { + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + fireEvent.dragStart(noteEl as Element, { dataTransfer: dt }) + expect(dt.setData).toHaveBeenCalledWith('noteId', '55') + } + }) + + // ── Note card drop: cross-day note drop onto assignment ─────────────── + + it('FE-PLANNER-DAYPLAN-075: dropping cross-day note onto assignment triggers note move', () => { + const place = buildPlace({ id: 1, name: 'Louvre' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + // Simulate dropping a note from another day onto this assignment + const draggable = screen.getByText('Louvre').closest('[draggable="true"]') + // dragDataRef has note from another day + ;(window as any).__dragData = null + const savedDragRef: any = { noteId: '55', fromDayId: '20' } + // We can't set dragDataRef directly, but we can use the getDragData fallback + // The fallback only reads placeId from window.__dragData, not noteId + // This test just verifies drop on assignment with no matching data doesn't crash + fireEvent.drop(draggable as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + expect(screen.getByText('Louvre')).toBeInTheDocument() + }) + + // ── handleOptimize: no-geo places skipped ──────────────────────────── + + it('FE-PLANNER-DAYPLAN-076: optimize with some places without geo coords still calls onReorder', async () => { + const user = userEvent.setup() + const onReorder = vi.fn().mockResolvedValue(undefined) + // Mix of geo and non-geo places + const places = [ + buildPlace({ id: 1, name: 'Geo Place A', lat: 48.85, lng: 2.35 }), + buildPlace({ id: 2, name: 'No Geo', lat: null as any, lng: null as any }), + buildPlace({ id: 3, name: 'Geo Place C', lat: 48.87, lng: 2.37 }), + ] + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assigns = { + '10': [ + buildAssignment({ id: 1, day_id: 10, order_index: 0, place: places[0] }), + buildAssignment({ id: 2, day_id: 10, order_index: 1, place: places[1] }), + buildAssignment({ id: 3, day_id: 10, order_index: 2, place: places[2] }), + ], + } + render() + const optimizeBtn = screen.getByRole('button', { name: /optimize/i }) + await user.click(optimizeBtn) + await waitFor(() => expect(onReorder).toHaveBeenCalled()) + }) + + // ── Lock hover tooltip ──────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-077: hovering over PlaceAvatar shows lock tooltip', async () => { + const user = userEvent.setup() + const place = buildPlace({ id: 42, name: 'Hovered Place', lat: 48.87, lng: 2.29 }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + render() + const placeEl = screen.getByText('Hovered Place') + const row = placeEl.closest('[style*="display: flex"][style*="gap: 8"]') + const lockDiv = row?.querySelector('[style*="cursor: pointer"][style*="position: relative"]') + if (lockDiv) { + fireEvent.mouseEnter(lockDiv as Element) + // Lock overlay should appear + await waitFor(() => { + const overlays = document.querySelectorAll('[style*="position: absolute"][style*="inset: 0"]') + expect(overlays.length).toBeGreaterThan(0) + }) + } + }) + + // ── Reservation badge on assignment ────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-078: assignment with linked reservation shows confirmed badge', () => { + const place = buildPlace({ id: 1, name: 'Le Jules Verne' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const res = buildReservation({ id: 77, trip_id: 1, type: 'restaurant', status: 'confirmed', assignment_id: 99 } as any) + render() + expect(screen.getByText('Le Jules Verne')).toBeInTheDocument() + // Badge shows confirmed status + expect(screen.getByText(/confirmed/i)).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-079: assignment with pending reservation shows pending badge', () => { + const place = buildPlace({ id: 1, name: 'Opera House' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const res = buildReservation({ id: 77, trip_id: 1, type: 'restaurant', status: 'pending', assignment_id: 99 } as any) + render() + expect(screen.getAllByText(/pending/i).length).toBeGreaterThan(0) + }) + + // ── timed place drag → timeConfirm modal ───────────────────────────────── + + it('FE-PLANNER-DAYPLAN-080: dragging timed place out of chronological order shows time-confirm modal', async () => { + const placeA = buildPlace({ id: 1, name: 'Morning Place', place_time: '08:00' }) + const placeB = buildPlace({ id: 2, name: 'Afternoon Place', place_time: '14:00' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + // A (08:00) at index 0, B (14:00) at index 1 + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: placeA }) + const a2 = buildAssignment({ id: 22, day_id: 10, order_index: 1, place: placeB }) + render() + + // DragStart on a2 (14:00, at index 1), drop onto a1 (08:00, at index 0) + // This would create [a2(14:00), a1(08:00)] — NOT chronological + const draggable2 = screen.getByText('Afternoon Place').closest('[draggable="true"]') + const draggable1 = screen.getByText('Morning Place').closest('[draggable="true"]') + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + fireEvent.dragStart(draggable2 as Element, { dataTransfer: dt }) + // Now drop on draggable1 (the assignment row drop handler) + fireEvent.drop(draggable1 as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + + await waitFor(() => { + expect(screen.getByText('Remove time?')).toBeInTheDocument() + }) + }) + + it('FE-PLANNER-DAYPLAN-081: clicking Confirm in time modal calls confirmTimeRemoval (updates assignment time)', async () => { + const user = userEvent.setup() + const { assignmentsApi } = await import('../../api/client') + const placeA = buildPlace({ id: 1, name: 'Morning Place', place_time: '08:00' }) + const placeB = buildPlace({ id: 2, name: 'Afternoon Place', place_time: '14:00' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: placeA }) + const a2 = buildAssignment({ id: 22, day_id: 10, order_index: 1, place: placeB }) + const onReorder = vi.fn().mockResolvedValue(undefined) + render() + + // Trigger the timeConfirm modal: drag a2 onto a1 + const draggable2 = screen.getByText('Afternoon Place').closest('[draggable="true"]') + const draggable1 = screen.getByText('Morning Place').closest('[draggable="true"]') + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + fireEvent.dragStart(draggable2 as Element, { dataTransfer: dt }) + fireEvent.drop(draggable1 as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + + // Wait for modal + await waitFor(() => expect(screen.getByText('Remove time?')).toBeInTheDocument()) + + // Click Confirm + const confirmBtn = screen.getByRole('button', { name: /confirm/i }) + await user.click(confirmBtn) + + await waitFor(() => expect((assignmentsApi as any).updateTime).toHaveBeenCalled()) + }) + + // ── applyMergedOrder with notes in list (noteUpdates branch) ────────────── + + it('FE-PLANNER-DAYPLAN-082: reordering day with notes populates noteUpdates in applyMergedOrder', async () => { + const { assignmentsApi } = await import('../../api/client') + const onReorder = vi.fn().mockResolvedValue(undefined) + const placeA = buildPlace({ id: 1, name: 'Place Alpha' }) + const placeB = buildPlace({ id: 2, name: 'Place Beta' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: placeA }) + const a2 = buildAssignment({ id: 22, day_id: 10, order_index: 2, place: placeB }) + // Note between assignments (sort_order=1 puts it between a1(0) and a2(2)) + const note = buildDayNote({ id: 55, day_id: 10, sort_order: 1, text: 'Mid Note' }) + mockDayNotesState.dayNotes = { '10': [note] } + render() + + // DragStart on a2 (idx 2), drop onto a1 (idx 0) — same day swap + const draggable2 = screen.getByText('Place Beta').closest('[draggable="true"]') + const draggable1 = screen.getByText('Place Alpha').closest('[draggable="true"]') + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + fireEvent.dragStart(draggable2 as Element, { dataTransfer: dt }) + fireEvent.drop(draggable1 as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + + await waitFor(() => expect(onReorder).toHaveBeenCalled()) + }) + + // ── handleOptimize with locked assignments ──────────────────────────────── + + it('FE-PLANNER-DAYPLAN-083: optimize respects locked assignments', async () => { + const user = userEvent.setup() + const onReorder = vi.fn().mockResolvedValue(undefined) + const places = [ + buildPlace({ id: 1, name: 'Place Lock', lat: 48.85, lng: 2.35 }), + buildPlace({ id: 2, name: 'Place Free A', lat: 48.86, lng: 2.36 }), + buildPlace({ id: 3, name: 'Place Free B', lat: 48.87, lng: 2.37 }), + ] + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assigns = { + '10': [ + buildAssignment({ id: 1, day_id: 10, order_index: 0, place: places[0] }), + buildAssignment({ id: 2, day_id: 10, order_index: 1, place: places[1] }), + buildAssignment({ id: 3, day_id: 10, order_index: 2, place: places[2] }), + ], + } + render() + + // Lock the first assignment by clicking its lock area + const placeEl = screen.getByText('Place Lock') + const row = placeEl.closest('[style*="display: flex"][style*="gap: 8"]') + const lockDiv = row?.querySelector('[style*="cursor: pointer"][style*="position: relative"]') + if (lockDiv) fireEvent.click(lockDiv as Element) + + const optimizeBtn = screen.getByRole('button', { name: /optimize/i }) + await user.click(optimizeBtn) + await waitFor(() => expect(onReorder).toHaveBeenCalled()) + }) + + // ── Drop on transport row (handleMergedDrop via transport onDrop) ────────── + + it('FE-PLANNER-DAYPLAN-084: dropping same-day assignment onto transport row calls handleMergedDrop', () => { + const place = buildPlace({ id: 1, name: 'Museum' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 11, day_id: 10, order_index: 0, place }) + const flight = buildReservation({ + id: 77, trip_id: 1, type: 'flight', status: 'confirmed', + reservation_time: '2025-06-01T10:00:00Z', + }) + render() + + const assignmentEl = screen.getByText('Museum').closest('[draggable="true"]') + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + fireEvent.dragStart(assignmentEl as Element, { dataTransfer: dt }) + + // Find the transport row and drop on it + const transportRows = document.querySelectorAll('[style*="border: 1px solid"][style*="cursor: pointer"]') + if (transportRows.length > 0) { + // Drop assignment on transport row + fireEvent.drop(transportRows[0] as Element, { + dataTransfer: { getData: vi.fn().mockReturnValue('') }, + clientY: 100, + }) + } + expect(screen.getByText('Museum')).toBeInTheDocument() + }) + + // ── PDF click with populated dayNotes ───────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-085: clicking PDF with populated dayNotes includes notes in call', async () => { + const user = userEvent.setup() + const { downloadTripPDF } = await import('../PDF/TripPDF') + const place = buildPlace({ id: 1, name: 'Eiffel' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const note = buildDayNote({ id: 55, day_id: 10, sort_order: 0, text: 'PDF Note' }) + mockDayNotesState.dayNotes = { '10': [note] } + render() + const pdfBtn = screen.getByRole('button', { name: /pdf/i }) + await user.click(pdfBtn) + await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledWith( + expect.objectContaining({ dayNotes: expect.arrayContaining([expect.objectContaining({ text: 'PDF Note' })]) }) + )) + }) + + // ── Accommodation sort: checkout day ───────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-086: accommodation that ends on current day shows checkout styling', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + // Accommodation: started day 8, ends day 10 → today is checkout day + const acc = { id: 1, start_day_id: 8, end_day_id: 10, place_id: 5, place_name: 'Grand Hotel' } + render() + expect(screen.getByText('Grand Hotel')).toBeInTheDocument() + }) + + // ── Note move arrows ────────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-087: clicking note move-down button calls moveNote', async () => { + const user = userEvent.setup() + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const note1 = buildDayNote({ id: 10, day_id: 10, sort_order: 0, text: 'Note One' }) + const note2 = buildDayNote({ id: 20, day_id: 10, sort_order: 1, text: 'Note Two' }) + mockDayNotesState.dayNotes = { '10': [note1, note2] } + render() + + // The first note should have a down arrow (not at bottom) + const noteEl = screen.getByText('Note One') + const noteCard = noteEl.closest('[style*="display: flex"][style*="gap: 8"]') + const buttons = noteCard?.querySelectorAll('.reorder-buttons button') + if (buttons && buttons.length >= 2) { + await user.click(buttons[1] as HTMLButtonElement) // down arrow + expect(mockDayNotesState.moveNote).toHaveBeenCalled() + } + }) + + // ── Drop zone at end of list ────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-088: drag over end-of-list zone sets dropTarget', () => { + const place = buildPlace({ id: 1, name: 'Spot A' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 11, day_id: 10, order_index: 0, place }) + render() + const assignmentEl = screen.getByText('Spot A').closest('[draggable="true"]') + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + fireEvent.dragStart(assignmentEl as Element, { dataTransfer: dt }) + + // Find the end-of-list drop zone (has minHeight: 12 and padding 2px 8px) + const endZones = document.querySelectorAll('[style*="min-height: 12"]') + if (endZones.length > 0) { + fireEvent.dragOver(endZones[0] as Element, { preventDefault: vi.fn() }) + } + expect(screen.getByText('Spot A')).toBeInTheDocument() + }) + + // ── Inner expanded-area onDrop: place from sidebar ──────────────────────── + + it('FE-PLANNER-DAYPLAN-089: dropping place from sidebar onto expanded content area calls onAssignToDay', () => { + const place = buildPlace({ id: 1, name: 'Existing Place' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 11, day_id: 10, order_index: 0, place }) + const onAssignToDay = vi.fn() + render() + + // The expanded content wrapper is the div with background: var(--bg-hover) paddingTop:6 + const expandedArea = document.querySelector('[style*="padding-top: 6"]') || + document.querySelector('[style*="paddingTop: 6"]') + + if (expandedArea) { + ;(window as any).__dragData = { placeId: '99' } + fireEvent.drop(expandedArea as Element, { + dataTransfer: { getData: vi.fn().mockReturnValue('') }, + }) + expect(onAssignToDay).toHaveBeenCalledWith(99, 10) + ;(window as any).__dragData = null + } + }) + + // ── ICS hover tooltip ───────────────────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-090: hovering ICS button shows tooltip', async () => { + const user = userEvent.setup() + render() + const icsBtn = screen.getByRole('button', { name: /ICS/i }) + await user.hover(icsBtn) + await waitFor(() => { + const tooltips = document.querySelectorAll('[style*="pointer-events: none"]') + expect(tooltips.length).toBeGreaterThan(0) + }) + }) + + // ── DragLeave on day header clears drag-over ────────────────────────────── + + it('FE-PLANNER-DAYPLAN-091: dragLeave on day header clears dragOverDayId', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + render() + const dayHeader = screen.getByText('Day 1').closest('[style*="cursor: pointer"]') + if (dayHeader) { + fireEvent.dragOver(dayHeader as Element, { preventDefault: vi.fn() }) + fireEvent.dragLeave(dayHeader as Element, { relatedTarget: document.body }) + } + expect(screen.getByText('Day 1')).toBeInTheDocument() + }) + + // ── applyMergedOrder: transport in merged list (transportUpdates branch) ── + + it('FE-PLANNER-DAYPLAN-092: reordering day with flight in merged list updates transport positions', async () => { + const { reservationsApi } = await import('../../api/client') as any + const onReorder = vi.fn().mockResolvedValue(undefined) + const placeA = buildPlace({ id: 1, name: 'Museum' }) + const placeB = buildPlace({ id: 2, name: 'Gallery' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: placeA }) + const a2 = buildAssignment({ id: 22, day_id: 10, order_index: 1, place: placeB }) + const flight = buildReservation({ + id: 77, trip_id: 1, type: 'flight', status: 'confirmed', + reservation_time: '2025-06-01T12:00:00Z', + }) + render() + + // DragStart on a2 (Gallery), drop on a1 (Museum) — same day + const draggable2 = screen.getByText('Gallery').closest('[draggable="true"]') + const draggable1 = screen.getByText('Museum').closest('[draggable="true"]') + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + fireEvent.dragStart(draggable2 as Element, { dataTransfer: dt }) + fireEvent.drop(draggable1 as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + + await waitFor(() => expect(onReorder).toHaveBeenCalled()) + }) + + // ── confirmTimeRemoval via arrow (reorderIds path) ───────────────────────── + + it('FE-PLANNER-DAYPLAN-093: arrow-reorder timed place shows modal then confirm removes time', async () => { + const user = userEvent.setup() + const { assignmentsApi } = await import('../../api/client') as any + const onReorder = vi.fn().mockResolvedValue(undefined) + const placeA = buildPlace({ id: 1, name: 'Early Place', place_time: '08:00' }) + const placeB = buildPlace({ id: 2, name: 'Later Place', place_time: '14:00' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: placeA }) + const a2 = buildAssignment({ id: 22, day_id: 10, order_index: 1, place: placeB }) + render() + + // Click down arrow on 'Early Place' (a1) — would move it after a2, breaking order + const earlyEl = screen.getByText('Early Place') + const row = earlyEl.closest('[style*="display: flex"][style*="gap: 8"]') + const reorderBtns = row?.querySelectorAll('.reorder-buttons button') + if (reorderBtns && reorderBtns.length >= 2) { + await user.click(reorderBtns[1] as HTMLButtonElement) // down button + // Modal should appear + await waitFor(() => expect(screen.getByText('Remove time?')).toBeInTheDocument()) + // Click Confirm + const confirmBtn = screen.getByRole('button', { name: /confirm/i }) + await user.click(confirmBtn) + await waitFor(() => expect(assignmentsApi.updateTime).toHaveBeenCalled()) + } + }) + + // ── Same-day assignment drop onto end-of-list zone ──────────────────────── + + it('FE-PLANNER-DAYPLAN-094: same-day assignment dropped on end-zone calls handleMergedDrop', async () => { + const onReorder = vi.fn().mockResolvedValue(undefined) + const placeA = buildPlace({ id: 1, name: 'First Stop' }) + const placeB = buildPlace({ id: 2, name: 'Second Stop' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const a1 = buildAssignment({ id: 11, day_id: 10, order_index: 0, place: placeA }) + const a2 = buildAssignment({ id: 22, day_id: 10, order_index: 1, place: placeB }) + render() + + // DragStart on a1 (First Stop), drop on end-of-list zone + const draggable1 = screen.getByText('First Stop').closest('[draggable="true"]') + const dt = { setData: vi.fn(), effectAllowed: '', getData: vi.fn().mockReturnValue('') } + fireEvent.dragStart(draggable1 as Element, { dataTransfer: dt }) + + const endZones = document.querySelectorAll('[style*="min-height: 12"]') + if (endZones.length > 0) { + fireEvent.drop(endZones[0] as Element, { dataTransfer: { getData: vi.fn().mockReturnValue('') } }) + } + + await waitFor(() => expect(onReorder).toHaveBeenCalled()) + }) + + // ── Accommodation check-in (start_day_id === day.id) styling ───────────── + + it('FE-PLANNER-DAYPLAN-095: accommodation check-in day shows check-in badge', () => { + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + // Accommodation starts on day 10 (check-in day) + const acc = { id: 1, start_day_id: 10, end_day_id: 12, place_id: 5, place_name: 'Boutique Hotel' } + render() + expect(screen.getByText('Boutique Hotel')).toBeInTheDocument() + }) + + // ── handleOptimize: selectedDayId null early return ─────────────────────── + + it('FE-PLANNER-DAYPLAN-096: optimize button with no selectedDay does nothing', async () => { + const user = userEvent.setup() + const onReorder = vi.fn() + const places = [ + buildPlace({ id: 1, name: 'P1', lat: 1, lng: 1 }), + buildPlace({ id: 2, name: 'P2', lat: 2, lng: 2 }), + buildPlace({ id: 3, name: 'P3', lat: 3, lng: 3 }), + ] + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + render() + // Optimize button should not be visible when no day is selected + expect(screen.queryByRole('button', { name: /optimize/i })).not.toBeInTheDocument() + }) + + // ── Edit reservation pencil button ─────────────────────────────────────── + + it('FE-PLANNER-DAYPLAN-097: pencil button on non-transport reservation calls onEditReservation', async () => { + const user = userEvent.setup() + const place = buildPlace({ id: 1, name: 'Hotel du Lac' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const res = buildReservation({ id: 77, trip_id: 1, type: 'hotel', status: 'pending', assignment_id: 99 } as any) + const onEditReservation = vi.fn() + const onEditTransport = vi.fn() + render() + const pencil = screen.getByTitle(/edit/i) + await user.click(pencil) + expect(onEditReservation).toHaveBeenCalledWith(res) + expect(onEditTransport).not.toHaveBeenCalled() + }) + + it('FE-PLANNER-DAYPLAN-098: pencil button on transport reservation calls onEditTransport', async () => { + const user = userEvent.setup() + const place = buildPlace({ id: 1, name: 'Geneva Airport' }) + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assignment = buildAssignment({ id: 99, day_id: 10, order_index: 0, place }) + const res = buildReservation({ id: 88, trip_id: 1, type: 'flight', status: 'pending', assignment_id: 99 } as any) + const onEditReservation = vi.fn() + const onEditTransport = vi.fn() + render() + const pencil = screen.getByTitle(/edit/i) + await user.click(pencil) + expect(onEditTransport).toHaveBeenCalledWith(res) + expect(onEditReservation).not.toHaveBeenCalled() + }) + + // ── showRouteToolsWhenExpanded (mobile route tools) ─────────────────────── + + it('FE-PLANNER-DAYPLAN-099: showRouteToolsWhenExpanded shows route tools on expanded day without selection', () => { + const places = [ + buildPlace({ id: 1, name: 'A', lat: 48.85, lng: 2.35 }), + buildPlace({ id: 2, name: 'B', lat: 48.86, lng: 2.36 }), + ] + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assigns = { + '10': [ + buildAssignment({ id: 1, day_id: 10, order_index: 0, place: places[0] }), + buildAssignment({ id: 2, day_id: 10, order_index: 1, place: places[1] }), + ], + } + render() + // Days are expanded by default, so route tools must be visible even with no selected day + expect(screen.getByRole('button', { name: /optimize/i })).toBeInTheDocument() + }) + + it('FE-PLANNER-DAYPLAN-100: optimize via showRouteToolsWhenExpanded reorders the expanded day', async () => { + const user = userEvent.setup() + const onReorder = vi.fn().mockResolvedValue(undefined) + const places = [ + buildPlace({ id: 1, name: 'A', lat: 48.85, lng: 2.35 }), + buildPlace({ id: 2, name: 'B', lat: 48.86, lng: 2.36 }), + buildPlace({ id: 3, name: 'C', lat: 48.87, lng: 2.37 }), + ] + const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }) + const assigns = { + '10': [ + buildAssignment({ id: 1, day_id: 10, order_index: 0, place: places[0] }), + buildAssignment({ id: 2, day_id: 10, order_index: 1, place: places[1] }), + buildAssignment({ id: 3, day_id: 10, order_index: 2, place: places[2] }), + ], + } + render() + const optimizeBtn = screen.getByRole('button', { name: /optimize/i }) + await user.click(optimizeBtn) + await waitFor(() => expect(onReorder).toHaveBeenCalledWith(10, expect.any(Array))) + }) +}) diff --git a/client/src/components/Planner/DayPlanSidebar.tsx b/client/src/components/Planner/DayPlanSidebar.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0072eb7d5753bba6732a2f708adf291b899fa67e --- /dev/null +++ b/client/src/components/Planner/DayPlanSidebar.tsx @@ -0,0 +1,2269 @@ +/* eslint-disable @typescript-eslint/no-unnecessary-type-assertion */ +interface DragDataPayload { placeId?: string; assignmentId?: string; noteId?: string; reservationId?: string; fromDayId?: string; phase?: 'single' | 'start' | 'middle' | 'end' } +declare global { interface Window { __dragData: DragDataPayload | null } } + +import React, { useState, useEffect, useLayoutEffect, useRef, useMemo } from 'react' +import { ChevronDown, ChevronRight, ChevronUp, Navigation, RotateCcw, ExternalLink, Clock, Pencil, GripVertical, Ticket, Plus, FileText, Trash2, Car, Lock, Hotel, Footprints, Route as RouteIcon } from 'lucide-react' +import { assignmentsApi, reservationsApi } from '../../api/client' +import { calculateRoute, calculateRouteWithLegs, optimizeRoute } from '../Map/RouteCalculator' +import PlaceAvatar from '../shared/PlaceAvatar' +import ConfirmDialog from '../shared/ConfirmDialog' +import { useContextMenu, ContextMenu } from '../shared/ContextMenu' +import Markdown from 'react-markdown' +import remarkGfm from 'remark-gfm' +import WeatherWidget from '../Weather/WeatherWidget' +import { useToast } from '../shared/Toast' +import { getCategoryIcon } from '../shared/categoryIcons' +import { useTripStore } from '../../store/tripStore' +import { useCanDo } from '../../store/permissionsStore' +import { useSettingsStore } from '../../store/settingsStore' +import { useTranslation } from '../../i18n' +import { isDayInAccommodationRange, getAccommodationAnchors, getDayBookendHotels } from '../../utils/dayOrder' +import { + TRANSPORT_TYPES, parseTimeToMinutes, getSpanPhase, getDisplayTimeForDay, getTransportRouteEndpoints, + getTransportForDay as _getTransportForDay, getMergedItems as _getMergedItems, + type MergedItem, +} from '../../utils/dayMerge' +import { formatDate, formatTime, dayTotalCost, splitReservationDateTime } from '../../utils/formatters' +import { useDayNotes } from '../../hooks/useDayNotes' +import { RES_ICONS, getNoteIcon } from './DayPlanSidebar.constants' +import { RouteConnector, HotelRouteConnector } from './DayPlanSidebarRouteConnector' +import { MobileAddPlaceButton } from './DayPlanSidebarMobileAddPlaceButton' +import { DayPlanSidebarToolbar } from './DayPlanSidebarToolbar' +import { DayPlanSidebarNoteModal } from './DayPlanSidebarNoteModal' +import { DayPlanSidebarTimeConfirmModal } from './DayPlanSidebarTimeConfirmModal' +import { DayPlanSidebarTransportDetailModal } from './DayPlanSidebarTransportDetailModal' +import { DayPlanSidebarFooter } from './DayPlanSidebarFooter' +import type { Trip, Day, Place, Category, Assignment, Accommodation, Reservation, AssignmentsMap, RouteResult, RouteSegment, DayNote } from '../../types' + +interface DayPlanSidebarProps { + tripId: number + trip: Trip + days: Day[] + places: Place[] + categories: Category[] + assignments: AssignmentsMap + selectedDayId: number | null + selectedPlaceId: number | null + selectedAssignmentId: number | null + onSelectDay: (dayId: number | null, skipFit?: boolean) => void + onPlaceClick: (placeId: number | null, assignmentId?: number | null) => void + onDayDetail: (day: Day) => void + accommodations?: Accommodation[] + onReorder: (dayId: number, orderedIds: number[]) => void + onReorderDays?: (orderedIds: number[]) => void + onAddDay?: (position?: number) => void + onUpdateDayTitle: (dayId: number, title: string) => void + onRouteCalculated: (route: RouteResult | null) => void + onAssignToDay: (placeId: number, dayId: number, position?: number) => void + onRemoveAssignment: (dayId: number, assignmentId: number) => void + onEditPlace: (place: Place, assignmentId?: number) => void + onDeletePlace: (placeId: number) => void + reservations?: Reservation[] + visibleConnectionIds?: number[] + onToggleConnection?: (reservationId: number) => void + externalTransportDetail?: Reservation | null + onExternalTransportDetailHandled?: () => void + onAddReservation: (dayId: number) => void + onNavigateToFiles?: () => void + routeShown?: boolean + routeProfile?: 'driving' | 'walking' + onToggleRoute?: () => void + onSetRouteProfile?: (profile: 'driving' | 'walking') => void + onAddPlace?: () => void + onAddPlaceToDay?: (placeId: number, dayId: number) => void + onExpandedDaysChange?: (expandedDayIds: Set) => void + pushUndo?: (label: string, undoFn: () => Promise | void) => void + canUndo?: boolean + lastActionLabel?: string | null + onUndo?: () => void + onRouteRefresh?: () => void + onAddTransport?: (dayId: number) => void + onEditTransport?: (reservation: Reservation) => void + onEditReservation?: (reservation: Reservation) => void + onAddBookingToAssignment?: (dayId: number, assignmentId: number) => void + initialScrollTop?: number + onScrollTopChange?: (top: number) => void + /** Mobile: show the route tools footer (Route toggle / Optimize / travel profile) on expanded days, since selecting a day closes the sheet */ + showRouteToolsWhenExpanded?: boolean +} + +/** + * Day-plan state + behaviour: expand/collapse, inline title edit, route legs + + * optimisation, day notes, and the drag-and-drop reorder/move machinery across + * days (places, transports, notes). Returns everything the timeline view renders + * from, keeping DayPlanSidebar a thin shell over one large day list. + */ +function useDayPlanSidebar(props: DayPlanSidebarProps) { + const { + tripId, + trip, days, places, categories, assignments, + selectedDayId, selectedPlaceId, selectedAssignmentId, + onSelectDay, onPlaceClick, onDayDetail, accommodations = [], + onReorder, onReorderDays, onAddDay, onUpdateDayTitle, onRouteCalculated, + onAssignToDay, onRemoveAssignment, onEditPlace, onDeletePlace, + reservations = [], + visibleConnectionIds = [], + onToggleConnection, + externalTransportDetail, + onExternalTransportDetailHandled, + onAddReservation, + onAddPlace, + onAddPlaceToDay, + onNavigateToFiles, + routeShown = false, + routeProfile = 'driving', + onToggleRoute, + onSetRouteProfile, + onExpandedDaysChange, + pushUndo, + canUndo = false, + lastActionLabel = null, + onUndo, + onRouteRefresh, + onAddTransport, + onEditTransport, + onEditReservation, + onAddBookingToAssignment, + initialScrollTop, + onScrollTopChange, + showRouteToolsWhenExpanded = false, + } = props + const toast = useToast() + const { t, language, locale } = useTranslation() + const ctxMenu = useContextMenu() + const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h' + const tripActions = useRef(useTripStore.getState()).current + const can = useCanDo() + const canEditDays = can('day_edit', trip) + + const { noteUi, setNoteUi, noteInputRef, dayNotes, openAddNote: _openAddNote, openEditNote: _openEditNote, cancelNote, saveNote, deleteNote: _deleteNote, moveNote: _moveNote } = useDayNotes(tripId) + + const [expandedDays, setExpandedDays] = useState(() => { + try { + const saved = sessionStorage.getItem(`day-expanded-${tripId}`) + if (saved) return new Set(JSON.parse(saved) as number[]) + } catch {} + return new Set(days.map(d => d.id)) + }) + useEffect(() => { onExpandedDaysChange?.(expandedDays) }, [expandedDays]) + const [editingDayId, setEditingDayId] = useState(null) + const [editTitle, setEditTitle] = useState('') + const [isCalculating, setIsCalculating] = useState(false) + const [routeInfo, setRouteInfo] = useState(null) + const [routeLegs, setRouteLegs] = useState>({}) + const [hotelLegs, setHotelLegs] = useState<{ top?: { seg: RouteSegment; name: string }; bottom?: { seg: RouteSegment; name: string } }>({}) + const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation) + const legsAbortRef = useRef(null) + const [draggingId, setDraggingId] = useState(null) + const [lockedIds, setLockedIds] = useState(new Set()) + const [lockHoverId, setLockHoverId] = useState(null) + const [undoHover, setUndoHover] = useState(false) + const [pdfHover, setPdfHover] = useState(false) + const [icsHover, setIcsHover] = useState(false) + const [hoveredAssignmentId, setHoveredAssignmentId] = useState(null) + const [dropTargetKey, _setDropTargetKey] = useState(null) + const dropTargetRef = useRef(null) + const setDropTargetKey = (key) => { dropTargetRef.current = key; _setDropTargetKey(key) } + const [dragOverDayId, setDragOverDayId] = useState(null) + const [transportDetail, setTransportDetail] = useState(null) + const [transportPosVersion, setTransportPosVersion] = useState(0) + + useEffect(() => { + if (externalTransportDetail) { + setTransportDetail(externalTransportDetail) + onExternalTransportDetailHandled?.() + } + }, [externalTransportDetail, onExternalTransportDetailHandled]) + const [timeConfirm, setTimeConfirm] = useState<{ + dayId: number; fromId: number; time: string; + // For drag & drop reorder + fromType?: string; toType?: string; toId?: number; insertAfter?: boolean; toLegIndex?: number | null; + // For arrow reorder + reorderIds?: number[]; + } | null>(null) + const inputRef = useRef(null) + const dragDataRef = useRef(null) + const scrollContainerRef = useRef(null) + useLayoutEffect(() => { + if (scrollContainerRef.current && initialScrollTop) { + scrollContainerRef.current.scrollTop = initialScrollTop + } + }, []) + const initedTransportIds = useRef(new Set()) // Speichert Drag-Daten als Backup (dataTransfer geht bei Re-Render verloren) + // Remember which assignment we last auto-scrolled into view so we don't + // keep yanking the user back whenever they scroll away while the same + // place stays selected. + const lastAutoScrolledIdRef = useRef(null) + useEffect(() => { + // Reset the scroll-lock whenever selection moves, so the next selected + // row triggers a fresh scroll-into-view on its ref. + if (!selectedAssignmentId && !selectedPlaceId) { + lastAutoScrolledIdRef.current = null + } + }, [selectedAssignmentId, selectedPlaceId]) + + const currency = trip?.currency || 'EUR' + + // Drag-Daten aus dataTransfer, Ref oder window lesen (dataTransfer geht bei Re-Render verloren) + const getDragData = (e) => { + const dt = e?.dataTransfer + // Interner Drag hat Vorrang (Ref wird nur bei assignmentId/noteId/reservationId gesetzt) + if (dragDataRef.current) { + return { + placeId: '', + assignmentId: dragDataRef.current.assignmentId || '', + noteId: dragDataRef.current.noteId || '', + reservationId: dragDataRef.current.reservationId || '', + fromDayId: parseInt(dragDataRef.current.fromDayId) || 0, + phase: (dragDataRef.current.phase || 'single') as 'single' | 'start' | 'middle' | 'end', + } + } + // Externer Drag (aus PlacesSidebar) + const ext = window.__dragData || {} + const placeId = dt?.getData('placeId') || ext.placeId || '' + return { placeId, assignmentId: '', noteId: '', reservationId: '', fromDayId: 0, phase: 'single' as const } + } + + // Only auto-expand genuinely new days (not on initial load from storage) + const prevDayCount = React.useRef(days.length) + useEffect(() => { + if (days.length > prevDayCount.current) { + // New days added — expand only those + setExpandedDays(prev => { + const n = new Set(prev) + days.forEach(d => { if (!prev.has(d.id)) n.add(d.id) }) + try { sessionStorage.setItem(`day-expanded-${tripId}`, JSON.stringify([...n])) } catch {} + return n + }) + } + prevDayCount.current = days.length + }, [days.length, tripId]) + + useEffect(() => { + if (editingDayId && inputRef.current) inputRef.current.focus() + }, [editingDayId]) + + // Globaler Aufräum-Listener: wenn ein Drag endet ohne Drop, alles zurücksetzen + useEffect(() => { + const cleanup = () => { + setDraggingId(null) + setDropTargetKey(null) + setDragOverDayId(null) + dragDataRef.current = null + window.__dragData = null + } + document.addEventListener('dragend', cleanup) + return () => document.removeEventListener('dragend', cleanup) + }, []) + + // Initialize missing transport positions outside of render to avoid setState-during-render + // eslint-disable-next-line react-hooks/exhaustive-deps + useEffect(() => { days.forEach(day => initTransportPositions(day.id)) }, [days, reservations]) + + const toggleDay = (dayId, e) => { + e.stopPropagation() + setExpandedDays(prev => { + const n = new Set(prev) + n.has(dayId) ? n.delete(dayId) : n.add(dayId) + try { sessionStorage.setItem(`day-expanded-${tripId}`, JSON.stringify([...n])) } catch {} + return n + }) + } + + // Get phase label for multi-day badge + const getSpanLabel = (r: Reservation, phase: string): string | null => { + if (phase === 'single') return null + if (r.type === 'flight') return t(`reservations.span.${phase === 'start' ? 'departure' : phase === 'end' ? 'arrival' : 'inTransit'}`) + if (r.type === 'car') return t(`reservations.span.${phase === 'start' ? 'pickup' : phase === 'end' ? 'return' : 'active'}`) + return t(`reservations.span.${phase === 'start' ? 'start' : phase === 'end' ? 'end' : 'ongoing'}`) + } + + const getDayOrder = (day: (typeof days)[number]) => (day as any).day_number ?? days.indexOf(day) + + const computeMultiDayMove = (r: Reservation, targetDayId: number, phase: 'single' | 'start' | 'middle' | 'end') => { + const startId = r.day_id ?? targetDayId + const endId = r.end_day_id ?? startId + const order = (id: number) => { const d = days.find(x => x.id === id); return d ? getDayOrder(d) : 0 } + if (phase === 'single' || startId === endId) return { day_id: targetDayId, end_day_id: targetDayId } + if (phase === 'start') { + if (order(targetDayId) > order(endId)) return { day_id: targetDayId, end_day_id: targetDayId } + return { day_id: targetDayId, end_day_id: endId } + } + // phase === 'end' + if (order(targetDayId) < order(startId)) return { day_id: targetDayId, end_day_id: targetDayId } + return { day_id: startId, end_day_id: targetDayId } + } + + const getTransportForDay = (dayId: number) => + _getTransportForDay({ reservations, dayId, dayAssignmentIds: (assignments[String(dayId)] || []).map(a => a.id), days }) + + // Get car rentals that are in "active" (middle) phase for a day — shown in day header, not timeline + const getActiveRentalsForDay = (dayId: number) => { + return reservations.filter(r => { + if (r.type !== 'car') return false + const startDayId = r.day_id + const endDayId = r.end_day_id + if (!startDayId || !endDayId || endDayId === startDayId) return false + const startDay = days.find(d => d.id === startDayId) + const endDay = days.find(d => d.id === endDayId) + const thisDay = days.find(d => d.id === dayId) + if (!startDay || !endDay || !thisDay) return false + return getDayOrder(thisDay) > getDayOrder(startDay) && getDayOrder(thisDay) < getDayOrder(endDay) + }) + } + + const getDayAssignments = (dayId) => + (assignments[String(dayId)] || []).slice().sort((a, b) => a.order_index - b.order_index) + + // Compute initial day_plan_position for a transport based on time + const computeTransportPosition = (r, da) => { + const minutes = parseTimeToMinutes(r.reservation_time) ?? 0 + // Find the last place with time <= transport time + let afterIdx = -1 + for (const a of da) { + const pm = parseTimeToMinutes(a.place?.place_time) + if (pm !== null && pm <= minutes) afterIdx = a.order_index + } + // Position: midpoint between afterIdx and afterIdx+1 (leaves room for other items) + return afterIdx >= 0 ? afterIdx + 0.5 : da.length + 0.5 + } + + // Auto-initialize transport positions on first render if not set + const initTransportPositions = (dayId) => { + const da = getDayAssignments(dayId) + const transport = getTransportForDay(dayId) + const needsInit = transport.filter(r => r.day_plan_position == null && !initedTransportIds.current.has(r.id)) + if (needsInit.length === 0) return + + const sorted = [...needsInit].sort((a, b) => + (parseTimeToMinutes(a.reservation_time) ?? 0) - (parseTimeToMinutes(b.reservation_time) ?? 0) + ) + const positions = sorted.map((r, idx) => ({ + id: r.id, + day_plan_position: computeTransportPosition(r, da) + idx * 0.01, + })) + // Mark as initialized immediately to prevent re-entry + for (const p of positions) initedTransportIds.current.add(p.id) + // Update store so subscribers see the new positions + useTripStore.setState(state => ({ + reservations: state.reservations.map(r => { + const p = positions.find(x => x.id === r.id) + if (!p) return r + return { ...r, day_plan_position: p.day_plan_position } + }) + })) + // Persist to server (fire and forget) + reservationsApi.updatePositions(tripId, positions).catch(() => {}) + } + + const getMergedItems = (dayId: number): MergedItem[] => + _getMergedItems({ + dayAssignments: getDayAssignments(dayId), + dayNotes: (dayNotes[String(dayId)] || []).slice().sort((a, b) => a.sort_order - b.sort_order), + dayTransports: getTransportForDay(dayId), + dayId, + getDisplayTime: getDisplayTimeForDay, + }) + + // Pre-compute merged items for all days so the render loop doesn't recompute on unrelated state changes (e.g. hover) + // eslint-disable-next-line react-hooks/exhaustive-deps + const mergedItemsMap = useMemo(() => { + const map: Record> = {} + days.forEach(day => { map[day.id] = getMergedItems(day.id) }) + return map + // getMergedItems is redefined each render but captures assignments/dayNotes/reservations/days via closure + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [days, assignments, dayNotes, reservations, transportPosVersion]) + + // Per-segment driving times for the selected day's connectors. Groups located + // places into runs (split at transports), one cached OSRM call per run, keyed by + // the start place's assignment id. Shares RouteCalculator's cache with the map. + useEffect(() => { + if (legsAbortRef.current) legsAbortRef.current.abort() + if (!selectedDayId || !routeShown) { setRouteLegs({}); setHotelLegs({}); return } + const merged = mergedItemsMap[selectedDayId] || [] + const runs: { id: number; lat: number; lng: number }[][] = [] + let cur: { id: number; lat: number; lng: number }[] = [] + for (const it of merged) { + if (it.type === 'place' && it.data.place?.lat && it.data.place?.lng) { + cur.push({ id: it.data.id, lat: it.data.place.lat, lng: it.data.place.lng }) + } else if (it.type === 'transport') { + const r = it.data + const { from, to } = getTransportRouteEndpoints(r, selectedDayId) + if (from || to) { + // Located transport: route to its departure point, break the run (the + // flight/train itself isn't driven), and let its arrival start the next. + if (from) cur.push({ id: r.id, lat: from.lat, lng: from.lng }) + if (cur.length >= 2) runs.push(cur) + cur = [] + if (to) cur.push({ id: r.id, lat: to.lat, lng: to.lng }) + } else if (cur.length > 0) { + // No location: ignore for routing, but attribute the through-leg to the + // booking so its distance/duration shows under it (purely cosmetic). + cur[cur.length - 1] = { ...cur[cur.length - 1], id: r.id } + } + } + } + if (cur.length >= 2) runs.push(cur) + + // Hotel bookend legs: the drive from the day's accommodation to the first located + // waypoint of the day (morning) and from the last one back to it (evening). Only when + // the "optimize from accommodation" setting is on and the day has a hotel. + const day = days.find(d => d.id === selectedDayId) + const { morning: startHotel, evening: endHotel } = + day && optimizeFromAccommodation !== false ? getDayBookendHotels(day, days, accommodations) : {} + const hotelName = (a: Accommodation) => (a as any).place_name || (a as any).reservation_title || '' + // Waypoints include transport endpoints (a car return, a taxi/train arrival), so the hotel + // legs connect even when the day starts or ends with a booking rather than a place. + const wayPts: { lat: number; lng: number }[] = [] + for (const it of merged) { + if (it.type === 'place' && it.data.place?.lat && it.data.place?.lng) { + wayPts.push({ lat: it.data.place.lat, lng: it.data.place.lng }) + } else if (it.type === 'transport') { + const { from, to } = getTransportRouteEndpoints(it.data, selectedDayId) + if (from) wayPts.push({ lat: from.lat, lng: from.lng }) + if (to) wayPts.push({ lat: to.lat, lng: to.lng }) + } + } + const firstWay = wayPts[0] + const lastWay = wayPts[wayPts.length - 1] + const wantTop = !!(startHotel && firstWay) + const wantBottom = !!(endHotel && lastWay) + + if (runs.length === 0 && !wantTop && !wantBottom) { setRouteLegs({}); setHotelLegs({}); return } + + const controller = new AbortController() + legsAbortRef.current = controller + ;(async () => { + const map: Record = {} + for (const run of runs) { + try { + const r = await calculateRouteWithLegs(run.map(p => ({ lat: p.lat, lng: p.lng })), { signal: controller.signal, profile: routeProfile }) + r.legs.forEach((leg, i) => { map[run[i].id] = leg }) + } catch (err) { + if (err instanceof Error && err.name === 'AbortError') return + } + } + + // One extra cached OSRM call per bookend; shares RouteCalculator's cache. + const legBetween = async (a: { lat: number; lng: number }, b: { lat: number; lng: number }): Promise => { + try { + const r = await calculateRouteWithLegs([a, b], { signal: controller.signal, profile: routeProfile }) + return r.legs[0] + } catch { return undefined } + } + const hotel: { top?: { seg: RouteSegment; name: string }; bottom?: { seg: RouteSegment; name: string } } = {} + if (wantTop) { + const seg = await legBetween({ lat: startHotel!.place_lat as number, lng: startHotel!.place_lng as number }, { lat: firstWay.lat, lng: firstWay.lng }) + if (seg) hotel.top = { seg, name: hotelName(startHotel!) } + } + if (wantBottom) { + const seg = await legBetween({ lat: lastWay.lat, lng: lastWay.lng }, { lat: endHotel!.place_lat as number, lng: endHotel!.place_lng as number }) + if (seg) hotel.bottom = { seg, name: hotelName(endHotel!) } + } + + if (!controller.signal.aborted) { setRouteLegs(map); setHotelLegs(hotel) } + })() + }, [selectedDayId, routeShown, routeProfile, mergedItemsMap, accommodations, days, optimizeFromAccommodation]) + + const openAddNote = (dayId, e) => { + e?.stopPropagation() + _openAddNote(dayId, getMergedItems, (id) => { + if (!expandedDays.has(id)) setExpandedDays(prev => new Set([...prev, id])) + }) + } + + // Check if a proposed reorder of place IDs would break chronological order + // of ALL timed items (places with time + transport bookings) + const wouldBreakChronology = (dayId: number, newPlaceIds: number[]) => { + const da = getDayAssignments(dayId) + const transport = getTransportForDay(dayId) + + // Simulate the merged list with places in new order + transports at their positions + // Places get sequential integer positions + const simItems: { pos: number; minutes: number }[] = [] + newPlaceIds.forEach((id, idx) => { + const a = da.find(x => x.id === id) + const m = parseTimeToMinutes(a?.place?.place_time) + if (m !== null) simItems.push({ pos: idx, minutes: m }) + }) + + // Transports: compute where they'd go with the new place order + for (const r of transport) { + const rMin = parseTimeToMinutes(r.reservation_time) + if (rMin === null) continue + // Find the last place (in new order) with time <= transport time + let afterIdx = -1 + newPlaceIds.forEach((id, idx) => { + const a = da.find(x => x.id === id) + const pm = parseTimeToMinutes(a?.place?.place_time) + if (pm !== null && pm <= rMin) afterIdx = idx + }) + const pos = afterIdx >= 0 ? afterIdx + 0.5 : newPlaceIds.length + 0.5 + simItems.push({ pos, minutes: rMin }) + } + + // Sort by position and check chronological order + simItems.sort((a, b) => a.pos - b.pos) + return !simItems.every((item, i) => i === 0 || item.minutes >= simItems[i - 1].minutes) + } + + const openEditNote = (dayId: number, note: DayNote, e?: React.MouseEvent) => { + e?.stopPropagation() + _openEditNote(dayId, note) + } + + // Deleting a note asks for confirmation first — the edit/delete icons sit close together and are + // easy to mis-tap on touch devices, where an accidental delete was previously unrecoverable. + const [pendingDeleteNote, setPendingDeleteNote] = useState<{ dayId: number; noteId: number } | null>(null) + + const deleteNote = async (dayId: number, noteId: number, e?: React.MouseEvent) => { + e?.stopPropagation() + await _deleteNote(dayId, noteId) + } + + // Unified reorder: assigns positions to ALL item types based on new visual order + const applyMergedOrder = async (dayId: number, newOrder: { type: string; data: any }[]) => { + // Capture previous place order for undo + const prevAssignmentIds = getDayAssignments(dayId).map(a => a.id) + + // Places get sequential integer positions (0, 1, 2, ...) + // Non-place items between place N-1 and place N get fractional positions + const assignmentIds: number[] = [] + const noteUpdates: { id: number; sort_order: number }[] = [] + const transportUpdates: { id: number; day_plan_position: number }[] = [] + // Multi-leg flight legs share a reservation id, so their positions can't live in + // the single per-booking slot — collect them per leg, keyed reservationId → legIndex → pos. + const legPosUpdates: Record> = {} + + let placeCount = 0 + let i = 0 + while (i < newOrder.length) { + if (newOrder[i].type === 'place') { + assignmentIds.push(newOrder[i].data.id) + placeCount++ + i++ + } else { + // Collect consecutive non-place items + const group: { type: string; data: any }[] = [] + while (i < newOrder.length && newOrder[i].type !== 'place') { + group.push(newOrder[i]) + i++ + } + // Fractional positions between (placeCount-1) and placeCount + const base = placeCount > 0 ? placeCount - 1 : -1 + group.forEach((g, idx) => { + const pos = base + (idx + 1) / (group.length + 1) + if (g.type === 'note') noteUpdates.push({ id: g.data.id, sort_order: pos }) + else if (g.type === 'transport') { + if (g.data.__leg) ((legPosUpdates[g.data.id] ??= {})[g.data.__leg.index] = pos) + else transportUpdates.push({ id: g.data.id, day_plan_position: pos }) + } + }) + } + } + + try { + // Update transport positions in store FIRST so the useEffect triggered by + // onReorder's optimistic assignment update reads the correct positions. + if (transportUpdates.length) { + useTripStore.setState(state => ({ + reservations: state.reservations.map(r => { + const tu = transportUpdates.find(u => u.id === r.id) + if (!tu) return r + const day_positions = { ...(r.day_positions || {}), [dayId]: tu.day_plan_position } + return { ...r, day_plan_position: tu.day_plan_position, day_positions } + }) + })) + setTransportPosVersion(v => v + 1) + } + // Per-leg positions of multi-leg flights live in metadata.legs[i].day_positions + // (the single per-booking slot can't hold one position per leg). + const legResIds = Object.keys(legPosUpdates) + if (legResIds.length) { + for (const ridStr of legResIds) { + const rid = Number(ridStr) + const r = useTripStore.getState().reservations.find(x => x.id === rid) + if (!r) continue + let parsed: any = {} + try { parsed = typeof r.metadata === 'string' ? JSON.parse(r.metadata || '{}') : (r.metadata || {}) } catch { parsed = {} } + if (!Array.isArray(parsed.legs)) continue + const legs = parsed.legs.map((leg: any, i: number) => { + const pos = legPosUpdates[rid][i] + return pos == null ? leg : { ...leg, day_positions: { ...(leg.day_positions || {}), [dayId]: pos } } + }) + // Send metadata as an OBJECT (like the form does) — passing a JSON string + // here double-encodes it on the server, which wipes metadata.legs on read + // and collapses the flight back to a single span. + const newMeta = { ...parsed, legs } + useTripStore.setState(state => ({ reservations: state.reservations.map(x => (x.id === rid ? { ...x, metadata: newMeta } : x)) })) + await tripActions.updateReservation(tripId, rid, { metadata: newMeta }) + } + setTransportPosVersion(v => v + 1) + } + if (assignmentIds.length) await onReorder(dayId, assignmentIds) + if (transportUpdates.length) { + onRouteRefresh?.() + await reservationsApi.updatePositions(tripId, transportUpdates, dayId) + } + for (const n of noteUpdates) { + await tripActions.updateDayNote(tripId, dayId, n.id, { sort_order: n.sort_order }) + } + if (prevAssignmentIds.length) { + const capturedDayId = dayId + const capturedPrevIds = prevAssignmentIds + pushUndo?.(t('undo.reorder'), async () => { + await tripActions.reorderAssignments(tripId, capturedDayId, capturedPrevIds) + }) + } + } catch (err: unknown) { toast.error(err instanceof Error ? err.message : t('common.unknownError')) } + } + + const handleMergedDrop = async (dayId, fromType, fromId, toType, toId, insertAfter = false, toLegIndex = null) => { + const m = getMergedItems(dayId) + // Multi-leg flights expose one item per leg sharing the same reservation id; + // disambiguate the drop target by leg index so you can drop BETWEEN legs. + const matchTo = (i: any) => i.type === toType && i.data.id === toId && (toLegIndex == null || i.data?.__leg?.index === toLegIndex) + + // Check if a timed place is being moved → would it break chronological order? + if (fromType === 'place') { + const fromItem = m.find(i => i.type === 'place' && i.data.id === fromId) + const fromMinutes = parseTimeToMinutes(fromItem?.data?.place?.place_time) + if (fromItem && fromMinutes !== null) { + const fromIdx = m.findIndex(i => i.type === fromType && i.data.id === fromId) + const toIdx = m.findIndex(matchTo) + if (fromIdx !== -1 && toIdx !== -1) { + const simulated = [...m] + const [moved] = simulated.splice(fromIdx, 1) + let insertIdx = simulated.findIndex(matchTo) + if (insertIdx === -1) insertIdx = simulated.length + if (insertAfter) insertIdx += 1 + simulated.splice(insertIdx, 0, moved) + + const timedInOrder = simulated + .map(i => { + if (i.type === 'transport') return parseTimeToMinutes(i.data?.reservation_time) + if (i.type === 'place') return parseTimeToMinutes(i.data?.place?.place_time) + return null + }) + .filter(t => t !== null) + const isChronological = timedInOrder.every((t, i) => i === 0 || t >= timedInOrder[i - 1]) + + if (!isChronological) { + const placeTime = fromItem.data.place.place_time + const timeStr = placeTime.includes(':') ? placeTime.substring(0, 5) : placeTime + setTimeConfirm({ dayId, fromType, fromId, toType, toId, insertAfter, toLegIndex, time: timeStr }) + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null + return + } + } + } + } + + // Build new order: remove the dragged item, insert at target position + const fromIdx = m.findIndex(i => i.type === fromType && i.data.id === fromId) + const toIdx = m.findIndex(matchTo) + if (fromIdx === -1 || toIdx === -1 || fromIdx === toIdx) { + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null + return + } + + const newOrder = [...m] + const [moved] = newOrder.splice(fromIdx, 1) + let adjustedTo = newOrder.findIndex(matchTo) + if (adjustedTo === -1) adjustedTo = newOrder.length + if (insertAfter) adjustedTo += 1 + newOrder.splice(adjustedTo, 0, moved) + + await applyMergedOrder(dayId, newOrder) + setDraggingId(null) + setDropTargetKey(null) + dragDataRef.current = null + } + + const confirmTimeRemoval = async () => { + if (!timeConfirm) return + const saved = { ...timeConfirm } + const { dayId, fromId, reorderIds, fromType, toType, toId, insertAfter, toLegIndex } = saved + setTimeConfirm(null) + + // Remove time from assignment + try { + await assignmentsApi.updateTime(tripId, fromId, { place_time: null, end_time: null }) + const key = String(dayId) + const currentAssignments = { ...assignments } + if (currentAssignments[key]) { + currentAssignments[key] = currentAssignments[key].map(a => + a.id === fromId ? { ...a, place: { ...a.place, place_time: null, end_time: null } } : a + ) + tripActions.setAssignments(currentAssignments) + } + } catch (err) { + toast.error(err instanceof Error ? err.message : t('common.unknownError')) + return + } + + // Build new merged order from either arrow reorderIds or drag & drop params + const m = getMergedItems(dayId) + + if (reorderIds) { + // Arrow reorder: rebuild merged list with places in the new order, + // keeping transports and notes at their relative positions + const newMerged: typeof m = [] + let rIdx = 0 + for (const item of m) { + if (item.type === 'place') { + // Replace with the place from reorderIds at this position + const nextId = reorderIds[rIdx++] + const replacement = m.find(i => i.type === 'place' && i.data.id === nextId) + if (replacement) newMerged.push(replacement) + } else { + newMerged.push(item) + } + } + await applyMergedOrder(dayId, newMerged) + return + } + + // Drag & drop reorder + if (fromType && toType) { + const matchTo = (i: any) => i.type === toType && i.data.id === toId && (toLegIndex == null || i.data?.__leg?.index === toLegIndex) + const fromIdx = m.findIndex(i => i.type === fromType && i.data.id === fromId) + const toIdx = m.findIndex(matchTo) + if (fromIdx === -1 || toIdx === -1 || fromIdx === toIdx) return + + const newOrder = [...m] + const [moved] = newOrder.splice(fromIdx, 1) + let adjustedTo = newOrder.findIndex(matchTo) + if (adjustedTo === -1) adjustedTo = newOrder.length + if (insertAfter) adjustedTo += 1 + newOrder.splice(adjustedTo, 0, moved) + + await applyMergedOrder(dayId, newOrder) + } + } + + const moveNote = async (dayId, noteId, direction) => { + await _moveNote(dayId, noteId, direction, getMergedItems) + } + + const startEditTitle = (day, e) => { + e.stopPropagation() + setEditTitle(day.title || '') + setEditingDayId(day.id) + } + + const saveTitle = async (dayId) => { + setEditingDayId(null) + await onUpdateDayTitle?.(dayId, editTitle.trim()) + } + + const handleCalculateRoute = async () => { + if (!selectedDayId) return + const da = getDayAssignments(selectedDayId) + const waypoints = da.map(a => a.place).filter(p => p?.lat && p?.lng).map(p => ({ lat: p.lat, lng: p.lng })) + if (waypoints.length < 2) { toast.error(t('dayplan.toast.needTwoPlaces')); return } + setIsCalculating(true) + try { + const result = await calculateRoute(waypoints, 'walking') + // Luftlinien zwischen Wegpunkten anzeigen + const lineCoords = waypoints.map(p => [p.lat, p.lng] as [number, number]) + setRouteInfo({ distance: result.distanceText, duration: result.durationText }) + onRouteCalculated?.({ ...result, coordinates: lineCoords }) + } catch { toast.error(t('dayplan.toast.routeError')) } + finally { setIsCalculating(false) } + } + + const toggleLock = (assignmentId) => { + const prevLocked = new Set(lockedIds) + setLockedIds(prev => { + const next = new Set(prev) + if (next.has(assignmentId)) next.delete(assignmentId) + else next.add(assignmentId) + return next + }) + pushUndo?.(t('undo.lock'), () => { setLockedIds(prevLocked) }) + } + + const handleOptimize = async (dayId: number | null = selectedDayId) => { + if (!dayId) return + const da = getDayAssignments(dayId) + if (da.length < 3) return + + const prevIds = da.map(a => a.id) + + // Separate fixed (stay at their index) and movable assignments. A place is + // fixed if it's locked OR has a set time — timed places are anchored by their + // time, so the optimizer must not reshuffle them. + const locked = new Map() // index -> assignment + const unlocked = [] + da.forEach((a, i) => { + if (lockedIds.has(a.id) || a.place?.place_time) locked.set(i, a) + else unlocked.push(a) + }) + + // Optimize only unlocked assignments (work on assignments, not places) + const unlockedWithCoords = unlocked.filter(a => a.place?.lat && a.place?.lng) + const unlockedNoCoords = unlocked.filter(a => !a.place?.lat || !a.place?.lng) + // Anchor the route on the day's accommodation (when enabled): a loop out from and back to the + // hotel, or — on a transfer day — a run from the hotel you leave to the one you arrive at. + const day = days.find(d => d.id === dayId) + const anchors = day && useSettingsStore.getState().settings.optimize_from_accommodation !== false + ? getAccommodationAnchors(day, days, accommodations) + : {} + const optimizedAssignments = unlockedWithCoords.length >= 2 + ? optimizeRoute(unlockedWithCoords.map(a => ({ ...a.place, _assignmentId: a.id })), anchors).map(p => unlockedWithCoords.find(a => a.id === p._assignmentId)).filter(Boolean) + : unlockedWithCoords + const optimizedQueue = [...optimizedAssignments, ...unlockedNoCoords] + + // Merge: locked stay at their index, fill gaps with optimized + const result = new Array(da.length) + locked.forEach((a, i) => { result[i] = a }) + let qi = 0 + for (let i = 0; i < result.length; i++) { + if (!result[i]) result[i] = optimizedQueue[qi++] + } + + await onReorder(dayId, result.map(a => a.id)) + const usedHotel = !!(anchors.start || anchors.end) + toast.success(usedHotel ? t('dayplan.toast.routeOptimizedFromHotel') : t('dayplan.toast.routeOptimized')) + const capturedDayId = dayId + pushUndo?.(t('undo.optimize'), async () => { + await tripActions.reorderAssignments(tripId, capturedDayId, prevIds) + }) + } + + + const handleDropOnDay = (e, dayId) => { + e.preventDefault() + e.stopPropagation() + setDragOverDayId(null) + const { placeId, assignmentId, noteId, reservationId: fromReservationId, fromDayId, phase } = getDragData(e) + if (fromReservationId && fromDayId !== dayId) { + const r = reservations.find(x => x.id === Number(fromReservationId)) + if (r) { const update = computeMultiDayMove(r, dayId, phase); tripActions.updateReservation(tripId, r.id, update).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) } + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; window.__dragData = null; return + } + if (placeId) { + onAssignToDay?.(parseInt(placeId), dayId) + } else if (assignmentId && fromDayId !== dayId) { + const srcAssignment = (useTripStore.getState().assignments[String(fromDayId)] || []).find(a => a.id === Number(assignmentId)) + const capturedFromDayId = fromDayId + const capturedOrderIndex = srcAssignment?.order_index ?? 0 + tripActions.moveAssignment(tripId, Number(assignmentId), fromDayId, dayId) + .then(() => { + pushUndo?.(t('undo.moveDay'), async () => { + await tripActions.moveAssignment(tripId, Number(assignmentId), dayId, capturedFromDayId, capturedOrderIndex) + }) + }) + .catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + } else if (noteId && fromDayId !== dayId) { + tripActions.moveDayNote(tripId, fromDayId, dayId, Number(noteId)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + } + setDraggingId(null) + setDropTargetKey(null) + dragDataRef.current = null + window.__dragData = null + } + + const handleDropOnRow = (e, dayId, toIdx) => { + e.preventDefault() + e.stopPropagation() + setDragOverDayId(null) + const placeId = e.dataTransfer.getData('placeId') + const fromAssignmentId = e.dataTransfer.getData('assignmentId') + + if (placeId) { + onAssignToDay?.(parseInt(placeId), dayId) + } else if (fromAssignmentId) { + const da = getDayAssignments(dayId) + const fromIdx = da.findIndex(a => String(a.id) === fromAssignmentId) + if (fromIdx === -1 || fromIdx === toIdx) { setDraggingId(null); dragDataRef.current = null; return } + const ids = da.map(a => a.id) + const [removed] = ids.splice(fromIdx, 1) + ids.splice(toIdx, 0, removed) + onReorder(dayId, ids) + } + setDraggingId(null) + } + + const totalCost = useMemo(() => days.reduce((s, d) => { + const da = assignments[String(d.id)] || [] + return s + da.reduce((s2, a) => s2 + (Number(a.place?.price) || 0), 0) + }, 0), [days, assignments]) + + // Bester verfügbarer Standort für Wetter: zugewiesene Orte zuerst, dann beliebiger Reiseort + const anyGeoAssignment = Object.values(assignments).flatMap(da => da).find(a => a.place?.lat && a.place?.lng) + const anyGeoPlace = anyGeoAssignment || (places || []).find(p => p.lat && p.lng) + + return { + tripId, + trip, + days, + places, + categories, + assignments, + selectedDayId, + selectedPlaceId, + selectedAssignmentId, + onSelectDay, + onPlaceClick, + onDayDetail, + accommodations, + onReorder, + onReorderDays, + onAddDay, + onUpdateDayTitle, + onRouteCalculated, + onAssignToDay, + onRemoveAssignment, + onEditPlace, + onDeletePlace, + reservations, + visibleConnectionIds, + onToggleConnection, + externalTransportDetail, + onExternalTransportDetailHandled, + onAddReservation, + onAddPlace, + onAddPlaceToDay, + onNavigateToFiles, + routeShown, + routeProfile, + onToggleRoute, + onSetRouteProfile, + onExpandedDaysChange, + pushUndo, + canUndo, + lastActionLabel, + onUndo, + onRouteRefresh, + onAddTransport, + onEditTransport, + onEditReservation, + onAddBookingToAssignment, + initialScrollTop, + onScrollTopChange, + showRouteToolsWhenExpanded, + toast, + t, + language, + locale, + ctxMenu, + timeFormat, + tripActions, + can, + canEditDays, + noteUi, + setNoteUi, + noteInputRef, + dayNotes, + openAddNote, + openEditNote, + cancelNote, + saveNote, + deleteNote, + pendingDeleteNote, + setPendingDeleteNote, + moveNote, + expandedDays, + setExpandedDays, + editingDayId, + setEditingDayId, + editTitle, + setEditTitle, + isCalculating, + setIsCalculating, + routeInfo, + setRouteInfo, + routeLegs, + setRouteLegs, + hotelLegs, + setHotelLegs, + legsAbortRef, + draggingId, + setDraggingId, + lockedIds, + setLockedIds, + lockHoverId, + setLockHoverId, + undoHover, + setUndoHover, + pdfHover, + setPdfHover, + icsHover, + setIcsHover, + hoveredAssignmentId, + setHoveredAssignmentId, + dropTargetKey, + _setDropTargetKey, + dropTargetRef, + setDropTargetKey, + dragOverDayId, + setDragOverDayId, + transportDetail, + setTransportDetail, + transportPosVersion, + setTransportPosVersion, + timeConfirm, + setTimeConfirm, + inputRef, + dragDataRef, + scrollContainerRef, + initedTransportIds, + lastAutoScrolledIdRef, + currency, + getDragData, + prevDayCount, + toggleDay, + getSpanLabel, + getDayOrder, + computeMultiDayMove, + getTransportForDay, + getActiveRentalsForDay, + getDayAssignments, + computeTransportPosition, + initTransportPositions, + getMergedItems, + mergedItemsMap, + wouldBreakChronology, + applyMergedOrder, + handleMergedDrop, + confirmTimeRemoval, + startEditTitle, + saveTitle, + handleCalculateRoute, + toggleLock, + handleOptimize, + handleDropOnDay, + handleDropOnRow, + totalCost, + anyGeoAssignment, + anyGeoPlace, + } +} + +const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarProps) { + const S = useDayPlanSidebar(props) + const { + tripId, + trip, + days, + places, + categories, + assignments, + selectedDayId, + selectedPlaceId, + selectedAssignmentId, + onSelectDay, + onPlaceClick, + onDayDetail, + accommodations, + onReorder, + onReorderDays, + onAddDay, + onUpdateDayTitle, + onRouteCalculated, + onAssignToDay, + onRemoveAssignment, + onEditPlace, + onDeletePlace, + reservations, + visibleConnectionIds, + onToggleConnection, + externalTransportDetail, + onExternalTransportDetailHandled, + onAddReservation, + onAddPlace, + onAddPlaceToDay, + onNavigateToFiles, + routeShown, + routeProfile, + onToggleRoute, + onSetRouteProfile, + onExpandedDaysChange, + pushUndo, + canUndo, + lastActionLabel, + onUndo, + onRouteRefresh, + onAddTransport, + onEditTransport, + onEditReservation, + onAddBookingToAssignment, + initialScrollTop, + onScrollTopChange, + showRouteToolsWhenExpanded, + toast, + t, + language, + locale, + ctxMenu, + timeFormat, + tripActions, + can, + canEditDays, + noteUi, + setNoteUi, + noteInputRef, + dayNotes, + openAddNote, + openEditNote, + cancelNote, + saveNote, + deleteNote, + pendingDeleteNote, + setPendingDeleteNote, + moveNote, + expandedDays, + setExpandedDays, + editingDayId, + setEditingDayId, + editTitle, + setEditTitle, + isCalculating, + setIsCalculating, + routeInfo, + setRouteInfo, + routeLegs, + setRouteLegs, + hotelLegs, + setHotelLegs, + legsAbortRef, + draggingId, + setDraggingId, + lockedIds, + setLockedIds, + lockHoverId, + setLockHoverId, + undoHover, + setUndoHover, + pdfHover, + setPdfHover, + icsHover, + setIcsHover, + hoveredAssignmentId, + setHoveredAssignmentId, + dropTargetKey, + _setDropTargetKey, + dropTargetRef, + setDropTargetKey, + dragOverDayId, + setDragOverDayId, + transportDetail, + setTransportDetail, + transportPosVersion, + setTransportPosVersion, + timeConfirm, + setTimeConfirm, + inputRef, + dragDataRef, + scrollContainerRef, + initedTransportIds, + lastAutoScrolledIdRef, + currency, + getDragData, + prevDayCount, + toggleDay, + getSpanLabel, + getDayOrder, + computeMultiDayMove, + getTransportForDay, + getActiveRentalsForDay, + getDayAssignments, + computeTransportPosition, + initTransportPositions, + getMergedItems, + mergedItemsMap, + wouldBreakChronology, + applyMergedOrder, + handleMergedDrop, + confirmTimeRemoval, + startEditTitle, + saveTitle, + handleCalculateRoute, + toggleLock, + handleOptimize, + handleDropOnDay, + handleDropOnRow, + totalCost, + anyGeoAssignment, + anyGeoPlace, + } = S + return ( +
+ {/* Toolbar */} + + + {/* Tagesliste */} +
onScrollTopChange?.((e.currentTarget as HTMLElement).scrollTop)}> + {days.map((day, index) => { + const isSelected = selectedDayId === day.id + const isExpanded = expandedDays.has(day.id) + const da = getDayAssignments(day.id) + const cost = dayTotalCost(day.id, assignments, currency) + const formattedDate = formatDate(day.date, locale) + const loc = da.find(a => a.place?.lat && a.place?.lng) + const isDragTarget = dragOverDayId === day.id + const merged = mergedItemsMap[day.id] || [] + const dayNoteUi = noteUi[day.id] + const placeItems = merged.filter(i => i.type === 'place') + + return ( +
+ {/* Tages-Header — akzeptiert Drops aus der PlacesSidebar */} +
{ onSelectDay(day.id); if (onDayDetail) onDayDetail(day) }} + onDragOver={e => { e.preventDefault(); if (dragOverDayId !== day.id) setDragOverDayId(day.id) }} + onDragLeave={e => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDragOverDayId(null) }} + onDrop={e => handleDropOnDay(e, day.id)} + style={{ + display: 'flex', alignItems: 'center', gap: 10, + padding: '11px 14px 11px 16px', + cursor: 'pointer', + background: isDragTarget ? 'rgba(17,24,39,0.07)' : (isSelected ? 'var(--bg-selected)' : 'transparent'), + transition: 'background 0.12s', + userSelect: 'none', + outline: isDragTarget ? '2px dashed rgba(17,24,39,0.25)' : 'none', + outlineOffset: -2, + borderRadius: isDragTarget ? 8 : 0, + touchAction: 'manipulation', + }} + onMouseEnter={e => { if (!isSelected && !isDragTarget) e.currentTarget.style.background = 'var(--bg-tertiary)' }} + onMouseLeave={e => { if (!isSelected) e.currentTarget.style.background = isDragTarget ? 'rgba(17,24,39,0.07)' : 'transparent' }} + > + {/* Tages-Badge: Nummer oben, darunter (falls vorhanden) das Wetter des Tages */} + {(() => { + // anyGeoPlace is an assignment (has .place) or a bare place — read coords from either. + const geoLat = anyGeoPlace ? ('place' in anyGeoPlace ? anyGeoPlace.place?.lat : anyGeoPlace.lat) : undefined + const geoLng = anyGeoPlace ? ('place' in anyGeoPlace ? anyGeoPlace.place?.lng : anyGeoPlace.lng) : undefined + const wLat = loc?.place?.lat ?? geoLat + const wLng = loc?.place?.lng ?? geoLng + const hasWeather = !!(day.date && anyGeoPlace && wLat != null && wLng != null) + return ( +
+
+ {index + 1} +
+ {hasWeather && ( + <> +
+
+ +
+ + )} +
+ ) + })()} + +
+ {editingDayId === day.id ? ( + setEditTitle(e.target.value)} + onBlur={() => saveTitle(day.id)} + onKeyDown={e => { if (e.key === 'Enter') saveTitle(day.id); if (e.key === 'Escape') setEditingDayId(null) }} + onClick={e => e.stopPropagation()} + style={{ + width: '100%', border: 'none', outline: 'none', + fontSize: 13, fontWeight: 600, color: 'var(--text-primary)', + background: 'transparent', padding: 0, fontFamily: 'inherit', + borderBottom: '1.5px solid var(--text-primary)', + }} + /> + ) : (<> +
+ + {day.title || t('dayplan.dayN', { n: index + 1 })} + + {formattedDate && ( + <> + + + {formattedDate} + + + )} +
+ {(() => { + const hasAccs = accommodations.some(a => isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days)) + const hasRentals = getActiveRentalsForDay(day.id).length > 0 + if (!hasAccs && !hasRentals) return null + return
+ })()} +
+ {(() => { + const dayAccs = accommodations.filter(a => isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days)) + // Sort: check-out first, then ongoing stays, then check-in last + .sort((a, b) => { + const aIsOut = a.end_day_id === day.id && a.start_day_id !== day.id + const bIsOut = b.end_day_id === day.id && b.start_day_id !== day.id + const aIsIn = a.start_day_id === day.id + const bIsIn = b.start_day_id === day.id + if (aIsOut && !bIsOut) return -1 + if (!aIsOut && bIsOut) return 1 + if (aIsIn && !bIsIn) return 1 + if (!aIsIn && bIsIn) return -1 + return 0 + }) + if (dayAccs.length === 0) return null + return dayAccs.map(acc => { + const isCheckIn = acc.start_day_id === day.id + const isCheckOut = acc.end_day_id === day.id + const iconColor = isCheckOut && !isCheckIn ? '#ef4444' : isCheckIn ? '#22c55e' : 'var(--text-faint)' + return ( + { e.stopPropagation(); if ((acc as any).place_id) onPlaceClick((acc as any).place_id) }} className="bg-surface-hover" style={{ display: 'inline-flex', alignItems: 'center', gap: 4, flexShrink: 1, minWidth: 0, cursor: (acc as any).place_id ? 'pointer' : 'default', borderRadius: 7, padding: '2px 7px 2px 6px' }}> + + {(acc as any).place_name || (acc as any).reservation_title} + + ) + }) + })()} + {/* Active rental car badges */} + {(() => { + const activeRentals = getActiveRentalsForDay(day.id) + if (activeRentals.length === 0) return null + return activeRentals.map(r => ( + { e.stopPropagation(); setTransportDetail(r) }} className="bg-surface-hover" style={{ display: 'inline-flex', alignItems: 'center', gap: 4, flexShrink: 1, minWidth: 0, cursor: 'pointer', borderRadius: 7, padding: '2px 7px 2px 6px' }}> + + {r.title} + + )) + })()} +
+ + )} + {cost && ( +
+ {cost} +
+ )} +
+ + {canEditDays ? ( + (() => { + const cell = { padding: 7, cursor: 'pointer', display: 'grid', placeItems: 'center' } as const + const div = '1px solid var(--border-faint)' + return ( +
+ + {onAddTransport ? ( + + ) :
} + + +
+ ) + })() + ) : ( + + )} +
+ + {/* Aufgeklappte Orte + Notizen */} + {isExpanded && ( +
{ e.preventDefault(); const cur = dropTargetRef.current; if (draggingId && (!cur || cur.startsWith('end-'))) setDropTargetKey(`end-${day.id}`) }} + onDrop={e => { + e.preventDefault() + e.stopPropagation() + const { placeId, assignmentId, noteId, reservationId: fromReservationId, fromDayId, phase } = getDragData(e) + // Drop on transport card (detected via dropTargetRef for sync accuracy) + if (dropTargetRef.current?.startsWith('transport-')) { + const isAfter = dropTargetRef.current.startsWith('transport-after-') + const parts = dropTargetRef.current.replace('transport-after-', '').replace('transport-', '').split('-') + const transportId = Number(parts[0]) + const legPart = parts.find(p => /^leg\d+$/.test(p)) + const toLegIndex = legPart ? Number(legPart.slice(3)) : null + + if (placeId) { + onAssignToDay?.(parseInt(placeId), day.id) + } else if (fromReservationId && fromDayId !== day.id) { + const r = reservations.find(x => x.id === Number(fromReservationId)) + if (r) { const update = computeMultiDayMove(r, day.id, phase); tripActions.updateReservation(tripId, r.id, update).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) } + } else if (fromReservationId) { + handleMergedDrop(day.id, 'transport', Number(fromReservationId), 'transport', transportId, isAfter, toLegIndex) + } else if (assignmentId && fromDayId !== day.id) { + tripActions.moveAssignment(tripId, Number(assignmentId), fromDayId, day.id).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + } else if (assignmentId) { + handleMergedDrop(day.id, 'place', Number(assignmentId), 'transport', transportId, isAfter, toLegIndex) + } else if (noteId && fromDayId !== day.id) { + tripActions.moveDayNote(tripId, fromDayId, day.id, Number(noteId)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + } else if (noteId) { + handleMergedDrop(day.id, 'note', Number(noteId), 'transport', transportId, isAfter, toLegIndex) + } + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; window.__dragData = null + return + } + + if (fromReservationId && fromDayId !== day.id) { + const r = reservations.find(x => x.id === Number(fromReservationId)) + if (r) { const update = computeMultiDayMove(r, day.id, phase); tripActions.updateReservation(tripId, r.id, update).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) } + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; return + } + if (!assignmentId && !noteId && !placeId) { dragDataRef.current = null; window.__dragData = null; return } + if (placeId) { + onAssignToDay?.(parseInt(placeId), day.id) + setDropTargetKey(null); window.__dragData = null; return + } + if (assignmentId && fromDayId !== day.id) { + tripActions.moveAssignment(tripId, Number(assignmentId), fromDayId, day.id).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; return + } + if (noteId && fromDayId !== day.id) { + tripActions.moveDayNote(tripId, fromDayId, day.id, Number(noteId)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; return + } + const m = getMergedItems(day.id) + if (m.length === 0) return + const lastItem = m[m.length - 1] + if (assignmentId && String(lastItem?.data?.id) !== assignmentId) + handleMergedDrop(day.id, 'place', Number(assignmentId), lastItem.type, lastItem.data.id, true) + else if (noteId && String(lastItem?.data?.id) !== noteId) + handleMergedDrop(day.id, 'note', Number(noteId), lastItem.type, lastItem.data.id, true) + }} + > + {isSelected && hotelLegs.top && ( + + )} + {merged.length === 0 && !dayNoteUi ? ( +
{ e.preventDefault(); if (dragOverDayId !== day.id) setDragOverDayId(day.id) }} + onDrop={e => handleDropOnDay(e, day.id)} + className={dragOverDayId === day.id ? 'bg-[rgba(17,24,39,0.05)]' : 'bg-transparent'} + style={{ padding: '16px', textAlign: 'center', borderRadius: 8, + border: dragOverDayId === day.id ? '2px dashed rgba(17,24,39,0.2)' : '2px dashed transparent', + }} + > + {t('dayplan.emptyDay')} +
+ ) : ( + merged.map((item, idx) => { + const legSuffix = item.data?.__leg ? `-leg${item.data.__leg.index}` : '' + const itemKey = item.type === 'transport' ? `transport-${item.data.id}${legSuffix}-${day.id}` : (item.type === 'place' ? `place-${item.data.id}` : `note-${item.data.id}`) + const showDropLine = (!!draggingId || !!dropTargetKey) && dropTargetKey === itemKey + const showDropLineAfter = item.type === 'transport' && (!!draggingId || !!dropTargetKey) && dropTargetKey === `transport-after-${item.data.id}${legSuffix}-${day.id}` + + if (item.type === 'place') { + const assignment = item.data + const place = assignment.place + if (!place) return null + const cat = categories.find(c => c.id === place.category_id) + const isPlaceSelected = selectedAssignmentId ? assignment.id === selectedAssignmentId : place.id === selectedPlaceId + const isDraggingThis = draggingId === assignment.id + const placeIdx = placeItems.findIndex(i => i.data.id === assignment.id) + + const arrowMove = (direction: 'up' | 'down') => { + const m = getMergedItems(day.id) + const myIdx = m.findIndex(i => i.type === 'place' && i.data.id === assignment.id) + if (myIdx === -1) return + const targetIdx = direction === 'up' ? myIdx - 1 : myIdx + 1 + if (targetIdx < 0 || targetIdx >= m.length) return + + // Build new order: swap this item with its neighbor in the merged list + const newOrder = [...m] + ;[newOrder[myIdx], newOrder[targetIdx]] = [newOrder[targetIdx], newOrder[myIdx]] + + // Check chronological order of all timed items in the new order + const placeTime = place.place_time + if (parseTimeToMinutes(placeTime) !== null) { + const timedInNewOrder = newOrder + .map(i => { + if (i.type === 'transport') return parseTimeToMinutes(i.data?.reservation_time) + if (i.type === 'place') return parseTimeToMinutes(i.data?.place?.place_time) + return null + }) + .filter(t => t !== null) + const isChronological = timedInNewOrder.every((t, i) => i === 0 || t >= timedInNewOrder[i - 1]) + if (!isChronological) { + const timeStr = placeTime.includes(':') ? placeTime.substring(0, 5) : placeTime + // Store the new merged order for confirm action + setTimeConfirm({ dayId: day.id, fromId: assignment.id, time: timeStr, reorderIds: newOrder.filter(i => i.type === 'place').map(i => i.data.id) }) + return + } + } + applyMergedOrder(day.id, newOrder) + } + const moveUp = (e) => { e.stopPropagation(); arrowMove('up') } + const moveDown = (e) => { e.stopPropagation(); arrowMove('down') } + + return ( + +
{ + if (!canEditDays) { e.preventDefault(); return } + e.dataTransfer.setData('assignmentId', String(assignment.id)) + e.dataTransfer.setData('fromDayId', String(day.id)) + e.dataTransfer.effectAllowed = 'move' + dragDataRef.current = { assignmentId: String(assignment.id), fromDayId: String(day.id) } + setDraggingId(assignment.id) + }} + onDragOver={e => { e.preventDefault(); e.stopPropagation(); setDragOverDayId(null); if (dropTargetKey !== `place-${assignment.id}`) setDropTargetKey(`place-${assignment.id}`) }} + onDrop={e => { + e.preventDefault(); e.stopPropagation() + const { placeId, assignmentId: fromAssignmentId, noteId, reservationId: fromReservationId, fromDayId, phase } = getDragData(e) + if (placeId) { + const pos = placeItems.findIndex(i => i.data.id === assignment.id) + onAssignToDay?.(parseInt(placeId), day.id, pos >= 0 ? pos : undefined) + setDropTargetKey(null); window.__dragData = null + } else if (fromReservationId && fromDayId !== day.id) { + const r = reservations.find(x => x.id === Number(fromReservationId)) + if (r) { const update = computeMultiDayMove(r, day.id, phase); tripActions.updateReservation(tripId, r.id, update).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) } + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null + } else if (fromReservationId) { + handleMergedDrop(day.id, 'transport', Number(fromReservationId), 'place', assignment.id) + } else if (fromAssignmentId && fromDayId !== day.id) { + const toIdx = getDayAssignments(day.id).findIndex(a => a.id === assignment.id) + tripActions.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id, toIdx).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null + } else if (fromAssignmentId) { + handleMergedDrop(day.id, 'place', Number(fromAssignmentId), 'place', assignment.id) + } else if (noteId && fromDayId !== day.id) { + const tm = getMergedItems(day.id) + const toIdx = tm.findIndex(i => i.type === 'place' && i.data.id === assignment.id) + const so = toIdx <= 0 ? (tm[0]?.sortKey ?? 0) - 1 : (tm[toIdx - 1].sortKey + tm[toIdx].sortKey) / 2 + tripActions.moveDayNote(tripId, fromDayId, day.id, Number(noteId), so).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null + } else if (noteId) { + handleMergedDrop(day.id, 'note', Number(noteId), 'place', assignment.id) + } + }} + ref={el => { + // Auto-scroll the selected row into view — but only on + // the transition "just became selected". Once we've + // scrolled for this assignment id, we won't scroll + // again until selection actually moves somewhere else. + if (el && isPlaceSelected && lastAutoScrolledIdRef.current !== assignment.id) { + const rect = el.getBoundingClientRect() + const nearTop = rect.top < 80 + const nearBottom = rect.bottom > window.innerHeight - 80 + if (nearTop || nearBottom) { + el.scrollIntoView({ behavior: 'smooth', block: 'center' }) + } + lastAutoScrolledIdRef.current = assignment.id + } + }} + onDragEnd={() => { setDraggingId(null); setDragOverDayId(null); setDropTargetKey(null); dragDataRef.current = null }} + onClick={() => { onPlaceClick(isPlaceSelected ? null : place.id, isPlaceSelected ? null : assignment.id); if (!isPlaceSelected) onSelectDay(day.id, true) }} + onContextMenu={e => ctxMenu.open(e, [ + canEditDays && onEditPlace && { label: t('common.edit'), icon: Pencil, onClick: () => onEditPlace(place, assignment.id) }, + canEditDays && onRemoveAssignment && { label: t('planner.removeFromDay'), icon: Trash2, onClick: () => onRemoveAssignment(day.id, assignment.id) }, + place.website && { label: t('inspector.website'), icon: ExternalLink, onClick: () => window.open(place.website, '_blank') }, + (place.lat && place.lng) && { label: 'Google Maps', icon: Navigation, onClick: () => window.open(`https://www.google.com/maps/search/?api=1&query=${place.google_place_id ? encodeURIComponent(place.name) + '&query_place_id=' + place.google_place_id : place.lat + ',' + place.lng}`, '_blank') }, + { divider: true }, + canEditDays && onDeletePlace && { label: t('common.delete'), icon: Trash2, danger: true, onClick: () => onDeletePlace(place.id) }, + ])} + onMouseEnter={e => { + if (!isPlaceSelected && !lockedIds.has(assignment.id)) + e.currentTarget.style.background = 'var(--bg-hover)' + const grip = e.currentTarget.querySelector('.dp-grip') as HTMLElement | null + if (grip) grip.style.opacity = '1' + setHoveredAssignmentId(assignment.id) + }} + onMouseLeave={e => { + if (!isPlaceSelected && !lockedIds.has(assignment.id)) + e.currentTarget.style.background = 'transparent' + const grip = e.currentTarget.querySelector('.dp-grip') as HTMLElement | null + if (grip) grip.style.opacity = '0.3' + setHoveredAssignmentId(null) + }} + style={{ + display: 'flex', alignItems: 'center', gap: 8, + padding: '7px 8px 7px 10px', + cursor: 'pointer', + background: lockedIds.has(assignment.id) + ? 'rgba(220,38,38,0.08)' + : isPlaceSelected ? 'var(--bg-selected)' : 'transparent', + borderLeft: lockedIds.has(assignment.id) + ? '3px solid #dc2626' + : '3px solid transparent', + borderTop: showDropLine ? '2px solid var(--text-primary)' : undefined, + transition: 'background 0.15s, border-color 0.15s', + opacity: isDraggingThis ? 0.4 : 1, + }} + > + {canEditDays &&
+ +
} +
{ e.stopPropagation(); toggleLock(assignment.id) }} + onMouseEnter={e => { e.stopPropagation(); setLockHoverId(assignment.id) }} + onMouseLeave={() => setLockHoverId(null)} + style={{ position: 'relative', flexShrink: 0, cursor: 'pointer' }} + > + + {/* Hover/locked overlay */} + {(lockHoverId === assignment.id || lockedIds.has(assignment.id)) && ( +
+ +
+ )} + {/* Custom tooltip */} + {lockHoverId === assignment.id && ( +
+ {lockedIds.has(assignment.id) + ? t('planner.clickToUnlock') + : t('planner.keepPosition')} +
+ )} +
+
+
+ {cat && (() => { + const CatIcon = getCategoryIcon(cat.icon) + return + })()} + + {place.name} + + {place.place_time && ( + + + {formatTime(place.place_time, locale, timeFormat)}{place.end_time ? ` – ${formatTime(place.end_time, locale, timeFormat)}` : ''} + + )} +
+ {(place.description || place.address || cat?.name) && ( +
+ {place.description || place.address || cat?.name || ''} +
+ )} + {(() => { + const res = reservations.find(r => r.assignment_id === assignment.id) + if (!res) return null + const confirmed = res.status === 'confirmed' + const hasEndpoints = onToggleConnection && (res.endpoints || []).length >= 2 + const active = hasEndpoints ? visibleConnectionIds.includes(res.id) : false + return ( +
+
+ {(() => { const RI = RES_ICONS[res.type] || Ticket; return })()} + {confirmed ? t('planner.resConfirmed') : t('planner.resPending')} + {(() => { + const { time: st } = splitReservationDateTime(res.reservation_time) + const { time: et } = splitReservationDateTime(res.reservation_end_time) + if (!st && !et) return null + return ( + + {st ? formatTime(st, locale, timeFormat) : ''} + {et ? ` – ${formatTime(et, locale, timeFormat)}` : ''} + + ) + })()} + {(() => { + const meta = typeof res.metadata === 'string' ? JSON.parse(res.metadata || '{}') : (res.metadata || {}) + if (!meta) return null + if (meta.airline && meta.flight_number) return {meta.airline} {meta.flight_number} + if (meta.flight_number) return {meta.flight_number} + if (meta.train_number) return {meta.train_number} + return null + })()} +
+ {hasEndpoints && ( + + )} + {canEditDays && (() => { + const isTransport = TRANSPORT_TYPES.has(res.type) + const handler = isTransport ? onEditTransport : onEditReservation + if (!handler) return null + return ( + + ) + })()} +
+ ) + })()} + {assignment.participants?.length > 0 && ( +
+ {assignment.participants.slice(0, 5).map((p, pi) => ( +
0 ? -4 : 0, flexShrink: 0, + overflow: 'hidden', + }}> + {p.avatar ? : p.username?.[0]?.toUpperCase()} +
+ ))} + {assignment.participants.length > 5 && ( + +{assignment.participants.length - 5} + )} +
+ )} +
+ {canEditDays &&
+ + +
} + {canEditDays && onAddBookingToAssignment && hoveredAssignmentId === assignment.id && ( + + )} +
+ {routeLegs[assignment.id] && } +
+ ) + } + + // Transport booking (flight, train, bus, car, cruise) + if (item.type === 'transport') { + const res = item.data + const spanPhase = getSpanPhase(res, day.id) + + // Car "active" (middle) days are shown in the day header, skip here + if (res.type === 'car' && spanPhase === 'middle') return null + + const TransportIcon = RES_ICONS[res.type] || Ticket + const color = '#3b82f6' + const meta = typeof res.metadata === 'string' ? JSON.parse(res.metadata || '{}') : (res.metadata || {}) + + // Subtitle aus Metadaten zusammensetzen + let subtitle = '' + if (res.__leg) { + // One leg of a multi-leg flight — show this segment's own route. + const parts = [res.__leg.airline, res.__leg.flight_number].filter(Boolean) + if (res.__leg.from || res.__leg.to) + parts.push([res.__leg.from, res.__leg.to].filter(Boolean).join(' → ')) + subtitle = parts.join(' · ') + } else if (res.type === 'flight') { + const parts = [meta.airline, meta.flight_number].filter(Boolean) + if (meta.departure_airport || meta.arrival_airport) + parts.push([meta.departure_airport, meta.arrival_airport].filter(Boolean).join(' → ')) + subtitle = parts.join(' · ') + } else if (res.type === 'train') { + subtitle = [meta.train_number, meta.platform ? `Gl. ${meta.platform}` : '', meta.seat ? `Sitz ${meta.seat}` : ''].filter(Boolean).join(' · ') + } + + // Multi-day span phase (single-leg / non-flight only — a + // multi-leg flight is shown as one row per leg, see below). + const spanLabel = res.__leg ? null : getSpanLabel(res, spanPhase) + const displayTime = getDisplayTimeForDay(res, day.id) + const legKey = res.__leg ? `leg${res.__leg.index}` : 'x' + + return ( + +
{ + if (!canEditDays) return + const target = reservations.find(x => x.id === res.id) ?? res + if (TRANSPORT_TYPES.has(res.type)) onEditTransport?.(target) + else onEditReservation?.(target) + }} + onDragOver={e => { + e.preventDefault(); e.stopPropagation() + const rect = e.currentTarget.getBoundingClientRect() + const inBottom = e.clientY > rect.top + rect.height / 2 + const ls = res.__leg ? `-leg${res.__leg.index}` : '' + const key = inBottom ? `transport-after-${res.id}${ls}-${day.id}` : `transport-${res.id}${ls}-${day.id}` + if (dropTargetRef.current !== key) setDropTargetKey(key) + }} + draggable={canEditDays && spanPhase !== 'middle' && !res.__leg} + onDragStart={e => { + if (!canEditDays || spanPhase === 'middle' || res.__leg) { e.preventDefault(); return } + // setData is required for the drag to start reliably (Firefox) and + // matches how place/note items initiate their drag. + e.dataTransfer.setData('reservationId', String(res.id)) + e.dataTransfer.setData('fromDayId', String(day.id)) + e.dataTransfer.effectAllowed = 'move' + dragDataRef.current = { reservationId: String(res.id), fromDayId: String(day.id), phase: spanPhase } + setDraggingId(res.id) + }} + onDragEnd={() => { setDraggingId(null); setDragOverDayId(null); setDropTargetKey(null); dragDataRef.current = null }} + onDrop={e => { + e.preventDefault(); e.stopPropagation() + const rect = e.currentTarget.getBoundingClientRect() + const insertAfter = e.clientY > rect.top + rect.height / 2 + const { placeId, assignmentId: fromAssignmentId, noteId, reservationId: fromReservationId, fromDayId, phase } = getDragData(e) + if (placeId) { + onAssignToDay?.(parseInt(placeId), day.id) + } else if (fromReservationId && fromDayId !== day.id) { + const r2 = reservations.find(x => x.id === Number(fromReservationId)) + if (r2) { const update = computeMultiDayMove(r2, day.id, phase); tripActions.updateReservation(tripId, r2.id, update).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) } + } else if (fromReservationId) { + handleMergedDrop(day.id, 'transport', Number(fromReservationId), 'transport', res.id, insertAfter, res.__leg?.index ?? null) + } else if (fromAssignmentId && fromDayId !== day.id) { + tripActions.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + } else if (fromAssignmentId) { + handleMergedDrop(day.id, 'place', Number(fromAssignmentId), 'transport', res.id, insertAfter, res.__leg?.index ?? null) + } else if (noteId && fromDayId !== day.id) { + tripActions.moveDayNote(tripId, fromDayId, day.id, Number(noteId)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + } else if (noteId) { + handleMergedDrop(day.id, 'note', Number(noteId), 'transport', res.id, insertAfter, res.__leg?.index ?? null) + } + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; window.__dragData = null + }} + onMouseEnter={e => { e.currentTarget.style.background = `${color}12` }} + onMouseLeave={e => { e.currentTarget.style.background = `${color}08` }} + style={{ + display: 'flex', alignItems: 'center', gap: 8, + padding: '7px 8px 7px 10px', + margin: '1px 8px', + borderRadius: 6, + border: `1px solid ${color}33`, + borderTop: showDropLine ? '2px solid var(--text-primary)' : undefined, + borderBottom: showDropLineAfter ? '2px solid var(--text-primary)' : undefined, + background: `${color}08`, + cursor: canEditDays && onEditTransport ? 'pointer' : 'default', userSelect: 'none', + transition: 'background 0.1s', + opacity: draggingId === res.id ? 0.4 : spanPhase === 'middle' ? 0.65 : 1, + }} + > + {canEditDays && spanPhase !== 'middle' && !res.__leg && ( +
+ +
+ )} +
+ +
+
+
+ {spanLabel && ( + + {spanLabel} + + )} + + {res.title} + + {(() => { + const { time: dispTime } = splitReservationDateTime(displayTime) + const { time: endTime } = splitReservationDateTime(res.reservation_end_time) + if (!dispTime && !endTime) return null + return ( + + + {dispTime ? formatTime(dispTime, locale, timeFormat) : ''} + {spanPhase === 'single' && endTime ? ` – ${formatTime(endTime, locale, timeFormat)}` : ''} + {meta.departure_timezone && spanPhase === 'start' && ` ${meta.departure_timezone}`} + {meta.arrival_timezone && spanPhase === 'end' && ` ${meta.arrival_timezone}`} + + ) + })()} +
+ {subtitle && ( +
+ {subtitle} +
+ )} +
+ {onToggleConnection && (!res.__leg || res.__leg.index === 0) && (res.endpoints || []).length >= 2 && (() => { + const active = visibleConnectionIds.includes(res.id) + return ( + + ) + })()} +
+ {routeLegs[res.id] && } +
+ ) + } + + // Notizkarte + const note = item.data + const NoteIcon = getNoteIcon(note.icon) + const noteIdx = idx + return ( + +
{ if (!canEditDays) { e.preventDefault(); return } e.dataTransfer.setData('noteId', String(note.id)); e.dataTransfer.setData('fromDayId', String(day.id)); e.dataTransfer.effectAllowed = 'move'; dragDataRef.current = { noteId: String(note.id), fromDayId: String(day.id) }; setDraggingId(`note-${note.id}`) }} + onDragEnd={() => { setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null }} + onDragOver={e => { e.preventDefault(); e.stopPropagation(); if (dropTargetKey !== `note-${note.id}`) setDropTargetKey(`note-${note.id}`) }} + onDrop={e => { + e.preventDefault(); e.stopPropagation() + const { placeId, noteId: fromNoteId, assignmentId: fromAssignmentId, reservationId: fromReservationId, fromDayId, phase } = getDragData(e) + if (placeId) { + // New place dropped onto a note: insert it among the + // assignments at the note's position (after the places + // above it), so it lands right where the note sits. + const tm = getMergedItems(day.id) + const noteIdx = tm.findIndex(i => i.type === 'note' && i.data.id === note.id) + const pos = tm.slice(0, noteIdx).filter(i => i.type === 'place').length + onAssignToDay?.(parseInt(placeId), day.id, pos) + setDropTargetKey(null); window.__dragData = null + } else if (fromReservationId && fromDayId !== day.id) { + const r = reservations.find(x => x.id === Number(fromReservationId)) + if (r) { const update = computeMultiDayMove(r, day.id, phase); tripActions.updateReservation(tripId, r.id, update).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) } + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null + } else if (fromReservationId) { + handleMergedDrop(day.id, 'transport', Number(fromReservationId), 'note', note.id) + } else if (fromNoteId && fromDayId !== day.id) { + const tm = getMergedItems(day.id) + const toIdx = tm.findIndex(i => i.type === 'note' && i.data.id === note.id) + const so = toIdx <= 0 ? (tm[0]?.sortKey ?? 0) - 1 : (tm[toIdx - 1].sortKey + tm[toIdx].sortKey) / 2 + tripActions.moveDayNote(tripId, fromDayId, day.id, Number(fromNoteId), so).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + setDraggingId(null); setDropTargetKey(null) + } else if (fromNoteId && fromNoteId !== String(note.id)) { + handleMergedDrop(day.id, 'note', Number(fromNoteId), 'note', note.id) + } else if (fromAssignmentId && fromDayId !== day.id) { + const tm = getMergedItems(day.id) + const noteIdx = tm.findIndex(i => i.type === 'note' && i.data.id === note.id) + const toIdx = tm.slice(0, noteIdx).filter(i => i.type === 'place').length + tripActions.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id, toIdx).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + setDraggingId(null); setDropTargetKey(null) + } else if (fromAssignmentId) { + handleMergedDrop(day.id, 'place', Number(fromAssignmentId), 'note', note.id) + } + }} + onContextMenu={canEditDays ? e => ctxMenu.open(e, [ + { label: t('common.edit'), icon: Pencil, onClick: () => openEditNote(day.id, note) }, + { divider: true }, + { label: t('common.delete'), icon: Trash2, danger: true, onClick: () => setPendingDeleteNote({ dayId: day.id, noteId: note.id }) }, + ]) : undefined} + onMouseEnter={e => { + const grip = e.currentTarget.querySelector('.dp-grip') as HTMLElement | null + if (grip) grip.style.opacity = '1' + const editBtns = e.currentTarget.querySelector('.note-edit-buttons') as HTMLElement | null + if (editBtns) editBtns.style.opacity = '1' + }} + onMouseLeave={e => { + const grip = e.currentTarget.querySelector('.dp-grip') as HTMLElement | null + if (grip) grip.style.opacity = '0.3' + const editBtns = e.currentTarget.querySelector('.note-edit-buttons') as HTMLElement | null + if (editBtns) editBtns.style.opacity = '0' + }} + style={{ + display: 'flex', alignItems: 'center', gap: 8, + padding: '7px 8px 7px 2px', + margin: '1px 8px', + borderRadius: 6, + border: '1px solid var(--border-faint)', + borderTop: showDropLine ? '2px solid var(--text-primary)' : undefined, + background: 'var(--bg-hover)', + opacity: draggingId === `note-${note.id}` ? 0.4 : 1, + transition: 'background 0.1s', cursor: 'grab', userSelect: 'none', + }} + > + {canEditDays &&
+ +
} +
+ +
+
+ + {note.text} + + {note.time && ( +
{note.time}
+ )} +
+ {canEditDays &&
+ + +
} + {canEditDays &&
+ + +
} +
+
+ ) + }) + )} + {isSelected && hotelLegs.bottom && ( + + )} + {/* Drop-Zone am Listenende — immer vorhanden als Drop-Target */} +
{ e.preventDefault(); e.stopPropagation(); if (dropTargetKey !== `end-${day.id}`) setDropTargetKey(`end-${day.id}`) }} + onDrop={e => { + e.preventDefault(); e.stopPropagation() + const { placeId, assignmentId, noteId, reservationId: fromReservationId, fromDayId, phase } = getDragData(e) + // Neuer Ort von der Orte-Liste + if (placeId) { + onAssignToDay?.(parseInt(placeId), day.id) + setDropTargetKey(null); window.__dragData = null; return + } + if (fromReservationId && fromDayId !== day.id) { + const r = reservations.find(x => x.id === Number(fromReservationId)) + if (r) { const update = computeMultiDayMove(r, day.id, phase); tripActions.updateReservation(tripId, r.id, update).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) } + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; window.__dragData = null; return + } + if (!assignmentId && !noteId && !fromReservationId) { dragDataRef.current = null; window.__dragData = null; return } + if (assignmentId && fromDayId !== day.id) { + tripActions.moveAssignment(tripId, Number(assignmentId), fromDayId, day.id).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; return + } + if (noteId && fromDayId !== day.id) { + tripActions.moveDayNote(tripId, fromDayId, day.id, Number(noteId)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : t('common.unknownError'))) + setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; return + } + const m = getMergedItems(day.id) + if (m.length === 0) return + const lastItem = m[m.length - 1] + if (assignmentId && String(lastItem?.data?.id) !== assignmentId) + handleMergedDrop(day.id, 'place', Number(assignmentId), lastItem.type, lastItem.data.id, true) + else if (noteId && String(lastItem?.data?.id) !== noteId) + handleMergedDrop(day.id, 'note', Number(noteId), lastItem.type, lastItem.data.id, true) + else if (fromReservationId && String(lastItem?.data?.id) !== fromReservationId) + handleMergedDrop(day.id, 'transport', Number(fromReservationId), lastItem.type, lastItem.data.id, true) + setDropTargetKey(null); dragDataRef.current = null; window.__dragData = null + }} + > + {dropTargetKey === `end-${day.id}` && ( +
+ )} +
+ + {/* Routen-Werkzeuge (ausgewählter Tag, 2+ Orte) */} + {(isSelected || (showRouteToolsWhenExpanded && isExpanded)) && getDayAssignments(day.id).length >= 2 && ( +
+
+ + +
+ {(['driving', 'walking'] as const).map(p => { + const ModeIcon = p === 'driving' ? Car : Footprints + const active = routeProfile === p + return ( + + ) + })} +
+
+ {isSelected && routeInfo && ( +
+ {routeInfo.distance} + · + {routeInfo.duration} +
+ )} +
+ )} + + {/* Mobile: Add Place from list */} + +
+ )} +
+ ) + })} +
+ + {/* Notiz-Popup-Modal — über Portal gerendert, um den backdropFilter-Stapelkontext zu umgehen */} + + + {/* Confirm: remove time when reordering a timed place */} + + + {/* Confirm: delete a day note — guards against accidental taps on touch devices */} + setPendingDeleteNote(null)} + onConfirm={() => { if (pendingDeleteNote) deleteNote(pendingDeleteNote.dayId, pendingDeleteNote.noteId) }} + title={t('dayplan.confirmDeleteNoteTitle')} + message={t('dayplan.confirmDeleteNoteBody')} + /> + + {/* Transport-Detail-Modal */} + + + {/* Budget-Fußzeile */} + + +
+ ) +}) + +export default DayPlanSidebar \ No newline at end of file diff --git a/client/src/components/Planner/DayPlanSidebarFooter.tsx b/client/src/components/Planner/DayPlanSidebarFooter.tsx new file mode 100644 index 0000000000000000000000000000000000000000..6346701d471d1a90d8d233ff4dd2b04d5d6845e6 --- /dev/null +++ b/client/src/components/Planner/DayPlanSidebarFooter.tsx @@ -0,0 +1,17 @@ +import { currencyDecimals } from '../../utils/formatters' + +interface DayPlanSidebarFooterProps { + totalCost: number + currency: string + t: (key: string, params?: Record) => string +} + +export function DayPlanSidebarFooter({ totalCost, currency, t }: DayPlanSidebarFooterProps) { + if (!(totalCost > 0)) return null + return ( +
+ {t('dayplan.totalCost')} + {totalCost.toFixed(currencyDecimals(currency))} {currency} +
+ ) +} diff --git a/client/src/components/Planner/DayPlanSidebarMobileAddPlaceButton.tsx b/client/src/components/Planner/DayPlanSidebarMobileAddPlaceButton.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e71e00e5eacaff09b45cc5f5be5520afe3b26ef1 --- /dev/null +++ b/client/src/components/Planner/DayPlanSidebarMobileAddPlaceButton.tsx @@ -0,0 +1,97 @@ +import { useState } from 'react' +import { Plus, X, MapPin } from 'lucide-react' +import { useTranslation } from '../../i18n' +import type { Place, AssignmentsMap } from '../../types' + +export function MobileAddPlaceButton({ dayId, places, assignments, onAssign, onAddNew }: { + dayId: number + places: Place[] + assignments: AssignmentsMap + onAssign?: (placeId: number, dayId: number) => void + onAddNew?: () => void +}) { + const { t } = useTranslation() + const [open, setOpen] = useState(false) + const [search, setSearch] = useState('') + + // Find places not assigned to this day + const assignedToDay = new Set((assignments[String(dayId)] || []).map(a => a.place_id)) + const available = places.filter(p => !assignedToDay.has(p.id)) + const filtered = search.trim() + ? available.filter(p => p.name.toLowerCase().includes(search.toLowerCase())) + : available + + return ( +
+ {!open ? ( + + ) : ( +
+
+ setSearch(e.target.value)} + placeholder={t('dayplan.mobile.searchPlaces')} + style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 13, fontFamily: 'inherit', color: 'var(--text-primary)' }} + /> + +
+
+ {filtered.length === 0 && ( +
+ {available.length === 0 ? t('dayplan.mobile.allAssigned') : t('dayplan.mobile.noMatch')} +
+ )} + {filtered.slice(0, 20).map(p => ( + + ))} +
+ {onAddNew && ( + + )} +
+ )} +
+ ) +} diff --git a/client/src/components/Planner/DayPlanSidebarNoteModal.tsx b/client/src/components/Planner/DayPlanSidebarNoteModal.tsx new file mode 100644 index 0000000000000000000000000000000000000000..21dfd276c666c4fe67f4cbfe285467b05e47e542 --- /dev/null +++ b/client/src/components/Planner/DayPlanSidebarNoteModal.tsx @@ -0,0 +1,82 @@ +import ReactDOM from 'react-dom' +import { NOTE_ICONS } from './DayPlanSidebar.constants' + +interface NoteModalUi { + mode: 'add' | 'edit' + icon: string + text: string + time: string +} + +interface DayPlanSidebarNoteModalProps { + noteUi: Record + setNoteUi: (updater: (prev: any) => any) => void + noteInputRef: React.RefObject + cancelNote: (dayId: number) => void + saveNote: (dayId: number) => void + t: (key: string, params?: Record) => string +} + +export function DayPlanSidebarNoteModal({ noteUi, setNoteUi, noteInputRef, cancelNote, saveNote, t }: DayPlanSidebarNoteModalProps) { + return ( + <> + {Object.entries(noteUi).map(([dayId, ui]) => ui && ReactDOM.createPortal( +
cancelNote(Number(dayId))}> +
e.stopPropagation()}> +
+ {ui.mode === 'add' ? t('dayplan.noteAdd') : t('dayplan.noteEdit')} +
+ {/* Icon-Auswahl */} +
+ {NOTE_ICONS.map(({ id, Icon }) => ( + + ))} +
+ setNoteUi(prev => ({ ...prev, [dayId]: { ...prev[dayId], text: e.target.value } }))} + onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); saveNote(Number(dayId)) } if (e.key === 'Escape') cancelNote(Number(dayId)) }} + placeholder={t('dayplan.noteTitle') + ' *'} + required + className="text-content" + style={{ fontSize: 13, fontWeight: 500, border: `1px solid ${!ui.text?.trim() ? 'var(--border-primary)' : 'var(--border-primary)'}`, borderRadius: 8, padding: '8px 10px', fontFamily: 'inherit', outline: 'none', width: '100%', boxSizing: 'border-box' }} + /> +