// Screens 1/2 — Home, Time Clock, Break, Patrol list, Active Patrol, Scan
const { Card, Pill, SectionLabel, ActionTile, Button, BottomNav, AppBar, Avatar, Screen } = window;
const { Icon, BDLogo } = window;
const _T = () => window.__BD_THEME__ || window.BD_TOKENS.dark;

// ════════════════════════════════════════════════════════════
// 1. HOME / DASHBOARD — supports density: simple | medium | dense
// ════════════════════════════════════════════════════════════
function ScreenHome({ density = 'medium', dark = true }) {
  const t = _T();
  const nav = window.Nav.useNav();
  const greeting = ['Good evening', 'Officer Smith'];
  const go = (n, p) => () => nav.push(n, p);

  return (
    <>
      <AppBar t={t}/>
      <Screen t={t} bottomPad={120}>
        {/* Greeting + status hero */}
        <div style={{ padding: '0 4px' }}>
          <div style={{ fontSize: 14, color: t.text3, fontWeight: 600 }}>{greeting[0]},</div>
          <div style={{ fontSize: 26, fontWeight: 800, color: t.text, letterSpacing: -0.4 }}>{greeting[1]}</div>
        </div>

        {/* Live shift card */}
        <Card t={t} pad={0} style={{ overflow: 'hidden', position: 'relative' }}>
          {/* gradient bg */}
          <div style={{
            position: 'absolute', inset: 0,
            background: `radial-gradient(120% 100% at 0% 0%, ${t.primary}33, transparent 60%), radial-gradient(120% 100% at 100% 100%, ${t.purple}26, transparent 50%)`,
            pointerEvents: 'none',
          }}/>
          <div style={{ position: 'relative', padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <Avatar size={48} name="JS" tone="gold" online t={t}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 16, fontWeight: 700, color: t.text, lineHeight: 1.1 }}>John Smith</div>
                <div style={{ fontSize: 12.5, color: t.text3, marginTop: 2 }}>SG-1024 · Day Shift</div>
              </div>
              <Pill tone="success" t={t}><span style={{ width: 6, height: 6, borderRadius: 999, background: t.success }}/>On Duty</Pill>
            </div>

            {/* shift line */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
              <Stat t={t} label="Clocked In" value="07:00" sub="May 14"/>
              <Stat t={t} label="Worked" value="07h 47m" sub="So far" tone="primary"/>
              <Stat t={t} label="Break" value="00h 30m" sub="Taken" tone="warn"/>
            </div>

            {/* current site */}
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: 12,
              background: t.surface2, border: `1px solid ${t.line}`, borderRadius: 12,
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: t.primarySoft, color: t.primary,
                display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon.Pin size={18}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: t.text }}>Main Building · North Gate</div>
                <div style={{ fontSize: 11.5, color: t.text3, marginTop: 1 }}>123 Security Blvd · Geofence active</div>
              </div>
              <Button tone="soft" size="md" t={t} icon={<Icon.Coffee size={16} sw={2}/>} onClick={go('break')}>Break</Button>
            </div>
          </div>
        </Card>

        {/* Primary actions */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <ActionTile t={t} tone="primary" icon={<Icon.Clock size={20} sw={2}/>} label="Time Clock" onClick={go('timeClock')}/>
          <ActionTile t={t} tone="success" icon={<Icon.Shield size={20} sw={2}/>} label="Patrol Tour" onClick={go('patrol')}/>
          <ActionTile t={t} tone="purple" icon={<Icon.Doc size={20} sw={2}/>} label="Reports & Logs" onClick={go('reports')}/>
          <ActionTile t={t} tone="warn"   icon={<Icon.AlertTri size={20} sw={2}/>} label="Incident" badge={2} onClick={go('incidents')}/>
          <ActionTile t={t} tone="teal"   icon={<Icon.Chat size={20} sw={2}/>} label="Messages" badge={3} onClick={go('messages')}/>
          <ActionTile t={t} tone="gold"   icon={<Icon.Cal size={20} sw={2}/>} label="Schedule" onClick={go('schedule')}/>
        </div>

        {/* Panic */}
        <button onClick={go('panic')} style={{
          appearance: 'none', cursor: 'pointer',
          background: `linear-gradient(180deg, ${t.danger}26, ${t.danger}10)`,
          border: `1px solid ${t.danger}55`, borderRadius: 16,
          padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, color: t.text,
        }}>
          <div style={{
            width: 40, height: 40, borderRadius: 12, background: t.danger,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
            boxShadow: `0 0 0 4px ${t.danger}26`,
          }}><Icon.AlertTri size={20} sw={2.2}/></div>
          <div style={{ flex: 1, textAlign: 'left' }}>
            <div style={{ fontSize: 14, fontWeight: 800, color: t.danger, letterSpacing: 0.4 }}>EMERGENCY / PANIC</div>
            <div style={{ fontSize: 12, color: t.text2, marginTop: 2 }}>Hold 3 sec · live location to dispatch</div>
          </div>
          <Icon.Chev size={18}/>
        </button>

        {/* Live status row (medium/dense) — quieter, single card with rows */}
        {density !== 'simple' && (
          <Card t={t} pad={0}>
            {[
              ['Last patrol', '10:05 AM', 'Main Building', t.success],
              ['Next checkpoint', 'South Gate', '120m away', t.primary],
              ['Active alerts', '2 open', 'View alerts', t.danger],
            ].map(([k,v,sub,c],i,a)=>(
              <div key={i} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px',
                borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
                <span style={{ width:6, height:6, borderRadius:999, background:c }}/>
                <div style={{ fontSize:12.5, color:t.text3, fontWeight:600, width:120 }}>{k}</div>
                <div style={{ flex:1, fontSize:13.5, fontWeight:700, color:t.text }}>{v}</div>
                <div style={{ fontSize:11.5, color:t.text3 }}>{sub}</div>
              </div>
            ))}
          </Card>
        )}

        {/* Dense extras */}
        {density === 'dense' && (
          <>
            <SectionLabel t={t} action="View all">Recent Activity</SectionLabel>
            <Card t={t} pad={0}>
              {[
                ['09:30', 'Patrol Completed', 'Main Building Patrol', 'success'],
                ['09:15', 'Checkpoint Scanned', 'Lobby Area · NFC', 'primary'],
                ['08:45', 'Break Ended', '15 min rest', 'warn'],
              ].map(([time, what, where, tone], i, arr) => (
                <ActivityRow key={i} t={t} time={time} what={what} where={where} tone={tone} last={i === arr.length - 1}/>
              ))}
            </Card>
          </>
        )}
      </Screen>
      <BottomNav active="home" t={t}/>
    </>
  );
}

function Stat({ t, label, value, sub, tone = 'text' }) {
  const c = tone === 'primary' ? t.primary : tone === 'warn' ? t.warn : t.text;
  return (
    <div style={{
      background: t.surface2, border: `1px solid ${t.line}`, borderRadius: 12,
      padding: 10, display: 'flex', flexDirection: 'column', gap: 2,
    }}>
      <div style={{ fontSize: 10.5, color: t.text3, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontSize: 15, fontWeight: 800, color: c, letterSpacing: -0.2 }}>{value}</div>
      <div style={{ fontSize: 10.5, color: t.text3 }}>{sub}</div>
    </div>
  );
}

function Mini({ t, icon, tone, label, value, sub }) {
  const c = t[tone] || t.primary, bg = t[tone + 'Soft'] || t.primarySoft;
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
      <div style={{ width: 30, height: 30, borderRadius: 9, background: bg, color: c,
        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{icon}</div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 10.5, color: t.text3, fontWeight: 700, letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</div>
        <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text, marginTop: 1 }}>{value}</div>
        <div style={{ fontSize: 11, color: t.text3 }}>{sub}</div>
      </div>
    </div>
  );
}

function ActivityRow({ t, time, what, where, tone, last }) {
  const c = t[tone] || t.primary;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: 12,
      borderBottom: last ? 'none' : `1px solid ${t.line}`,
    }}>
      <div style={{ width: 8, height: 8, borderRadius: 999, background: c, flexShrink: 0 }}/>
      <div style={{ width: 44, fontSize: 11.5, color: t.text3, fontWeight: 700 }}>{time}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 700, color: t.text }}>{what}</div>
        <div style={{ fontSize: 11.5, color: t.text3 }}>{where}</div>
      </div>
      <Icon.Chev size={14} stroke={t.text3}/>
    </div>
  );
}

// ════════════════════════════════════════════════════════════
// 2. TIME CLOCK
// ════════════════════════════════════════════════════════════
function ScreenTimeClock({ dark = true }) {
  const t = _T();
  const nav = window.Nav.useNav();
  return (
    <>
      <AppBar t={t} title="Time Clock" back/>
      <Screen t={t}>
        {/* Identity card */}
        <Card t={t}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <Avatar size={48} name="JS" tone="gold" online t={t}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15.5, fontWeight: 700, color: t.text }}>John Smith</div>
              <div style={{ fontSize: 12, color: t.text3 }}>Security Guard · ID SG-1024</div>
            </div>
            <Pill tone="success" t={t}>On Duty</Pill>
          </div>
          <div style={{ height: 1, background: t.line, margin: '12px 0' }}/>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: 11, color: t.text3, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>Today</div>
              <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text, marginTop: 2 }}>Tue · May 14</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 11, color: t.text3, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>Day Shift</div>
              <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text, marginTop: 2 }}>07:00 — 15:00</div>
            </div>
          </div>
        </Card>

        {/* Big clock */}
        <Card t={t} hi style={{
          background: `linear-gradient(180deg, ${t.surface2}, ${t.surface})`,
          textAlign: 'center', padding: '20px 16px',
        }}>
          <div style={{ fontSize: 11.5, color: t.primary, fontWeight: 800, letterSpacing: 1.2, textTransform: 'uppercase' }}>Current time</div>
          <div style={{
            fontFamily: '"SF Mono","JetBrains Mono",ui-monospace,monospace',
            fontSize: 56, fontWeight: 800, color: t.text, letterSpacing: -1.5, lineHeight: 1.05, marginTop: 4,
          }}>02:47<span style={{ fontSize: 26, marginLeft: 6, color: t.text2 }}>PM</span></div>
          <div style={{ fontSize: 12.5, color: t.text3, marginTop: 6 }}>Tuesday · May 14, 2025 · UTC−5</div>

          {/* progress ring representation */}
          <div style={{ marginTop: 14 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: t.text3, fontWeight: 700, marginBottom: 6 }}>
              <span>Shift progress</span><span style={{ color: t.primary }}>97%</span>
            </div>
            <div style={{ height: 6, borderRadius: 999, background: t.surface2, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: '97%', background: `linear-gradient(90deg, ${t.primary}, ${t.purple})` }}/>
            </div>
          </div>
        </Card>

        {/* Today summary 4-up */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <SummaryTile t={t} icon={<Icon.Power size={18}/>} tone="success" label="Time In" value="07:00 AM" sub="May 14"/>
          <SummaryTile t={t} icon={<Icon.Logout size={18}/>} tone="muted" label="Time Out" value="—" sub="Not yet"/>
          <SummaryTile t={t} icon={<Icon.Clock size={18}/>} tone="primary" label="Worked" value="07h 47m" sub="So far"/>
          <SummaryTile t={t} icon={<Icon.Coffee size={18}/>} tone="warn" label="Break" value="00h 30m" sub="Total"/>
        </div>

        {/* CTA buttons */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Button t={t} tone="success" full size="lg" icon={<Icon.Power size={18} sw={2.2}/>} onClick={()=>nav.showToast('Already clocked in','muted')}>Clock In</Button>
          <Button t={t} tone="danger" full size="lg" icon={<Icon.Logout size={18} sw={2.2}/>} onClick={()=>nav.openSheet('clockOut')}>Clock Out</Button>
        </div>

        {/* Recent activity */}
        <SectionLabel t={t} action="See all">Recent activity</SectionLabel>
        <Card t={t} pad={0}>
          {[
            ['Clocked In', '07:00 AM · May 14', 'success', 'On Time'],
            ['Break Started', '10:30 AM · 30 min', 'warn', 'Rest'],
            ['Break Ended', '11:00 AM', 'success', 'Returned'],
          ].map(([w, when, tone, badge], i, a) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: 12,
              borderBottom: i === a.length - 1 ? 'none' : `1px solid ${t.line}`,
            }}>
              <div style={{
                width: 32, height: 32, borderRadius: 10, background: t[tone + 'Soft'], color: t[tone],
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><Icon.Clock size={16} sw={2}/></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: t.text }}>{w}</div>
                <div style={{ fontSize: 11.5, color: t.text3 }}>{when}</div>
              </div>
              <Pill tone={tone} t={t} size="sm">{badge}</Pill>
            </div>
          ))}
        </Card>
      </Screen>
      <BottomNav active="home" t={t}/>
    </>
  );
}

function SummaryTile({ t, icon, tone, label, value, sub }) {
  const c = t[tone] || t.text, bg = t[tone + 'Soft'] || t.line;
  return (
    <div style={{ background: t.surface, border: `1px solid ${t.line}`, borderRadius: 14, padding: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ width: 28, height: 28, borderRadius: 8, background: bg, color: c,
          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{icon}</div>
        <div style={{ fontSize: 11, color: t.text3, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>{label}</div>
      </div>
      <div style={{ fontSize: 18, fontWeight: 800, color: c, marginTop: 8, letterSpacing: -0.4 }}>{value}</div>
      <div style={{ fontSize: 11.5, color: t.text3, marginTop: 1 }}>{sub}</div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════
// 3. TAKE A BREAK
// ════════════════════════════════════════════════════════════
function ScreenBreak({ dark = true }) {
  const t = _T();
  const nav = window.Nav.useNav();
  return (
    <>
      <AppBar t={t} title="Take a Break" back/>
      <Screen t={t}>
        <div style={{ textAlign: 'center', padding: '8px 4px' }}>
          <div style={{
            width: 56, height: 56, borderRadius: 999, background: t.warnSoft, color: t.warn,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 8,
          }}><Icon.Coffee size={26}/></div>
          <div style={{ fontSize: 22, fontWeight: 800, color: t.text, letterSpacing: -0.3 }}>Step away for a moment</div>
          <div style={{ fontSize: 13, color: t.text3, marginTop: 4 }}>Pick a break type — your shift timer will pause.</div>
        </div>

        <Card t={t}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <Avatar size={44} name="JS" tone="gold" online t={t}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>John Smith · Day Shift</div>
              <div style={{ fontSize: 12, color: t.text3 }}>Started 07:00 · Worked 02h 15m</div>
            </div>
            <Pill tone="warn" t={t} size="sm">No break taken</Pill>
          </div>
        </Card>

        <SectionLabel t={t}>Select break type</SectionLabel>
        <BreakOption t={t} tone="primary" icon={<Icon.Coffee size={22}/>}
          title="Rest Break" duration="15 — 30 min"
          desc="Quick rest. Resume your shift when ready."
          paid="Unpaid · pauses timer"
          onClick={()=>{ nav.showToast('Rest break started','success'); nav.pop(); }}/>
        <BreakOption t={t} tone="purple" icon={<Icon.Briefcase size={22}/>}
          title="Lunch Break" duration="30 — 60 min"
          desc="Take your meal. We'll log the time automatically."
          paid="Unpaid · pauses timer"
          onClick={()=>{ nav.showToast('Lunch break started','success'); nav.pop(); }}/>
        <BreakOption t={t} tone="warn" icon={<Icon.Stopwatch size={22}/>}
          title="Welfare Check" duration="2 — 5 min"
          desc="Quick wellness check-in with dispatch."
          paid="Paid · timer continues"
          onClick={()=>{ nav.showToast('Welfare check logged','success'); nav.pop(); }}/>

        <div style={{
          display: 'flex', alignItems: 'flex-start', gap: 10, padding: 12,
          background: t.primarySoft, border: `1px solid ${t.line}`, borderRadius: 12,
        }}>
          <Icon.Info size={18} stroke={t.primary}/>
          <div style={{ fontSize: 12, color: t.text2, lineHeight: 1.5 }}>
            All breaks are policy-tracked. Make sure your post is covered before stepping away.
          </div>
        </div>
      </Screen>
      <BottomNav active="home" t={t}/>
    </>
  );
}

function BreakOption({ t, tone, icon, title, duration, desc, paid, onClick }) {
  const c = t[tone];
  return (
    <Card t={t} style={{ position: 'relative' }}>
      <div style={{ display: 'flex', gap: 12 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12, background: t[tone + 'Soft'], color: c,
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>{icon}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>{title}</div>
            <Pill tone={tone} t={t} size="sm">{duration}</Pill>
          </div>
          <div style={{ fontSize: 12.5, color: t.text3, marginTop: 4, lineHeight: 1.45 }}>{desc}</div>
          <div style={{ fontSize: 11.5, color: t.text3, marginTop: 8, fontWeight: 600 }}>{paid}</div>
        </div>
      </div>
      <button onClick={onClick} style={{
        appearance: 'none', cursor: 'pointer', marginTop: 12, width: '100%',
        padding: '11px 14px', borderRadius: 12, border: 'none',
        background: c, color: '#fff', fontSize: 14, fontWeight: 700, fontFamily: window.BD_FONT,
      }}>Start {title}</button>
    </Card>
  );
}

// ════════════════════════════════════════════════════════════
// 4. PATROL TOURS — list / overview
// ════════════════════════════════════════════════════════════
function ScreenPatrolList({ dark = true }) {
  const t = _T();
  const nav = window.Nav.useNav();
  return (
    <>
      <AppBar t={t} title="Patrol Tours" back={false}/>
      <Screen t={t}>
        {/* Header with inline progress — no colored 4-up tiles */}
        <div style={{ padding: '0 4px', display:'flex', alignItems:'flex-end', justifyContent:'space-between' }}>
          <div>
            <div style={{ fontSize: 12.5, color: t.text3, fontWeight: 600 }}>Today · Tue, May 14</div>
            <div style={{ fontSize: 22, fontWeight: 800, color: t.text, letterSpacing: -0.3 }}>3 routes assigned</div>
          </div>
          <div style={{ textAlign:'right' }}>
            <div style={{ fontSize: 11, color: t.text3, fontWeight: 700, letterSpacing:0.4, textTransform:'uppercase' }}>Completion</div>
            <div style={{ fontSize: 18, fontWeight: 800, color: t.primary, letterSpacing: -0.3 }}>86%</div>
          </div>
        </div>

        {/* Single quiet progress bar with inline counts */}
        <div style={{ background:t.surface, border:`1px solid ${t.line}`, borderRadius:12, padding:'12px 14px' }}>
          <div style={{ display:'flex', height:6, borderRadius:999, overflow:'hidden', background:t.surface2 }}>
            <div style={{ flex:24, background:t.success }}/>
            <div style={{ flex:2, background:t.warn }}/>
            <div style={{ flex:2, background:t.danger }}/>
          </div>
          <div style={{ display:'flex', justifyContent:'space-between', marginTop:8, fontSize:11.5, color:t.text3, fontWeight:600 }}>
            <span><b style={{color:t.success}}>24</b> done</span>
            <span><b style={{color:t.warn}}>2</b> in progress</span>
            <span><b style={{color:t.danger}}>2</b> missed</span>
            <span style={{color:t.text2}}>28 total</span>
          </div>
        </div>

        {/* filter chips */}
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto', padding: '0 4px' }}>
          {['Active', 'Today', 'Completed', 'Missed', 'All'].map((c, i) => (
            <button key={c} style={{
              appearance: 'none', cursor: 'pointer', padding: '7px 13px', borderRadius: 999,
              border: i === 0 ? 'none' : `1px solid ${t.line}`,
              background: i === 0 ? t.primary : t.surface,
              color: i === 0 ? '#fff' : t.text2,
              fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap', fontFamily: window.BD_FONT,
            }}>{c}</button>
          ))}
        </div>

        <PatrolRow t={t} status="active" name="Main Building Patrol" id="PR-001" progress={2} total={6} time="09:15 → 10:15" eta="33%" onClick={()=>nav.push('activePatrol')}/>
        <PatrolRow t={t} status="next" name="Warehouse Patrol" id="PR-002" progress={0} total={8} time="11:00 → 12:30" onClick={()=>nav.push('activePatrol')}/>
        <PatrolRow t={t} status="done" name="Perimeter Sweep" id="PR-003" progress={5} total={5} time="07:15 → 08:00" onClick={()=>nav.push('patrolSummary')}/>
        <PatrolRow t={t} status="missed" name="Night Round" id="PR-008" progress={3} total={6} time="03:00 → 04:00" onClick={()=>nav.openSheet('missedReason')}/>
      </Screen>
      <BottomNav active="patrol" t={t}/>
    </>
  );
}

function PatrolRow({ t, status, name, id, progress, total, time, eta, onClick }) {
  const cfg = {
    active:  { tone: 'primary', label: 'In progress', cta: 'Resume' },
    next:    { tone: 'gold',    label: 'Up next',    cta: 'Start' },
    done:    { tone: 'success', label: 'Completed',  cta: 'View' },
    missed:  { tone: 'danger',  label: 'Missed',     cta: 'Review' },
  }[status];
  const pct = total ? Math.round(progress / total * 100) : 0;
  return (
    <Card t={t}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 38, height: 38, borderRadius: 10, background: t[cfg.tone + 'Soft'], color: t[cfg.tone],
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}><Icon.Map size={18}/></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <div style={{ fontSize: 14.5, fontWeight: 700, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{name}</div>
            <Pill tone={cfg.tone} t={t} size="sm">{cfg.label}</Pill>
          </div>
          <div style={{ fontSize: 11.5, color: t.text3, marginTop: 2, display: 'flex', gap: 10 }}>
            <span>{id}</span><span>·</span><span>{time}</span>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: t.text3, fontWeight: 700, marginBottom: 4 }}>
            <span>{progress} of {total} checkpoints</span><span>{eta || pct + '%'}</span>
          </div>
          <div style={{ height: 5, borderRadius: 999, background: t.surface2 }}>
            <div style={{ height: '100%', width: `${pct}%`, background: t[cfg.tone], borderRadius: 999 }}/>
          </div>
        </div>
        <Button t={t} tone={status === 'active' ? 'primary' : 'ghost'} size="md" onClick={onClick}>{cfg.cta}</Button>
      </div>
    </Card>
  );
}

// ════════════════════════════════════════════════════════════
// 5. ACTIVE PATROL — map + checkpoint list
// ════════════════════════════════════════════════════════════
function ScreenActivePatrol({ dark = true }) {
  const t = _T();
  const nav = window.Nav.useNav();
  return (
    <>
      <AppBar t={t} title="Main Building Patrol" back/>
      <Screen t={t} bottomPad={120}>
        {/* Combined progress + map in one tight card */}
        <Card t={t} pad={0} style={{ overflow: 'hidden' }}>
          <div style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12, borderBottom:`1px solid ${t.line}` }}>
            <div style={{ position: 'relative', width: 44, height: 44 }}>
              <svg width="44" height="44" viewBox="0 0 44 44">
                <circle cx="22" cy="22" r="18" fill="none" stroke={t.line} strokeWidth="4"/>
                <circle cx="22" cy="22" r="18" fill="none" stroke={t.primary} strokeWidth="4"
                  strokeDasharray={`${2 * Math.PI * 18 * 0.33} 999`}
                  strokeLinecap="round" transform="rotate(-90 22 22)"/>
              </svg>
              <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 11, fontWeight: 800, color: t.text }}>2/6</div>
            </div>
            <div style={{ flex: 1, minWidth:0 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>PR-001 · 33% complete</div>
              <div style={{ fontSize: 11.5, color: t.text3, marginTop: 1 }}>Started 09:15 · Due 10:15 · 38 min left</div>
            </div>
            <Pill tone="primary" t={t} size="sm">Live</Pill>
          </div>

          {/* MAP — flush to card */}
          <div style={{ position: 'relative', height: 130, background:
            `radial-gradient(120% 80% at 30% 30%, ${t.surfaceHi}, ${t.bg2})`,
          }}>
            <svg viewBox="0 0 360 130" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
              <g stroke={t.line} strokeWidth="1">
                {Array.from({ length: 9 }).map((_, i) => <line key={i} x1={i * 45} y1="0" x2={i * 45} y2="130"/>)}
                {Array.from({ length: 4 }).map((_, i) => <line key={i} x1="0" y1={i * 33} x2="360" y2={i * 33}/>)}
              </g>
              <path d="M20 100 L120 60 L200 75 L280 45 L340 60" stroke={t.lineStrong} strokeWidth="3" fill="none" strokeLinecap="round"/>
              <path d="M40 95 L100 70" stroke={t.success} strokeWidth="3" strokeDasharray="6 4" fill="none"/>
              <path d="M100 70 L180 80 L260 50 L320 70" stroke={t.text3} strokeWidth="2" strokeDasharray="3 5" fill="none"/>
              <Node cx={40} cy={95} n="1" tone={t.success}/>
              <Node cx={100} cy={70} n="2" tone={t.success}/>
              <Node cx={180} cy={80} n="3" tone={t.primary} pulse/>
              <Node cx={260} cy={50} n="4" tone={t.text3}/>
              <Node cx={320} cy={70} n="5" tone={t.text3}/>
              <Node cx={340} cy={105} n="6" tone={t.text3}/>
            </svg>
            <div style={{ position: 'absolute', left: 10, bottom: 8, display: 'flex', gap: 10,
              padding: '5px 9px', background: t.chrome, borderRadius: 999, border: `1px solid ${t.line}`,
              backdropFilter: 'blur(10px)' }}>
              <Legend t={t} c={t.success} l="Done"/>
              <Legend t={t} c={t.primary} l="Now"/>
              <Legend t={t} c={t.text3} l="Pending"/>
            </div>
          </div>
        </Card>

        <SectionLabel t={t} action="History">Checkpoints</SectionLabel>
        <Card t={t} pad={0}>
          {[
            ['Main Entrance', 'QR · Required', 'done', '09:15'],
            ['Lobby Area', 'NFC · Required', 'done', '09:22'],
            ['Parking Area', 'QR · Required', 'now', null],
            ['Building Perimeter West', 'QR · Required', 'pending', null],
            ['Loading Dock', 'NFC · Required', 'pending', null],
            ['Main Entrance (Return)', 'QR · Required', 'pending', null],
          ].map((row, i, a) => (
            <CheckpointRow key={i} t={t} idx={i + 1} row={row} last={i === a.length - 1}/>
          ))}
        </Card>

        <Button t={t} tone="primary" full size="lg" icon={<Icon.Scan size={20} sw={2.2}/>} onClick={()=>nav.push('scan')}>Scan checkpoint</Button>
      </Screen>
      <BottomNav active="patrol" t={t}/>
    </>
  );
}

function Node({ cx, cy, n, tone, pulse }) {
  return (
    <g>
      {pulse && <circle cx={cx} cy={cy} r="14" fill={tone} opacity="0.25"/>}
      <circle cx={cx} cy={cy} r="10" fill={tone} stroke="#fff" strokeWidth="2"/>
      <text x={cx} y={cy + 3.5} textAnchor="middle" fill="#fff" fontSize="10" fontWeight="700" fontFamily="Inter">{n}</text>
    </g>
  );
}

function Legend({ t, c, l }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
      <span style={{ width: 8, height: 8, borderRadius: 999, background: c }}/>
      <span style={{ fontSize: 11, color: t.text2, fontWeight: 600 }}>{l}</span>
    </div>
  );
}

function CheckpointRow({ t, idx, row, last }) {
  const [name, type, status, time] = row;
  const cfg = {
    done:    { tone: t.success, icon: <Icon.Check size={14} sw={3}/>, fill: true },
    now:     { tone: t.primary, icon: <span style={{ fontSize: 11, fontWeight: 800, color: '#fff' }}>{idx}</span>, fill: true, pulse: true },
    pending: { tone: t.text3,   icon: <span style={{ fontSize: 11, fontWeight: 800, color: t.text3 }}>{idx}</span>, fill: false },
  }[status];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
      borderBottom: last ? 'none' : `1px solid ${t.line}`,
      position: 'relative',
    }}>
      <div style={{ position: 'relative' }}>
        <div style={{
          width: 30, height: 30, borderRadius: 999, flexShrink: 0,
          background: cfg.fill ? cfg.tone : 'transparent',
          border: cfg.fill ? 'none' : `2px solid ${cfg.tone}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
        }}>{cfg.icon}</div>
        {cfg.pulse && <div style={{ position: 'absolute', inset: -4, borderRadius: 999, border: `2px solid ${cfg.tone}55` }}/>}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: status === 'pending' ? t.text2 : t.text }}>{name}</div>
        <div style={{ fontSize: 11.5, color: t.text3, marginTop: 1 }}>{type}</div>
      </div>
      {status === 'done' && <div style={{ fontSize: 12, color: t.success, fontWeight: 700 }}>{time}</div>}
      {status === 'now' && <Button t={t} tone="primary" size="md" onClick={()=>{ const nav=window.__BD_NAV__; nav && nav.push('scan'); }}>Scan</Button>}
      {status === 'pending' && <Icon.Lock size={14} stroke={t.text3}/>}
    </div>
  );
}

// ════════════════════════════════════════════════════════════
// 6. SCAN — full-screen camera-style
// ════════════════════════════════════════════════════════════
function ScreenScan({ dark = true }) {
  const t = _T();
  const nav = window.Nav.useNav();
  const [mode, setMode] = React.useState('QR Code');
  const [flash, setFlash] = React.useState(false);
  return (
    <>
      {/* full-bleed scan, no app bar */}
      <div style={{
        flex: 1, position: 'relative', overflow: 'hidden',
        background: '#000',
      }}>
        {/* simulated camera viewfinder */}
        <div style={{
          position: 'absolute', inset: 0,
          background: `radial-gradient(60% 50% at 50% 50%, #1a1f2c 0%, #050810 100%)`,
        }}/>
        {/* fake building outlines */}
        <svg viewBox="0 0 390 700" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
          <g stroke="#ffffff10" strokeWidth="1">
            <rect x="60" y="200" width="120" height="180"/>
            <rect x="200" y="240" width="140" height="200"/>
            <line x1="60" y1="380" x2="340" y2="380"/>
          </g>
        </svg>

        {/* top chrome */}
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0, padding: '54px 16px 12px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          background: 'linear-gradient(180deg, rgba(0,0,0,0.6), transparent)',
        }}>
          <button onClick={()=>nav.pop()} style={{
            appearance: 'none', border: '1px solid rgba(255,255,255,0.16)', background: 'rgba(0,0,0,0.4)',
            width: 36, height: 36, borderRadius: 999, color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
            backdropFilter: 'blur(10px)',
          }}><Icon.X size={18} sw={2}/></button>
          <div style={{
            background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(10px)',
            border: '1px solid rgba(255,255,255,0.16)', borderRadius: 999,
            padding: '6px 12px', color: '#fff', fontSize: 12.5, fontWeight: 700,
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: t.primary, boxShadow: `0 0 0 3px ${t.primary}33` }}/>
            Patrol PR-001 · CP 3 of 6
          </div>
          <button onClick={()=>setFlash(f=>!f)} style={{
            appearance: 'none', border: '1px solid rgba(255,255,255,0.16)', background: flash ? 'rgba(255,255,255,0.95)' : 'rgba(0,0,0,0.4)',
            width: 36, height: 36, borderRadius: 999, color: flash ? '#000' : '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
            backdropFilter: 'blur(10px)',
          }}><Icon.Flash size={18} sw={2}/></button>
        </div>

        {/* scan target */}
        <div style={{
          position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -55%)',
          width: 240, height: 240,
        }}>
          <div style={{ position: 'absolute', inset: 0, border: '2px solid rgba(255,255,255,0.08)', borderRadius: 24 }}/>
          {/* corners */}
          {['TL','TR','BL','BR'].map(corner => {
            const base = { position: 'absolute', width: 36, height: 36, borderColor: t.primary, borderStyle: 'solid' };
            const map = {
              TL: { top: -2, left: -2, borderWidth: '4px 0 0 4px', borderTopLeftRadius: 22 },
              TR: { top: -2, right: -2, borderWidth: '4px 4px 0 0', borderTopRightRadius: 22 },
              BL: { bottom: -2, left: -2, borderWidth: '0 0 4px 4px', borderBottomLeftRadius: 22 },
              BR: { bottom: -2, right: -2, borderWidth: '0 4px 4px 0', borderBottomRightRadius: 22 },
            };
            return <div key={corner} style={{ ...base, ...map[corner] }}/>;
          })}
          {/* scan line */}
          <div style={{
            position: 'absolute', top: '40%', left: 12, right: 12, height: 2,
            background: `linear-gradient(90deg, transparent, ${t.primary}, transparent)`,
            boxShadow: `0 0 12px ${t.primary}`,
          }}/>
          {/* target QR illustration */}
          <div style={{ position: 'absolute', inset: 32, opacity: 0.18 }}>
            <Icon.QR size={176} stroke="#fff" sw={1.4}/>
          </div>
        </div>

        {/* helper text */}
        <div style={{
          position: 'absolute', top: 'calc(50% + 80px)', left: 0, right: 0, textAlign: 'center',
        }}>
          <div style={{ color: '#fff', fontSize: 16, fontWeight: 700, letterSpacing: -0.2 }}>Align the QR or NFC tag</div>
          <div style={{ color: 'rgba(255,255,255,0.6)', fontSize: 12.5, marginTop: 4 }}>Holding still… auto-detecting</div>
        </div>

        {/* mode tabs */}
        <div style={{
          position: 'absolute', bottom: 240, left: 0, right: 0,
          display: 'flex', justifyContent: 'center', gap: 8,
        }}>
          {[['QR Code'], ['NFC Tag'], ['Manual'], ['Voice']].map(([l], i) => (
            <button key={i} onClick={()=>{
              if (l==='Voice') { nav.showToast('Listening for voice tag…','primary'); setTimeout(()=>nav.replace('scanSuccess'), 900); return; }
              setMode(l);
              if (l==='Manual') { nav.showToast('Enter checkpoint code','primary'); }
            }} style={{
              appearance:'none', cursor:'pointer', padding: '8px 14px', borderRadius: 999,
              background: mode===l ? '#fff' : 'rgba(255,255,255,0.08)',
              color: mode===l ? '#000' : 'rgba(255,255,255,0.7)',
              fontSize: 12.5, fontWeight: 700,
              border: `1px solid ${mode===l ? '#fff' : 'rgba(255,255,255,0.12)'}`,
              backdropFilter: 'blur(10px)', fontFamily: window.BD_FONT,
            }}>{l}</button>
          ))}
        </div>

        {/* bottom panel — capture extras */}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0,
          padding: '14px 16px 36px',
          background: 'linear-gradient(180deg, transparent, rgba(0,0,0,0.85))',
        }}>
          <Card t={t} style={{ background: 'rgba(15,23,42,0.85)', backdropFilter: 'blur(16px)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
              <div style={{ width: 32, height: 32, borderRadius: 10, background: t.primarySoft, color: t.primary,
                display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon.Pin size={16}/></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>Parking Area · QR-1003</div>
                <div style={{ fontSize: 11.5, color: t.text3 }}>Photo & voice optional</div>
              </div>
              <Pill tone="warn" t={t} size="sm">Required scan</Pill>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <ScanExtra t={t} icon={<Icon.Camera size={18}/>} label="Photo" tone="purple" onClick={()=>nav.showToast('Photo captured','success')}/>
              <ScanExtra t={t} icon={<Icon.Mic size={18}/>}    label="Voice" tone="teal" onClick={()=>nav.showToast('Recording voice memo…','primary')}/>
              <ScanExtra t={t} icon={<Icon.Edit size={18}/>}   label="Note"  tone="gold" onClick={()=>nav.showToast('Note attached','muted')}/>
            </div>
            <button onClick={()=>nav.replace('scanSuccess')} style={{
              appearance:'none', cursor:'pointer', marginTop: 10, width:'100%', padding:'12px 14px',
              borderRadius:12, border:'none', background:t.primary, color:'#fff',
              fontSize:14, fontWeight:800, fontFamily: window.BD_FONT,
            }}>Confirm scan</button>
          </Card>
        </div>
      </div>
    </>
  );
}

function ScanExtra({ t, icon, label, tone, onClick }) {
  const c = t[tone];
  return (
    <button onClick={onClick} style={{
      flex: 1, appearance: 'none', cursor: 'pointer', padding: '10px 8px',
      background: t[tone + 'Soft'], color: c, border: `1px solid ${c}33`, borderRadius: 12,
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
      fontSize: 12.5, fontWeight: 700, fontFamily: window.BD_FONT,
    }}>{icon}{label}</button>
  );
}

Object.assign(window, {
  ScreenHome, ScreenTimeClock, ScreenBreak, ScreenPatrolList, ScreenActivePatrol, ScreenScan,
});
