// PitStop UI Kit — Trip workspace (NEW IA)
// The Plan tab is GONE. The itinerary now lives on the Trip front page as an
// agenda + horizontal day-rail (layout "C"): a day rail owns the date, a slim
// day strip + route map give context, and a time-led agenda lists the day.
// "Edit plan" flips the page into a planning mode (reorder / delete / add);
// adding opens the full-screen AddFlow (screens-add.jsx).
// Recreated from apps/web/src/pages/TripView.tsx + components/trip/*.

const TABS = [
  { id: 'home', label: 'Trip', icon: 'route' },
  { id: 'nearby', label: 'Nearby', icon: 'utensils' },
  { id: 'highlights', label: 'Highlights', icon: 'camera' },
  { id: 'tab', label: 'Costs', icon: 'wallet' },
];

// #717 retired the bottom bar from the app (tabs moved under the header,
// Nearby became the Find nearby button). Kept only so the dated wireframes
// under wireframes/5xx still render as they were drawn — don't use it for
// new screens; use TripTabs + FindNearbyButton + SubPageHeader.
function BottomNav({ active, onSelect, badges = {} }) {
  return (
    <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 20, background: 'hsl(var(--bg) / 0.95)',
      backdropFilter: 'blur(12px)', borderTop: '1px solid hsl(var(--line))', paddingBottom: 22 }}>
      <div style={{ display: 'flex', padding: '0 14px' }}>
        {TABS.map(t => {
          const on = active === t.id;
          return (
            <button key={t.id} onClick={() => onSelect(t.id)} style={{ flex: 1, display: 'flex', flexDirection: 'column',
              alignItems: 'center', gap: 5, padding: '9px 0 10px', position: 'relative', background: 'transparent',
              border: 'none', cursor: 'pointer', color: on ? 'hsl(var(--ember))' : 'hsl(var(--muted-ink))' }}>
              {on && <span style={{ position: 'absolute', top: 0, left: '50%', transform: 'translateX(-50%)', width: 24, height: 2, borderRadius: 999, background: 'hsl(var(--ember))' }} />}
              <span style={{ position: 'relative' }}>
                <Icon name={t.icon} size={20} />
                {badges[t.id] > 0 && <span style={{ position: 'absolute', top: -6, right: -10, background: 'hsl(var(--ember))', color: 'hsl(var(--bg))', fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 9, minWidth: 16, height: 16, borderRadius: 999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 3px' }}>{badges[t.id]}</span>}
              </span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 8.5, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.16em' }}>{t.label}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// Recreated from apps/web/src/components/trip/TripTabs.tsx (#717, option A):
// row 2 of the trip header. A dot marks something new; the bell owns counts.
const TRIP_TABS = [
  { id: 'home', label: 'Trip', icon: 'route' },
  { id: 'highlights', label: 'Highlights', icon: 'camera' },
  { id: 'tab', label: 'Costs', icon: 'wallet' },
];

function TripTabs({ active, onSelect, unseen = {} }) {
  return (
    <div role="tablist" aria-label="Trip sections" style={{ display: 'flex', padding: '0 8px', borderTop: '1px solid hsl(var(--line))' }}>
      {TRIP_TABS.map(t => {
        const on = active === t.id;
        return (
          <button key={t.id} role="tab" aria-selected={on} onClick={() => onSelect && onSelect(t.id)} style={{ flex: 1, height: 44,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, background: 'transparent', border: 'none',
            borderBottom: `2px solid ${on ? 'hsl(var(--ember))' : 'transparent'}`, cursor: 'pointer',
            color: on ? 'hsl(var(--ember))' : 'hsl(var(--muted-ink))', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 13 }}>
            <Icon name={t.icon} size={16} />
            {t.label}
            {unseen[t.id] && <span aria-hidden="true" style={{ width: 6, height: 6, borderRadius: 999, background: 'hsl(var(--ember))', marginTop: -8 }} />}
          </button>
        );
      })}
    </div>
  );
}

// Recreated from apps/web/src/components/trip/FindNearbyButton.tsx (#717, N3).
function FindNearbyButton({ onClick }) {
  return (
    <button onClick={onClick} style={{ position: 'absolute', right: 16, bottom: 34, zIndex: 20, height: 52, padding: '0 20px 0 16px',
      border: 'none', borderRadius: 999, background: 'hsl(var(--ember))', color: 'hsl(var(--bg))', fontFamily: 'var(--font-sans)',
      fontWeight: 800, fontSize: 14, display: 'flex', alignItems: 'center', gap: 8, boxShadow: 'var(--shadow-card)', cursor: 'pointer' }}>
      <Icon name="utensils" size={18} />
      Find nearby
    </button>
  );
}

// Recreated from apps/web/src/components/SubPageHeader.tsx (#717, S1): every
// page below a trip. Back to an explicit place; no tabs, bell or avatar.
function SubPageHeader({ onBack, backLabel = 'Back to trip', context, title, action }) {
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 10, background: 'hsl(var(--bg) / 0.95)', backdropFilter: 'blur(12px)',
      borderBottom: '1px solid hsl(var(--line))', padding: '50px 8px 8px', display: 'flex', alignItems: 'center', gap: 4 }}>
      <button onClick={onBack} aria-label={backLabel} style={{ width: 44, height: 44, border: 'none', background: 'transparent', borderRadius: 999,
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'hsl(var(--ink))', cursor: 'pointer', flexShrink: 0 }}>
        <Icon name="arrow-left" size={20} />
      </button>
      <div style={{ flex: 1, minWidth: 0, lineHeight: 1.25 }}>
        {context && <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 11, letterSpacing: '0.02em', color: 'hsl(var(--muted-ink))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{context}</div>}
        <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 15, color: 'hsl(var(--ink))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
      </div>
      {action}
    </div>
  );
}

// Matches apps/web/src/pages/TripView.tsx (#717, #723): row 1 is global — the
// brand mark goes to all trips (not a back arrow), the trip name (⌄ opens the
// trip sheet), bell + profile; row 2 is this trip's tabs.
function TripTopStrip({ name, onBack, unread = 0, onOpenNotifications, tab, onTab, onOpenTrip }) {
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 10, background: 'hsl(var(--bg) / 0.95)', backdropFilter: 'blur(12px)',
      borderBottom: '1px solid hsl(var(--line))' }}>
    <div style={{ padding: '56px 16px 12px', display: 'flex', alignItems: 'center', gap: 8 }}>
      <button onClick={onBack} aria-label="All trips" style={{ border: 'none', background: 'transparent', padding: '2px 4px', borderRadius: 6, cursor: 'pointer', display: 'flex', flexShrink: 0 }}>
        <DotsLogo width={36} height={18} />
      </button>
      <span style={{ color: 'hsl(var(--muted-ink) / 0.5)', flexShrink: 0 }}>/</span>
      <button onClick={onOpenTrip} aria-label={`${name}: trip details and options`} style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', gap: 4, border: 'none', background: 'transparent', padding: '2px 4px', cursor: 'pointer', textAlign: 'left' }}>
        <span style={{ minWidth: 0, fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 14, color: 'hsl(var(--ink))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</span>
        <Icon name="chevron-down" size={16} color="hsl(var(--muted-ink))" />
      </button>
      <NotificationBell count={unread} onOpen={onOpenNotifications} />
      <ProfileButton initials="AB" />
    </div>
    {tab && <TripTabs active={tab} onSelect={onTab} unseen={{ highlights: true, tab: true }} />}
    </div>
  );
}

// ── Status pill ────────────────────────────────────────────────────────────
function StatusPill({ children, accent }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', height: 22, padding: '0 10px', borderRadius: 999,
      background: accent ? 'var(--ember-soft)' : 'hsl(var(--paper-raise))',
      color: accent ? 'hsl(var(--ember))' : 'hsl(var(--muted-ink))',
      fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9.5, textTransform: 'uppercase', letterSpacing: '0.12em', whiteSpace: 'nowrap' }}>
      {children}
    </span>
  );
}

function MetaPill({ children, tone }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', height: 19, padding: '0 8px', borderRadius: 999,
      background: `hsl(var(--${tone}) / 0.16)`, color: `hsl(var(--${tone}))`,
      fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.1em', whiteSpace: 'nowrap', flexShrink: 0 }}>
      {children}
    </span>
  );
}

// ════════════════════════════════════════════════════════════════════════
// Itinerary front page (layout C) data
// ════════════════════════════════════════════════════════════════════════
const DAYS = [
  { dow: 'Monday',    short: 'Mon', dom: '22', mon: 'Apr', accent: 1, wx: 'sun',        temp: '21°/14°', total: '1 flight · 1 drive',
    items: [ { type: 'flight', title: 'Oslo → Olbia', time: '14:20', meta: '2h 55m · SK4721' },
             { type: 'drive', title: 'Olbia Airport → Cala Gonone', time: '17:30', meta: '64 km · 1h 10m' } ],
    tonight: { title: 'Hotel Bue Marino', sub: 'Via Marco Polo, Cala Gonone', pill: 'Check-in · from 18:40', tone: 'in' } },
  { dow: 'Tuesday',   short: 'Tue', dom: '23', mon: 'Apr', accent: 2, wx: 'cloud-sun',  temp: '22°/15°', total: '76 km riding',
    items: [ { type: 'ride', title: 'Cala Gonone coastal loop', time: '09:00', meta: '72.1 km · 4h 00m', nav: true },
             { type: 'food', title: 'Il Pescatore', sub: 'Harbour front', time: 'Lunch' },
             { type: 'walk', title: 'Cala Luna beach walk', time: '16:00', meta: '4.2 km · 1h 10m' } ],
    tonight: { title: 'Hotel Bue Marino', sub: 'Via Marco Polo, Cala Gonone', pill: 'Night 2', tone: 'night' } },
  { dow: 'Wednesday', short: 'Wed', dom: '24', mon: 'Apr', accent: 3, wx: 'cloud-rain', temp: '19°/12°', total: '58 km riding',
    morning: { title: 'Hotel Bue Marino', sub: 'Via Marco Polo, Cala Gonone', pill: 'Check-out · by 10:00', tone: 'out' },
    items: [ { type: 'ride', title: 'Cala Gonone → Golfo Aranci', time: '11:30', meta: '58.5 km · 3h 38m', nav: true },
             { type: 'poi', title: 'Spiaggia di Cala Luna', sub: 'Swim stop', time: '13:15' } ],
    tonight: { title: 'Stazzo in Piazza, San Pantaleo', sub: 'Piazza Pasquale Tola, Olbia', pill: 'Check-in · from 16:00', tone: 'in' } },
  { dow: 'Thursday',  short: 'Thu', dom: '25', mon: 'Apr', accent: 4, wx: 'cloud-sun',  temp: '20°/13°', total: '66 km riding',
    items: [ { type: 'ride', title: 'San Pantaleo ridge loop', time: '09:30', meta: '66.0 km · 3h 52m', nav: true },
             { type: 'food', title: 'Dinner — Trattoria del Porto', sub: 'Booked for 4', time: '20:30' } ],
    tonight: { title: 'Stazzo in Piazza, San Pantaleo', sub: 'Piazza Pasquale Tola, Olbia', pill: 'Night 2', tone: 'night' } },
  { dow: 'Friday',    short: 'Fri', dom: '26', mon: 'Apr', accent: 5, wx: 'sun',        temp: '23°/15°', total: '65 km · 1 flight',
    morning: { title: 'Stazzo in Piazza, San Pantaleo', sub: 'Piazza Pasquale Tola, Olbia', pill: 'Check-out · by 09:00', tone: 'out' },
    items: [ { type: 'ride', title: 'San Pantaleo → Olbia', time: '10:00', meta: '65.0 km · 3h 30m', nav: true },
             { type: 'flight', title: 'Olbia → Oslo', time: '18:40', meta: '3h 05m · SK4722' } ] },
];

// ── Day rail — horizontal date pills (owns the selected date) ─────────────
function DayRail({ days, current, onSelect }) {
  return (
    <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '14px 16px 4px', scrollbarWidth: 'none' }}>
      {days.map((d, i) => {
        const on = i === current;
        return (
          <button key={i} onClick={() => onSelect(i)} style={{ flexShrink: 0, width: 58, padding: '9px 0 8px', borderRadius: 'var(--radius-md)',
            border: 'none',
            background: on ? 'hsl(var(--ember))' : 'hsl(var(--paper))', cursor: 'pointer', textAlign: 'center',
            boxShadow: on ? 'var(--shadow-soft)' : 'none', transition: 'all .15s' }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.12em',
              color: on ? 'rgba(255,255,255,0.85)' : 'hsl(var(--muted-ink))' }}>{d.short}</div>
            <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 19, letterSpacing: '-0.02em', marginTop: 1,
              color: on ? '#fff' : 'hsl(var(--ink))' }}>{d.dom}</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.12em', marginTop: 1,
              color: on ? 'rgba(255,255,255,0.85)' : 'hsl(var(--muted-ink))' }}>{d.mon}</div>
            <div style={{ width: 5, height: 5, borderRadius: 999, margin: '6px auto 0',
              background: on ? 'rgba(255,255,255,0.9)' : `hsl(var(--day-${d.accent}))` }} />
          </button>
        );
      })}
    </div>
  );
}

// ── Day route map (compact) ───────────────────────────────────────────────
function DayMap({ accent, overlay }) {
  return (
    <div style={{ position: 'relative', height: 132, background: 'linear-gradient(150deg, hsl(205 28% 30%), hsl(212 30% 22%))', overflow: 'hidden', borderRadius: 'var(--radius-md)', border: '1px solid hsl(var(--line))' }}>
      <div className="bg-dot-grid" style={{ position: 'absolute', inset: 0, opacity: 0.5 }} />
      <svg width="100%" height="100%" viewBox="0 0 360 132" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0 }}>
        <path d="M 40 108 C 110 92 140 60 200 60 S 290 42 330 24" fill="none" stroke={`hsl(var(--day-${accent}))`} strokeWidth="2.5" strokeLinecap="round" strokeDasharray="1 5" opacity="0.95" />
        <circle cx="40" cy="108" r="5" fill={`hsl(var(--day-${accent}))`} stroke="hsl(var(--paper))" strokeWidth="2" />
        <circle cx="330" cy="24" r="5" fill={`hsl(var(--day-${accent}))`} stroke="hsl(var(--paper))" strokeWidth="2" />
      </svg>
      <button style={{ position: 'absolute', top: 10, right: 10, height: 30, padding: '0 12px', borderRadius: 999, border: 'none', cursor: 'pointer',
        background: 'hsl(var(--paper) / 0.92)', backdropFilter: 'blur(8px)', boxShadow: 'var(--shadow-soft)', display: 'inline-flex', alignItems: 'center', gap: 6,
        fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 12, color: 'hsl(var(--ink))' }}>
        <Icon name="maximize-2" size={13} color="hsl(var(--ink))" /> Map
      </button>
      {overlay && (
        <span style={{ position: 'absolute', top: 10, left: 10, height: 30, padding: '0 11px', borderRadius: 999,
          background: 'hsl(var(--paper) / 0.92)', backdropFilter: 'blur(8px)', boxShadow: 'var(--shadow-soft)', display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          {overlay}
        </span>
      )}
    </div>
  );
}

// ── Stay band — stays frame the day: "This morning" / "Tonight" (#547) ────
const BAND_TONE = { out: 'soft-red', in: 'soft-green', night: 'muted-ink' };
function StayBand({ when, stay }) {
  const tone = BAND_TONE[stay.tone] || 'muted-ink';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 12, background: 'hsl(var(--paper-raise))', border: '1px solid var(--line)' }}>
      <span style={{ width: 32, height: 32, borderRadius: 999, background: 'hsl(var(--type-stay))', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name={when === 'Tonight' ? 'moon' : 'sunrise'} size={15} color="#fff" />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.16em', color: 'hsl(var(--muted-ink))' }}>{when}</div>
        <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 14, color: 'hsl(var(--ink))', marginTop: 2 }}>{stay.title}</div>
        {stay.sub && <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 11.5, color: 'hsl(var(--muted-ink))', marginTop: 1 }}>{stay.sub}</div>}
      </div>
      <span style={{ display: 'inline-flex', alignItems: 'center', height: 22, padding: '0 9px', borderRadius: 999, background: `hsl(var(--${tone}) / 0.16)`, color: `hsl(var(--${tone}))`, fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.08em', whiteSpace: 'nowrap' }}>{stay.pill}</span>
    </div>
  );
}

// ── Agenda row (view) — time gutter · type node · content ─────────────────
function AgendaRow({ item, first, last }) {
  const t = ITEM_TYPE[item.type] || ITEM_TYPE.note;
  // The gutter is for HH:MM; a rough slot ("Lunch") reads as a pill instead.
  const isClock = /^\d{2}:\d{2}$/.test(item.time || '');
  const showTime = isClock;
  const slot = item.time && !isClock && item.time !== '—' ? item.time : null;
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'stretch' }}>
      {/* time gutter */}
      <div style={{ width: 42, flexShrink: 0, paddingTop: 7, textAlign: 'right' }}>
        <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 11.5, letterSpacing: '0.02em', color: showTime ? 'hsl(var(--ink))' : 'hsl(var(--muted-ink) / 0.6)', fontVariantNumeric: 'tabular-nums' }}>{showTime ? item.time : '·'}</span>
      </div>
      {/* node + connector */}
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0, alignSelf: 'stretch' }}>
        <span style={{ flex: 1, width: 2, minHeight: 6, background: first ? 'transparent' : 'hsl(var(--ink) / 0.14)' }} />
        <span style={{ width: 34, height: 34, borderRadius: 999, background: `hsl(${t.color})`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name={t.icon} size={16} color="#fff" />
        </span>
        <span style={{ flex: 1, width: 2, minHeight: 6, background: last ? 'transparent' : 'hsl(var(--ink) / 0.14)' }} />
      </div>
      {/* content */}
      <div style={{ flex: 1, minWidth: 0, paddingTop: 2, paddingBottom: last ? 0 : 18 }}>
        <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 15, color: 'hsl(var(--ink))', lineHeight: 1.25, textWrap: 'pretty' }}>{item.title}</div>
        {item.sub && <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 500, fontSize: 12.5, color: 'hsl(var(--muted-ink))', marginTop: 2 }}>{item.sub}</div>}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
          {item.status === 'out' && <MetaPill tone="soft-red">Check-out</MetaPill>}
          {item.status === 'in' && <MetaPill tone="soft-green">Check-in</MetaPill>}
          {item.status === 'stay' && <MetaPill tone="muted-ink">Overnight</MetaPill>}
          {slot && <MetaPill tone="muted-ink">{slot}</MetaPill>}
          {item.meta && <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 10.5, letterSpacing: '0.03em', color: 'hsl(var(--muted-ink))', whiteSpace: 'nowrap' }}>{item.meta}</span>}
          {item.nav && (
            <button style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 5, background: 'transparent', border: 'none', cursor: 'pointer', color: 'hsl(var(--ember))', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 12 }}>
              <Icon name="navigation" size={13} color="hsl(var(--ember))" /> Route
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ── Agenda row (edit) — grip · node · title · move/delete ─────────────────
function EditRow({ item, i, count, onMove, onDelete }) {
  const t = ITEM_TYPE[item.type] || ITEM_TYPE.note;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 8px 8px 6px', borderRadius: 'var(--radius-md)',
      background: 'hsl(var(--paper-raise))', border: '1px solid hsl(var(--line))' }}>
      <span style={{ display: 'flex', color: 'hsl(var(--muted-ink) / 0.7)', cursor: 'grab', flexShrink: 0 }}><Icon name="grip-vertical" size={18} /></span>
      <span style={{ width: 32, height: 32, borderRadius: 999, background: `hsl(${t.color})`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name={t.icon} size={15} color="#fff" />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 14, color: 'hsl(var(--ink))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.title}</div>
        <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 10.5, color: 'hsl(var(--muted-ink))', marginTop: 1 }}>{item.time && item.time !== '—' ? item.time : 'no time'} {item.meta ? `· ${item.meta.split(' · ')[0]}` : ''}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 2, flexShrink: 0 }}>
        <button onClick={() => onMove(i, -1)} disabled={i === 0} style={{ width: 30, height: 30, border: 'none', background: 'transparent', cursor: i === 0 ? 'default' : 'pointer', opacity: i === 0 ? 0.3 : 1, color: 'hsl(var(--muted-ink))', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chevron-up" size={17} /></button>
        <button onClick={() => onMove(i, 1)} disabled={i === count - 1} style={{ width: 30, height: 30, border: 'none', background: 'transparent', cursor: i === count - 1 ? 'default' : 'pointer', opacity: i === count - 1 ? 0.3 : 1, color: 'hsl(var(--muted-ink))', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="chevron-down" size={17} /></button>
        <button onClick={() => onDelete(i)} style={{ width: 30, height: 30, border: 'none', background: 'transparent', cursor: 'pointer', color: 'hsl(var(--soft-red))', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="trash-2" size={16} /></button>
      </div>
    </div>
  );
}

// ── Latest activity feed (kept from the old front page) ───────────────────
function LatestActivity() {
  const feed = [
    { kind: 'comment', init: 'T', i: 0, title: 'Agreed — the non-MIPS helmet just sits better.', t: '16d' },
    { kind: 'comment', init: 'S', i: 4, title: 'That look is only possible without a MIPS helmet.', t: '17d' },
    { kind: 'highlight', tone: '350 30% 42%', title: 'Sardinia’s pride', t: '30d' },
  ];
  return (
    <div>
      <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.16em', color: 'hsl(var(--muted-ink))', padding: '0 16px 10px' }}>Latest activity</div>
      <div style={{ padding: '0 16px' }}>
        <Card style={{ padding: '2px 16px' }}>
          {feed.map((f, i) => (
            <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', padding: '13px 0', borderTop: i ? '1px solid hsl(var(--line))' : 'none', cursor: 'pointer' }}>
              {f.kind === 'highlight'
                ? <span style={{ width: 34, height: 34, borderRadius: 8, flexShrink: 0, background: `linear-gradient(150deg, hsl(${f.tone}), hsl(${f.tone.split(' ')[0]} ${parseInt(f.tone.split(' ')[1])-6}% ${parseInt(f.tone.split(' ')[2])-14}%))`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="image" size={14} color="rgba(255,255,255,0.85)" /></span>
                : <Avatar initials={f.init} i={f.i} size={34} />}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.14em', color: 'hsl(var(--muted-ink))' }}>{f.kind}</span>
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 10, color: 'hsl(var(--muted-ink))', flexShrink: 0 }}>{f.t}</span>
                </div>
                <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 14.5, lineHeight: 1.4, color: 'hsl(var(--ink))', marginTop: 3 }}>{f.title}</div>
              </div>
            </div>
          ))}
        </Card>
      </div>
    </div>
  );
}

// ── THE MERGED FRONT PAGE ─────────────────────────────────────────────────
function TripHomeTab({ trip, days, dayIdx, setDayIdx, editing, setEditing, onAdd, onMove, onDelete }) {
  const d = days[dayIdx];
  const wx = d.wx;
  return (
    <div style={{ padding: '0 0 120px' }}>
      {/* #723: no trip row and no day heading. The rail carries the date
          (month under the number); trip things live in the trip sheet. */}
      <DayRail days={days} current={dayIdx} onSelect={setDayIdx} />

      {/* day route map with the day's weather + totals as a chip */}
      <div style={{ padding: '10px 16px 0' }}><DayMap accent={d.accent} overlay={<>
        <Icon name={wx} size={15} color="hsl(var(--ember))" />
        <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 12, color: 'hsl(var(--ink))' }}>{d.temp}</span>
        <span style={{ width: 3, height: 3, borderRadius: 999, background: 'hsl(var(--muted-ink))' }} />
        <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'hsl(var(--muted-ink))', whiteSpace: 'nowrap' }}>{d.total}</span>
      </>} /></div>

      {/* plan header — Day x / y · The plan · n items, with Edit/Done */}
      <div style={{ padding: '16px 16px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
        <span style={{ flex: 1, minWidth: 0, fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'hsl(var(--muted-ink))' }}>
          {`Day ${dayIdx + 1} / ${days.length} · The plan${d.items.length ? ` · ${d.items.length} item${d.items.length === 1 ? '' : 's'}` : ''}`}
        </span>
        {editing
          ? <Btn size="sm" onClick={() => setEditing(false)}><Icon name="check" size={15} color="#fff" strokeWidth={2.4} /> Done</Btn>
          : <button onClick={() => setEditing(true)} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, height: 32, padding: '0 13px', borderRadius: 999, cursor: 'pointer',
              background: 'transparent', border: '1px solid var(--line-strong)', color: 'hsl(var(--ink))',
              fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 12 }}>
              <Icon name="pencil" size={14} /> Edit
            </button>}
      </div>

      {/* agenda / editable list */}
      <div style={{ padding: '16px 16px 0' }}>
        {editing ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
              <Icon name="list" size={15} color="hsl(var(--muted-ink))" />
              <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'hsl(var(--muted-ink))' }}>Reorder · edit · delete</span>
            </div>
            {d.items.map((item, j) => (
              <EditRow key={j} item={item} i={j} count={d.items.length} onMove={onMove} onDelete={onDelete} />
            ))}
            <button onClick={() => onAdd()} style={{ marginTop: 4, width: '100%', height: 48, borderRadius: 'var(--radius-md)', border: '1px dashed hsl(var(--ember))', background: 'var(--ember-soft)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, color: 'hsl(var(--ember))', fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 13.5 }}>
              <Icon name="plus" size={18} color="hsl(var(--ember))" strokeWidth={2.2} /> Add to this day
            </button>
            {/* quick-add tray — fast path to a type */}
            <div style={{ marginTop: 8 }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 9.5, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'hsl(var(--muted-ink))', marginBottom: 10 }}>Quick add</div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                {ADD_ORDER.map(k => {
                  const t = ITEM_TYPE[k];
                  return (
                    <button key={k} title={t.label} onClick={() => onAdd(k)} style={{ width: 40, height: 40, borderRadius: 12, border: 'none', cursor: 'pointer',
                      background: `hsl(${t.color} / 0.16)`, color: `hsl(${t.color})`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <Icon name={t.icon} size={19} color={`hsl(${t.color})`} />
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        ) : (
          <>
            {d.morning && <div style={{ marginBottom: 12 }}><StayBand when="This morning" stay={d.morning} /></div>}
            {d.items.map((item, j) => (
              <AgendaRow key={j} item={item} first={j === 0} last={j === d.items.length - 1} />
            ))}
            {d.tonight && <div style={{ marginTop: 12 }}><StayBand when="Tonight" stay={d.tonight} /></div>}
            <button onClick={() => onAdd()} style={{ marginTop: 6, width: '100%', height: 44, borderRadius: 'var(--radius-md)', border: '1px dashed hsl(var(--line-strong))', background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, color: 'hsl(var(--muted-ink))', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 13 }}>
              <Icon name="plus" size={16} color="hsl(var(--muted-ink))" /> Add to this day
            </button>
          </>
        )}
      </div>

      {/* activity feed (view mode only) */}
      {!editing && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24, padding: '24px 0 0' }}>
          <LatestActivity />
        </div>
      )}
    </div>
  );
}

// ── Nearby tab ────────────────────────────────────────────────
function NearbyTab() {
  const [sort, setSort] = useState('distance');
  const [cat, setCat] = useState('all');
  const pois = [
    { n: 'Caffè Nettuno', t: 'Café', r: 4.7, d: '120 m · 2 min walk', tone: 'open', state: 'Open', detail: 'until 18:00' },
    { n: 'Trattoria del Mare', t: 'Restaurant', r: 4.9, d: '340 m · 4 min walk', tone: 'closing', state: 'Closes in 25 min' },
    { n: 'Bar Centrale', t: 'Bar', r: 4.4, d: '410 m · 5 min walk', tone: 'closed', state: 'Closed', detail: 'opens Sat 08:00' },
    { n: 'Forno Sardo', t: 'Bakery', r: 4.6, d: '560 m · 7 min walk' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <div className="bg-dot-grid" style={{ position: 'relative', height: 220, flexShrink: 0,
        background: 'linear-gradient(135deg, hsl(var(--paper-raise)), hsl(var(--paper-hi)))', borderBottom: '1px solid hsl(var(--line))', overflow: 'hidden' }}>
        <svg width="100%" height="100%" viewBox="0 0 380 220" style={{ position: 'absolute', inset: 0 }} preserveAspectRatio="none">
          <path d="M 20 180 C 90 120, 130 150, 190 90 S 320 60, 360 30" fill="none" stroke="hsl(var(--ember))" strokeWidth="3" strokeLinecap="round" opacity="0.85" />
        </svg>
        <span style={{ position: 'absolute', left: 178, top: 78, width: 18, height: 18, borderRadius: 999, background: 'hsl(var(--ember))', border: '3px solid hsl(var(--ink))', boxShadow: '0 0 10px rgba(0,0,0,0.3)' }} />
        {[[60, 150], [240, 70], [320, 110]].map(([x, y], i) => (
          <span key={i} style={{ position: 'absolute', left: x, top: y, width: 24, height: 24, borderRadius: 999, background: 'hsl(var(--paper))', border: '2px solid hsl(var(--ink))', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 11, color: 'hsl(var(--ink))', boxShadow: 'var(--shadow-soft)' }}>{i + 1}</span>
        ))}
        <div style={{ position: 'absolute', bottom: 12, left: 0, right: 0, display: 'flex', gap: 8, justifyContent: 'center' }}>
          <Btn variant="outline" size="sm" style={{ background: 'hsl(var(--paper) / 0.95)', backdropFilter: 'blur(8px)', textTransform: 'none', letterSpacing: 0, fontWeight: 700, boxShadow: 'var(--shadow-soft)' }}><Icon name="crosshair" size={15} /> Use my location</Btn>
          <Btn variant="outline" size="sm" style={{ background: 'hsl(var(--paper) / 0.95)', backdropFilter: 'blur(8px)', textTransform: 'none', letterSpacing: 0, fontWeight: 700, boxShadow: 'var(--shadow-soft)' }}><Icon name="map-pin" size={15} /> Drop a pin</Btn>
        </div>
      </div>
      <div style={{ padding: '14px 16px 110px' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
          <Chip active={sort === 'distance'} onClick={() => setSort('distance')}>Distance</Chip>
          <Chip active={sort === 'rating'} onClick={() => setSort('rating')}>Top rated</Chip>
          <Chip active={cat === 'food'} onClick={() => setCat(cat === 'food' ? 'all' : 'food')}>Food</Chip>
          <Chip active={cat === 'drink'} onClick={() => setCat(cat === 'drink' ? 'all' : 'drink')}>Drink</Chip>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {pois.map((p, i) => (
            <Card key={i} hoverable style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ width: 26, height: 26, borderRadius: 999, background: 'hsl(var(--ink))', color: 'hsl(var(--bg))', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 12, flexShrink: 0 }}>{i + 1}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'hsl(var(--muted-ink))' }}>{p.t}</div>
                <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 15, color: 'hsl(var(--ink))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.n}</div>
                {/* #719: one meta line, status dot + bold state word, then distance. Never wraps. */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3, minWidth: 0 }}>
                  {p.tone && <span style={{ width: 6, height: 6, borderRadius: 999, flexShrink: 0, background: { open: 'hsl(var(--soft-green))', closing: 'hsl(var(--warm))', closed: 'hsl(var(--soft-red))' }[p.tone] }} />}
                  {p.state && <span style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'hsl(var(--muted-ink))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    <b style={{ color: 'hsl(var(--ink))' }}>{p.state}</b>{p.detail ? ` ${p.detail}` : ''}
                  </span>}
                  <span style={{ fontFamily: 'var(--font-sans)', fontSize: 12, color: 'hsl(var(--muted-ink))', whiteSpace: 'nowrap', flexShrink: 0 }}>{p.state ? `· ${p.d.split(' · ')[0]}` : p.d}</span>
                </div>
              </div>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, alignSelf: 'flex-start', fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 12, color: 'hsl(var(--ink))', flexShrink: 0 }}><Icon name="star" size={12} color="hsl(var(--warm))" /> {p.r}</span>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Highlights (unchanged) ────────────────────────────────────────────────
function HighlightsTab() {
  const cards = [
    { loc: 'Cala Luna', tone: '210 45% 62%' }, { loc: 'Gola di Gorropu', tone: '142 30% 52%' },
    { loc: 'Cala Gonone', tone: '27 55% 60%' }, { loc: 'Ridge summit', tone: '215 22% 55%' },
    { loc: 'Harbour dawn', tone: '207 50% 58%' }, { loc: 'Olive grove', tone: '90 28% 52%' },
  ];
  return (
    <div style={{ padding: '16px 16px 110px' }}>
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.22em', color: 'hsl(var(--muted-ink))' }}>Highlights</div>
        <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 22, color: 'hsl(var(--ink))', letterSpacing: '-0.02em', marginTop: 2 }}>42 highlights</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {cards.map((c, i) => (
          <div key={i} style={{ borderRadius: 'var(--radius)', overflow: 'hidden', boxShadow: 'var(--shadow-card)', aspectRatio: '3/4', position: 'relative', background: `linear-gradient(160deg, hsl(${c.tone}), hsl(${c.tone.split(' ')[0]} ${parseInt(c.tone.split(' ')[1])-10}% ${parseInt(c.tone.split(' ')[2])-18}%))` }}>
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(0,0,0,0.45), transparent 55%)' }} />
            <div style={{ position: 'absolute', top: 8, right: 8, width: 20, height: 20, borderRadius: 999, background: 'rgba(255,255,255,0.25)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="camera" size={11} color="#fff" />
            </div>
            <div style={{ position: 'absolute', left: 10, bottom: 9, fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 12, color: '#fff', textShadow: '0 1px 3px rgba(0,0,0,0.4)' }}>{c.loc}</div>
          </div>
        ))}
      </div>
      <div style={{ textAlign: 'center', marginTop: 14, fontFamily: 'var(--font-sans)', fontSize: 11, color: 'hsl(var(--muted-ink))', fontStyle: 'italic' }}>Highlights are user photos — placeholders shown here.</div>
    </div>
  );
}

// #537 design proposal: current spending and frozen requests stay separate.
const COSTS_SAMPLE = [
  { id: 'dinner', who: 'AB', title: 'Dinner at the pub', amount: '€80.00', payer: 'Alex', date: '22 Apr 2026', split: '4 ways' },
  { id: 'train', who: 'MA', title: 'Train tickets', amount: '€40.00', payer: 'Mara', date: '21 Apr 2026', split: '4 ways' },
];

function CostsHistory({ onOpen }) {
  return (
    <section style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <Kicker>History</Kicker>
      <div style={{ background: 'hsl(var(--paper))', border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' }}>
        {[
          { id: 'awaiting', range: '20–21 Apr · EUR', total: '€240.00', state: 'Awaiting payments · 2 left' },
          { id: 'settled', range: '18–20 Apr · EUR', total: '€160.00', state: 'Settled' },
        ].map((period, i) => (
          <button key={period.id} onClick={() => onOpen?.(period.id)} style={{ width: '100%', padding: 14, border: 'none',
            borderTop: i ? '1px solid var(--line)' : 'none', background: 'transparent', textAlign: 'left', cursor: 'pointer',
            fontFamily: 'var(--font-sans)', color: 'hsl(var(--ink))' }}>
            <span style={{ display: 'flex', justifyContent: 'space-between', gap: 12, fontWeight: 800, fontSize: 13 }}>
              <span>{period.range}</span><span>{period.total}</span>
            </span>
            <span style={{ display: 'block', marginTop: 5, fontSize: 12, fontWeight: 600,
              color: period.id === 'awaiting' ? 'hsl(var(--ember))' : 'hsl(var(--muted-ink))' }}>{period.state}</span>
          </button>
        ))}
      </div>
    </section>
  );
}

function TheTab({ empty = false, fresh = false, deleted = false, onAdd, onSettle, onExpense, onHistory }) {
  const expenses = empty || fresh ? [] : COSTS_SAMPLE.filter(e => !deleted || e.id !== 'dinner');
  const total = deleted ? '€40.00' : '€120.00';
  return (
    <div style={{ padding: '16px 16px 110px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div>
        <Kicker>Costs</Kicker>
        <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 22, color: 'hsl(var(--ink))', letterSpacing: '-0.02em', marginTop: 2 }}>Open costs</div>
      </div>
      {!expenses.length ? (
        <div style={{ padding: '18px 0 4px' }}>
          <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 18, color: 'hsl(var(--ink))' }}>
            {fresh ? 'A fresh tab is ready' : 'Nothing on the tab yet'}
          </div>
          <p style={{ fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 13, lineHeight: 1.6, color: 'hsl(var(--muted-ink))' }}>
            {fresh ? 'Earlier expenses are frozen. Keep adding what you pay next.' : 'Add what you paid — PitStop works out who owes whom.'}
          </p>
        </div>
      ) : (
        <div style={{ padding: 16, background: 'hsl(var(--paper))', border: '1px solid var(--line)', borderRadius: 14 }}>
          <Kicker>Current total · EUR</Kicker>
          <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 34, color: 'hsl(var(--ink))', marginTop: 4 }}>{total}</div>
          <div style={{ fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 600, color: 'hsl(var(--muted-ink))', marginTop: 6 }}>
            {deleted ? 'You owe Mara €10.00' : 'You are owed €50.00'} · Not settled up yet
          </div>
        </div>
      )}
      <div style={{ display: 'flex', gap: 8 }}>
        <Btn full onClick={onAdd}><Icon name="plus" size={16} /> Add expense</Btn>
        {!!expenses.length && <Btn variant="outline" onClick={onSettle}>Settle up</Btn>}
      </div>
      {!!expenses.length && (
        <div style={{ background: 'hsl(var(--paper))', border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' }}>
          {expenses.map((e, i) => (
            <button key={e.id} onClick={() => onExpense?.(e)} style={{ width: '100%', padding: 14, display: 'flex',
              alignItems: 'center', gap: 10, background: 'transparent', border: 'none',
              borderTop: i ? '1px dotted var(--line-strong)' : 'none', textAlign: 'left', cursor: 'pointer' }}>
              <Avatar initials={e.who} i={i} size={30} />
              <span style={{ flex: 1, fontFamily: 'var(--font-sans)', color: 'hsl(var(--ink))' }}>
                <span style={{ display: 'block', fontWeight: 800, fontSize: 13 }}>{e.title}</span>
                <span style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'hsl(var(--muted-ink))', marginTop: 3 }}>
                  {e.date} · {e.payer} paid · {e.split}
                </span>
              </span>
              <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 14, color: 'hsl(var(--ink))' }}>{e.amount}</span>
            </button>
          ))}
        </div>
      )}
      {!empty && <CostsHistory onOpen={onHistory} />}
    </div>
  );
}

// ── Trip sheet (#723) — opened from the trip name in the header ──────────
// Recreated from apps/web/src/components/trip/TripSheet.tsx: name, dates +
// countdown, members (→ people sheet), invite, and the owner/admin options.
function TripSheet({ trip, onClose }) {
  const row = (icon, label, sub, danger, right) => (
    <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 4px', borderTop: '1px solid var(--line)' }}>
      <Icon name={icon} size={18} color={danger ? 'hsl(var(--soft-red))' : 'hsl(var(--ink))'} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 14.5, color: danger ? 'hsl(var(--soft-red))' : 'hsl(var(--ink))' }}>{label}</div>
        {sub && <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 500, fontSize: 12, color: 'hsl(var(--muted-ink))', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, zIndex: 40, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: '100%', background: 'hsl(var(--paper))', borderRadius: '22px 22px 0 0', padding: '10px 18px 34px', boxShadow: 'var(--shadow-card)' }}>
        <div style={{ width: 40, height: 4, borderRadius: 999, background: 'var(--line-strong)', margin: '0 auto 14px' }} />
        <div style={{ fontFamily: 'var(--font-sans)', fontWeight: 800, fontSize: 19, letterSpacing: '-0.02em', color: 'hsl(var(--ink))' }}>{trip.name}</div>
        <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'hsl(var(--muted-ink))', margin: '6px 0 14px' }}>{`${trip.range} · Day 3 of 5`}</div>
        {row('users', `Members · ${trip.people.length}`, 'Owner first, then everyone on the trip', false, <AvatarStack people={trip.people} size={24} />)}
        {row('user-plus', 'Invite people')}
        {row('calendar-days', 'Edit dates')}
        {row('pencil', 'Rename trip')}
        {row('trash-2', 'Delete trip', null, true)}
      </div>
    </div>
  );
}

// ── Workspace shell — holds itinerary state + the add overlay ─────────────
function TripWorkspace({ trip, onBack }) {
  useLucide();
  const [tab, setTab] = useState('home');
  const [days, setDays] = useState(() => DAYS.map(d => ({ ...d, items: d.items.map(it => ({ ...it })) })));
  const [dayIdx, setDayIdx] = useState(2);
  const [editing, setEditing] = useState(false);
  const [adding, setAdding] = useState(null); // null | { initialType }
  const [tripSheet, setTripSheet] = useState(false);
  const inbox = useNotificationInbox();

  const move = (i, dir) => setDays(prev => prev.map((d, di) => {
    if (di !== dayIdx) return d;
    const items = [...d.items]; const j = i + dir;
    if (j < 0 || j >= items.length) return d;
    [items[i], items[j]] = [items[j], items[i]];
    return { ...d, items };
  }));
  const del = (i) => setDays(prev => prev.map((d, di) => di === dayIdx ? { ...d, items: d.items.filter((_, k) => k !== i) } : d));
  const addItem = (item) => {
    setDays(prev => prev.map((d, di) => di === dayIdx ? { ...d, items: [...d.items, item] } : d));
    setAdding(null);
  };

  const dayLabel = `${days[dayIdx].dow} ${days[dayIdx].dom} ${days[dayIdx].mon}`;
  return (
    <div style={{ height: '100%', background: 'hsl(var(--bg))', position: 'relative', overflow: 'hidden' }}>
      {/* scroll region fills the device; the nav + add overlay stay pinned to it */}
      <div className="pitstop-scroll" style={{ position: 'absolute', inset: 0, overflowY: 'auto' }}>
        {tab === 'nearby'
          ? <SubPageHeader onBack={() => setTab('home')} backLabel="Back to trip" context={trip.name} title="Nearby" />
          : <TripTopStrip name={trip.name} onBack={onBack} unread={inbox.unread} onOpenNotifications={inbox.openSheet} tab={tab} onTab={setTab} onOpenTrip={() => setTripSheet(true)} />}
        {tab === 'home' && <TripHomeTab trip={trip} days={days} dayIdx={dayIdx} setDayIdx={setDayIdx}
          editing={editing} setEditing={setEditing}
          onAdd={(initialType) => setAdding({ initialType: initialType || null })} onMove={move} onDelete={del} />}
        {tab === 'nearby' && <NearbyTab />}
        {tab === 'highlights' && <HighlightsTab />}
        {tab === 'tab' && <TheTab />}
      </div>
      {tab === 'home' && !editing && <FindNearbyButton onClick={() => setTab('nearby')} />}
      {inbox.sheet}
      {tripSheet && <TripSheet trip={trip} onClose={() => setTripSheet(false)} />}
      {adding && <AddFlow dayLabel={dayLabel} initialType={adding.initialType} onClose={() => setAdding(null)} onSave={addItem} />}
    </div>
  );
}

Object.assign(window, { TripWorkspace, TripSheet, BottomNav, TripTabs, FindNearbyButton, SubPageHeader, DAYS, DayRail, AgendaRow, TheTab, CostsHistory });
