// Interactive flow screens — drawer, dispatch list, call detail, map, login.
// Each screen is a self-contained component that takes navigation callbacks.

const { useState: useStateS, useEffect: useEffectS } = React;

// ─────── Sample data ─────────────────────────────────────────
const SAMPLE_CALLS = [
  {
    id: 1, number: '3206', status: 'towing',
    statusSentence: 'L. Brown is towing', type: 'Tow',
    vehicleYear: "17'", vehicleMakeModel: 'Chevrolet Corvette', vehicleColor: 'Red',
    account: 'McDonald Investments',
    receivedTime: '4:28 PM', timeAgo: '25m ago', eta: '5:45 PM',
    pickup: '157 Carney Drive, Saint Clair, MI 48079',
    dropoff: '1655 Yeager St, Port Huron, MI 48060',
  },
  {
    id: 2, number: '3205', status: 'onscene',
    statusSentence: 'W. Smith is on scene', type: 'Tow',
    vehicleYear: "18'", vehicleMakeModel: 'GMC Yukon', vehicleColor: 'Black',
    account: "Newfie's Chevrolet",
    receivedTime: '4:27 PM', timeAgo: '26m ago', eta: '6:35 PM',
    pickup: '1296 Pickwick Pl, Flint, MI 48507',
    dropoff: '345 Cox Rd, St Clair, MI 48079',
  },
  {
    id: 3, number: '3204', status: 'enroute',
    statusSentence: 'E. Brown is en route', type: 'Tow',
    vehicleYear: "16'", vehicleMakeModel: 'Jaguar XF', vehicleColor: 'Black',
    account: 'Cash / Private Retail Customer',
    receivedTime: '4:25 PM', timeAgo: '28m ago', eta: '6:25 PM',
    pickup: '5402 Lapeer Rd, Burton, MI 48509',
    dropoff: '880 W Maple Rd, Troy, MI 48084',
  },
];

const SAMPLE_WAITING = [
  {
    id: 10, number: '3210', status: 'waiting',
    statusSentence: 'Unassigned', type: 'Roadside · Lockout',
    vehicleYear: "21'", vehicleMakeModel: 'Honda Civic', vehicleColor: 'Silver',
    account: 'AAA',
    receivedTime: '4:48 PM', timeAgo: '6m ago',
    pickup: '4400 Court St, Saginaw, MI 48602',
    dropoff: '—',
  },
  {
    id: 11, number: '3209', status: 'waiting',
    statusSentence: 'Unassigned', type: 'Tow · Accident',
    vehicleYear: "19'", vehicleMakeModel: 'Ford F-150', vehicleColor: 'White',
    account: 'State Farm',
    receivedTime: '4:42 PM', timeAgo: '12m ago',
    pickup: 'I-94 W at Exit 198, Detroit, MI',
    dropoff: 'Bobby\'s Auto Body, Detroit, MI',
  },
];

window.SAMPLE_CALLS = SAMPLE_CALLS;
window.SAMPLE_WAITING = SAMPLE_WAITING;

// ─────── Driver profile (used in drawer header) ──────────────
function DrawerHeader({ name = 'Ellie Brown', role = 'Driver', onClose }) {
  return (
    <div style={{
      padding: '20px 16px 16px',
      background: 'var(--tb-surface-2)',
      borderBottom: '1px solid var(--tb-divider)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 48, height: 48, borderRadius: '50%',
          background: 'var(--blue-3)', color: 'var(--blue-11)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 17, fontWeight: 600,
        }}>{name.split(' ').map(s => s[0]).join('')}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--tb-on-surface)' }}>{name}</div>
          <div style={{ fontSize: 13, color: 'var(--tb-on-surface-muted)' }}>{role}</div>
        </div>
        <button onClick={onClose} style={{
          padding: '6px 10px', borderRadius: 999,
          border: 0, background: 'var(--green-3)', color: 'var(--green-11)',
          fontSize: 12, fontWeight: 600,
          display: 'inline-flex', alignItems: 'center', gap: 4, cursor: 'pointer',
        }}>
          <I.DollarSign size={14}/>
          Clock in
        </button>
      </div>
    </div>
  );
}

function DrawerLink({ icon, label, badge, active, onClick }) {
  const [pressed, setPressed] = useStateS(false);
  return (
    <button
      onClick={onClick}
      onMouseDown={() => setPressed(true)} onMouseUp={() => setPressed(false)} onMouseLeave={() => setPressed(false)}
      style={{
        display: 'flex', alignItems: 'center', gap: 14,
        width: '100%', height: 52,
        padding: '0 16px',
        background: active ? 'var(--blue-3)' : (pressed ? 'var(--slate-3)' : 'transparent'),
        color: active ? 'var(--blue-11)' : 'var(--tb-on-surface)',
        border: 0,
        borderLeft: `3px solid ${active ? 'var(--tb-primary)' : 'transparent'}`,
        fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: active ? 600 : 500,
        cursor: 'pointer', textAlign: 'left',
        transition: 'background 80ms var(--ease-in)',
      }}>
      <div style={{ display: 'flex', color: active ? 'var(--blue-11)' : 'var(--tb-on-surface-muted)' }}>
        {React.createElement(icon, { size: 20 })}
      </div>
      <span style={{ flex: 1 }}>{label}</span>
      {badge && (
        <span style={{
          padding: '2px 7px', fontSize: 11, fontWeight: 700,
          borderRadius: 999, background: 'var(--red-9)', color: 'white',
        }}>{badge}</span>
      )}
    </button>
  );
}

function NavDrawerScreen({ active = 'dispatching', onNavigate, onClose, checkedIn, onCheckedInChange }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--tb-surface)' }}>
      <DrawerHeader name="Ellie Brown" role="Driver" onClose={onClose}/>

      <div style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: '14px 16px',
        borderBottom: '1px solid var(--tb-divider)',
        background: 'var(--tb-surface)',
      }}>
        <div style={{ display: 'flex', color: checkedIn ? 'var(--green-11)' : 'var(--tb-on-surface-faint)' }}>
          <I.User size={20}/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--tb-on-surface)' }}>Checked in</div>
          <div style={{ fontSize: 12, color: 'var(--tb-on-surface-muted)' }}>{checkedIn ? 'Available for calls' : 'Off duty'}</div>
        </div>
        <TBSwitch checked={checkedIn} onChange={onCheckedInChange}/>
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        <DrawerLink icon={I.Truck} label="Dispatching" active={active === 'dispatching'} badge="3" onClick={() => onNavigate?.('dispatching')}/>
        <DrawerLink icon={I.Lock} label="Impounds" active={active === 'impounds'} onClick={() => onNavigate?.('impounds')}/>
        <DrawerLink icon={I.Tag} label="Stickering" active={active === 'stickering'} onClick={() => onNavigate?.('stickering')}/>
        <DrawerLink icon={I.Briefcase} label="Accounts" active={active === 'accounts'} onClick={() => onNavigate?.('accounts')}/>
        <DrawerLink icon={I.MessageCircle} label="Chats" badge="2" active={active === 'chats'} onClick={() => onNavigate?.('chats')}/>
        <DrawerLink icon={I.ClipboardCheck} label="Equipment Inspection" active={active === 'inspection'} onClick={() => onNavigate?.('inspection')}/>
      </div>

      <div style={{ borderTop: '1px solid var(--tb-divider)' }}>
        <DrawerLink icon={I.Settings} label="Settings" onClick={() => onNavigate?.('settings')}/>
        <DrawerLink icon={I.LogOut} label="Log out" onClick={() => onNavigate?.('logout')}/>
      </div>
    </div>
  );
}

// ─────── Dispatch list screen ────────────────────────────────
function DispatchListScreen({ onOpenCall, onOpenDrawer, refreshing, onRefresh, tab, onTabChange }) {
  const [t, setT] = useStateS(tab || 'active');
  const activeTab = tab !== undefined ? tab : t;
  const setTab = onTabChange || setT;

  const calls = activeTab === 'active' ? SAMPLE_CALLS
    : activeTab === 'waiting' ? SAMPLE_WAITING
    : activeTab === 'completed' ? [{...SAMPLE_CALLS[0], status: 'completed', statusSentence: 'Cleared 2:14 PM'}, {...SAMPLE_CALLS[1], status: 'completed', statusSentence: 'Cleared 11:48 AM'}]
    : [];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', position: 'relative' }}>
      <TBTabs
        items={[
          { value: 'waiting', label: 'Waiting', count: SAMPLE_WAITING.length },
          { value: 'active', label: 'Active', count: SAMPLE_CALLS.length },
          { value: 'completed', label: 'Completed' },
          { value: 'canceled', label: 'Canceled' },
        ]}
        value={activeTab}
        onChange={setTab}
        variant="primary"
        scrollable
      />
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--tb-surface-1)' }}>
        <TBPullToRefresh refreshing={refreshing}/>
        {calls.length === 0 ? (
          <EmptyState/>
        ) : (
          calls.map(c => (
            <TBCallCard key={c.id} call={c}
              onClick={() => onOpenCall?.(c)}
              onEdit={() => onOpenCall?.(c)}
              onUpdateStatus={() => onOpenCall?.(c, 'updateStatus')}
              onCallContact={() => {}}
            />
          ))
        )}
        <div style={{ height: 80 }}/>
      </div>
      <div style={{ position: 'absolute', right: 16, bottom: 16, zIndex: 5 }}>
        <TBFab icon={I.Plus} onClick={() => {}}/>
      </div>
    </div>
  );
}

function EmptyState() {
  return (
    <div style={{
      padding: '64px 32px', textAlign: 'center',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 56, height: 56, borderRadius: '50%',
        background: 'var(--blue-3)', color: 'var(--blue-11)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      }}><I.CheckCircle size={28}/></div>
      <div style={{ fontSize: 17, fontWeight: 600, color: 'var(--tb-on-surface)' }}>No calls yet</div>
      <div style={{ fontSize: 13, color: 'var(--tb-on-surface-muted)', maxWidth: 240 }}>
        Create the first one to get started.
      </div>
      <TBButton variant="filled" icon={I.Plus} size="sm">New call</TBButton>
    </div>
  );
}

// ─────── Call detail screen (#3176) ──────────────────────────
function CallDetailScreen({ onBack, onUpdateStatus }) {
  const [sheetOpen, setSheetOpen] = useStateS(false);
  const [status, setStatus] = useStateS('onscene');
  const accent = (TBT.status[status] || {}).solid || 'var(--green-9)';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', position: 'relative', background: 'var(--tb-surface-1)' }}>
      {/* status accent strip — follows the current status */}
      <div style={{ height: 4, background: accent, transition: 'background 200ms var(--ease-in)' }}/>

      {/* Vehicle header */}
      <div style={{ padding: '14px 16px', background: 'var(--tb-surface)' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 6 }}>
          <h2 style={{ margin: 0, fontSize: 20, fontWeight: 600, letterSpacing: '-0.01em', color: 'var(--tb-on-surface)' }}>
            06' Acura TL <span style={{ color: 'var(--tb-on-surface-muted)', fontWeight: 500 }}>(Black)</span>
          </h2>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
          <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--tb-on-surface-muted)' }}>Fuel Delivery</span>
          <TBStatusPill status={status} size="sm"/>
        </div>
        <div style={{ fontSize: 13, color: 'var(--tb-on-surface-muted)' }}>
          Joes Apt. Complex · 04:06 PM
        </div>
      </div>

      {/* Address */}
      <div style={{ background: 'var(--tb-surface)', marginTop: 8 }}>
        <TBDetailRow icon={I.MapPin}
          value={<>
            <div>1234 6th St, Marysville, MI 48040, USA</div>
            <div style={{ fontSize: 12, color: 'var(--tb-on-surface-muted)', marginTop: 2 }}>(1234 6th Street) · 7.4 mi</div>
          </>}
          action={<TBButton variant="text" size="sm" icon={I.Navigation}>Go</TBButton>}
        />
      </div>

      {/* Contacts */}
      <div style={{ background: 'var(--tb-surface)', marginTop: 8 }}>
        <TBSectionHeader>Contacts</TBSectionHeader>
        <TBDetailRow icon={I.User}
          value={<>
            <div style={{ fontWeight: 500 }}>John Smith</div>
            <div style={{ fontSize: 13, color: 'var(--blue-11)', fontWeight: 500 }}>810-320-5063</div>
          </>}
          action={<button style={{
            width: 40, height: 40, borderRadius: '50%',
            border: 0, background: 'var(--green-3)', color: 'var(--green-11)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}><I.Phone size={18}/></button>}
        />
      </div>

      {/* Vehicle / details */}
      <div style={{ background: 'var(--tb-surface)', marginTop: 8 }}>
        <TBSectionHeader>Vehicle</TBSectionHeader>
        <TBDetailRow icon={I.Hash} label="Plate" value="XDAN / MI"/>
        <TBDetailRow icon={I.Scan} label="VIN" value="19UUA65506A059978"
          action={<TBButton variant="text" size="sm">Scan</TBButton>}/>
        <TBDetailRow icon={I.User} label="Driver" value="Lesa Brown — Unit #3"/>
        <TBDetailRow icon={I.KeyRound} label="Keys" value="Yes"/>
      </div>

      {/* Times */}
      <div style={{ background: 'var(--tb-surface)', marginTop: 8 }}>
        <TBSectionHeader>Times</TBSectionHeader>
        <div style={{ padding: '4px 16px 12px' }}>
          <TimeRow color="var(--amber-10)" label="Received" value="10/07/2019 · 04:06 PM"/>
          <TimeRow color="var(--blue-10)" label="Dispatched" value="10/07/2019 · 04:07 PM"/>
          <TimeRow color="var(--green-10)" label="On scene" value="10/08/2019 · 01:03 PM"/>
        </div>
      </div>

      {/* Photos */}
      <div style={{ background: 'var(--tb-surface)', marginTop: 8 }}>
        <TBSectionHeader>Photos
          <TBChip variant="assist" leadingIcon={I.Plus}>Add</TBChip>
        </TBSectionHeader>
        <div style={{ display: 'flex', gap: 10, padding: '4px 16px 16px', overflowX: 'auto' }}>
          <TBPhotoTile label="Front"/>
          <TBPhotoTile label="Rear"/>
          <TBPhotoTile label="Damage" count={2}/>
          <TBPhotoTile label="Add"/>
        </div>
      </div>

      {/* Bottom action bar */}
      <div style={{ height: 64 }}/>
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 22 }}>
        <TBBottomActionBar items={[
          { icon: I.Refresh, label: 'Change Status', onClick: () => setSheetOpen(true) },
          { icon: I.Camera, label: 'Add Photo' },
          { icon: I.Map, label: 'Show Map' },
          { icon: I.Layers, label: 'More' },
        ]}/>
      </div>

      {/* Status update sheet */}
      <TBBottomSheet open={sheetOpen} onDismiss={() => setSheetOpen(false)} title="Update status">
        {['waiting','enroute','onscene','towing','completed','canceled'].map(s => {
          const isCurrent = s === status;
          return (
            <button key={s}
              onClick={() => { setStatus(s); setSheetOpen(false); onUpdateStatus?.(s); }}
              style={{
                width: '100%', display: 'flex', alignItems: 'center', gap: 14,
                padding: '14px 24px', border: 0,
                background: isCurrent ? 'var(--blue-a3)' : 'transparent',
                cursor: 'pointer', textAlign: 'left',
              }}>
              <TBStatusPill status={s}/>
              <span style={{ flex: 1 }}/>
              {isCurrent
                ? <I.Check size={18} color="var(--tb-primary)"/>
                : <I.ChevronRight size={18} color="var(--tb-on-surface-faint)"/>}
            </button>
          );
        })}
        <div style={{ height: 12 }}/>
      </TBBottomSheet>
    </div>
  );
}

function TimeRow({ color, label, value }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '6px 0' }}>
      <span style={{ width: 10, height: 10, borderRadius: '50%', background: color, flexShrink: 0 }}/>
      <span style={{ flex: 1, fontSize: 14, color: 'var(--tb-on-surface)' }}>{label}</span>
      <span style={{ fontSize: 13, color: 'var(--tb-on-surface-muted)', fontVariantNumeric: 'tabular-nums' }}>{value}</span>
    </div>
  );
}

// ─────── Map screen ──────────────────────────────────────────
function MapScreen({ onOpenCall }) {
  const [filter, setFilter] = useStateS('calls');
  const [selected, setSelected] = useStateS(null);
  const dark = typeof document !== 'undefined' && document.documentElement.getAttribute('data-theme') === 'dark';

  return (
    <div style={{ position: 'relative', height: '100%', background: dark ? '#1a1d22' : '#dde3eb', overflow: 'hidden' }}>
      {/* Stylized map (SVG) */}
      <svg viewBox="0 0 360 600" preserveAspectRatio="xMidYMid slice"
           style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <defs>
          <pattern id="tb-grid" width="48" height="48" patternUnits="userSpaceOnUse">
            <path d="M48 0H0V48" fill="none" stroke={dark ? '#2a2e34' : '#cbd2db'} strokeWidth="1"/>
          </pattern>
        </defs>
        <rect width="360" height="600" fill={dark ? '#13161a' : '#e6ebf2'}/>
        <rect width="360" height="600" fill="url(#tb-grid)"/>
        {/* water */}
        <path d="M0,420 Q90,400 180,440 T360,420 L360,600 L0,600 Z" fill={dark ? '#1f2731' : '#cfdcec'}/>
        {/* roads */}
        <path d="M-20,180 L380,200" stroke={dark ? '#454a52' : '#ffffff'} strokeWidth="6" fill="none"/>
        <path d="M120,-20 L160,620" stroke={dark ? '#454a52' : '#ffffff'} strokeWidth="6" fill="none"/>
        <path d="M-20,360 L380,330" stroke={dark ? '#3b4046' : '#ffffff'} strokeWidth="4" fill="none"/>
        <path d="M250,-20 L280,620" stroke={dark ? '#3b4046' : '#ffffff'} strokeWidth="4" fill="none"/>
      </svg>

      {/* Filter chips top */}
      <div style={{
        position: 'absolute', top: 12, left: 12, right: 12,
        display: 'flex', gap: 8, justifyContent: 'center',
      }}>
        <div style={{ display: 'inline-flex', padding: 4, background: 'var(--tb-surface)', borderRadius: 999, boxShadow: 'var(--tb-elev-1)' }}>
          <SegBtn active={filter==='drivers'} onClick={() => setFilter('drivers')} icon={I.User}>Drivers</SegBtn>
          <SegBtn active={filter==='calls'} onClick={() => setFilter('calls')} icon={I.MapPin}>Calls</SegBtn>
        </div>
      </div>

      {/* Pins */}
      <Pin top={210} left={80} number="3204" status="enroute" onClick={() => setSelected('3204')}/>
      <Pin top={310} left={210} number="3205" status="onscene" onClick={() => setSelected('3205')}/>
      <Pin top={150} left={250} number="3206" status="towing" onClick={() => setSelected('3206')}/>
      <Pin top={400} left={130} number="3207" status="waiting" onClick={() => setSelected('3207')}/>

      {/* Floating action stack (right) */}
      <div style={{ position: 'absolute', right: 12, bottom: 96, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <RoundIconBtn icon={I.Layers}/>
        <RoundIconBtn icon={I.Crosshair}/>
      </div>

      {/* Bottom info card if a pin is selected */}
      {selected && (
        <div style={{
          position: 'absolute', left: 12, right: 12, bottom: 16,
          background: 'var(--tb-surface)',
          borderRadius: 16,
          boxShadow: 'var(--tb-elev-3)',
          padding: 14,
          animation: 'tb-slideup 200ms var(--ease-in)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <span style={{
              padding: '2px 8px', borderRadius: 4, background: 'var(--tb-primary)',
              color: 'white', fontSize: 13, fontWeight: 700,
            }}>{selected}</span>
            <TBStatusPill status={selected==='3204'?'enroute':selected==='3205'?'onscene':selected==='3206'?'towing':'waiting'} size="sm"/>
            <span style={{ flex: 1 }}/>
            <button onClick={() => setSelected(null)} style={{
              background: 'transparent', border: 0, color: 'var(--tb-on-surface-muted)',
              cursor: 'pointer', display: 'inline-flex',
            }}><I.X size={18}/></button>
          </div>
          <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--tb-on-surface)' }}>
            17' Chevrolet Corvette <span style={{ color: 'var(--tb-on-surface-muted)', fontWeight: 500 }}>(Red)</span>
          </div>
          <div style={{ fontSize: 13, color: 'var(--tb-on-surface-muted)', marginTop: 2 }}>
            157 Carney Drive, Saint Clair
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
            <TBButton variant="filled" size="sm" icon={I.Navigation} fullWidth>Directions</TBButton>
            <TBButton variant="outlined" size="sm" icon={I.Eye} onClick={() => onOpenCall?.()}>Open</TBButton>
          </div>
        </div>
      )}
    </div>
  );
}

function SegBtn({ active, onClick, icon, children }) {
  return (
    <button onClick={onClick} style={{
      padding: '8px 16px',
      borderRadius: 999, border: 0,
      background: active ? 'var(--tb-primary)' : 'transparent',
      color: active ? 'white' : 'var(--tb-on-surface-muted)',
      fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600,
      display: 'inline-flex', alignItems: 'center', gap: 6, cursor: 'pointer',
    }}>
      {React.createElement(icon, { size: 16 })}{children}
    </button>
  );
}

function RoundIconBtn({ icon, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 44, height: 44, borderRadius: '50%',
      background: 'var(--tb-surface)', color: 'var(--tb-on-surface)',
      border: 0, boxShadow: 'var(--tb-elev-2)',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      cursor: 'pointer',
    }}>{React.createElement(icon, { size: 20 })}</button>
  );
}

function Pin({ top, left, number, status, onClick }) {
  const dark = typeof document !== 'undefined' && document.documentElement.getAttribute('data-theme') === 'dark';
  const palette = (dark ? TBT.statusDark : TBT.status)[status];
  return (
    <button onClick={onClick} style={{
      position: 'absolute', top, left,
      transform: 'translate(-50%, -100%)',
      background: 'transparent', border: 0, padding: 0, cursor: 'pointer',
    }}>
      <div style={{
        background: palette.solid, color: 'white',
        padding: '4px 10px', borderRadius: 8,
        fontSize: 12, fontWeight: 700, fontVariantNumeric: 'tabular-nums',
        boxShadow: '0 4px 12px rgba(0,0,0,0.25)',
        position: 'relative',
      }}>
        {number}
        <span style={{
          position: 'absolute', left: '50%', bottom: -5,
          transform: 'translateX(-50%) rotate(45deg)',
          width: 10, height: 10, background: palette.solid,
        }}/>
      </div>
    </button>
  );
}

// ─────── Login screen ────────────────────────────────────────
function LoginScreen() {
  const [pwd, setPwd] = useStateS('');
  const [show, setShow] = useStateS(false);
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', height: '100%',
      padding: '40px 24px 24px',
      background: 'var(--tb-surface)',
    }}>
      <div style={{ marginBottom: 32, marginTop: 8 }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12,
          background: 'linear-gradient(135deg, var(--blue-9), var(--blue-11))',
          color: 'white',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 24, fontWeight: 700, letterSpacing: '-0.04em',
          marginBottom: 24,
        }}>T</div>
        <h1 style={{ margin: 0, fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--tb-on-surface)' }}>Sign in</h1>
        <p style={{ margin: '8px 0 0', fontSize: 14, color: 'var(--tb-on-surface-muted)' }}>
          Use your Towbook driver credentials.
        </p>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <TBTextField label="Email or username" leadingIcon={I.Mail} value="ellie.brown"/>
        <TBTextField label="Password" type={show ? 'text' : 'password'}
          leadingIcon={I.Lock}
          trailingIcon={show ? I.EyeOff : I.Eye2}
          value={pwd} onChange={setPwd}/>
      </div>

      <div style={{ marginTop: 24 }}>
        <TBButton variant="filled" fullWidth size="lg">Sign in</TBButton>
      </div>
      <button style={{
        marginTop: 12, padding: '12px 0',
        background: 'transparent', border: 0,
        color: 'var(--blue-11)', fontWeight: 600, fontSize: 14,
        cursor: 'pointer',
      }}>Forgot password?</button>

      <div style={{ flex: 1 }}/>
      <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--tb-on-surface-faint)' }}>
        Towbook · v8.2.0
      </div>
    </div>
  );
}

// ─────── Equipment inspection screen ─────────────────────────
function InspectionScreen() {
  const [data, setData] = useStateS({});
  const set = (k, v) => setData(prev => ({...prev, [k]: v}));
  const items = [
    'Engine oil level', 'Transmission fluid level', 'Brake fluid level',
    'Windshield washer fluid', 'Hoses & belts', 'Battery cable connections',
    'Tire condition (front)', 'Tire condition (rear)', 'Lights & turn signals',
    'Mirrors & glass', 'Wheel lift function', 'Boom & winch operation',
  ];
  return (
    <div style={{ background: 'var(--tb-surface-1)', minHeight: '100%' }}>
      <div style={{ background: 'var(--tb-surface)', padding: '14px 16px', borderBottom: '1px solid var(--tb-divider)' }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--tb-on-surface)' }}>Pre-shift inspection</div>
        <div style={{ fontSize: 13, color: 'var(--tb-on-surface-muted)', marginTop: 2 }}>Unit #3 · {Object.keys(data).filter(k => data[k]).length}/{items.length} complete</div>
        <div style={{ marginTop: 10 }}>
          <TBLinearProgress value={Object.keys(data).filter(k => data[k]).length / items.length}/>
        </div>
      </div>
      <TBSectionHeader>Truck</TBSectionHeader>
      <div style={{ background: 'var(--tb-surface)' }}>
        {items.map((label, i) => (
          <TBInspectionRow key={i} label={label}
            value={data[i]} onChange={(v) => set(i, v)}
            photoCount={data[i] === 'fail' ? 1 : 0}/>
        ))}
      </div>
      <div style={{ padding: 16 }}>
        <TBButton variant="filled" fullWidth size="lg" icon={I.Check}>Submit inspection</TBButton>
      </div>
    </div>
  );
}

Object.assign(window, {
  NavDrawerScreen, DispatchListScreen, CallDetailScreen,
  MapScreen, LoginScreen, InspectionScreen,
});
