Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

41.1 KB
Raw Blame
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type ReactNode } from 'react'
import { Outlet, useSearchParams } from 'react-router'
import { BookOpen, ChevronLeft, MapPin, Grid3x3, Map as MapIcon, MoreHorizontal, Play, Image, Camera, EyeOff, Satellite, Settings2, X, Route, ListChecks } from 'lucide-react'
import JourneyLayeredMap from '../../../components/Journey/JourneyLayeredMap'
import type { BaseLayer } from '../../../components/Map/MapLayerSwitcher'
import PhotoLightbox from '../../../components/Journey/PhotoLightbox'
import ContributorInviteDialog from '../../../components/Journey/ContributorInviteDialog'
import ConfirmDialog from '../../../components/shared/ConfirmDialog'
import { ProviderPicker } from '../../../components/Journey/JourneyDetailPageProviderPicker'
import { photoUrl, posterlessVideo } from '../../../pages/journeyDetail/JourneyDetailPage.helpers'
import { useJourneyDetail, type JourneyDetailOptions } from '../../../pages/journeyDetail/useJourneyDetail'
import { useJourneyStore } from '../../../store/journeyStore'
import { useAddonStore } from '../../../store/addonStore'
import DawarichIcon from '../../../components/shared/DawarichIcon'
import DawarichSuggestionsPanel from '../../../components/Dawarich/DawarichSuggestionsPanel'
import { FormSheetHeader } from '../trip/sheets/PlSheetChrome'
import type { JourneyEntry, GalleryPhoto } from '../../../store/journeyStore'
import { useAuthStore } from '../../../store/authStore'
import { journeyApi, addonsApi, memoriesApi } from '../../../api/client'
import MSheet from '../../components/MSheet'
import MDancingTrek from '../../components/MDancingTrek'
import MListRow from '../../components/MListRow'
import MToggle from '../../components/MToggle'
import JourneyEntryCover from '../../../components/Journey/JourneyEntryCover'
import JourneyDayScrubber from '../../../components/Journey/JourneyDayScrubber'
import { dayColorOf } from '../../../components/Journey/journeyCard'
import { useJourneyCarouselSync } from '../../../components/Journey/useJourneyCarouselSync'
import { useGalleryUpload } from '../../../components/Journey/useGalleryUpload'
import { dayPrepText, dayPrepUnsettled } from '../../../components/Journey/journeyRecordingPrepModel'
import MJourneyEntrySheet from './MJourneyEntrySheet'
import { useIsSplit, useIsWide } from '../../../hooks/sizeClass'
import MJourneyFeed from './MJourneyFeed'
import MJourneySettingsSheet from './MJourneySettingsSheet'
import MJourneyDayImportSheet from './MJourneyDayImportSheet'
import MJourneyRecordingSheet from './MJourneyRecordingSheet'
import { createPortal } from 'react-dom'
import { useTabHeadSlot } from '../trip/tabHeadSlot'
import MSkeleton from '../../components/MSkeleton'

/**
 * Journey detail — integrated map with the horizontal 280px card timeline
 * (Journey tab) and the 2-column photo gallery (Gallery tab). Cards and map
 * markers stay in sync; tapping the centered card opens the entry sheet.
 *
 * A trip that links the journal shows this same screen in its own tab
 * (`embedded`): the trip's back button and controls sit on top, so the screen
 * drops its own back button and leaves the trip's URL alone.
 */
/**
 * A phone on its side, or a folded Duo on its side (about 540px high): too short
 * for the regular strip of cards and the map above it. Higher than the shell's
 * 500px for that Duo, whose regular cards left the map a band under the header.
 */
const SHORT_WINDOW = '(max-height: 600px)'
function subscribeShort(onChange: () => void) {
  const mq = window.matchMedia(SHORT_WINDOW)
  mq.addEventListener('change', onChange)
  return () => mq.removeEventListener('change', onChange)
}
const readShort = () => window.matchMedia(SHORT_WINDOW).matches

export default function MJourneyDetail({ journeyId, embedded = false }: JourneyDetailOptions = {}) {
  // Larger cards on a wide window, where the strip has the room for the whole name.
  const wide = useIsWide()
  // With room for two panes the entries stand as a feed beside the map (MJourneyFeed)
  // instead of the strip of cards over it.
  const split = useIsSplit()
  // On a short window the cards are smaller and the map is framed above them.
  const short = useSyncExternalStore(subscribeShort, readShort, () => false)
  // The map runs under the rail (m-bleed); framing keeps the journey clear of it.
  // The rail's share is the root's own negative margin, as the browser resolves it.
  const rootRef = useRef<HTMLDivElement>(null)
  const [railInset, setRailInset] = useState(0)
  useLayoutEffect(() => {
    const root = rootRef.current
    if (root) setRailInset(Math.max(0, -parseFloat(getComputedStyle(root).marginInlineStart) || 0))
  }, [wide])
  const {
    id, navigate, toast, t, locale,
    current, loading,
    canEditEntries, canEditJourney,
    view, setView,
    editingEntry, setEditingEntry,
    lightbox, setLightbox, deleteTarget, setDeleteTarget,
    showInvite, setShowInvite,
    showSettings, setShowSettings,
    hideSkeletons, setHideSkeletons,
    sidebarMapItems, tracks, mapLayers, entryTitleOf, mapPhotos, openMapPhotos, recordings, canTakeOverRecording, dayImport, dayImportDates, dawarichByDate, recordingPrep,
    dismissSuggestion, restoreSuggestions, openAtEntryId,
    loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos,
    addPickedProviderPhotos, addEntryProviderPhotos, writeAboutPlace,
  } = useJourneyDetail({ journeyId, embedded })
  // A trip tab: the header goes into the trip shell's top row (tabHeadSlot.ts).
  const shellSlot = useTabHeadSlot()
  const headSlot = embedded ? shellSlot : null

  // The dock's FAB is a sibling of this screen: on the Gallery it becomes the
  // upload button, so it has to know which tab is open — and it stops knowing
  // when this screen goes away.
  const setMobileGalleryOpen = useJourneyStore(state => state.setMobileGalleryOpen)
  useEffect(() => {
    setMobileGalleryOpen(view === 'gallery')
    return () => setMobileGalleryOpen(false)
  }, [view, setMobileGalleryOpen])

  const dayImportRow = (date: string, closeMenu: () => void) => {
    const waiting = dawarichByDate.get(date)?.length ?? 0
    const prep = recordingPrep.dayPrep(date)
    const unsettled = dayPrepUnsettled(prep)
    return (
      <MListRow
        key={date}
        icon={ListChecks}
        label={t('journey.dayImport.openOn', {
          date: new Date(date + 'T00:00:00').toLocaleDateString(locale, { day: 'numeric', month: 'long' }),
        })}
        trailing={waiting > 0 || unsettled ? (
          <span className="inline-flex items-center gap-1.5">
            {unsettled && prep && (
              <span className="h-1.5 w-1.5 rounded-full bg-warning" role="img" aria-label={dayPrepText(prep, t, locale)} />
            )}
            {waiting > 0 && (
              <span className="rounded-full bg-m-ic px-2 py-0.5 font-geist text-caption font-bold tabular-nums text-m-muted">
                {waiting}
              </span>
            )}
          </span>
        ) : undefined}
        onClick={() => { closeMenu(); dayImport.open(date) }}
      />
    )
  }

  // Stable identity: the scroll effect in useJourneyCarouselSync re-attaches on every
  // change and would otherwise drop the pending settle timer on any unrelated render.
  const entries = useMemo(
    () => (current?.entries || []).filter(e => !hideSkeletons || e.type !== 'skeleton'),
    [current?.entries, hideSkeletons],
  )

  // An existing entry opens to be read, also for those who may edit it (#3007);
  // the pencil in its sheet switches to the editor. New entries and suggestions
  // open in the editor straight away.
  const [editEntryId, setEditEntryId] = useState<number | null>(null)
  const readingEntry = !!editingEntry && canEditEntries && editingEntry.id !== 0
    && editingEntry.type !== 'skeleton' && editEntryId !== editingEntry.id

  const {
    mapRef, carouselRef, cardRefs, activeIndex, focusIndex, setActiveIndex, scrubberDays,
    syncMapToCard, handleMarkerClick, handleCardTap, openEntryById, jumpToDay,
  } = useJourneyCarouselSync<JourneyEntry>({
    entries, mapEntries: sidebarMapItems, onOpenEntry: setEditingEntry, syncMapOnTap: true, layoutKey: split,
  })
  const feed = split && view === 'timeline' && entries.length > 0

  // The map's box changes when the feed comes or goes (a rotation, Split View).
  useEffect(() => {
    const timer = window.setTimeout(() => mapRef.current?.invalidateSize(), 320)
    return () => window.clearTimeout(timer)
  }, [feed, mapRef])

  // Initial focus — give Leaflet time to initialise and fit bounds first. Opens on
  // today when today is part of the journey (see openAtEntryId), rather than always
  // at the first entry (discussion #2299).
  useEffect(() => {
    if (entries.length === 0) return
    const target = openAtEntryId ? entries.findIndex(e => String(e.id) === openAtEntryId) : -1
    const index = target === -1 ? 0 : target
    const timer = window.setTimeout(() => {
      setActiveIndex(index)
      syncMapToCard(index)
      if (index > 0) cardRefs.current.get(index)?.scrollIntoView({ inline: 'center', block: 'nearest' })
    }, 500)
    return () => window.clearTimeout(timer)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [entries.length, openAtEntryId])

  /**
   * Move an entry within its day, from the entry sheet's header.
   *
   * Same rules as the desktop arrows: suggestions do not take part, because they
   * are the trip's order rather than the traveller's, and a day with one entry
   * has nothing to reorder. The whole day goes back to the server, which is what
   * the reorder endpoint expects.
   */
  const moveWithinDay = useCallback(async (entry: JourneyEntry, direction: -1 | 1) => {
    if (!current) return
    const sameDay = entries.filter(e => e.entry_date === entry.entry_date && e.type !== 'skeleton')
    const index = sameDay.findIndex(e => e.id === entry.id)
    const target = index + direction
    if (index === -1 || target < 0 || target >= sameDay.length) return
    const reordered = [...sameDay]
    const [moved] = reordered.splice(index, 1)
    reordered.splice(target, 0, moved)
    try {
      await reorderEntries(current.id, reordered.map(e => e.id))
      await loadJourney(current.id)
    } catch {
      toast.error(t('common.errorTitle'))
    }
  }, [current, entries, reorderEntries, loadJourney, toast, t])

  /** Where in the day's run an entry sits, so the sheet knows which arrows to offer. */
  const dayNeighbours = useCallback((entry: JourneyEntry) => {
    const sameDay = entries.filter(e => e.entry_date === entry.entry_date && e.type !== 'skeleton')
    const index = sameDay.findIndex(e => e.id === entry.id)
    return { canMoveUp: index > 0, canMoveDown: index >= 0 && index < sameDay.length - 1 }
  }, [entries])

  // Gallery upload — device files plus the connected photo providers (Immich/Synology).
  const galleryFileRef = useRef<HTMLInputElement>(null)
  const [availableProviders, setAvailableProviders] = useState<{ id: string; name: string }[]>([])
  // Whether the probe below has finished — not whether it found anything.
  const [providersReady, setProvidersReady] = useState(false)
  const [showUploadMenu, setShowUploadMenu] = useState(false)
  // The map's base, switched from the bar: the satellite imagery or the map (#2594).
  const [mapBase, setMapBase] = useState<BaseLayer>('default')
  const [showActionMenu, setShowActionMenu] = useState(false)
  const [pickerProvider, setPickerProvider] = useState<string | null>(null)
  // The gallery photo waiting on its delete confirm; entries have their own deleteTarget.
  const [photoDeleteTarget, setPhotoDeleteTarget] = useState<GalleryPhoto | null>(null)
  const deleteGalleryPhoto = useJourneyStore(state => state.deleteGalleryPhoto)
  const dawarichEnabled = useAddonStore(state => state.isEnabled)('dawarich')
  const [dawarichOpen, setDawarichOpen] = useState(false)
  /**
   * How tall the card rail over the dock currently is.
   *
   * Measured rather than written down: the rail is a day scrubber over a row of covers,
   * and a cover grows from 152 to 180px when it becomes the active one. The Dawarich
   * button above it used to clear a hard-coded 128px, which was short of the rail on any
   * screen and left the button sitting over the cards. Zero while there is no rail, which
   * is also the empty-journal case, and the button then sits straight above the dock.
   */
  const [railHeight, setRailHeight] = useState(0)
  const railRef = useRef<HTMLDivElement>(null)
  const { uploading, handleGalleryUpload } = useGalleryUpload({
    journeyId: current?.id ?? null,
    onUploaded: () => loadJourney(Number(id)),
    toast,
    t,
  })

  useEffect(() => {
    const node = railRef.current
    if (!node) { setRailHeight(0); return }
    // Observed rather than read once: the rail changes height when the active card grows,
    // and a height read at mount would be the wrong one from the first swipe onwards.
    if (typeof ResizeObserver === 'undefined') { setRailHeight(node.offsetHeight); return }
    const observer = new ResizeObserver(() => setRailHeight(node.offsetHeight))
    observer.observe(node)
    setRailHeight(node.offsetHeight)
    return () => observer.disconnect()
  }, [view, entries.length, split])

  const openUpload = useCallback(() => {
    if (availableProviders.length > 0) setShowUploadMenu(true)
    else galleryFileRef.current?.click()
  }, [availableProviders.length])

  // The dock's FAB asks through the URL, the way every other "+" in the shell
  // does. The parameter is cleared straight away so going back does not reopen
  // the picker; the intent is held in state until the provider probe has
  // answered, because "device or Immich?" cannot be asked before we know
  // whether there is an Immich.
  const [params, setParams] = useSearchParams()
  const [pendingUpload, setPendingUpload] = useState(false)
  useEffect(() => {
    if (embedded || params.get('create') !== 'photo') return
    setParams(prev => {
      const next = new URLSearchParams(prev)
      next.delete('create')
      return next
    }, { replace: true })
    if (!canEditEntries) return
    setView('gallery')
    setPendingUpload(true)
  }, [params, setParams, canEditEntries, setView, embedded])

  useEffect(() => {
    if (!pendingUpload || !providersReady) return
    setPendingUpload(false)
    openUpload()
  }, [pendingUpload, providersReady, openUpload])

  useEffect(() => {
    let active = true
    ;void (async () => {
      try {
        const addonsData = await addonsApi.enabled()
        const enabled = (addonsData.addons || []).filter(
          (a: { type: string; enabled: boolean }) => a.type === 'photo_provider' && a.enabled,
        )
        const connected: { id: string; name: string }[] = []
        for (const p of enabled) {
          // The probes run one after another, so leaving the screen has to stop
          // the queue rather than let every remaining provider be asked anyway.
          if (!active) return
          try {
            // Same probe the desktop gallery uses, so a NAS cannot read as
            // connected on one surface and not the other.
            if ((await memoriesApi.status(p.id)).connected) connected.push({ id: p.id, name: p.name })
          } catch { /* provider stays hidden */ }
        }
        if (active) setAvailableProviders(connected)
      } catch { /* no providers */ }
      finally { if (active) setProvidersReady(true) }
    })()
    return () => { active = false }
  }, [])

  const openLightbox = (photos: GalleryPhoto[], index: number) => {
    setLightbox({
      photos: photos.map(p => ({
        id: p.id,
        src: photoUrl(p, 'original'),
        thumbSrc: photoUrl(p, 'thumbnail'),
        caption: p.caption ?? null,
        provider: p.provider,
        asset_id: p.asset_id,
        owner_id: p.owner_id,
        mediaType: p.media_type,
      })),
      index,
    })
  }

  if (loading || !current) {
    return (
      <MSkeleton variant="detail" className="h-dvh overflow-hidden" />
    )
  }

  const gallery = current.gallery || []
  const dark = document.documentElement.classList.contains('dark')

  // The suggestions switch used to be desktop-only (#1848). It lives in the
  // header overflow sheet here, together with the settings entry, so the header
  // keeps a single "more" affordance.
  //
  // There is no book export here any more: the book is a Studio document now,
  // and Studio needs the room of a desktop, an iPad on its side or an unfolded
  // Duo (split), where the header offers it. A phone-sized PDF of a book laid
  // out for print was the old export's answer to a question nobody was asking.
  const toggleSkeletons = async (next: boolean) => {
    setHideSkeletons(next)
    try {
      await journeyApi.updatePreferences(current.id, { hide_skeletons: next })
    } catch {
      /* cosmetic preference — the local flip stands until the next load */
    }
  }

  return (
    // h-dvh, not h-full: the shell stopped providing a definite height (#1809)
    // and a map on a percentage of an auto-height parent collapses to zero.
    <div ref={rootRef} className="m-bleed relative h-dvh overflow-hidden" style={headSlot ? IN_SHELL_ROW : undefined}>
      {/* Integrated map — always mounted, the gallery overlays it. Beside the feed
          it begins where the feed ends, so its controls and its framing stay in
          the part that can be seen. */}
      <div
        className="absolute inset-y-0 end-0 start-0 z-0"
        style={feed ? { insetInlineStart: 'calc(var(--m-rail-w, 0px) + var(--m-pane-aside-w))' } : undefined}
      >
        <JourneyLayeredMap
          ref={mapRef}
          layers={mapLayers}
          hideLayerControl
          controlsTop="calc(var(--m-safe-top, 12px) + 50px)"
          // Its satellite switch sits in the bar above, beside the menu.
          baseLayer={mapBase}
          onOpenEntry={handleMarkerClick}
          onWriteAboutPlace={writeAboutPlace}
          entryTitleOf={entryTitleOf}
          checkins={[]}
          entries={sidebarMapItems}
          tracks={tracks}
          photos={mapPhotos}
          onPhotoClick={openMapPhotos}
          height={9999}
          dark={dark}
          activeMarkerId={entries[activeIndex] ? String(entries[activeIndex].id) : null}
          onMarkerClick={handleMarkerClick}
          onMarkerCardClick={openEntryById}
          fullScreen
          paddingBottom={short ? 280 : 250}
          paddingStart={feed ? 0 : railInset}
        />
      </div>

      {/* Gallery tab overlay */}
      {view === 'gallery' && (
        <div className="m-span-x absolute inset-y-0 z-[5] overflow-y-auto bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] px-4 pt-[calc(var(--m-safe-top,12px)+56px)] pb-[calc(var(--bottom-nav-h,84px)+16px)] wide:px-6">
          {gallery.length === 0 ? (
            <div className="flex min-h-full flex-col items-center justify-center px-8 py-10 text-center">
              <MDancingTrek scene="journey" className="mb-2" />
              <p className="font-geist text-[0.8125rem] font-medium text-m-muted">{t('journey.detail.noPhotos')}</p>
            </div>
          ) : (
            <div className="grid grid-cols-2 gap-2 wide:grid-cols-[repeat(auto-fill,minmax(180px,1fr))] wide:gap-3">
              {gallery.map((photo, i) => (
                // A wrapper, not one button: the delete sits beside the tile's own
                // button instead of inside it (#2593).
                <div key={photo.id} className="relative aspect-square overflow-hidden rounded-[14px]">
                  <button
                    type="button"
                    onClick={() => openLightbox(gallery, i)}
                    className="relative block h-full w-full"
                  >
                    {posterlessVideo(photo) ? (
                      <span className="block h-full w-full bg-[color:var(--m-ic)]" />
                    ) : (
                      <img src={photoUrl(photo, 'thumbnail')} alt={photo.caption || ''} loading="lazy" className="h-full w-full object-cover" />
                    )}
                    {photo.media_type === 'video' && (
                      <span className="pointer-events-none absolute inset-0 flex items-center justify-center">
                        <span className="flex h-9 w-9 items-center justify-center rounded-full bg-black/55 text-white backdrop-blur">
                          <Play size={16} className="ml-[2px]" fill="currentColor" />
                        </span>
                      </span>
                    )}
                  </button>
                  {canEditEntries && (
                    <button
                      type="button"
                      onClick={() => setPhotoDeleteTarget(photo)}
                      aria-label={t('common.delete')}
                      className="absolute end-[6px] top-[6px] flex h-7 w-7 items-center justify-center rounded-full bg-[color:var(--overlay)] text-[color:var(--m-knob)] backdrop-blur"
                    >
                      <X size={13} />
                    </button>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* The entries as a feed beside the map, on a window with room for two panes. */}
      {feed && (
        <div
          className="absolute inset-y-0 z-[6] overflow-y-auto overflow-x-hidden border-e border-[color:var(--m-rowbr)] bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] px-4 pb-[calc(var(--bottom-nav-h,84px)+16px)] pt-[calc(var(--m-safe-top,12px)+60px)]"
          // Entries scrolled up fade out under the header's pills instead of showing through between them:
          // gone down to the pills' lower edge (38px tall), whole again before the first day's head.
          style={{
            insetInlineStart: 'var(--m-rail-w, 0px)',
            width: 'var(--m-pane-aside-w)',
            maskImage: 'linear-gradient(180deg, transparent calc(var(--m-safe-top, 12px) + 40px), #000 calc(var(--m-safe-top, 12px) + 60px))',
          }}
        >
          <MJourneyFeed
            entries={entries}
            days={scrubberDays}
            activeIndex={activeIndex}
            cardRefs={cardRefs}
            onCardTap={handleCardTap}
            showMood={current.show_mood !== 0}
            showWeather={current.show_weather !== 0}
            t={t}
            locale={locale}
          />
        </div>
      )}

      {/* Header: back — segment — upload / overflow menu. Beside the feed it keeps
          to the feed, as the trip's controls keep to its pane. */}
      <HeaderFrame slot={headSlot} feed={!!feed}>
        {embedded ? (
          <span className="w-[38px] flex-none" aria-hidden />
        ) : (
          <button
            type="button"
            onClick={() => navigate('/journey')}
            aria-label={t('journey.detail.backToJourney')}
            className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-full bg-[color:var(--m-sheet)] text-m-ink shadow-[0_5px_14px_-6px_rgba(0,0,0,.3)]"
          >
            <ChevronLeft size={18} strokeWidth={2.2} className="rtl:-scale-x-100" />
          </button>
        )}
        <div
          data-view-switch
          className="absolute left-1/2 top-0 flex -translate-x-1/2 rounded-full wide:static wide:translate-x-0 bg-[color:var(--m-sheet)] p-[3px] shadow-[0_5px_14px_-6px_rgba(0,0,0,.3)]"
        >
          <button
            type="button"
            onClick={() => setView('timeline')}
            className={`flex items-center gap-[5px] rounded-full px-[13px] py-[6px] text-[0.75rem] font-bold ${
              view === 'timeline' ? 'bg-m-act text-m-actfg' : 'text-m-muted'
            }`}
          >
            <MapPin size={13} strokeWidth={2.2} />
            {t('journey.detail.journeyTab')}
          </button>
          <button
            type="button"
            onClick={() => setView('gallery')}
            className={`flex items-center gap-[5px] rounded-full px-[13px] py-[6px] text-[0.75rem] font-bold ${
              view === 'gallery' ? 'bg-m-act text-m-actfg' : 'text-m-muted'
            }`}
          >
            <Grid3x3 size={13} strokeWidth={2.2} />
            {t('journey.share.gallery')}
          </button>
        </div>
        <span className="ms-auto flex flex-none items-center gap-2">
          {/* Uploading lives on the dock's FAB while the Gallery is open — the
              one big action on the screen. A second button up here would be the
              same thing twice, so it only appears while an upload is running,
              as its progress. */}
          {view === 'gallery' && canEditEntries && uploading && (
            <span
              role="status"
              aria-label={t('common.upload')}
              className="flex h-[38px] w-[38px] items-center justify-center rounded-full bg-m-act text-m-actfg shadow-[0_5px_14px_-6px_rgba(0,0,0,.3)]"
            >
              <span className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
            </span>
          )}
          {split && (
            <button
              type="button"
              onClick={() => void navigate(`/journey/${current.id}/studio`)}
              aria-label={t('journey.studio.openAria')}
              className="flex h-[38px] w-[38px] items-center justify-center rounded-full bg-[color:var(--m-sheet)] text-m-ink shadow-[0_5px_14px_-6px_rgba(0,0,0,.3)]"
            >
              <BookOpen size={17} strokeWidth={2} />
            </button>
          )}
          {view === 'timeline' && (
            <button
              type="button"
              onClick={() => setMapBase((was) => (was === 'satellite' ? 'default' : 'satellite'))}
              aria-pressed={mapBase === 'satellite'}
              aria-label={t(mapBase === 'satellite' ? 'map.baseLayer.switchToDefault' : 'map.baseLayer.switchToSatellite')}
              className={`flex h-[38px] w-[38px] items-center justify-center rounded-full shadow-[0_5px_14px_-6px_rgba(0,0,0,.3)] ${mapBase === 'satellite' ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-sheet)] text-m-ink'}`}
            >
              {mapBase === 'satellite' ? <MapIcon size={17} strokeWidth={2} /> : <Satellite size={17} strokeWidth={2} />}
            </button>
          )}
          <button
            type="button"
            onClick={() => setShowActionMenu(true)}
            aria-label={t('files.menu')}
            className="flex h-[38px] w-[38px] items-center justify-center rounded-full bg-[color:var(--m-sheet)] text-m-ink shadow-[0_5px_14px_-6px_rgba(0,0,0,.3)]"
          >
            <MoreHorizontal size={17} strokeWidth={2} />
          </button>
        </span>
      </HeaderFrame>

      {/* The stays Dawarich recorded for these dates, as candidate entries. Over
          the map rather than in the header: it belongs to what is on the map,
          and the header is already three controls wide on a phone. Sits above
          the card rail so it never covers the card somebody is reading. */}
      {dawarichEnabled && canEditEntries && view === 'timeline' && (
        <button
          type="button"
          onClick={() => setDawarichOpen(true)}
          aria-label={t('dawarich.suggestions.title')}
          className="absolute right-4 z-[9] flex h-[46px] w-[46px] items-center justify-center overflow-hidden rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] shadow-[0_6px_18px_-8px_rgba(0,0,0,.35)]"
          // The rail's own offset over the dock, its measured height, then a gap. The 128px
          // this used to guess at was short of the rail, so the button lay on the cards.
          style={{ bottom: `calc(var(--bottom-nav-h, 84px) + 2px + ${railHeight}px + 12px)` }}
        >
          <DawarichIcon size={46} />
        </button>
      )}

      {dawarichOpen && current && (
        <MSheet open onClose={() => setDawarichOpen(false)} variant="bottom" material="glass" ariaLabel={t('dawarich.suggestions.title')}>
          <div className="flex max-h-[82dvh] min-h-0 flex-col">
            <FormSheetHeader
              leading={
                <span className="flex h-10 w-10 flex-none overflow-hidden rounded-[13px]">
                  <DawarichIcon size={40} />
                </span>
              }
              title={t('dawarich.suggestions.title')}
              onClose={() => setDawarichOpen(false)}
              closeLabel={t('common.close')}
            />
            <div className="min-h-0 flex-1 overflow-y-auto px-[14px] pb-4">
              {/* Whole days first: a day with stays and nothing written yet is reached
                  from here, since it has no card to open the overflow menu on. */}
              {dayImportDates.length > 0 && (
                <div className="mb-2 flex flex-col border-b border-[color:var(--m-gbr)] pb-2">
                  {dayImportDates.map(date => dayImportRow(date, () => setDawarichOpen(false)))}
                </div>
              )}
              {/* Journal entries and nothing else: a journey is for writing, and
                  the trip planner already offers the same stay as a place. */}
              <DawarichSuggestionsPanel
                bare
                journals={[{ id: current.id, label: current.title }]}
                onAccepted={() => { void loadJourney(current.id) }}
              />
            </div>
          </div>
        </MSheet>
      )}

      {/* Day bar + horizontal card timeline. The dock is a floating pill 62px tall
          inside the 84px the variable reserves, so +16 left a band of map doing
          nothing between the cards and it; two pixels keeps a hair of daylight and
          gives the strip the rest. */}
      {view === 'timeline' && entries.length > 0 && !feed && (
        <div ref={railRef} className="m-span-x absolute z-[8] bottom-[calc(var(--bottom-nav-h,84px)+2px)]">
        {/* The days and the date on a plate of their own, so the map's names do
            not run through them. */}
        <div className="mx-3 rounded-[18px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] pt-[6px] backdrop-blur-[18px] backdrop-saturate-[1.4] empty:hidden">
          <JourneyDayScrubber
            days={scrubberDays}
            activeDate={entries[activeIndex]?.entry_date ?? null}
            onPick={jumpToDay}
          />
        </div>
        <div
          ref={carouselRef}
          className={`flex items-end gap-[22px] overflow-x-auto px-6 pb-1 ${short ? 'pt-[22px]' : 'pt-[30px]'} [-webkit-overflow-scrolling:touch] [scrollbar-width:none]`}
          style={{ scrollSnapType: 'x mandatory' }}
        >
          {entries.map((entry, i) => (
            <div
              key={entry.id}
              ref={node => { if (node) cardRefs.current.set(i, node); else cardRefs.current.delete(i) }}
              style={{ scrollSnapAlign: 'center' }}
            >
              <JourneyEntryCover
                entry={entry}
                dayColor={dayColorOf(scrubberDays, entry.entry_date)}
                isActive={i === focusIndex}
                onClick={() => handleCardTap(entry, i)}
                showMood={current.show_mood !== 0}
                showWeather={current.show_weather !== 0}
                tone="mobile"
                // Short before wide: a folded Duo on its side is wide (over 500px high) and short.
                size={short ? 'compact' : wide ? 'large' : 'regular'}
              />
            </div>
          ))}
        </div>
        </div>
      )}

      <input ref={galleryFileRef} type="file" accept="image/*,video/*" multiple className="hidden" onChange={handleGalleryUpload} />

      {/* Upload source chooser (device / providers) */}
      {/* Opaque, not the glass default: these two sit over a full-screen map whose
          card carousel is bright and busy, and the frosted material let the titles
          behind read straight through the menu. */}
      <MSheet open={showUploadMenu} onClose={() => setShowUploadMenu(false)} variant="bottom" material="glass" ariaLabel={t('common.upload')}>
        <div className="flex flex-col gap-2 p-[10px]">
          <MListRow
            icon={Camera}
            label={t('mobileJourney.uploadFromDevice')}
            onClick={() => { setShowUploadMenu(false); galleryFileRef.current?.click() }}
          />
          {availableProviders.map(p => (
            <MListRow
              key={p.id}
              icon={Image}
              label={t('mobileJourney.browseProvider', { name: p.name })}
              onClick={() => { setShowUploadMenu(false); setPickerProvider(p.id) }}
            />
          ))}
        </div>
      </MSheet>

      {/* Journey actions: book export, suggestions switch, settings */}
      <MSheet open={showActionMenu} onClose={() => setShowActionMenu(false)} variant="bottom" material="glass" ariaLabel={t('files.menu')}>
        <div className="flex flex-col gap-1 p-[10px]">
          <div className="flex items-center gap-[11px] px-[10px] py-[11px]">
            <EyeOff size={16} strokeWidth={2} className="flex-none text-m-muted" />
            <span className="min-w-0 flex-1 truncate text-[0.84375rem] font-semibold">{t('journey.skeletons.hide')}</span>
            <MToggle checked={hideSkeletons} onChange={toggleSkeletons} ariaLabel={t('journey.skeletons.hide')} />
          </div>
          {/* The recorded route of the day the card rail is on (JRN-01): taking it
              over, or checking, replacing or dropping the one kept. */}
          {canEditEntries && view === 'timeline' && entries[activeIndex] &&
            (canTakeOverRecording || recordings.byDate.has(entries[activeIndex].entry_date)) && (
            <MListRow
              icon={Route}
              label={t('journey.recording.takeOverDay', {
                date: new Date(entries[activeIndex].entry_date + 'T00:00:00').toLocaleDateString(locale, { day: 'numeric', month: 'long' }),
              })}
              onClick={() => { setShowActionMenu(false); recordings.open(entries[activeIndex].entry_date) }}
            />
          )}
          {/* The same day with its stays (JRN-02), counting the ones still waiting. */}
          {canEditEntries && canTakeOverRecording && view === 'timeline' && entries[activeIndex] &&
            dayImportRow(entries[activeIndex].entry_date, () => setShowActionMenu(false))}
          {canEditJourney && (
            <MListRow
              icon={Settings2}
              label={t('journey.settings.title')}
              onClick={() => { setShowActionMenu(false); setShowSettings(true) }}
            />
          )}
        </div>
      </MSheet>

      {/* Entry sheet (new / edit / read-only) */}
      {editingEntry && (
        <MJourneyEntrySheet
          entry={editingEntry}
          galleryPhotos={gallery}
          quickCapture={editingEntry.id === 0}
          readOnly={!canEditEntries || readingEntry}
          onEdit={readingEntry ? () => setEditEntryId(editingEntry.id) : undefined}
          showVerdict={current.show_verdict !== 0}
          showMood={current.show_mood !== 0}
          showWeather={current.show_weather !== 0}
          userId={useAuthStore.getState().user?.id || 0}
          trips={current.trips}
          photoProviders={availableProviders}
          onMoveEarlier={
            canEditEntries && !readingEntry && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveUp
              ? () => { void moveWithinDay(editingEntry, -1) }
              : undefined
          }
          onMoveLater={
            canEditEntries && !readingEntry && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveDown
              ? () => { void moveWithinDay(editingEntry, 1) }
              : undefined
          }
          onDismiss={
            canEditEntries && editingEntry.type === 'skeleton' && editingEntry.id !== 0
              ? () => { setEditingEntry(null); void dismissSuggestion(editingEntry) }
              : undefined
          }
          onClose={() => { setEditingEntry(null); setEditEntryId(null) }}
          onSave={async (data, existingEntryId) => {
            // existingEntryId is what the sheet already persisted in an earlier
            // save attempt — without it a retry would create a second entry.
            const currentEntryId = existingEntryId ?? editingEntry.id
            let entryId = currentEntryId
            if (currentEntryId === 0) {
              const created = await useJourneyStore.getState().createEntry(current.id, data)
              entryId = created.id
            } else {
              await updateEntry(currentEntryId, data)
            }
            return entryId
          }}
          onUploadPhotos={uploadPhotos}
          onAddProviderPhotos={addEntryProviderPhotos}
          onDelete={editingEntry.id > 0 && canEditEntries
            ? () => { const target = editingEntry; setEditingEntry(null); setDeleteTarget(target) }
            : undefined}
          onDone={() => {
            setEditingEntry(null)
            loadJourney(Number(id))
          }}
        />
      )}

      {recordings.dialog && <MJourneyRecordingSheet {...recordings.dialog} />}
      {dayImport.dialog && <MJourneyDayImportSheet {...dayImport.dialog} prep={recordingPrep.prep ? recordingPrep : undefined} />}

      {/* Journey settings */}
      {showSettings && (
        <MJourneySettingsSheet
          journey={current}
          onClose={() => setShowSettings(false)}
          onSaved={() => { setShowSettings(false); loadJourney(Number(id)) }}
          onOpenInvite={() => setShowInvite(true)}
          onRefresh={() => loadJourney(Number(id))}
          onRestoreSuggestions={canEditEntries ? restoreSuggestions : undefined}
          recordingPrep={recordingPrep.prep ? recordingPrep : undefined}
        />
      )}

      {/* Contributor invite */}
      {showInvite && (
        <ContributorInviteDialog
          journeyId={current.id}
          existingUserIds={current.contributors.map(c => c.user_id)}
          onClose={() => setShowInvite(false)}
          onInvited={() => { setShowInvite(false); loadJourney(Number(id)) }}
        />
      )}

      {/* Provider photo picker (Immich / Synology) */}
      {pickerProvider && (
        <ProviderPicker
          provider={pickerProvider}
          userId={useAuthStore.getState().user?.id || 0}
          entries={current.entries.filter(e => e.type !== 'skeleton' || e.title)}
          trips={current.trips}
          existingAssetIds={new Set(gallery.filter(p => p.asset_id).map(p => p.asset_id!))}
          onClose={() => setPickerProvider(null)}
          onAdd={async (groups, entryId) => {
            await addPickedProviderPhotos(current.id, pickerProvider, groups, entryId)
            setPickerProvider(null)
          }}
        />
      )}

      {/* Delete entry confirm */}
      <ConfirmDialog
        isOpen={!!deleteTarget}
        onClose={() => setDeleteTarget(null)}
        onConfirm={async () => {
          if (!deleteTarget) return
          await deleteEntry(deleteTarget.id)
          setDeleteTarget(null)
          loadJourney(Number(id))
        }}
        title={t('journey.entries.deleteTitle')}
        message={t('journey.deleteConfirmMessage', { title: deleteTarget?.title || '' })}
        confirmLabel={t('common.delete')}
        danger
      />

      {/* Delete gallery photo confirm: final, and it leaves every entry that used the photo */}
      <ConfirmDialog
        isOpen={!!photoDeleteTarget}
        onClose={() => setPhotoDeleteTarget(null)}
        onConfirm={() => {
          if (!photoDeleteTarget) return
          deleteGalleryPhoto(current.id, photoDeleteTarget.id).catch(() => {
            toast.error(t('common.error'))
            void loadJourney(Number(id))
          })
        }}
        title={t('journey.gallery.deleteTitle')}
        message={t('journey.gallery.deleteMessage')}
        confirmLabel={t('common.delete')}
        danger
      />

      {/* Lightbox */}
      {lightbox && (
        <PhotoLightbox
          photos={lightbox.photos.map(p => ({
            id: p.id.toString(),
            src: p.src,
            caption: p.caption,
            provider: p.provider,
            asset_id: p.asset_id,
            owner_id: p.owner_id,
            mediaType: p.mediaType,
          }))}
          startIndex={lightbox.index}
          onClose={() => setLightbox(null)}
        />
      )}
      {/* TREK Studio, the book designer, opens over the journey on a screen with room for
          two panes, as on the desktop (its route is a child of this one). The phone keeps
          the journey alone, whatever the address says. */}
      {split && !embedded && <Outlet />}
    </div>
  )
}

/**
 * With the header in the shell's row, what the screen measures from its top
 * starts right under that row instead of under a row of its own.
 */
const IN_SHELL_ROW = { '--m-safe-top': 'calc(var(--m-safe-t, env(safe-area-inset-top, 0px)) + 6px)' } as CSSProperties

/** The header row: on the screen, or in the trip shell's top row when the journal is a trip tab. */
function HeaderFrame({ slot, feed, children }: { slot: HTMLElement | null; feed: boolean; children: ReactNode }) {
  if (slot) {
    return createPortal(
      <div className="flex min-w-0 flex-1 items-center gap-2 [&>span:first-child]:hidden [&>span:last-child]:ms-0 [&_[data-view-switch]]:static [&_[data-view-switch]]:translate-x-0">
        {children}
      </div>,
      slot
    )
  }
  return (
    <div
      className="m-bar-x absolute top-[var(--m-safe-top,12px)] z-10 flex items-center justify-between gap-2"
      style={feed ? { insetInlineEnd: 'calc(100% - var(--m-rail-w, 0px) - var(--m-pane-aside-w) + 16px)' } : undefined}
    >
      {children}
    </div>
  )
}