// ByDuty Guard — extra screens needed for full app wiring
// Splash, Forgot/Reset, Profile setup, Scan success/fail, Missed reason,
// Patrol summary, Audio recorder, Video recorder, Photo viewer,
// Broadcast composer, PTT overlay, Calendar day, Vehicle log, Equipment,
// Approval detail, SOS post-event, Search, Empty/Offline, Success.

const { Card, Pill, SectionLabel, Button, BottomNav, AppBar, Avatar, Screen } = window;
const { Icon, BDLogo } = window;
const _TX = () => window.__BD_THEME__ || window.BD_TOKENS.dark;
const useNavX = () => window.Nav.useNav();

// ─────────── SPLASH ───────────
function ScreenSplash() {
  const t = _TX(); const nav = useNavX();
  React.useEffect(() => { const id = setTimeout(() => nav.replace('login'), 1300); return () => clearTimeout(id); }, []);
  return (
    <div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center',
      background: `radial-gradient(120% 80% at 50% 30%, ${t.primary}33, ${t.bg})`, flexDirection:'column', gap:18 }}>
      <div style={{ padding:18, borderRadius:28, background:t.surface, border:`1px solid ${t.line}`,
        boxShadow:`0 20px 60px ${t.primary}33` }}><BDLogo size={56}/></div>
      <div style={{ fontSize:24, fontWeight:800, color:t.text, letterSpacing:-0.4 }}>ByDuty</div>
      <div style={{ fontSize:12, color:t.text3, fontWeight:600, letterSpacing:1, textTransform:'uppercase' }}>Guard Operations</div>
      <div style={{ marginTop:30, width:160, height:3, borderRadius:999, background:t.surface, overflow:'hidden' }}>
        <div style={{ width:'40%', height:'100%', background:t.primary, animation:'bdSpin 1.4s linear infinite' }}/>
      </div>
    </div>
  );
}

// ─────────── FORGOT / RESET ───────────
function ScreenForgot() {
  const t = _TX(); const nav = useNavX();
  return (
    <>
      <AppBar t={t} title="Forgot passcode" back bell={false}/>
      <Screen t={t}>
        <div style={{ padding:'8px 4px' }}>
          <div style={{ fontSize:24, fontWeight:800, color:t.text, letterSpacing:-0.4 }}>Reset your passcode</div>
          <div style={{ fontSize:13, color:t.text3, marginTop:6, lineHeight:1.5 }}>
            Enter the email tied to your badge. We'll send a 6-digit code to verify your identity.
          </div>
        </div>
        <Card t={t}>
          <div style={{ fontSize:11, color:t.text3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>Work email</div>
          <div style={{ fontSize:15, color:t.text, marginTop:6, fontWeight:600 }}>m.chen@byduty.co</div>
        </Card>
        <Button t={t} tone="primary" full size="lg" onClick={() => nav.push('reset')}>Send code</Button>
        <Button t={t} tone="ghost" full size="md" onClick={() => nav.openSheet('contactSupport')}>Contact dispatch</Button>
      </Screen>
    </>
  );
}

function ScreenReset() {
  const t = _TX(); const nav = useNavX();
  const dots = [1,1,1,1,1,0];
  return (
    <>
      <AppBar t={t} title="Verify code" back bell={false}/>
      <Screen t={t}>
        <div style={{ padding:'8px 4px' }}>
          <div style={{ fontSize:24, fontWeight:800, color:t.text, letterSpacing:-0.4 }}>Enter the 6-digit code</div>
          <div style={{ fontSize:13, color:t.text3, marginTop:6, lineHeight:1.5 }}>Sent to m.chen@byduty.co · expires in 4:58</div>
        </div>
        <div style={{ display:'flex', gap:10, justifyContent:'center', padding:'12px 0' }}>
          {dots.map((on,i)=>(
            <div key={i} style={{ width:46, height:54, borderRadius:12,
              background: t.surface, border:`1px solid ${on?t.primary:t.line}`,
              display:'flex', alignItems:'center', justifyContent:'center',
              fontSize:22, fontWeight:800, color:t.text }}>{on?String((i+3)%9):''}</div>
          ))}
        </div>
        <div style={{ textAlign:'center', fontSize:12.5, color:t.text3 }}>
          Didn't receive it? <span style={{ color:t.primary, fontWeight:700 }}>Resend</span>
        </div>
        <Button t={t} tone="primary" full size="lg" onClick={() => nav.replace('home')}>Verify & sign in</Button>
      </Screen>
    </>
  );
}

// ─────────── PROFILE SETUP (post-onboarding) ───────────
function ScreenProfileSetup() {
  const t = _TX(); const nav = useNavX();
  return (
    <>
      <div style={{ padding:'54px 18px 0', display:'flex', justifyContent:'space-between' }}>
        <BDLogo size={28}/>
        <span style={{ fontSize:12, color:t.text3, fontWeight:700 }}>4 of 4</span>
      </div>
      <Screen t={t} bottomPad={130}>
        <div style={{ padding:'8px 4px' }}>
          <div style={{ fontSize:12, color:t.primary, fontWeight:800, letterSpacing:1.2, textTransform:'uppercase' }}>Final step</div>
          <div style={{ fontSize:24, fontWeight:800, color:t.text, letterSpacing:-0.4, marginTop:4 }}>Confirm your profile</div>
          <div style={{ fontSize:13, color:t.text3, marginTop:6, lineHeight:1.5 }}>This is what your supervisor and team will see.</div>
        </div>
        <Card t={t}>
          <div style={{ display:'flex', alignItems:'center', gap:12 }}>
            <Avatar size={56} name="MC" tone="gold" t={t}/>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:16, fontWeight:800, color:t.text }}>Marcus Chen</div>
              <div style={{ fontSize:12, color:t.text3 }}>Officer · Badge B-2841</div>
            </div>
            <Button t={t} tone="soft" size="md">Change</Button>
          </div>
        </Card>
        {[
          ['Phone','+1 (555) 014-2210'],
          ['Emergency contact','Add'],
          ['Default site','Westgate Plaza'],
          ['Preferred shift','Night (18:00 – 02:00)'],
        ].map(([k,v],i)=>(
          <Card key={i} t={t}>
            <div style={{ display:'flex', alignItems:'center' }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:11, color:t.text3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>{k}</div>
                <div style={{ fontSize:14, color:t.text, marginTop:3, fontWeight:600 }}>{v}</div>
              </div>
              <Icon.Chev size={14} stroke={t.text3}/>
            </div>
          </Card>
        ))}
      </Screen>
      <div style={{ position:'absolute', left:0, right:0, bottom:0, padding:'10px 16px 32px',
        background: `linear-gradient(180deg, transparent, ${t.bg2})`, display:'flex', gap:10 }}>
        <Button t={t} tone="primary" full size="lg" onClick={() => { nav.reset('home'); window.Nav.useNav; }}>Enter app</Button>
      </div>
    </>
  );
}

// ─────────── SCAN SUCCESS / FAIL ───────────
function ScreenScanSuccess({ cpName='North Gate' }) {
  const t = _TX(); const nav = useNavX();
  return (
    <div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column',
      background:`radial-gradient(120% 70% at 50% 40%, ${t.success}22, ${t.bg})`, padding:'0 24px', gap:18 }}>
      <div style={{ width:120, height:120, borderRadius:999, background:t.successSoft,
        display:'flex', alignItems:'center', justifyContent:'center', position:'relative' }}>
        <div style={{ position:'absolute', inset:-10, borderRadius:999, border:`2px solid ${t.success}55` }}/>
        <Icon.Check size={64} stroke={t.success} sw={3.2}/>
      </div>
      <div style={{ textAlign:'center' }}>
        <div style={{ fontSize:24, fontWeight:800, color:t.text, letterSpacing:-0.4 }}>Checkpoint scanned</div>
        <div style={{ fontSize:14, color:t.text2, marginTop:6 }}>{cpName} · {new Date().toLocaleTimeString([], { hour:'2-digit', minute:'2-digit' })}</div>
      </div>
      <Card t={t} style={{ width:'100%' }}>
        <div style={{ display:'flex', justifyContent:'space-between', fontSize:12 }}>
          <span style={{ color:t.text3 }}>Patrol</span>
          <span style={{ color:t.text, fontWeight:700 }}>Perimeter A · 4 of 8</span>
        </div>
        <div style={{ height:6, borderRadius:999, background:t.surface2, marginTop:8, overflow:'hidden' }}>
          <div style={{ width:'50%', height:'100%', background:t.success }}/>
        </div>
      </Card>
      <div style={{ display:'flex', gap:10, width:'100%' }}>
        <Button t={t} tone="ghost" size="lg" style={{ flex:1 }} onClick={() => nav.popTo('activePatrol')}>Back to patrol</Button>
        <Button t={t} tone="primary" size="lg" style={{ flex:1 }} onClick={() => nav.replace('scan')}>Next checkpoint</Button>
      </div>
    </div>
  );
}

function ScreenScanFail() {
  const t = _TX(); const nav = useNavX();
  return (
    <div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column',
      background:`radial-gradient(120% 70% at 50% 40%, ${t.danger}22, ${t.bg})`, padding:'0 24px', gap:18 }}>
      <div style={{ width:120, height:120, borderRadius:999, background:t.dangerSoft,
        display:'flex', alignItems:'center', justifyContent:'center' }}>
        <Icon.X size={56} stroke={t.danger} sw={3.2}/>
      </div>
      <div style={{ textAlign:'center' }}>
        <div style={{ fontSize:24, fontWeight:800, color:t.text, letterSpacing:-0.4 }}>Scan failed</div>
        <div style={{ fontSize:14, color:t.text2, marginTop:6, lineHeight:1.5 }}>
          QR code unreadable, or you're outside the geofence.
        </div>
      </div>
      <Card t={t} style={{ width:'100%' }}>
        {[
          ['Distance from checkpoint','142 m','danger'],
          ['Required radius','20 m','muted'],
          ['Last successful scan','Loading Bay · 12 min ago','muted'],
        ].map(([k,v,tone],i,a)=>(
          <div key={i} style={{ display:'flex', justifyContent:'space-between', padding:'8px 0',
            borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
            <span style={{ fontSize:12.5, color:t.text3 }}>{k}</span>
            <span style={{ fontSize:13, fontWeight:700, color: tone==='danger'?t.danger:t.text }}>{v}</span>
          </div>
        ))}
      </Card>
      <div style={{ display:'flex', gap:10, width:'100%' }}>
        <Button t={t} tone="ghost" size="lg" style={{ flex:1 }} onClick={() => nav.openSheet('missedReason')}>Mark missed</Button>
        <Button t={t} tone="primary" size="lg" style={{ flex:1 }} onClick={() => nav.pop()}>Try again</Button>
      </div>
    </div>
  );
}

// ─────────── PATROL COMPLETE SUMMARY ───────────
function ScreenPatrolSummary() {
  const t = _TX(); const nav = useNavX();
  return (
    <>
      <AppBar t={t} title="Patrol complete" back bell={false}/>
      <Screen t={t}>
        <div style={{ textAlign:'center', padding:'10px 8px' }}>
          <div style={{ display:'inline-flex', width:88, height:88, borderRadius:999,
            background:t.successSoft, alignItems:'center', justifyContent:'center', marginBottom:10 }}>
            <Icon.Shield size={44} stroke={t.success}/>
          </div>
          <div style={{ fontSize:22, fontWeight:800, color:t.text, letterSpacing:-0.4 }}>Perimeter A</div>
          <div style={{ fontSize:13, color:t.text3, marginTop:2 }}>completed at {new Date().toLocaleTimeString([], { hour:'2-digit', minute:'2-digit' })}</div>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8 }}>
          {[['7/8','Scanned','success'],['1','Missed','warn'],['24m','Duration','primary']].map(([n,l,tone],i)=>(
            <Card key={i} t={t}>
              <div style={{ fontSize:22, fontWeight:800, color:t[tone], letterSpacing:-0.3 }}>{n}</div>
              <div style={{ fontSize:11, color:t.text3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase', marginTop:2 }}>{l}</div>
            </Card>
          ))}
        </div>
        <SectionLabel t={t}>Checkpoints</SectionLabel>
        <Card t={t} pad={0}>
          {[
            ['NG-01','North Gate','19:02','success'],
            ['LB-02','Loading Bay','19:05','success'],
            ['ES-03','East Stair','19:09','success'],
            ['SH-04','Service Hall','19:12','success'],
            ['GL-05','Garage Lvl 2','19:14','success'],
            ['SX-06','South Exit','19:18','success'],
            ['MR-07','Mech Room','—','warn','Door locked – key missing'],
            ['ML-08','Main Lobby','19:25','success'],
          ].map(([code,name,time,tone,reason],i,a)=>(
            <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 14px',
              borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
              <span style={{ width:6, height:6, borderRadius:999, background:t[tone] }}/>
              <span style={{ fontSize:11, color:t.text3, fontWeight:700, fontFamily:'"JetBrains Mono",monospace', width:50 }}>{code}</span>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:t.text }}>{name}</div>
                {reason && <div style={{ fontSize:11.5, color:t.warn, marginTop:1 }}>{reason}</div>}
              </div>
              <span style={{ fontSize:11.5, color:t.text3, fontFamily:'"JetBrains Mono",monospace' }}>{time}</span>
            </div>
          ))}
        </Card>
        <SectionLabel t={t}>Notes</SectionLabel>
        <Card t={t}>
          <div style={{ fontSize:13, color:t.text2, lineHeight:1.5 }}>
            All exterior locks secured. Mech room not accessed — supervisor to follow up with facilities for replacement key.
          </div>
        </Card>
        <Button t={t} tone="primary" full size="lg" onClick={() => { nav.popTo('patrol'); }}>Done</Button>
      </Screen>
    </>
  );
}

// ─────────── MISSED CHECKPOINT REASON (sheet) ───────────
function SheetMissedReason({ close }) {
  const t = _TX(); const nav = useNavX();
  const [r, setR] = React.useState('locked');
  const reasons = [
    ['locked','Area was locked',<Icon.Lock size={16}/>],
    ['unsafe','Unsafe to access',<Icon.AlertTri size={16}/>],
    ['hardware','Beacon / QR damaged',<Icon.Wrench size={16}/>],
    ['signal','No signal in area',<Icon.Signal size={16}/>],
    ['other','Other',<Icon.More size={16}/>],
  ];
  return (
    <window.Sheet title="Why was this missed?" subtitle="Required" close={close}
      footer={<Button t={t} tone="primary" full size="lg" onClick={() => { nav.showToast('Marked missed','warn'); close(); }}>Mark missed</Button>}>
      {reasons.map(([k,l,icon])=>(
        <div key={k} onClick={()=>setR(k)} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 4px',
          cursor:'pointer', borderBottom:`1px solid ${t.line}` }}>
          <div style={{ width:32, height:32, borderRadius:9, background: r===k?t.primarySoft:t.surface,
            color: r===k?t.primary:t.text2, border:`1px solid ${t.line}`,
            display:'flex', alignItems:'center', justifyContent:'center' }}>{icon}</div>
          <div style={{ flex:1, fontSize:14, fontWeight:600, color:t.text }}>{l}</div>
          <div style={{ width:20, height:20, borderRadius:999, border:`2px solid ${r===k?t.primary:t.lineStrong}`,
            display:'flex', alignItems:'center', justifyContent:'center' }}>
            {r===k && <span style={{ width:10, height:10, borderRadius:999, background:t.primary }}/>}
          </div>
        </div>
      ))}
      <div style={{ marginTop:12, padding:12, background:t.surface, border:`1px solid ${t.line}`, borderRadius:12 }}>
        <div style={{ fontSize:11, color:t.text3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>Note (optional)</div>
        <div style={{ fontSize:13, color:t.text3, marginTop:6 }}>Add details for your supervisor…</div>
      </div>
    </window.Sheet>
  );
}

// ─────────── AUDIO RECORDER (full screen) ───────────
function ScreenAudioRecorder() {
  const t = _TX(); const nav = useNavX();
  const [recording, setRecording] = React.useState(true);
  const [secs, setSecs] = React.useState(8);
  React.useEffect(() => {
    if (!recording) return;
    const id = setInterval(() => setSecs(s => s+1), 1000);
    return () => clearInterval(id);
  }, [recording]);
  const fmt = (s) => `${Math.floor(s/60)}:${String(s%60).padStart(2,'0')}`;
  return (
    <>
      <AppBar t={t} title="Voice memo" back bell={false}/>
      <div style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
        padding:'0 24px', gap:24 }}>
        <div style={{ fontSize:64, fontWeight:800, color:t.text, fontFamily:'"JetBrains Mono",monospace', letterSpacing:-2 }}>{fmt(secs)}</div>
        {/* waveform */}
        <div style={{ display:'flex', alignItems:'center', gap:3, height:80, width:'100%' }}>
          {Array.from({length:48}).map((_,i)=>{
            const v = recording ? 0.3 + Math.abs(Math.sin((i + secs*4)*0.5))*0.7 : 0.3;
            return <div key={i} style={{ flex:1, height:`${v*100}%`, borderRadius:2,
              background: recording ? t.primary : t.lineStrong, opacity: i < secs*4 ? 1 : 0.4,
              transition:'height 0.15s' }}/>;
          })}
        </div>
        <button onClick={() => setRecording(r=>!r)} style={{
          appearance:'none', cursor:'pointer', border:'none', width:88, height:88, borderRadius:999,
          background: recording ? t.danger : t.primary, color:'#fff',
          display:'flex', alignItems:'center', justifyContent:'center',
          boxShadow: `0 12px 32px ${recording?t.danger:t.primary}66`,
        }}>
          {recording
            ? <span style={{ width:28, height:28, borderRadius:6, background:'#fff' }}/>
            : <Icon.Mic size={36}/>}
        </button>
        <div style={{ fontSize:13, color:t.text3 }}>{recording ? 'Tap to pause · long-hold to cancel' : 'Paused'}</div>
        <div style={{ display:'flex', gap:10, width:'100%' }}>
          <Button t={t} tone="ghost" size="lg" style={{ flex:1 }} onClick={() => nav.pop()}>Cancel</Button>
          <Button t={t} tone="success" size="lg" style={{ flex:2 }} icon={<Icon.Check size={16} sw={2.4}/>}
            onClick={() => { nav.showToast('Voice memo attached','success'); nav.pop(); }}>Save · {fmt(secs)}</Button>
        </div>
      </div>
    </>
  );
}

// ─────────── VIDEO RECORDER (full screen camera) ───────────
function ScreenVideoRecorder() {
  const t = _TX(); const nav = useNavX();
  const [recording, setRecording] = React.useState(false);
  const [secs, setSecs] = React.useState(0);
  React.useEffect(() => {
    if (!recording) return;
    const id = setInterval(() => setSecs(s => s+1), 1000);
    return () => clearInterval(id);
  }, [recording]);
  return (
    <div style={{ flex:1, position:'relative', overflow:'hidden', background:'#0A0A0A' }}>
      {/* fake viewfinder — gradient + grid */}
      <svg viewBox="0 0 390 844" style={{ position:'absolute', inset:0, width:'100%', height:'100%' }}>
        <defs>
          <linearGradient id="vf" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#1a2a3a"/>
            <stop offset="100%" stopColor="#080812"/>
          </linearGradient>
        </defs>
        <rect width="390" height="844" fill="url(#vf)"/>
        {/* faux scene */}
        <g opacity="0.4">
          <rect x="80" y="380" width="230" height="160" fill="#2a3a50" rx="4"/>
          <rect x="120" y="320" width="150" height="80" fill="#34465e" rx="4"/>
          <circle cx="195" cy="180" r="60" fill="#1c2538" opacity="0.6"/>
        </g>
        {/* rule of thirds */}
        <g stroke="#fff" strokeOpacity="0.15" strokeWidth="0.5">
          <line x1="130" y1="0" x2="130" y2="844"/>
          <line x1="260" y1="0" x2="260" y2="844"/>
          <line x1="0" y1="280" x2="390" y2="280"/>
          <line x1="0" y1="560" x2="390" y2="560"/>
        </g>
      </svg>
      {/* top chrome */}
      <div style={{ position:'absolute', top:54, left:0, right:0, padding:'0 16px',
        display:'flex', alignItems:'center', justifyContent:'space-between', zIndex:5 }}>
        <button onClick={() => nav.pop()} style={{ width:40, height:40, borderRadius:999,
          background:'rgba(0,0,0,0.5)', backdropFilter:'blur(10px)', border:'1px solid rgba(255,255,255,0.2)',
          color:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon.X size={18} sw={2}/>
        </button>
        {recording && (
          <div style={{ padding:'6px 12px', borderRadius:999, background:'#FF3B30',
            display:'flex', alignItems:'center', gap:6, color:'#fff', fontSize:12, fontWeight:700,
            fontFamily:'"JetBrains Mono",monospace' }}>
            <span style={{ width:8, height:8, borderRadius:999, background:'#fff', animation:'bdPulse 1.2s ease-out infinite' }}/>
            REC {Math.floor(secs/60)}:{String(secs%60).padStart(2,'0')}
          </div>
        )}
        <button style={{ width:40, height:40, borderRadius:999, background:'rgba(0,0,0,0.5)', backdropFilter:'blur(10px)',
          border:'1px solid rgba(255,255,255,0.2)', color:'#fff', cursor:'pointer',
          display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon.Bolt size={18}/>
        </button>
      </div>
      {/* shutter */}
      <div style={{ position:'absolute', bottom:60, left:0, right:0, display:'flex', alignItems:'center',
        justifyContent:'space-around', padding:'0 24px', zIndex:5 }}>
        <button style={{ width:54, height:54, borderRadius:12, background:'rgba(0,0,0,0.5)', border:'1px solid rgba(255,255,255,0.2)',
          color:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon.Camera size={22}/>
        </button>
        <button onClick={() => {
          if (recording) { setRecording(false); window.Nav.useNav; }
          else setRecording(true);
        }} style={{ width:78, height:78, borderRadius:999, padding:0, border:'4px solid rgba(255,255,255,0.85)',
          background:'transparent', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <span style={{
            width: recording ? 28 : 62, height: recording ? 28 : 62,
            borderRadius: recording ? 6 : 999, background:'#FF3B30',
            transition:'all 0.2s',
          }}/>
        </button>
        <button style={{ width:54, height:54, borderRadius:12, background:'rgba(0,0,0,0.5)', border:'1px solid rgba(255,255,255,0.2)',
          color:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon.Refresh size={22}/>
        </button>
      </div>
      {recording === false && secs > 0 && (
        <div style={{ position:'absolute', bottom:140, left:16, right:16, padding:12,
          background:'rgba(0,0,0,0.6)', backdropFilter:'blur(10px)', borderRadius:12,
          display:'flex', alignItems:'center', gap:10, zIndex:5 }}>
          <Icon.Check size={18} stroke="#34D399" sw={2.4}/>
          <div style={{ flex:1, color:'#fff', fontSize:13, fontWeight:600 }}>
            Saved · {Math.floor(secs/60)}:{String(secs%60).padStart(2,'0')}
          </div>
          <button onClick={() => { window.__BD_NAV__.showToast('Video attached','success'); window.__BD_NAV__.pop(); }}
            style={{ padding:'6px 12px', borderRadius:8, background:'#fff', color:'#000', border:'none', fontSize:12, fontWeight:700, cursor:'pointer' }}>Attach</button>
        </div>
      )}
    </div>
  );
}

// ─────────── PHOTO VIEWER ───────────
function ScreenPhotoViewer({ idx=0, label='Door handle damage' }) {
  const t = _TX(); const nav = useNavX();
  return (
    <div style={{ flex:1, position:'relative', background:'#000', overflow:'hidden' }}>
      {/* placeholder photo */}
      <div style={{ flex:1, position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center' }}>
        <svg viewBox="0 0 390 600" style={{ width:'100%', height:'auto', maxHeight:'100%' }}>
          <defs>
            <linearGradient id="pv" x1="0" x2="1" y1="0" y2="1">
              <stop offset="0%" stopColor="#243245"/>
              <stop offset="100%" stopColor="#0a0e1a"/>
            </linearGradient>
          </defs>
          <rect width="390" height="600" fill="url(#pv)"/>
          <rect x="120" y="200" width="150" height="280" fill="#3d4d63" rx="4"/>
          <circle cx="245" cy="340" r="14" fill="#1a2030" stroke="#5a6a82" strokeWidth="2"/>
          <rect x="240" y="334" width="20" height="6" rx="3" fill="#9aa6c0"/>
        </svg>
      </div>
      {/* top */}
      <div style={{ position:'absolute', top:54, left:0, right:0, padding:'0 16px',
        display:'flex', alignItems:'center', justifyContent:'space-between', zIndex:5 }}>
        <button onClick={() => nav.pop()} style={{ width:40, height:40, borderRadius:999,
          background:'rgba(0,0,0,0.5)', backdropFilter:'blur(10px)', border:'1px solid rgba(255,255,255,0.2)',
          color:'#fff', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon.X size={18} sw={2}/>
        </button>
        <div style={{ color:'#fff', fontSize:14, fontWeight:600 }}>{idx+1} of 3</div>
        <button style={{ width:40, height:40, borderRadius:999, background:'rgba(0,0,0,0.5)', backdropFilter:'blur(10px)',
          border:'1px solid rgba(255,255,255,0.2)', color:'#fff', cursor:'pointer',
          display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon.More size={18}/>
        </button>
      </div>
      {/* bottom caption */}
      <div style={{ position:'absolute', bottom:40, left:16, right:16, padding:'14px 16px',
        background:'rgba(0,0,0,0.55)', backdropFilter:'blur(10px)', borderRadius:14, zIndex:5 }}>
        <div style={{ fontSize:12, color:'rgba(255,255,255,0.7)', fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>Evidence</div>
        <div style={{ fontSize:15, color:'#fff', fontWeight:700, marginTop:3 }}>{label}</div>
        <div style={{ fontSize:11, color:'rgba(255,255,255,0.7)', marginTop:3 }}>INC-2841 · 4 min ago · 3.2 MB</div>
      </div>
    </div>
  );
}

// ─────────── BROADCAST COMPOSER ───────────
function ScreenBroadcast() {
  const t = _TX(); const nav = useNavX();
  return (
    <>
      <AppBar t={t} title="Broadcast" back bell={false}/>
      <Screen t={t}>
        <div style={{ padding:'8px 4px' }}>
          <div style={{ fontSize:22, fontWeight:800, color:t.text, letterSpacing:-0.4 }}>Send to all officers</div>
          <div style={{ fontSize:13, color:t.text3, marginTop:4 }}>Broadcasts push to every officer on shift.</div>
        </div>
        <SectionLabel t={t}>Recipients</SectionLabel>
        <Card t={t}>
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <div style={{ width:36, height:36, borderRadius:10, background:t.primarySoft, color:t.primary,
              display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.Users size={18}/></div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:14, fontWeight:700, color:t.text }}>All on-duty · 5 officers</div>
              <div style={{ fontSize:11.5, color:t.text3 }}>Marcus, Priya, Diego, Sasha, Tom</div>
            </div>
            <Button t={t} tone="ghost" size="md">Change</Button>
          </div>
        </Card>
        <SectionLabel t={t}>Priority</SectionLabel>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:6 }}>
          {[['Info','primary'],['Caution','warn',true],['Critical','danger']].map(([l,tone,active])=>(
            <div key={l} style={{ padding:'10px 6px', borderRadius:12, textAlign:'center',
              background: active?t[tone+'Soft']:t.surface, color: active?t[tone]:t.text2,
              border:`1px solid ${active?t[tone]:t.line}`, fontSize:12.5, fontWeight:700 }}>{l}</div>
          ))}
        </div>
        <SectionLabel t={t}>Message</SectionLabel>
        <Card t={t} style={{ minHeight:120 }}>
          <div style={{ fontSize:14, color:t.text3, lineHeight:1.5 }}>
            Severe weather warning until 14:00. Move all outdoor patrols to interior posts. Confirm with reply.
          </div>
        </Card>
        <Card t={t}>
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <div style={{ width:36, height:36, borderRadius:10, background:t.warnSoft, color:t.warn,
              display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.Bell size={18}/></div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:13.5, fontWeight:700, color:t.text }}>Require acknowledgment</div>
              <div style={{ fontSize:11.5, color:t.text3 }}>Officers must tap "got it" to clear</div>
            </div>
            <window.Toggle on/>
          </div>
        </Card>
        <Button t={t} tone="primary" full size="lg" icon={<Icon.Send size={16} sw={2.2}/>}
          onClick={() => { nav.showToast('Broadcast sent to 5 officers','success'); nav.pop(); }}>Send broadcast</Button>
      </Screen>
    </>
  );
}

// ─────────── PUSH-TO-TALK overlay ───────────
function ScreenPTT() {
  const t = _TX(); const nav = useNavX();
  const [holding, setHolding] = React.useState(false);
  const [secs, setSecs] = React.useState(0);
  React.useEffect(() => {
    if (!holding) return;
    const id = setInterval(() => setSecs(s => s+1), 1000);
    return () => clearInterval(id);
  }, [holding]);
  React.useEffect(() => { if (!holding) setSecs(0); }, [holding]);
  return (
    <div style={{ flex:1, position:'relative',
      background: holding
        ? `radial-gradient(120% 80% at 50% 50%, ${t.danger}66, ${t.bg})`
        : `radial-gradient(120% 80% at 50% 50%, ${t.primary}33, ${t.bg})`,
      display:'flex', flexDirection:'column' }}>
      <AppBar t={t} title="Push to talk · Channel 1" back bell={false}/>
      <div style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
        padding:'0 24px', gap:30 }}>
        <div style={{ textAlign:'center' }}>
          <div style={{ fontSize:13, color:t.text3, fontWeight:700, letterSpacing:1, textTransform:'uppercase' }}>
            {holding ? 'You are transmitting' : 'Channel 1 · Westgate Plaza'}
          </div>
          <div style={{ fontSize:34, fontWeight:800, color:t.text, marginTop:6, letterSpacing:-0.5 }}>
            {holding ? `Transmitting · ${secs}s` : '5 listeners'}
          </div>
        </div>
        {/* avatars */}
        <div style={{ display:'flex', gap:8 }}>
          {[['MC','gold'],['PN','primary'],['DA','purple'],['SB','success'],['TR','pink']].map(([n,tone],i)=>(
            <div key={i} style={{ position:'relative' }}>
              <Avatar size={40} name={n} tone={tone} t={t}/>
              {n==='PN' && <span style={{ position:'absolute', bottom:-2, right:-2, width:14, height:14, borderRadius:999, background:t.warn, border:`2px solid ${t.bg}` }}/>}
            </div>
          ))}
        </div>
        {/* hold button */}
        <button
          onMouseDown={() => setHolding(true)} onMouseUp={() => setHolding(false)} onMouseLeave={() => setHolding(false)}
          onTouchStart={() => setHolding(true)} onTouchEnd={() => setHolding(false)}
          style={{
            appearance:'none', cursor:'pointer', border:'none',
            width:200, height:200, borderRadius:999,
            background: holding ? t.danger : t.primary, color:'#fff',
            boxShadow: holding ? `0 0 0 16px ${t.danger}33, 0 0 0 32px ${t.danger}1a` : `0 12px 40px ${t.primary}55`,
            display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:8,
            transition:'all 0.15s', transform: holding?'scale(1.04)':'scale(1)',
          }}>
          <Icon.Mic size={56}/>
          <div style={{ fontSize:14, fontWeight:800, letterSpacing:1, textTransform:'uppercase' }}>{holding?'Talking':'Hold to talk'}</div>
        </button>
        <div style={{ fontSize:12, color:t.text3 }}>Release to stop transmitting</div>
      </div>
    </div>
  );
}

// ─────────── CALENDAR / DAY DETAIL ───────────
function ScreenCalendar() {
  const t = _TX(); const nav = useNavX();
  const days = Array.from({length:35}, (_,i) => i - 2);
  const today = 14;
  return (
    <>
      <AppBar t={t} title="Calendar" back/>
      <Screen t={t}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 4px' }}>
          <div style={{ fontSize:22, fontWeight:800, color:t.text, letterSpacing:-0.3 }}>April 2025</div>
          <div style={{ display:'flex', gap:6 }}>
            <button style={{ width:34, height:34, borderRadius:10, background:t.surface, border:`1px solid ${t.line}`, color:t.text2, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.ArrowL size={16}/></button>
            <button style={{ width:34, height:34, borderRadius:10, background:t.surface, border:`1px solid ${t.line}`, color:t.text2, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', transform:'rotate(180deg)' }}><Icon.ArrowL size={16}/></button>
          </div>
        </div>
        <Card t={t} pad={10}>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:0, marginBottom:6 }}>
            {['S','M','T','W','T','F','S'].map((d,i)=>(
              <div key={i} style={{ textAlign:'center', fontSize:11, color:t.text3, fontWeight:700 }}>{d}</div>
            ))}
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:4 }}>
            {days.map((d,i)=>{
              const inMonth = d > 0 && d <= 30;
              const isToday = d === today;
              const onShift = inMonth && [3,4,5,8,9,10,11,14,15,16,17,21,22,23,24,28,29,30].includes(d);
              return (
                <div key={i} onClick={()=>inMonth && nav.push('calendarDay',{day:d})} style={{
                  aspectRatio:'1', borderRadius:9, position:'relative', cursor: inMonth?'pointer':'default',
                  background: isToday ? t.primary : 'transparent',
                  display:'flex', alignItems:'center', justifyContent:'center',
                  fontSize:13, fontWeight: isToday?800:600,
                  color: !inMonth ? t.text3+'66' : isToday ? '#fff' : t.text,
                }}>{inMonth ? d : ''}
                  {onShift && !isToday && <span style={{ position:'absolute', bottom:4, width:4, height:4, borderRadius:999, background:t.success }}/>}
                  {isToday && onShift && <span style={{ position:'absolute', bottom:4, width:4, height:4, borderRadius:999, background:'#fff' }}/>}
                </div>
              );
            })}
          </div>
        </Card>
        <SectionLabel t={t}>Upcoming</SectionLabel>
        {[
          ['Tue Apr 15','Night · North Gate','18:00 – 02:00','primary'],
          ['Wed Apr 16','Night · North Gate','18:00 – 02:00','primary'],
          ['Thu Apr 17','Night · Lobby','18:00 – 02:00','primary'],
          ['Fri Apr 18','OFF','Day off','muted'],
        ].map(([d,p,h,tone],i)=>(
          <div key={i} onClick={()=>nav.push('calendarDay',{label:d})} style={{ display:'flex', alignItems:'center', gap:12, padding:12,
            background:t.surface, border:`1px solid ${t.line}`, borderRadius:12, cursor:'pointer' }}>
            <div style={{ width:44, textAlign:'center' }}>
              <div style={{ fontSize:10, color:t.text3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>{d.split(' ')[0]}</div>
              <div style={{ fontSize:18, fontWeight:800, color:t.text, marginTop:1 }}>{d.split(' ')[2]}</div>
            </div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:13.5, fontWeight:700, color:t.text }}>{p}</div>
              <div style={{ fontSize:11.5, color:t.text3, marginTop:1 }}>{h}</div>
            </div>
            <Icon.Chev size={14} stroke={t.text3}/>
          </div>
        ))}
      </Screen>
      <BottomNav active="more" t={t} onChange={k=>nav.tab(k)}/>
    </>
  );
}

function ScreenCalendarDay({ label='Tue Apr 15' }) {
  const t = _TX(); const nav = useNavX();
  return (
    <>
      <AppBar t={t} title={label} back bell={false}/>
      <Screen t={t}>
        <Card t={t}>
          <div style={{ display:'flex', alignItems:'center', gap:12 }}>
            <div style={{ width:44, height:44, borderRadius:11, background:t.primarySoft, color:t.primary,
              display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.Cal size={22}/></div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:11, color:t.text3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>Night Shift</div>
              <div style={{ fontSize:16, fontWeight:800, color:t.text }}>18:00 – 02:00</div>
              <div style={{ fontSize:12, color:t.text3, marginTop:2 }}>Westgate Plaza · North Gate</div>
            </div>
          </div>
          <div style={{ display:'flex', gap:6, marginTop:12 }}>
            <Pill tone="success" t={t} size="sm">Confirmed</Pill>
            <Pill tone="primary" t={t} size="sm">8h 0m</Pill>
            <Pill tone="muted" t={t} size="sm">Partner: Sasha B.</Pill>
          </div>
        </Card>
        <SectionLabel t={t}>Actions</SectionLabel>
        <Card t={t} pad={0}>
          {[
            ['Request swap',<Icon.Swap size={18}/>,'primary',()=>nav.push('shiftSwap')],
            ['Request time off',<Icon.Cal size={18}/>,'purple',()=>nav.openSheet('timeOff')],
            ['Notify supervisor',<Icon.Chat size={18}/>,'warn',()=>nav.push('chat',{threadId:'th2'})],
          ].map(([l,icon,tone,onClick],i,a)=>(
            <div key={i} onClick={onClick} style={{ display:'flex', alignItems:'center', gap:12, padding:'13px 14px', cursor:'pointer',
              borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
              <div style={{ width:32, height:32, borderRadius:9, background:t[tone+'Soft'], color:t[tone],
                display:'flex', alignItems:'center', justifyContent:'center' }}>{icon}</div>
              <div style={{ flex:1, fontSize:14, fontWeight:600, color:t.text }}>{l}</div>
              <Icon.Chev size={14} stroke={t.text3}/>
            </div>
          ))}
        </Card>
      </Screen>
    </>
  );
}

// ─────────── VEHICLE LOG ───────────
function ScreenVehicleLog() {
  const t = _TX(); const nav = useNavX();
  const vehicles = window.Store.useStore(s => s.vehicles);
  return (
    <>
      <AppBar t={t} title="Vehicle Log" back right={
        <Button t={t} tone="primary" size="md" icon={<Icon.Plus size={14} sw={2.2}/>} onClick={()=>nav.openSheet('vehicleEntry')}>Add</Button>
      }/>
      <Screen t={t}>
        <div style={{ padding:'0 4px' }}>
          <div style={{ fontSize:13, color:t.text3, fontWeight:600 }}>Today · {new Date().toLocaleDateString()}</div>
          <div style={{ fontSize:22, fontWeight:800, color:t.text, letterSpacing:-0.3 }}>{vehicles.length} entries</div>
        </div>
        {vehicles.map((v,i)=>(
          <Card key={v.id} t={t}>
            <div style={{ display:'flex', alignItems:'flex-start', gap:12 }}>
              <div style={{ width:42, height:42, borderRadius:11, background: v.out?t.surface2:t.primarySoft,
                color: v.out?t.text3:t.primary,
                display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.Truck size={20}/></div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:8 }}>
                  <div style={{ fontSize:14, fontWeight:800, color:t.text, fontFamily:'"JetBrains Mono",monospace' }}>{v.plate}</div>
                  <Pill tone={v.out?'muted':'primary'} t={t} size="sm">{v.out?'Out':'On site'}</Pill>
                </div>
                <div style={{ fontSize:12.5, color:t.text2, marginTop:2 }}>{v.desc}</div>
                <div style={{ fontSize:11.5, color:t.text3, marginTop:2 }}>{v.purpose}</div>
                <div style={{ display:'flex', gap:10, marginTop:8, fontSize:11.5, color:t.text3 }}>
                  <span><Icon.ArrowL size={11}/> In {timeAgo(v.in)}</span>
                  {v.out && <span>· Out {timeAgo(v.out)}</span>}
                </div>
              </div>
            </div>
          </Card>
        ))}
      </Screen>
      <BottomNav active="more" t={t} onChange={k=>nav.tab(k)}/>
    </>
  );
}

// ─────────── EQUIPMENT ───────────
function ScreenEquipment() {
  const t = _TX(); const nav = useNavX();
  const equipment = window.Store.useStore(s => s.equipment);
  const ic = (k) => k==='camera'?<Icon.Camera size={18}/>:k==='radio'?<Icon.Headset size={18}/>:k==='flashlight'?<Icon.Bolt size={18}/>:<Icon.Truck size={18}/>;
  return (
    <>
      <AppBar t={t} title="Equipment" back/>
      <Screen t={t}>
        <div style={{ padding:'0 4px' }}>
          <div style={{ fontSize:13, color:t.text3, fontWeight:600 }}>Checked out to you</div>
          <div style={{ fontSize:22, fontWeight:800, color:t.text, letterSpacing:-0.3 }}>
            {equipment.filter(e=>e.holder==='g1').length} items
          </div>
        </div>
        <SectionLabel t={t}>Yours</SectionLabel>
        {equipment.filter(e=>e.holder==='g1').map(e=>(
          <Card key={e.id} t={t}>
            <div style={{ display:'flex', alignItems:'center', gap:12 }}>
              <div style={{ width:42, height:42, borderRadius:11, background:t.primarySoft, color:t.primary,
                display:'flex', alignItems:'center', justifyContent:'center' }}>{ic(e.kind)}</div>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:14, fontWeight:700, color:t.text }}>{e.name}</div>
                {e.battery!=null && (
                  <div style={{ display:'flex', alignItems:'center', gap:6, marginTop:4 }}>
                    <div style={{ flex:1, height:4, borderRadius:999, background:t.surface2, maxWidth:80 }}>
                      <div style={{ width:`${e.battery}%`, height:'100%', borderRadius:999,
                        background: e.battery<30?t.danger:e.battery<60?t.warn:t.success }}/>
                    </div>
                    <span style={{ fontSize:11, color:t.text3, fontWeight:700, fontFamily:'"JetBrains Mono",monospace' }}>{e.battery}%</span>
                  </div>
                )}
              </div>
              <Button t={t} tone="ghost" size="md" onClick={()=>nav.showToast(`${e.name} returned`,'success')}>Return</Button>
            </div>
          </Card>
        ))}
        <SectionLabel t={t}>Available</SectionLabel>
        {equipment.filter(e=>!e.holder).map(e=>(
          <Card key={e.id} t={t}>
            <div style={{ display:'flex', alignItems:'center', gap:12 }}>
              <div style={{ width:42, height:42, borderRadius:11, background:t.surface2, color:t.text2,
                display:'flex', alignItems:'center', justifyContent:'center' }}>{ic(e.kind)}</div>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:14, fontWeight:700, color:t.text }}>{e.name}</div>
                <div style={{ fontSize:11.5, color:t.text3, marginTop:2 }}>Available · battery {e.battery}%</div>
              </div>
              <Button t={t} tone="primary" size="md" onClick={()=>nav.showToast(`${e.name} checked out`,'success')}>Take</Button>
            </div>
          </Card>
        ))}
      </Screen>
      <BottomNav active="more" t={t} onChange={k=>nav.tab(k)}/>
    </>
  );
}

// ─────────── APPROVAL DETAIL (supervisor) ───────────
function ScreenApprovalDetail({ id }) {
  const t = _TX(); const nav = useNavX();
  const approvals = window.Store.useStore(s => s.approvals);
  const a = approvals.find(x=>x.id===id) || approvals[0];
  const tone = a.kind==='time-off'?'purple':a.kind==='swap'?'teal':a.kind==='timesheet'?'primary':'warn';
  return (
    <>
      <AppBar t={t} title="Review" back bell={false}/>
      <Screen t={t}>
        <Card t={t}>
          <div style={{ display:'flex', alignItems:'center', gap:12 }}>
            <Avatar size={48} name={a.whom.split(' ').map(s=>s[0]).join('').slice(0,2)} tone={tone} t={t}/>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:11, color:t[tone], fontWeight:800, letterSpacing:0.5, textTransform:'uppercase' }}>{a.kind.replace('-',' ')}</div>
              <div style={{ fontSize:16, fontWeight:800, color:t.text }}>{a.whom}</div>
              <div style={{ fontSize:12, color:t.text3, marginTop:2 }}>Submitted {timeAgo(a.t)}</div>
            </div>
          </div>
        </Card>
        <SectionLabel t={t}>Request</SectionLabel>
        <Card t={t}>
          <div style={{ fontSize:14, color:t.text, lineHeight:1.5 }}>{a.detail}</div>
        </Card>
        <SectionLabel t={t}>Coverage impact</SectionLabel>
        <Card t={t} pad={0}>
          {[
            ['Site coverage','Westgate Plaza · 4 of 5 posts','primary'],
            ['Hours affected','24h over 3 days','muted'],
            ['Available cover','D. Brown, T. Reilly','success'],
          ].map(([k,v,tone],i,a)=>(
            <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 14px',
              borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
              <div style={{ flex:1, fontSize:12.5, color:t.text3, fontWeight:600 }}>{k}</div>
              <div style={{ fontSize:13, color: t[tone]||t.text, fontWeight:700 }}>{v}</div>
            </div>
          ))}
        </Card>
        <SectionLabel t={t}>Note from requester</SectionLabel>
        <Card t={t}>
          <div style={{ fontSize:13, color:t.text2, lineHeight:1.5, fontStyle:'italic' }}>
            "Family event. Already coordinated with David and Tom for coverage."
          </div>
        </Card>
        <div style={{ display:'flex', gap:10 }}>
          <Button t={t} tone="ghost" size="lg" style={{ flex:1 }} onClick={()=>{
            window.Store.actions.decideApproval(a.id,'denied'); nav.showToast('Denied','danger'); nav.pop();
          }}>Deny</Button>
          <Button t={t} tone="success" size="lg" style={{ flex:2 }} icon={<Icon.Check size={16} sw={2.4}/>}
            onClick={()=>{
              window.Store.actions.decideApproval(a.id,'approved'); nav.showToast('Approved','success'); nav.pop();
            }}>Approve</Button>
        </div>
      </Screen>
    </>
  );
}

// ─────────── SOS POST-EVENT ───────────
function ScreenSOSPost() {
  const t = _TX(); const nav = useNavX();
  return (
    <>
      <AppBar t={t} title="Alert resolved" back bell={false}/>
      <Screen t={t}>
        <Card t={t}>
          <div style={{ display:'flex', alignItems:'center', gap:12 }}>
            <div style={{ width:48, height:48, borderRadius:12, background:t.successSoft, color:t.success,
              display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.Check size={24} sw={2.4}/></div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:11, color:t.success, fontWeight:800, letterSpacing:0.5, textTransform:'uppercase' }}>Alert ended</div>
              <div style={{ fontSize:16, fontWeight:800, color:t.text }}>Help arrived · 2 min 14s</div>
              <div style={{ fontSize:12, color:t.text3 }}>Supervisor + 2 officers responded</div>
            </div>
          </div>
        </Card>
        <SectionLabel t={t}>Quick report</SectionLabel>
        <Card t={t} style={{ minHeight:80 }}>
          <div style={{ fontSize:11, color:t.text3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>What happened?</div>
          <div style={{ fontSize:13, color:t.text3, marginTop:8 }}>Tap to add a brief description for your supervisor…</div>
        </Card>
        <SectionLabel t={t}>Was this</SectionLabel>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:6 }}>
          {[['Real','danger'],['Drill','warn',true],['Mistake','muted']].map(([l,tone,active])=>(
            <div key={l} style={{ padding:'10px 6px', borderRadius:12, textAlign:'center',
              background: active?t[tone+'Soft']:t.surface, color: active?t[tone]:t.text2,
              border:`1px solid ${active?t[tone]:t.line}`, fontSize:12.5, fontWeight:700 }}>{l}</div>
          ))}
        </div>
        <SectionLabel t={t}>Timeline</SectionLabel>
        <Card t={t} pad={0}>
          {[
            ['00:00','Alert triggered (long press)','danger'],
            ['00:08','Live audio + GPS streaming','primary'],
            ['00:24','Supervisor accepted','success'],
            ['01:02','Officer Brooks en route','primary'],
            ['02:14','You ended the alert','muted'],
          ].map(([t1,what,tone],i,a)=>(
            <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 14px',
              borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
              <span style={{ fontSize:11, color:t.text3, fontWeight:700, fontFamily:'"JetBrains Mono",monospace', width:42 }}>{t1}</span>
              <span style={{ width:6, height:6, borderRadius:999, background:t[tone] }}/>
              <span style={{ flex:1, fontSize:13, color:t.text }}>{what}</span>
            </div>
          ))}
        </Card>
        <Button t={t} tone="primary" full size="lg" onClick={()=>{ nav.showToast('Report saved','success'); nav.popTo('home'); }}>File report</Button>
      </Screen>
    </>
  );
}

// ─────────── GLOBAL SEARCH ───────────
function ScreenSearch() {
  const t = _TX(); const nav = useNavX();
  return (
    <>
      <AppBar t={t} title="Search" back bell={false}/>
      <Screen t={t}>
        <div style={{ display:'flex', alignItems:'center', gap:8, padding:'10px 14px',
          background:t.surface, border:`1px solid ${t.primary}`, borderRadius:14 }}>
          <Icon.Search size={16} stroke={t.primary}/>
          <span style={{ flex:1, fontSize:14, color:t.text, fontWeight:600 }}>marc</span>
          <Icon.X size={14} stroke={t.text3}/>
        </div>
        <SectionLabel t={t}>Officers</SectionLabel>
        <Card t={t} pad={0}>
          {[['Marcus Chen','MC','gold','Officer · Westgate'],['Marcia Lopez','ML','purple','Officer · Harbor']].map(([n,init,tone,sub],i,a)=>(
            <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 14px',
              borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
              <Avatar size={32} name={init} tone={tone} t={t}/>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13.5, fontWeight:700, color:t.text }}>
                  <span style={{ color:t.primary }}>Marc</span>{n.slice(4)}
                </div>
                <div style={{ fontSize:11.5, color:t.text3 }}>{sub}</div>
              </div>
              <Icon.Chev size={14} stroke={t.text3}/>
            </div>
          ))}
        </Card>
        <SectionLabel t={t}>Incidents</SectionLabel>
        <Card t={t}>
          <div style={{ fontSize:13, color:t.text3 }}>No matching incidents.</div>
        </Card>
        <SectionLabel t={t}>Recent</SectionLabel>
        {['mech room','vendor','swap fri','overnight','fire lane'].map((q,i)=>(
          <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 4px' }}>
            <Icon.Clock size={14} stroke={t.text3}/>
            <span style={{ flex:1, fontSize:13, color:t.text2 }}>{q}</span>
            <Icon.X size={12} stroke={t.text3}/>
          </div>
        ))}
      </Screen>
    </>
  );
}

// ─────────── EMPTY / OFFLINE ───────────
function ScreenOffline() {
  const t = _TX(); const nav = useNavX();
  return (
    <>
      <AppBar t={t} title="" back bell={false}/>
      <div style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
        padding:'0 32px', gap:16, textAlign:'center' }}>
        <div style={{ width:88, height:88, borderRadius:999, background:t.warnSoft, color:t.warn,
          display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.Wifi size={40}/></div>
        <div style={{ fontSize:22, fontWeight:800, color:t.text, letterSpacing:-0.3 }}>You're offline</div>
        <div style={{ fontSize:13, color:t.text3, lineHeight:1.5 }}>
          Patrols and incidents will queue and sync automatically when a connection is restored.
        </div>
        <Card t={t} style={{ width:'100%' }}>
          <div style={{ display:'flex', justifyContent:'space-between', fontSize:12 }}>
            <span style={{ color:t.text3 }}>Queued</span>
            <span style={{ color:t.text, fontWeight:700 }}>3 scans · 1 incident</span>
          </div>
        </Card>
        <Button t={t} tone="primary" full size="lg" icon={<Icon.Refresh size={16}/>}
          onClick={()=>{ nav.showToast('Reconnected','success'); nav.pop(); }}>Try again</Button>
      </div>
    </>
  );
}

// ─────────── helpers / extras ───────────
function timeAgo(iso) {
  if (!iso) return '';
  const d = new Date(iso); const m = Math.floor((Date.now()-d.getTime())/60000);
  if (m < 1) return 'just now';
  if (m < 60) return m+' min ago';
  if (m < 1440) return Math.floor(m/60)+'h ago';
  return Math.floor(m/1440)+'d ago';
}

// Toggle (used in a few places)
function Toggle({ on, onChange }) {
  const t = _TX();
  return (
    <button onClick={()=>onChange?.(!on)} style={{
      appearance:'none', cursor:'pointer', border:'none', padding:0,
      width:46, height:28, borderRadius:999,
      background: on ? t.primary : t.lineStrong,
      position:'relative', transition:'all 0.2s',
    }}>
      <span style={{ position:'absolute', top:3, left: on?22:3, width:22, height:22, borderRadius:999,
        background:'#fff', boxShadow:'0 2px 4px rgba(0,0,0,0.2)', transition:'left 0.2s' }}/>
    </button>
  );
}

// Sheet: time-off
function SheetTimeOff({ close }) {
  const t = _TX(); const nav = useNavX();
  return (
    <window.Sheet title="Request time off" subtitle="New request" close={close}
      footer={<Button t={t} tone="primary" full size="lg" onClick={()=>{ nav.showToast('Request submitted','success'); close(); }}>Submit</Button>}>
      {[['Type','PTO'],['From','Sat Apr 19'],['To','Mon Apr 21'],['Hours','24h']].map(([k,v],i,a)=>(
        <div key={i} style={{ display:'flex', alignItems:'center', padding:'12px 4px',
          borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
          <div style={{ flex:1, fontSize:13.5, color:t.text2, fontWeight:600 }}>{k}</div>
          <div style={{ fontSize:14, color:t.text, fontWeight:700 }}>{v}</div>
          <Icon.Chev size={14} stroke={t.text3} style={{ marginLeft:8 }}/>
        </div>
      ))}
      <div style={{ marginTop:12, padding:12, background:t.surface, border:`1px solid ${t.line}`, borderRadius:12, minHeight:80 }}>
        <div style={{ fontSize:11, color:t.text3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>Reason</div>
        <div style={{ fontSize:13, color:t.text3, marginTop:6 }}>Optional message to your supervisor…</div>
      </div>
    </window.Sheet>
  );
}

// Sheet: filter incidents
function SheetIncidentsFilter({ close }) {
  const t = _TX(); const nav = useNavX();
  return (
    <window.Sheet title="Filter" subtitle="Incidents" close={close}
      footer={<div style={{ display:'flex', gap:10 }}>
        <Button t={t} tone="ghost" size="lg" style={{flex:1}} onClick={close}>Reset</Button>
        <Button t={t} tone="primary" size="lg" style={{flex:2}} onClick={()=>{ nav.showToast('Filters applied','primary'); close(); }}>Apply</Button>
      </div>}>
      <SectionLabel t={t}>Status</SectionLabel>
      <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
        {[['Open',true],['In review',true],['Closed',false]].map(([l,on])=>(
          <Pill key={l} tone={on?'primary':'muted'} t={t}>{l}</Pill>
        ))}
      </div>
      <SectionLabel t={t} style={{marginTop:14}}>Severity</SectionLabel>
      <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
        {[['Low','success',false],['Medium','warn',true],['High','danger',true]].map(([l,tone,on])=>(
          <Pill key={l} tone={on?tone:'muted'} t={t}>{l}</Pill>
        ))}
      </div>
      <SectionLabel t={t} style={{marginTop:14}}>Site</SectionLabel>
      {['Westgate Plaza','Harbor Tower','Northpoint','Crestview'].map((s,i)=>(
        <div key={s} style={{ display:'flex', alignItems:'center', padding:'10px 4px', borderBottom:`1px solid ${t.line}` }}>
          <span style={{ flex:1, fontSize:14, color:t.text }}>{s}</span>
          <div style={{ width:20, height:20, borderRadius:5, border:`2px solid ${i===0?t.primary:t.lineStrong}`,
            background: i===0?t.primary:'transparent', display:'flex', alignItems:'center', justifyContent:'center' }}>
            {i===0 && <Icon.Check size={12} sw={3.2} stroke="#fff"/>}
          </div>
        </div>
      ))}
    </window.Sheet>
  );
}

// Sheet: contact support
function SheetContactSupport({ close }) {
  const t = _TX(); const nav = useNavX();
  return (
    <window.Sheet title="Contact dispatch" subtitle="24/7 support" close={close}>
      {[
        ['Call dispatch','+1 (800) 555-9000',<Icon.Phone size={20}/>,'primary'],
        ['Message',`Open chat`,<Icon.Chat size={20}/>,'purple'],
        ['Email','support@byduty.co',<Icon.Doc size={20}/>,'teal'],
      ].map(([l,sub,icon,tone],i,a)=>(
        <div key={i} onClick={()=>{ nav.showToast('Opening '+l.toLowerCase(),'primary'); close(); }} style={{
          display:'flex', alignItems:'center', gap:12, padding:'14px 4px', cursor:'pointer',
          borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
          <div style={{ width:40, height:40, borderRadius:11, background:t[tone+'Soft'], color:t[tone],
            display:'flex', alignItems:'center', justifyContent:'center' }}>{icon}</div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:14, fontWeight:700, color:t.text }}>{l}</div>
            <div style={{ fontSize:12, color:t.text3 }}>{sub}</div>
          </div>
          <Icon.Chev size={14} stroke={t.text3}/>
        </div>
      ))}
    </window.Sheet>
  );
}

// Sheet: shift swap
function SheetShiftSwapPick({ close }) {
  const t = _TX(); const nav = useNavX();
  return (
    <window.Sheet title="Pick a partner" subtitle="Shift swap" close={close}>
      {[['Sasha Brooks','SB','success','Westgate · same site'],
        ['David Brown','DB','warn','Off Friday'],
        ['Tom Reilly','TR','pink','Crestview · cross-site']].map(([n,init,tone,sub],i,a)=>(
        <div key={n} onClick={()=>{ nav.showToast('Swap request sent to '+n.split(' ')[0],'success'); close(); }}
          style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 4px', cursor:'pointer',
            borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
          <Avatar size={36} name={init} tone={tone} t={t}/>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:14, fontWeight:700, color:t.text }}>{n}</div>
            <div style={{ fontSize:11.5, color:t.text3 }}>{sub}</div>
          </div>
          <Icon.Chev size={14} stroke={t.text3}/>
        </div>
      ))}
    </window.Sheet>
  );
}

// Sheet: visitor entry
function SheetVisitorEntry({ close }) {
  const t = _TX(); const nav = useNavX();
  return (
    <window.Sheet title="Check in visitor" close={close}
      footer={<Button t={t} tone="primary" full size="lg" onClick={()=>{
        window.Store.actions.addVisitor({ name:'New Visitor', org:'—', host:'—', plate:'—' });
        nav.showToast('Visitor checked in','success'); close();
      }}>Check in</Button>}>
      {[['Name','Tap to enter'],['Organization','Optional'],['Host','Search staff…'],['Plate / Vehicle','Optional'],['Photo / ID','Tap to capture']].map(([k,v],i,a)=>(
        <div key={i} style={{ display:'flex', alignItems:'center', padding:'12px 4px',
          borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
          <div style={{ flex:1, fontSize:13, color:t.text3, fontWeight:600 }}>{k}</div>
          <div style={{ fontSize:13, color:t.text }}>{v}</div>
          <Icon.Chev size={14} stroke={t.text3} style={{ marginLeft:8 }}/>
        </div>
      ))}
    </window.Sheet>
  );
}

// Sheet: vehicle entry
function SheetVehicleEntry({ close }) {
  const t = _TX(); const nav = useNavX();
  return (
    <window.Sheet title="Log vehicle" close={close}
      footer={<Button t={t} tone="primary" full size="lg" onClick={()=>{ nav.showToast('Vehicle logged','success'); close(); }}>Log entry</Button>}>
      {[['Plate','XXX-0000'],['Description','Make / model / color'],['Purpose','Delivery / resident / vendor'],['Direction','Inbound']].map(([k,v],i,a)=>(
        <div key={i} style={{ display:'flex', alignItems:'center', padding:'12px 4px',
          borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
          <div style={{ flex:1, fontSize:13, color:t.text3, fontWeight:600 }}>{k}</div>
          <div style={{ fontSize:13, color:t.text }}>{v}</div>
        </div>
      ))}
    </window.Sheet>
  );
}

// Sheet: clock-out confirmation
function SheetClockOut({ close }) {
  const t = _TX(); const nav = useNavX();
  return (
    <window.Sheet title="End your shift?" subtitle="6h 32m worked" close={close}
      footer={<div style={{ display:'flex', gap:10 }}>
        <Button t={t} tone="ghost" size="lg" style={{flex:1}} onClick={close}>Cancel</Button>
        <Button t={t} tone="danger" size="lg" style={{flex:2}} onClick={()=>{
          window.Store.actions.clockOut(); nav.showToast('Clocked out','primary'); nav.replace('home'); close();
        }}>Clock out</Button>
      </div>}>
      <Card t={t} pad={0}>
        {[['Started','13:28'],['Ending','19:00'],['Breaks','30 min'],['Net hours','6h 02m']].map(([k,v],i,a)=>(
          <div key={k} style={{ display:'flex', padding:'11px 14px',
            borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
            <div style={{ flex:1, fontSize:13, color:t.text3 }}>{k}</div>
            <div style={{ fontSize:13, color:t.text, fontWeight:700 }}>{v}</div>
          </div>
        ))}
      </Card>
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:12, marginTop:10,
        background:t.warnSoft, border:`1px solid ${t.warn}33`, borderRadius:12 }}>
        <Icon.AlertTri size={18} stroke={t.warn}/>
        <div style={{ flex:1, fontSize:12, color:t.text2, lineHeight:1.5 }}>
          Pending: <b style={{color:t.text}}>1 patrol incomplete</b>. Submit a DAR to close out.
        </div>
      </div>
    </window.Sheet>
  );
}

// Sheet: break picker
function SheetBreakKind({ close }) {
  const t = _TX(); const nav = useNavX();
  return (
    <window.Sheet title="Take a break" close={close}>
      {[['Short break','15 min','primary',<Icon.Clock size={20}/>],
        ['Lunch','30 min','success',<Icon.ClipChk size={20}/>],
        ['Custom','Set duration','muted',<Icon.More size={20}/>]].map(([l,sub,tone,icon],i,a)=>(
        <div key={l} onClick={()=>{
          window.Store.actions.startBreak(l==='Lunch'?'lunch':'short');
          nav.showToast(`${l} started`,'primary'); close();
        }} style={{ display:'flex', alignItems:'center', gap:12, padding:'14px 4px', cursor:'pointer',
          borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
          <div style={{ width:42, height:42, borderRadius:11, background:t[tone+'Soft']||t.surface, color:t[tone]||t.text2,
            display:'flex', alignItems:'center', justifyContent:'center' }}>{icon}</div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:14, fontWeight:700, color:t.text }}>{l}</div>
            <div style={{ fontSize:12, color:t.text3 }}>{sub}</div>
          </div>
          <Icon.Chev size={14} stroke={t.text3}/>
        </div>
      ))}
    </window.Sheet>
  );
}

// Sheet: geofence violation alert
function SheetGeofence({ close }) {
  const t = _TX(); const nav = useNavX();
  return (
    <window.Sheet title="Outside geofence" subtitle="Geofence alert" close={close}
      footer={<div style={{ display:'flex', gap:10 }}>
        <Button t={t} tone="ghost" size="lg" style={{flex:1}} onClick={close}>I'm aware</Button>
        <Button t={t} tone="primary" size="lg" style={{flex:2}} onClick={()=>{ nav.showToast('Supervisor notified','primary'); close(); }}>Notify supervisor</Button>
      </div>}>
      <div style={{ display:'flex', alignItems:'center', gap:12, padding:'14px',
        background:t.dangerSoft, border:`1px solid ${t.danger}33`, borderRadius:12 }}>
        <div style={{ width:44, height:44, borderRadius:12, background:t.danger, color:'#fff',
          display:'flex', alignItems:'center', justifyContent:'center' }}><Icon.AlertTri size={22}/></div>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:14, fontWeight:800, color:t.text }}>You've left the site perimeter</div>
          <div style={{ fontSize:12, color:t.text2, marginTop:2 }}>142m from Westgate Plaza · clock-in still active</div>
        </div>
      </div>
      <Card t={t} style={{ marginTop:10 }}>
        <div style={{ fontSize:13, color:t.text2, lineHeight:1.5 }}>
          If this is intentional (e.g. external escort), tap "I'm aware". Otherwise return to the site to clear this alert.
        </div>
      </Card>
    </window.Sheet>
  );
}

// Sheet: incident comment input
function SheetComment({ incId, close }) {
  const t = _TX(); const nav = useNavX();
  const [text, setText] = React.useState('');
  return (
    <window.Sheet title="Add comment" close={close}
      footer={<Button t={t} tone="primary" full size="lg" onClick={()=>{
        window.Store.actions.addIncidentComment(incId || 'i1', text || 'New comment');
        nav.showToast('Comment added','success'); close();
      }}>Post</Button>}>
      <div style={{ padding:14, background:t.surface, border:`1px solid ${t.primary}`, borderRadius:12, minHeight:100 }}>
        <div style={{ fontSize:14, color: text ? t.text : t.text3, lineHeight:1.5 }}>{text || 'Add a note for the team…'}</div>
      </div>
      <div style={{ display:'flex', gap:6, marginTop:8 }}>
        {['Looks good','Will follow up','See attached','Closing out'].map(q=>(
          <Pill key={q} tone="muted" t={t} style={{ cursor:'pointer' }}>
            <span onClick={()=>setText(q)}>{q}</span>
          </Pill>
        ))}
      </div>
    </window.Sheet>
  );
}

// Sheet: home density picker
function SheetDensity({ close }) {
  const t = _TX(); const nav = useNavX();
  return (
    <window.Sheet title="Home density" close={close}>
      {['simple','medium','dense'].map((k,i,a)=>(
        <div key={k} onClick={()=>{
          if (window.__BD_SET_TWEAK__) window.__BD_SET_TWEAK__('density', k);
          nav.showToast('Density: '+k,'primary'); close();
        }} style={{ display:'flex', alignItems:'center', padding:'14px 4px', cursor:'pointer',
          borderBottom: i===a.length-1?'none':`1px solid ${t.line}` }}>
          <div style={{ flex:1, fontSize:14, fontWeight:700, color:t.text, textTransform:'capitalize' }}>{k}</div>
          <Icon.Chev size={14} stroke={t.text3}/>
        </div>
      ))}
    </window.Sheet>
  );
}

Object.assign(window, {
  ScreenSplash, ScreenForgot, ScreenReset, ScreenProfileSetup,
  ScreenScanSuccess, ScreenScanFail, ScreenPatrolSummary,
  ScreenAudioRecorder, ScreenVideoRecorder, ScreenPhotoViewer,
  ScreenBroadcast, ScreenPTT, ScreenCalendar, ScreenCalendarDay,
  ScreenVehicleLog, ScreenEquipment, ScreenApprovalDetail,
  ScreenSOSPost, ScreenSearch, ScreenOffline,
  Toggle, timeAgo,
  // sheets
  SheetMissedReason, SheetTimeOff, SheetIncidentsFilter, SheetContactSupport,
  SheetShiftSwapPick, SheetVisitorEntry, SheetVehicleEntry,
  SheetClockOut, SheetBreakKind, SheetGeofence, SheetComment, SheetDensity,
});
