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.

31.3 KB
Raw Blame
import { ReactNode, useEffect, useState } from 'react'
import { useSearchParams } from 'react-router'
import {
  Bookmark, Check, CheckCheck, CheckSquare, ChevronDown, Copy, CopyPlus,
  FolderInput, Layers, List, Map as MapIcon, Pencil, Search, Settings2, Shapes, Share2,
  Tag, Tags, Trash2,
} from 'lucide-react'
import type { CollectionStatus } from '@trek/shared'
import MDancingTrek, { type TrekScene } from '../../components/MDancingTrek'
import { useCollections } from '../../../pages/collections/useCollections'
import { STATUS_ORDER } from '../../../pages/collections/collectionsModel'
import type { StatusFilter } from '../../../store/collectionStore'
import { ALL_SAVED } from '../../../store/collectionStore'
import CollectionMap from '../../../components/Collections/CollectionMap'
import MCollPlaceRow from './MCollPlaceRow'
import MCollPlaceSheet from './MCollPlaceSheet'
import MCollAddSheet from './MCollAddSheet'
import MCollShareSheet from './MCollShareSheet'
import MCollEditSheet from './MCollEditSheet'
import MCollLabelsSheet from './MCollLabelsSheet'
import MCollTripPickerSheet from './MCollTripPickerSheet'
import MCollListPickerSheet from './MCollListPickerSheet'
import MCollTours from './MCollTours'
import MCollInvites from './MCollInvites'
import { STATUS_SPEC, categoryMeta } from './collectionsMobileModel'
import MConfirmSheet from '../settings/MConfirmSheet'
import MCollListNav from './MCollListNav'
import { useIsSplit } from '../../../hooks/sizeClass'
import { skipNextRouteTransition } from '../../routeTransition'
import MSkeleton from '../../components/MSkeleton'

const HEADER_CIRCLE =
  'flex h-[38px] w-[38px] flex-none items-center justify-center rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] text-m-ink shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)]'

// min-w-0 is what lets the truncate on the chip labels engage: a flex item keeps
// min-width:auto by default, so the row grew past the panel instead of shrinking
// its chips. The labels are short enough to fit in every locale now, but a long
// label name in the filter chip, or a bumped-up text size, still has to ellipsise
// inside the panel rather than spill out of it.
const FILTER_CHIP =
  'flex min-w-0 flex-1 items-center justify-center gap-[5px] rounded-full py-2 text-[0.75rem] font-semibold'

const CHIP_IDLE = 'border border-[color:var(--m-rowbr)] bg-m-sheetop text-m-ink'
const CHIP_ON = 'border border-transparent bg-m-act text-m-actfg'

const DROP_PANEL =
  'rounded-[14px] border border-[color:var(--m-rowbr)] bg-m-sheetop shadow-[0_20px_44px_-18px_rgba(0,0,0,.45)]'

/** The filter chips that open a dropdown; at most one is open at a time. */
type FilterDrop = 'status' | 'category' | 'label'

/** One row of the status or category dropdown: icon, name, count. */
function DropRow({ icon, label, count, on, onPick }: {
  icon: ReactNode
  label: string
  count: number
  on: boolean
  onPick: () => void
}) {
  return (
    <button
      type="button"
      onClick={onPick}
      className={`flex w-full items-center gap-[9px] rounded-[11px] p-[10px] text-[0.8125rem] font-semibold text-m-ink ${on ? 'bg-[color:var(--m-ic)]' : ''}`}
    >
      {icon}
      <span dir="auto" className="min-w-0 flex-1 truncate text-start">{label}</span>
      <span className="font-geist text-[0.6875rem] font-bold text-m-faint">{count}</span>
    </button>
  )
}

function EmptyNote({ icon, scene, title }: { icon?: ReactNode; scene?: TrekScene; title: string }) {
  return (
    <div className="flex min-h-[60vh] flex-col items-center justify-center gap-[6px] px-6 text-center">
      {scene ? (
        <MDancingTrek scene={scene} className="mb-2" />
      ) : (
        <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-[color:var(--m-ic)] text-m-faint">{icon}</span>
      )}
      <p className="font-geist text-[0.8125rem] font-medium text-m-muted">{title}</p>
    </div>
  )
}

/**
 * Mobile collections screen: list switcher (dropdown + left drawer), list/map
 * view toggle with clustering, real status/label filter chips, the select mode
 * bulk actions and all collection sheets. State and mutations come from the
 * shared useCollections() page hook.
 */
export default function MCollections() {
  const c = useCollections()
  const { t } = c

  const [drop, setDrop] = useState(false)
  // With room for two panes the lists stand in a column beside the places
  // (MCollListNav) instead of behind the header's dropdown.
  const split = useIsSplit()
  const [filterDrop, setFilterDrop] = useState<FilterDrop | null>(null)
  const toggleDrop = (drop: FilterDrop) => setFilterDrop(cur => (cur === drop ? null : drop))

  // The bottom-nav "+" hands off via the ?create= contract.
  const [searchParams, setSearchParams] = useSearchParams()
  const createParam = searchParams.get('create')
  const { activeId, canEdit, setShowAddPlace, ownedLists, setEditorTarget } = c
  const listCount = c.collections.length
  const listsLoading = c.loading
  useEffect(() => {
    if (createParam !== 'place' && createParam !== '1') return
    // Wait for the lists: whether there is one decides what "+" means.
    if (listsLoading) return
    const next = new URLSearchParams(searchParams)
    next.delete('create')
    setSearchParams(next, { replace: true })
    // Without a list yet, "+" starts the first one; places come after.
    if (listCount === 0) {
      setEditorTarget('new')
      return
    }
    // Open whenever the user can add somewhere: an editable active list, or at
    // least one owned list to pick as the target in the sheet.
    if ((typeof activeId === 'number' && canEdit) || ownedLists.length > 0) setShowAddPlace(true)
  }, [createParam, searchParams, setSearchParams, activeId, canEdit, ownedLists.length, setShowAddPlace, listsLoading, listCount, setEditorTarget])

  // Close transient popovers when the active list changes under them.
  useEffect(() => {
    setDrop(false)
    setFilterDrop(null)
  }, [c.activeId])

  // The mobile toolbar has no rating filter control, but the shared hook still
  // applies whatever was set on desktop: keep it cleared so resizing to phone
  // doesn't silently filter the list and map (#1435). The category filter has
  // its own chip here (#2618), so it carries over.
  const { ratingFilter, setRatingFilter } = c
  useEffect(() => {
    if (ratingFilter !== 'all') setRatingFilter('all')
  }, [ratingFilter, setRatingFilter])

  const title = c.isAllSaved ? t('collections.allSaved') : (c.activeCollection?.name ?? t('collections.title'))
  const isRealList = !c.isAllSaved && typeof c.activeId === 'number'
  const canManageLabels = isRealList && c.canEdit
  const canEditList = isRealList && c.isOwner && c.activeCollection != null
  const canAddPlace = typeof c.activeId === 'number' && c.canEdit
  const noLists = !c.loading && c.collections.length === 0
  const hasPlaces = c.places.length > 0
  const showSelect = c.isAllSaved || c.activeCollection != null

  const statusLabel = c.statusFilter === 'all'
    ? t('collections.status.filterAll')
    : t(STATUS_SPEC[c.statusFilter].labelKey)
  // A category picked on another list (or on desktop) stays set when this list
  // has none of it, so the chip stays reachable to clear it again.
  const showCategoryChip = c.categoryOptions.length > 0 || c.categoryFilter !== 'all'
  const categoryLabel = c.categoryFilter === 'all'
    ? t('collections.status.filterAll')
    : (c.categoryOptions.find(o => o.id === c.categoryFilter)?.name
      ?? c.categories.find(o => o.id === c.categoryFilter)?.name
      ?? t('collections.status.filterAll'))
  const categoryTotal = c.categoryOptions.reduce((n, o) => n + o.count, 0)
  const labelLabel = c.labelFilter.length === 0
    ? t('collections.status.filterAll')
    : c.labelFilter.length === 1
      ? (c.labelOptions.find(l => l.id === c.labelFilter[0])?.name ?? '1')
      : String(c.labelFilter.length)

  const selectList = (id: number | typeof ALL_SAVED) => {
    setDrop(false)
    // Another list is the same screen with other content, not a page opened
    // over it: the URL changes, but the page must not slide in.
    skipNextRouteTransition()
    c.handleSelectList(id)
  }

  const openNewList = () => {
    setDrop(false)
    c.setEditorTarget('new')
  }

  const pickStatusFilter = (f: StatusFilter) => {
    c.setStatusFilter(f)
    setFilterDrop(null)
  }

  const pickCategoryFilter = (f: number | 'all') => {
    c.setCategoryFilter(f)
    setFilterDrop(null)
  }

  const openLabelManager = () => {
    setFilterDrop(null)
    c.setShowLabelManager(true)
  }

  const toggleLabelFilter = (id: number) => {
    c.setLabelFilter(c.labelFilter.includes(id) ? c.labelFilter.filter(x => x !== id) : [...c.labelFilter, id])
  }

  const navLists = [...c.ownedLists, ...c.sharedLists].map(l => ({
    id: l.id, name: l.name, place_count: l.place_count, color: l.color || '#6366F1',
  }))
  const listNav = (
    <MCollListNav
      lists={navLists}
      allSaved={c.isAllSaved}
      activeId={c.activeId}
      onSelect={selectList}
      onNewList={openNewList}
      t={t}
    />
  )

  const none = c.selectedIds.length === 0
  const selectChip = (disabled: boolean) =>
    `flex flex-none items-center gap-[5px] rounded-full border border-[color:var(--m-rowbr)] bg-m-sheetop px-3 py-2 text-[0.75rem] font-semibold text-m-ink ${disabled ? 'opacity-40' : ''}`

  return (
    <div
      // Map view fills the viewport like the trip and journal maps do (#2104);
      // h-dvh because the shell owns no scroll container (#1809). List view
      // keeps the document as the scroller.
      className={`px-4 pb-[calc(var(--bottom-nav-h,84px)+12px)] pt-[var(--m-safe-top,12px)] wide:px-6 split:grid split:grid-cols-[260px_minmax(0,1fr)] split:gap-8 ${c.view === 'map' ? 'flex h-dvh flex-col overflow-hidden' : 'wide:mx-auto wide:max-w-[1040px] split:max-w-[1240px] split:items-start'}`}
    >
      {split && (
        <nav
          aria-label={t('collections.title')}
          className="sticky top-[var(--m-safe-top,12px)] flex max-h-[calc(100dvh-var(--m-safe-top,12px)-16px)] flex-col gap-1 self-start overflow-y-auto rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] p-[6px] shadow-[0_16px_40px_-24px_rgba(0,0,0,.3)] [scrollbar-width:none]"
        >
          <div className="mb-1 px-[10px] pb-1 pt-[9px] text-subtitle font-bold text-m-ink">{t('collections.title')}</div>
          {listNav}
        </nav>
      )}
      <div className={`min-w-0 ${c.view === 'map' ? 'flex min-h-0 flex-1 flex-col' : ''}`}>
      {/* Header: back · list switcher · edit · share. Beside the lists it names the list on show. */}
      <div className="mb-3 flex flex-none items-center gap-2 pt-2">
        {split ? (
          <h1 className="flex min-w-0 flex-1 items-center gap-2 text-title font-extrabold text-m-ink">
            {!c.isAllSaved && c.activeCollection && (
              <span className="h-[11px] w-[11px] flex-none rounded-full" style={{ background: navLists.find(l => l.id === c.activeId)?.color }} />
            )}
            <span className="min-w-0 truncate">{title}</span>
          </h1>
        ) : (
        <button
          type="button"
          onClick={() => setDrop(v => !v)}
          aria-expanded={drop}
          className="flex h-[38px] min-w-0 flex-1 items-center gap-[7px] rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] px-[14px] text-[0.8125rem] font-bold text-m-ink shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)]"
        >
          <Bookmark size={14} strokeWidth={2.2} className="flex-none" />
          <span className="min-w-0 flex-1 truncate text-start">{title}</span>
          <ChevronDown size={13} strokeWidth={2} className="flex-none text-m-faint" />
        </button>
        )}
        {canEditList && (
          <button type="button" onClick={() => c.setEditorTarget(c.activeCollection!)} aria-label={t('collections.editListTitle')} className={HEADER_CIRCLE}>
            <Pencil size={15} strokeWidth={2.2} />
          </button>
        )}
        {c.canShare && (
          <button type="button" onClick={() => c.setShowShare(true)} aria-label={t('collections.share.title')} className={HEADER_CIRCLE}>
            <Share2 size={15} strokeWidth={2.2} />
          </button>
        )}
      </div>

      {/* List switcher dropdown (in flow, like the design). In map view it is a
          flex item of a viewport-high column, so it has to cap itself and give
          way rather than push its last entries under the dock (#2104). */}
      {drop && !split && (
        <div className="-mt-[6px] mb-3 max-h-[50dvh] min-h-0 overflow-y-auto rounded-2xl border border-[color:var(--m-rowbr)] bg-m-sheetop p-[6px] shadow-[0_16px_40px_-20px_rgba(0,0,0,.4)]">
          {listNav}
        </div>
      )}

      <MCollInvites invites={c.orderedInvites} onAccept={c.handleAcceptInvite} onDecline={c.handleDeclineInvite} t={t} />

      {c.loading && c.collections.length === 0 ? (
        <MSkeleton variant="rows" count={5} className="pt-2" />
      ) : noLists ? (
        <div className="mt-6">
          {/* The dock's "+" starts the first list (see the ?create= handoff above). */}
          <EmptyNote scene="collections" title={t('collections.empty.firstTitle')} />
        </div>
      ) : (
        <>
          {/* Toolbar: view toggle · search · filter chips / select actions */}
          <div className="mt-3 flex-none rounded-[18px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] p-[10px]">
            <div className="flex items-center gap-2">
              <span className="flex flex-none rounded-xl bg-[color:var(--m-ic)] p-[3px]">
                <button
                  type="button"
                  onClick={() => c.setView('list')}
                  aria-label={t('collections.view.list')}
                  aria-pressed={c.view === 'list'}
                  className={`flex h-[30px] w-[38px] items-center justify-center rounded-[9px] ${c.view === 'list' ? 'bg-m-act text-m-actfg' : 'text-m-muted'}`}
                >
                  <List size={15} strokeWidth={2} />
                </button>
                <button
                  type="button"
                  onClick={() => c.setView('map')}
                  aria-label={t('collections.view.map')}
                  aria-pressed={c.view === 'map'}
                  className={`flex h-[30px] w-[38px] items-center justify-center rounded-[9px] ${c.view === 'map' ? 'bg-m-act text-m-actfg' : 'text-m-muted'}`}
                >
                  <MapIcon size={15} strokeWidth={2} />
                </button>
              </span>
              <div className="flex h-9 min-w-0 flex-1 items-center gap-2 rounded-xl border border-[color:var(--m-rowbr)] bg-m-sheetop px-[13px]">
                <Search size={15} strokeWidth={2.2} className="flex-none text-m-muted" />
                <input
                  value={c.search}
                  onChange={e => c.setSearch(e.target.value)}
                  enterKeyHint="search" placeholder={t('collections.search')}
                  className="min-w-0 flex-1 bg-transparent font-geist text-[0.78125rem] text-m-ink outline-none placeholder:text-m-faint"
                />
              </div>
            </div>

            {c.view === 'list' && !c.selectMode && (
              <div className="relative mt-2 flex items-center gap-[6px]">
                <button
                  type="button"
                  onClick={() => toggleDrop('status')}
                  aria-expanded={filterDrop === 'status'}
                  className={`${FILTER_CHIP} ${c.statusFilter !== 'all' ? CHIP_ON : CHIP_IDLE}`}
                >
                  <Layers size={13} strokeWidth={2} className="flex-none" />
                  <span className="truncate">{statusLabel}</span>
                  <ChevronDown size={12} strokeWidth={2} className={`flex-none ${c.statusFilter !== 'all' ? '' : 'text-m-faint'}`} />
                </button>
                {showCategoryChip && (
                  <button
                    type="button"
                    onClick={() => toggleDrop('category')}
                    aria-expanded={filterDrop === 'category'}
                    aria-label={`${t('categories.title')}: ${categoryLabel}`}
                    className={`${FILTER_CHIP} ${c.categoryFilter !== 'all' ? CHIP_ON : CHIP_IDLE}`}
                  >
                    <Shapes size={13} strokeWidth={2} className="flex-none" />
                    <span dir="auto" className="truncate">{categoryLabel}</span>
                    <ChevronDown size={12} strokeWidth={2} className={`flex-none ${c.categoryFilter !== 'all' ? '' : 'text-m-faint'}`} />
                  </button>
                )}
                {isRealList && (
                  <button
                    type="button"
                    onClick={() => toggleDrop('label')}
                    aria-expanded={filterDrop === 'label'}
                    className={`${FILTER_CHIP} ${c.labelFilter.length > 0 ? CHIP_ON : CHIP_IDLE}`}
                  >
                    <Tag size={13} strokeWidth={2} className="flex-none" />
                    <span className="truncate">{labelLabel}</span>
                    <ChevronDown size={12} strokeWidth={2} className={`flex-none ${c.labelFilter.length > 0 ? '' : 'text-m-faint'}`} />
                  </button>
                )}
                {showSelect && (
                  <button type="button" onClick={() => c.setSelectMode(true)} className={`${FILTER_CHIP} ${CHIP_IDLE}`}>
                    <CheckSquare size={13} strokeWidth={2} className="flex-none" />
                    <span className="truncate">{t('collections.select')}</span>
                  </button>
                )}

                {filterDrop && (
                  <button
                    type="button"
                    aria-label={t('common.close')}
                    className="fixed inset-0 z-10 cursor-default"
                    onClick={() => setFilterDrop(null)}
                  />
                )}
                {filterDrop === 'status' && (
                  <div className={`absolute inset-x-0 top-[calc(100%+6px)] z-20 p-[6px] ${DROP_PANEL}`}>
                    <DropRow
                      icon={<Layers size={15} strokeWidth={2} className="flex-none" />}
                      label={t('collections.status.filterAll')}
                      count={c.counts.all}
                      on={c.statusFilter === 'all'}
                      onPick={() => pickStatusFilter('all')}
                    />
                    {STATUS_ORDER.map(s => {
                      const meta = STATUS_SPEC[s]
                      const Icon = meta.icon
                      return (
                        <DropRow
                          key={s}
                          icon={<Icon size={15} strokeWidth={2} className="flex-none" style={{ color: meta.color }} />}
                          label={t(meta.labelKey)}
                          count={c.counts[s]}
                          on={c.statusFilter === s}
                          onPick={() => pickStatusFilter(s)}
                        />
                      )
                    })}
                  </div>
                )}
                {filterDrop === 'category' && (
                  <div className={`absolute inset-x-0 top-[calc(100%+6px)] z-20 max-h-[300px] overflow-y-auto p-[6px] ${DROP_PANEL}`}>
                    <DropRow
                      icon={<Shapes size={15} strokeWidth={2} className="flex-none" />}
                      label={t('collections.status.filterAll')}
                      count={categoryTotal}
                      on={c.categoryFilter === 'all'}
                      onPick={() => pickCategoryFilter('all')}
                    />
                    {c.categoryOptions.map(o => {
                      const meta = categoryMeta(o)
                      const Icon = meta?.icon ?? Shapes
                      return (
                        <DropRow
                          key={o.id}
                          icon={<Icon size={15} strokeWidth={2} className="flex-none" style={{ color: meta?.color }} />}
                          label={o.name}
                          count={o.count}
                          on={c.categoryFilter === o.id}
                          onPick={() => pickCategoryFilter(o.id)}
                        />
                      )
                    })}
                  </div>
                )}
                {filterDrop === 'label' && (
                  <div className={`absolute inset-x-0 top-[calc(100%+6px)] z-20 max-h-[300px] overflow-y-auto p-[6px] ${DROP_PANEL}`}>
                    <button
                      type="button"
                      onClick={() => { c.setLabelFilter([]); setFilterDrop(null) }}
                      className={`flex w-full items-center gap-[9px] rounded-[11px] p-[10px] text-[0.8125rem] font-semibold text-m-ink ${c.labelFilter.length === 0 ? 'bg-[color:var(--m-ic)]' : ''}`}
                    >
                      <Tag size={15} strokeWidth={2} />
                      <span className="flex-1 text-start">{t('collections.status.filterAll')}</span>
                    </button>
                    {c.labelOptions.map(l => {
                      const on = c.labelFilter.includes(l.id)
                      return (
                        <button
                          key={l.id}
                          type="button"
                          onClick={() => toggleLabelFilter(l.id)}
                          className={`flex w-full items-center gap-[10px] rounded-[11px] p-[10px] text-start ${on ? 'bg-[color:var(--m-ic)]' : ''}`}
                        >
                          <span className="h-[9px] w-[9px] flex-none rounded-full" style={{ background: l.color || '#6366F1' }} />
                          <span dir="auto" className="min-w-0 flex-1 truncate text-[0.8125rem] font-semibold text-m-ink">{l.name}</span>
                          <span className="font-geist text-[0.6875rem] font-bold text-m-faint">{l.count}</span>
                          {on && <Check size={14} strokeWidth={2.6} className="flex-none text-m-ink" />}
                        </button>
                      )
                    })}
                    {c.labelOptions.length === 0 && (
                      <div className="p-[10px] text-center font-geist text-[0.71875rem] text-m-faint">{t('collections.labels.empty')}</div>
                    )}
                    {/* Managing the labels sits under their list, which keeps the row at
                        four chips now that the category chip joined it (#2618). */}
                    {canManageLabels && (
                      <button
                        type="button"
                        onClick={openLabelManager}
                        className="mt-1 flex w-full items-center gap-[9px] rounded-[11px] border-t border-[color:var(--m-rowbr)] p-[10px] text-[0.8125rem] font-semibold text-m-ink"
                      >
                        <Settings2 size={15} strokeWidth={2} className="flex-none" />
                        <span className="flex-1 text-start">{c.labelOptions.length > 0 ? t('collections.labels.manage') : t('collections.labels.add')}</span>
                      </button>
                    )}
                  </div>
                )}
              </div>
            )}

            {/* Selecting: what is picked and the way out on one line, the actions as icons on
                the next, so nothing scrolls sideways or hides the way back. */}
            {c.view === 'list' && c.selectMode && (
              <div className="mt-2">
                <div className="flex items-center gap-2">
                  <button type="button" onClick={c.handleSelectAll} className={selectChip(false)}>
                    <CheckCheck size={13} strokeWidth={2.2} />
                    {c.allVisibleSelected ? t('collections.deselectAll') : t('collections.selectAll')}
                  </button>
                  <span className="min-w-0 flex-1 truncate text-center font-geist text-[0.6875rem] font-bold text-m-muted">
                    {t('collections.selectedCount', { count: c.selectedIds.length })}
                  </span>
                  <button type="button" onClick={() => c.setSelectMode(false)} className="flex-none rounded-full bg-m-act px-[14px] py-2 text-caption font-semibold text-m-actfg">
                    {t('packing.editDone')}
                  </button>
                </div>
                <div className="mt-2 flex items-center justify-between gap-[6px]">
                  {canManageLabels && (
                    <SelectionAction label={t('collections.labels.assign')} onClick={() => c.setLabelPickerOpen(true)} disabled={none}>
                      <Tags size={16} strokeWidth={2} />
                    </SelectionAction>
                  )}
                  <SelectionAction label={t('collections.copyToTrip')} onClick={c.openCopyForSelection} disabled={none}>
                    <Copy size={16} strokeWidth={2} />
                  </SelectionAction>
                  {c.canDelete && (
                    <SelectionAction label={t('collections.moveToList')} onClick={() => c.setListPickerMode('move')} disabled={none}>
                      <FolderInput size={16} strokeWidth={2} />
                    </SelectionAction>
                  )}
                  <SelectionAction label={t('collections.duplicateToList')} onClick={() => c.setListPickerMode('copy')} disabled={none}>
                    <CopyPlus size={16} strokeWidth={2} />
                  </SelectionAction>
                  {c.canDelete && (
                    <SelectionAction label={t('common.delete')} onClick={c.handleDeleteSelected} disabled={none} danger>
                      <Trash2 size={16} strokeWidth={2} />
                    </SelectionAction>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* List view */}
          {/* The whole tours the list keeps (LIB-03) open it, as rows like its places. */}
          {c.view === 'list' && <MCollTours search={c.search} />}
          {c.view === 'list' && (
            c.placesLoading && !hasPlaces ? (
              <MSkeleton variant="rows" count={5} className="pt-2" />
            ) : !hasPlaces ? (
              <EmptyNote scene="collections" title={t('collections.empty.title')} />
            ) : c.visiblePlaces.length === 0 ? (
              <EmptyNote icon={<Search size={19} strokeWidth={1.8} />} title={t('collections.empty.noMatchTitle')} />
            ) : (
              // Two columns of rows where the page has the room for them.
              <div className="wide:grid wide:grid-cols-[repeat(auto-fill,minmax(min(100%,380px),1fr))] wide:gap-x-3">
                {c.visiblePlaces.map(p => (
                  <MCollPlaceRow
                    key={p.id}
                    place={p}
                    selectMode={c.selectMode}
                    selected={c.selectedIds.includes(p.id)}
                    canEdit={c.canEdit}
                    onOpen={c.setSelectedPlaceId}
                    onToggleSelect={c.toggleSelect}
                    onSetStatus={(id: number, status: CollectionStatus) => c.handleStatusChange(id, status)}
                    t={t}
                  />
                ))}
              </div>
            )
          )}

          {/* Map view — the real map stack with marker clustering */}
          {c.view === 'map' && (
            c.mappable.length === 0 ? (
              <EmptyNote icon={<MapIcon size={19} strokeWidth={1.8} />} title={t('collections.empty.noMatchTitle')} />
            ) : (
              <div className="relative mt-3 min-h-0 flex-1 overflow-hidden rounded-[20px] border border-[color:var(--m-rowbr)]">
                <CollectionMap
                  places={c.mappable}
                  selectedPlaceId={c.selectedPlaceId}
                  onOpenPlace={c.setSelectedPlaceId}
                  onDeselect={() => c.setSelectedPlaceId(null)}
                  dark={c.dark}
                />
              </div>
            )
          )}
        </>
      )}

      </div>

      {/* Sheets */}
      <MCollPlaceSheet
        place={c.selectedPlace}
        canEdit={c.canEdit}
        canDelete={c.canDelete}
        categories={c.categories}
        labels={c.labels}
        onClose={c.handleCloseDetail}
        onSetStatus={c.handleDetailStatus}
        onSave={patch => c.updatePlace(c.selectedPlace!.id, patch)}
        onUploadImage={file => c.uploadPlaceImage(c.selectedPlace!.id, file)}
        onCopyToTrip={c.openCopyForSelectedPlace}
        onRemove={c.handleDetailRemove}
        onRate={r => c.handleRatePlace(c.selectedPlace!.id, r)}
        t={t}
      />

      <MCollAddSheet
        open={c.showAddPlace}
        collectionId={canAddPlace ? (c.activeId as number) : null}
        collectionName={canAddPlace ? (c.activeCollection?.name ?? '') : ''}
        lists={c.ownedLists}
        categories={c.categories}
        onClose={() => c.setShowAddPlace(false)}
        onAdded={c.handlePlaceAdded}
        t={t}
      />

      <MCollShareSheet
        open={c.showShare && c.canShare}
        collectionId={typeof c.activeId === 'number' ? c.activeId : null}
        collectionName={c.activeCollection?.name ?? ''}
        isOwner={c.isOwner}
        members={c.members}
        onClose={() => c.setShowShare(false)}
        onAfterLeave={c.handleAfterLeave}
        t={t}
      />

      <MCollEditSheet
        target={c.editorTarget}
        onClose={() => c.setEditorTarget(null)}
        onCreated={c.handleEditorCreated}
        onRequestDelete={c.setConfirmDeleteList}
        t={t}
      />

      <MCollLabelsSheet
        open={c.showLabelManager || c.labelPickerOpen}
        mode={c.labelPickerOpen ? 'assign' : 'manage'}
        labels={c.labelOptions}
        selectedCount={c.selectedIds.length}
        onCreate={c.handleCreateLabel}
        onUpdate={c.handleUpdateLabel}
        onDelete={c.handleDeleteLabel}
        onAssign={c.handleBulkAssignLabels}
        onSwitchToManage={() => { c.setLabelPickerOpen(false); c.setShowLabelManager(true) }}
        onClose={() => { c.setShowLabelManager(false); c.setLabelPickerOpen(false) }}
        t={t}
      />

      <MCollTripPickerSheet
        open={c.copyIds != null}
        count={c.copyIds?.length ?? 0}
        onCopy={c.handleCopyToTrip}
        onClose={c.closeCopy}
        t={t}
      />

      <MCollListPickerSheet
        mode={c.listPickerMode}
        lists={c.writableLists.filter(l => l.id !== c.activeId)}
        count={c.selectedIds.length}
        onPick={id => (c.listPickerMode === 'move' ? c.handleMoveToList(id) : c.handleDuplicateToList(id))}
        onClose={() => c.setListPickerMode(null)}
        t={t}
      />

      {/* Delete-list confirm */}
      <MConfirmSheet
        open={c.confirmDeleteList != null}
        onClose={() => c.setConfirmDeleteList(null)}
        title={t('collections.deleteList')}
        message={t('collections.deleteListConfirm')}
        confirmLabel={t('common.delete')}
        cancelLabel={t('common.cancel')}
        danger
        onConfirm={c.handleDeleteList}
      />
    </div>
  )
}

/** One action on the picked places: an icon, named by its label, as wide as its share of the row. */
function SelectionAction({ label, onClick, disabled, danger = false, children }: {
  label: string
  onClick: () => void
  disabled: boolean
  danger?: boolean
  children: ReactNode
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      aria-label={label}
      title={label}
      className={`flex h-10 min-w-0 flex-1 items-center justify-center rounded-full border border-[color:var(--m-rowbr)] bg-m-sheetop disabled:opacity-40 ${danger ? 'text-[color:var(--m-st-danger)]' : 'text-m-ink'}`}
    >
      {children}
    </button>
  )
}