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30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import type { StoreApi } from 'zustand'
import type { TripStoreState } from '../tripStore'
import type { Assignment, Place, Day, DayNote, PackingItem, TodoItem, BudgetItem, BudgetItemMember, Reservation, Trip, TripFile, WebSocketEvent } from '../../types'
import { offlineDb } from '../../db/offlineDb'

type SetState = StoreApi<TripStoreState>['setState']
type GetState = StoreApi<TripStoreState>['getState']

// ── Dexie write-through ───────────────────────────────────────────────────────

/**
 * Persist remote event to IndexedDB so the data is available offline.
 * Fire-and-forget: errors are swallowed to never block the Zustand update.
 * Called AFTER set() so `state` already reflects the update.
 */
function writeToDexie(
  type: string,
  payload: Record<string, unknown>,
  state: TripStoreState,
): void {
  ;(async () => {
    try {
      switch (type) {
        // ── Places ──────────────────────────────────────────────────────────
        case 'place:created':
        case 'place:updated':
          await offlineDb.places.put(payload.place as Place)
          break
        case 'place:deleted':
          await offlineDb.places.delete(payload.placeId as number)
          break

        // ── Assignments (embedded in Day rows) ──────────────────────────────
        // Read the already-updated Day from the Zustand state and persist it.
        case 'assignment:created':
        case 'assignment:updated': {
          const assignment = payload.assignment as Assignment
          await _writeDayToDb(assignment.day_id, state)
          break
        }
        case 'assignment:deleted': {
          await _writeDayToDb(payload.dayId as number, state)
          break
        }
        case 'assignment:moved': {
          const movedAssignment = payload.assignment as Assignment
          await Promise.all([
            _writeDayToDb(payload.oldDayId as number, state),
            _writeDayToDb(movedAssignment.day_id, state),
          ])
          break
        }
        case 'assignment:reordered':
          await _writeDayToDb(payload.dayId as number, state)
          break

        // ── Days ─────────────────────────────────────────────────────────────
        case 'day:created':
        case 'day:updated': {
          const day = payload.day as Day
          await _writeDayToDb(day.id, state)
          break
        }
        case 'day:deleted':
          await offlineDb.days.delete(payload.dayId as number)
          break

        // ── Day notes (embedded in Day rows) ─────────────────────────────────
        case 'dayNote:created':
        case 'dayNote:updated':
        case 'dayNote:deleted':
          await _writeDayToDb(payload.dayId as number, state)
          break

        // ── Packing ──────────────────────────────────────────────────────────
        case 'packing:created':
        case 'packing:updated':
          await offlineDb.packingItems.put(payload.item as PackingItem)
          break
        case 'packing:deleted':
          await offlineDb.packingItems.delete(payload.itemId as number)
          break

        // ── Todo ─────────────────────────────────────────────────────────────
        case 'todo:created':
        case 'todo:updated':
          await offlineDb.todoItems.put(payload.item as TodoItem)
          break
        case 'todo:deleted':
          await offlineDb.todoItems.delete(payload.itemId as number)
          break

        // ── Budget ───────────────────────────────────────────────────────────
        case 'budget:created':
        case 'budget:updated':
          await offlineDb.budgetItems.put(payload.item as BudgetItem)
          break
        case 'budget:deleted':
          await offlineDb.budgetItems.delete(payload.itemId as number)
          break
        case 'budget:members-updated':
        case 'budget:member-paid-updated':
        case 'budget:reordered': {
          // Partial update β€” read canonical item(s) from updated Zustand state
          if (type === 'budget:reordered') {
            await offlineDb.budgetItems.bulkPut(state.budgetItems)
          } else {
            const item = state.budgetItems.find(i => i.id === (payload.itemId as number))
            if (item) await offlineDb.budgetItems.put(item)
          }
          break
        }

        // ── Reservations ─────────────────────────────────────────────────────
        case 'reservation:created':
        case 'reservation:updated':
          await offlineDb.reservations.put(payload.reservation as Reservation)
          break
        case 'reservation:deleted':
          await offlineDb.reservations.delete(payload.reservationId as number)
          break

        // ── Trip ─────────────────────────────────────────────────────────────
        case 'trip:updated':
          await offlineDb.trips.put(payload.trip as Trip)
          break

        // ── Files ─────────────────────────────────────────────────────────────
        case 'file:created':
        case 'file:updated':
          await offlineDb.tripFiles.put(payload.file as TripFile)
          break
        case 'file:deleted':
          await offlineDb.tripFiles.delete(payload.fileId as number)
          break

        default:
          break
      }
    } catch {
      // Dexie write failures are non-fatal β€” online state is source of truth
    }
  })()
}

/** Write a Day (with its current assignments + notes from Zustand) to Dexie. */
async function _writeDayToDb(dayId: number, state: TripStoreState): Promise<void> {
  const day = state.days.find(d => d.id === dayId)
  if (!day) return
  await offlineDb.days.put({
    ...day,
    assignments: state.assignments[String(dayId)] ?? [],
    notes_items: state.dayNotes[String(dayId)] ?? [],
  })
}

// ── Zustand event reducer ─────────────────────────────────────────────────────

/**
 * Applies a remote WebSocket event to the local Zustand store, keeping state in sync across collaborators.
 * Each event type maps to an immutable state update (create/update/delete) for the relevant entity.
 * After the Zustand update, the change is also written through to IndexedDB for offline access.
 */
export function handleRemoteEvent(set: SetState, get: GetState, event: WebSocketEvent): void {
  const { type, ...payload } = event

  set(state => {
    switch (type) {
      // Places
      case 'place:created':
        if (state.places.some(p => p.id === (payload.place as Place).id)) return {}
        return { places: [payload.place as Place, ...state.places] }
      case 'place:updated':
        return {
          places: state.places.map(p => p.id === (payload.place as Place).id ? payload.place as Place : p),
          assignments: Object.fromEntries(
            Object.entries(state.assignments).map(([dayId, items]) => [
              dayId,
              items.map(a => a.place?.id === (payload.place as Place).id ? { ...a, place: payload.place as Place } : a)
            ])
          ),
        }
      case 'place:deleted':
        return {
          places: state.places.filter(p => p.id !== payload.placeId),
          assignments: Object.fromEntries(
            Object.entries(state.assignments).map(([dayId, items]) => [
              dayId,
              items.filter(a => a.place?.id !== payload.placeId)
            ])
          ),
        }

      // Assignments
      case 'assignment:created': {
        const incoming = payload.assignment as Assignment
        const dayKey = String(incoming.day_id)
        const existing = state.assignments[dayKey] || []
        const placeId = incoming.place?.id ?? incoming.place_id

        // Already have this exact assignment id β†’ duplicate broadcast or the
        // echo of an already-committed assignment. No-op.
        if (existing.some(a => a.id === incoming.id)) return {}

        // Reconcile our own optimistic create: replace the temp (negative-id)
        // assignment of the same place on this day with the real one. Guarded on
        // a real placeId so an assignment with no place can never collapse onto
        // another place-less one (undefined === undefined).
        if (placeId != null) {
          const tempIdx = existing.findIndex(a => a.id < 0 && a.place?.id === placeId)
          if (tempIdx !== -1) {
            const next = existing.slice()
            next[tempIdx] = incoming
            return { assignments: { ...state.assignments, [dayKey]: next } }
          }
        }

        // Genuinely new β€” including a legitimate second assignment of a place
        // already on this day (no temp version to reconcile). Append.
        return {
          assignments: {
            ...state.assignments,
            [dayKey]: [...existing, incoming],
          }
        }
      }
      case 'assignment:updated': {
        const dayKey = String((payload.assignment as Assignment).day_id)
        return {
          assignments: {
            ...state.assignments,
            [dayKey]: (state.assignments[dayKey] || []).map(a =>
              a.id === (payload.assignment as Assignment).id ? { ...a, ...(payload.assignment as Assignment) } : a
            ),
          }
        }
      }
      case 'assignment:deleted': {
        const dayKey = String(payload.dayId)
        return {
          assignments: {
            ...state.assignments,
            [dayKey]: (state.assignments[dayKey] || []).filter(a => a.id !== payload.assignmentId),
          }
        }
      }
      case 'assignment:moved': {
        const oldKey = String(payload.oldDayId)
        const newKey = String(payload.newDayId)
        const movedAssignment = payload.assignment as Assignment
        return {
          assignments: {
            ...state.assignments,
            [oldKey]: (state.assignments[oldKey] || []).filter(a => a.id !== movedAssignment.id),
            [newKey]: [...(state.assignments[newKey] || []).filter(a => a.id !== movedAssignment.id), movedAssignment],
          }
        }
      }
      case 'assignment:reordered': {
        const dayKey = String(payload.dayId)
        const currentItems = state.assignments[dayKey] || []
        const orderedIds: number[] = (payload.orderedIds as number[] | undefined) || []
        const reordered = orderedIds.map((id, idx) => {
          const item = currentItems.find(a => a.id === id)
          return item ? { ...item, order_index: idx } : null
        }).filter((item): item is Assignment => item !== null)
        return {
          assignments: {
            ...state.assignments,
            [dayKey]: reordered,
          }
        }
      }

      // Days
      case 'day:created':
        if (state.days.some(d => d.id === (payload.day as Day).id)) return {}
        return { days: [...state.days, payload.day as Day] }
      case 'day:updated':
        return {
          days: state.days.map(d => d.id === (payload.day as Day).id ? payload.day as Day : d),
        }
      case 'day:deleted': {
        const removedDayId = String(payload.dayId)
        const newAssignments = { ...state.assignments }
        delete newAssignments[removedDayId]
        const newDayNotes = { ...state.dayNotes }
        delete newDayNotes[removedDayId]
        return {
          days: state.days.filter(d => d.id !== payload.dayId),
          assignments: newAssignments,
          dayNotes: newDayNotes,
        }
      }
      case 'day:reordered': {
        // Apply the new order instantly when we know all ids; the authoritative
        // dates + re-stamped booking times are pulled by the refresh below.
        const orderedIds = payload.orderedIds as number[] | undefined
        if (!orderedIds || orderedIds.length !== state.days.length) return {}
        const byId = new Map(state.days.map(d => [d.id, d]))
        if (!orderedIds.every(id => byId.has(id))) return {}
        return { days: orderedIds.map((id, i) => ({ ...byId.get(id)!, day_number: i + 1 })) }
      }

      // Day Notes
      case 'dayNote:created': {
        const dayKey = String(payload.dayId)
        const existingNotes = (state.dayNotes[dayKey] || [])
        if (existingNotes.some(n => n.id === (payload.note as DayNote).id)) return {}
        return {
          dayNotes: {
            ...state.dayNotes,
            [dayKey]: [...existingNotes, payload.note as DayNote],
          }
        }
      }
      case 'dayNote:updated': {
        const dayKey = String(payload.dayId)
        return {
          dayNotes: {
            ...state.dayNotes,
            [dayKey]: (state.dayNotes[dayKey] || []).map(n => n.id === (payload.note as DayNote).id ? payload.note as DayNote : n),
          }
        }
      }
      case 'dayNote:deleted': {
        const dayKey = String(payload.dayId)
        return {
          dayNotes: {
            ...state.dayNotes,
            [dayKey]: (state.dayNotes[dayKey] || []).filter(n => n.id !== payload.noteId),
          }
        }
      }

      // Packing
      case 'packing:created':
        if (state.packingItems.some(i => i.id === (payload.item as PackingItem).id)) return {}
        return { packingItems: [...state.packingItems, payload.item as PackingItem] }
      case 'packing:updated':
        return {
          packingItems: state.packingItems.map(i => i.id === (payload.item as PackingItem).id ? payload.item as PackingItem : i),
        }
      case 'packing:deleted':
        return {
          packingItems: state.packingItems.filter(i => i.id !== payload.itemId),
        }

      // Todo
      case 'todo:created':
        if (state.todoItems.some(i => i.id === (payload.item as TodoItem).id)) return {}
        return { todoItems: [...state.todoItems, payload.item as TodoItem] }
      case 'todo:updated':
        return {
          todoItems: state.todoItems.map(i => i.id === (payload.item as TodoItem).id ? payload.item as TodoItem : i),
        }
      case 'todo:deleted':
        return {
          todoItems: state.todoItems.filter(i => i.id !== payload.itemId),
        }

      // Budget
      case 'budget:created':
        if (state.budgetItems.some(i => i.id === (payload.item as BudgetItem).id)) return {}
        return { budgetItems: [...state.budgetItems, payload.item as BudgetItem] }
      case 'budget:updated':
        return {
          budgetItems: state.budgetItems.map(i => i.id === (payload.item as BudgetItem).id ? payload.item as BudgetItem : i),
        }
      case 'budget:deleted':
        return {
          budgetItems: state.budgetItems.filter(i => i.id !== payload.itemId),
        }
      case 'budget:members-updated':
        return {
          budgetItems: state.budgetItems.map(i =>
            i.id === payload.itemId ? { ...i, members: payload.members as BudgetItemMember[], persons: payload.persons as number } : i
          ),
        }
      case 'budget:member-paid-updated':
        return {
          budgetItems: state.budgetItems.map(i =>
            i.id === payload.itemId
              // `paid` arrives over the wire as the raw value the server emits;
              // it's stored verbatim. The member type models it as a number, so
              // narrow without changing the value.
              ? { ...i, members: (i.members || []).map(m => m.user_id === payload.userId ? { ...m, paid: payload.paid as number } : m) }
              : i
          ),
        }
      case 'budget:reordered': {
        if (payload.orderedIds) {
          const orderedIds = payload.orderedIds as number[]
          const byId = new Map(state.budgetItems.map(i => [i.id, i]))
          const reordered = orderedIds.map((id, idx): BudgetItem | null => {
            const item = byId.get(id)
            return item ? { ...item, sort_order: idx } : null
          }).filter((i): i is BudgetItem => i !== null)
          const remaining = state.budgetItems.filter(i => !orderedIds.includes(i.id))
          return { budgetItems: [...reordered, ...remaining] }
        }
        if (payload.orderedCategories) {
          const orderedCategories = payload.orderedCategories as string[]
          const grouped = new Map<string, BudgetItem[]>()
          for (const item of state.budgetItems) {
            const cat = item.category || 'Other'
            if (!grouped.has(cat)) grouped.set(cat, [])
            grouped.get(cat)!.push(item)
          }
          const reordered: BudgetItem[] = []
          for (const cat of orderedCategories) {
            const items = grouped.get(cat)
            if (items) reordered.push(...items)
          }
          for (const [cat, items] of grouped) {
            if (!orderedCategories.includes(cat)) reordered.push(...items)
          }
          return { budgetItems: reordered }
        }
        return {}
      }

      // Reservations
      case 'reservation:created':
        if (state.reservations.some(r => r.id === (payload.reservation as Reservation).id)) return {}
        return { reservations: [payload.reservation as Reservation, ...state.reservations] }
      case 'reservation:updated':
        return {
          reservations: state.reservations.map(r => r.id === (payload.reservation as Reservation).id ? payload.reservation as Reservation : r),
        }
      case 'reservation:deleted':
        return {
          reservations: state.reservations.filter(r => r.id !== payload.reservationId),
        }

      // Trip
      case 'trip:updated':
        return { trip: payload.trip as Trip }

      // Files
      case 'file:created':
        if (state.files.some(f => f.id === (payload.file as TripFile).id)) return {}
        return { files: [payload.file as TripFile, ...state.files] }
      case 'file:updated':
        return {
          files: state.files.map(f => f.id === (payload.file as TripFile).id ? payload.file as TripFile : f),
        }
      case 'file:deleted':
        return {
          files: state.files.filter(f => f.id !== payload.fileId),
        }

      // Memories / Photos
      case 'memories:updated':
        window.dispatchEvent(new CustomEvent('memories:updated', { detail: payload }))
        return {}

      default:
        return {}
    }
  })

  // A reorder/insert re-pins dates and re-stamps booking times server-side, so
  // pull the authoritative days + reservations for collaborators.
  if (type === 'day:reordered') {
    const tripId = get().trip?.id
    if (tripId) {
      get().refreshDays(tripId)
      get().loadReservations(tripId)
    }
  }

  // Write the change through to IndexedDB using the post-update state
  writeToDexie(type, payload as Record<string, unknown>, get())
}