/* ══════════════════════════════════════════════════
   PHONE SCREENS — the entregga driver app UI, recreated.

   Mirrors the app as of v1.9.16 (light "cream" redesign).
   Layout: PRIMITIVES → SHELL → STATUS SCREENS → LIST
   SCREENS → REGISTRY.

   The registry at the bottom must stay in this file, below
   the screens it names: it is evaluated at load time, not
   render time, so a forward reference would be undefined.

   NOTE: no real personal data belongs in here. The driver is
   always "Nome do Motorista" / motorista@empresa.com.br.
══════════════════════════════════════════════════ */

const PHONE = {
  driver:  'Nome do Motorista',
  email:   'motorista@empresa.com.br',
  company: 'Fast Via',
  shift:   '07:00 - 19:00 | Seg-Sex',
  version: '1.9.16 (41)',
  clock:   '14:07',
  since:   '13:40',
};

/* ══════════════ PRIMITIVES ══════════════
   Hoisted to module scope. Previously these were closures
   rebuilt on every render inside each screen component. */

const IconTile = ({ tint, color, size = 34, r = 10, children }) => (
  <div style={{ width:size, height:size, borderRadius:r, background:tint, color,
                display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
    {children}
  </div>
);

const StatCard = ({ icon, tint, color, value, label }) => (
  <div style={{ background:T.surface, border:`1px solid ${T.line}`, borderRadius:T.rCard, padding:'10px 11px 11px' }}>
    <IconTile tint={tint} color={color} size={30} r={9}>{icon}</IconTile>
    <div key={value} style={{ fontSize:18, fontWeight:700, color:T.ink, lineHeight:1.1, marginTop:8, animation:'counterTick .4s ease' }}>{value}</div>
    <div style={{ fontSize:10, color:T.muted, marginTop:2 }}>{label}</div>
  </div>
);

/* minWidth:0 — these sit in a 3-up grid inside the phone; without it the
   grid tracks are floored at min-content and the row overflows the screen
   on a 320px device. */
const MiniCard = ({ icon, value, label, color = T.green }) => (
  <div style={{ background:T.surface, border:`1px solid ${T.line}`, borderRadius:T.rChip, padding:'8px 7px', display:'flex', alignItems:'center', gap:6, minWidth:0 }}>
    <span style={{ color, display:'flex', flexShrink:0 }}>{icon}</span>
    <div style={{ minWidth:0 }}>
      <div style={{ fontSize:11.5, fontWeight:700, color, lineHeight:1.1 }}>{value}</div>
      <div style={{ fontSize:8.5, color:T.muted, marginTop:1 }}>{label}</div>
    </div>
  </div>
);

/* variant: neutral (PAUSAR) | danger (PARAR/SAIR) | go (RETOMAR/INICIAR)
   In the real app the primary action is solid crimson — see the
   PAUSADO/PARADO screenshots — never green. */
const PillButton = ({ variant = 'neutral', icon, label, onClick, mt = 0 }) => {
  const v = {
    neutral: { bg:T.cream2,  fg:T.ink,   bd:T.line },
    danger:  { bg:T.redTint, fg:T.red,   bd:'transparent' },
    go:      { bg:T.brand,   fg:'#fff',  bd:'transparent' },
  }[variant];
  return (
    <button onClick={onClick}
      style={{ width:'100%', padding:'11px', borderRadius:T.rBtn, background:v.bg, border:`1px solid ${v.bd}`,
               color:v.fg, fontWeight:700, fontSize:13, letterSpacing:'.02em', display:'flex',
               alignItems:'center', justifyContent:'center', gap:10, cursor:'pointer',
               fontFamily:'inherit', marginTop:mt }}>
      <span style={{ display:'flex' }}>{icon}</span> {label}
    </button>
  );
};

const SectionLabel = ({ children }) => (
  <div style={{ fontSize:9.5, fontWeight:700, color:T.muted, letterSpacing:'.14em', margin:'16px 4px 8px' }}>{children}</div>
);

const Row = ({ icon, label, right, last }) => (
  <div style={{ display:'flex', alignItems:'center', gap:11, padding:'12px 13px',
                borderBottom: last ? 'none' : `1px solid ${T.line}` }}>
    <span style={{ width:18, display:'flex', alignItems:'center', justifyContent:'center', color:T.muted, flexShrink:0 }}>{icon}</span>
    <span style={{ flex:1, fontSize:12.5, fontWeight:600, color:T.ink }}>{label}</span>
    <span style={{ fontSize:11.5, color:T.muted, fontWeight:500, textAlign:'right' }}>{right}</span>
  </div>
);

/* One diagnostics line: green tile + check when healthy, neutral tile + info otherwise. */
const DiagRow = ({ icon, label, ok }) => (
  <div style={{ background:T.surface, border:`1px solid ${T.line}`, borderRadius:T.rChip,
                padding:'9px 11px', display:'flex', alignItems:'center', gap:10, marginBottom:6 }}>
    <IconTile size={28} r={9} tint={ok ? T.greenTint : T.cream2} color={ok ? T.green : T.muted}>
      {icon}
    </IconTile>
    <span style={{ flex:1, fontSize:11.5, fontWeight:600, color:T.ink, lineHeight:1.3 }}>{label}</span>
    {ok
      ? <span style={{ width:17, height:17, borderRadius:'50%', background:T.green, color:'#fff',
                       display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><PCheck sz={10}/></span>
      : <span style={{ color:T.muted, display:'flex', flexShrink:0 }}><PInfo sz={15}/></span>}
    <span style={{ color:T.muted, display:'flex', flexShrink:0 }}><PChevron sz={13}/></span>
  </div>
);

/* ══════════════ SHELL ══════════════ */

const StatusBar = () => (
  <div style={{ position:'absolute', top:0, left:0, right:0, height:34, padding:'0 20px',
                display:'flex', alignItems:'center', justifyContent:'space-between',
                fontSize:11.5, fontWeight:700, color:T.ink, zIndex:6 }}>
    <span style={{ display:'inline-flex', alignItems:'center', gap:5 }}>
      {PHONE.clock}
      {/* the app's persistent tracking notification badge */}
      <span style={{ width:13, height:13, borderRadius:'50%', background:T.brand, color:'#fff',
                     display:'inline-flex', alignItems:'center', justifyContent:'center' }}><PPin sz={8} sw={3}/></span>
    </span>
    <span style={{ display:'inline-flex', alignItems:'center', gap:4, color:T.ink }}>
      <PWifi sz={11} sw={2.4}/>
      <span style={{ display:'inline-flex', alignItems:'flex-end', gap:1.5, height:9 }}>
        {[3,5,7,9].map(h => <span key={h} style={{ width:2, height:h, borderRadius:1, background:T.ink }}/>)}
      </span>
      <span style={{ display:'inline-flex', alignItems:'center', width:20, height:11, border:`1.4px solid ${T.ink}`,
                     borderRadius:3.5, padding:1.4 }}>
        <span style={{ width:'63%', height:'100%', background:T.green, borderRadius:1.5 }}/>
      </span>
    </span>
  </div>
);

const AppHeader = ({ title, subtitle, onBack, onGear, onDiag }) => (
  <div style={{ display:'flex', alignItems:onBack?'center':'flex-start', gap:10, marginBottom:12 }}>
    {onBack && (
      <button onClick={onBack} aria-label="Voltar"
        style={{ width:34, height:34, borderRadius:T.rChip, background:T.surface, border:`1px solid ${T.line}`,
                 color:T.ink, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', padding:0, flexShrink:0 }}>
        <PBack sz={17}/>
      </button>
    )}
    <div style={{ flex:1, minWidth:0, textAlign:onBack?'center':'left', marginRight:onBack?34:0 }}>
      <div style={{ fontSize:onBack?15:17, fontWeight:700, color:T.ink, letterSpacing:'-.01em' }}>{title}</div>
      {subtitle && <div style={{ fontSize:10.5, color:T.muted, marginTop:3 }}>{subtitle}</div>}
    </div>
    {(onDiag || onGear) && (
      <div style={{ display:'flex', gap:7, flexShrink:0 }}>
        {onDiag && (
          <button onClick={onDiag} aria-label="Diagnóstico" className="tap-tile"
            style={{ width:36, height:36, borderRadius:T.rChip, background:T.surface, border:`1px solid ${T.line}`,
                     color:T.ink, display:'flex', alignItems:'center', justifyContent:'center', padding:0 }}>
            <PKit sz={18}/>
          </button>
        )}
        {onGear && (
          <button onClick={onGear} aria-label="Configurações" className="tap-tile"
            style={{ width:36, height:36, borderRadius:T.rChip, background:T.surface, border:`1px solid ${T.line}`,
                     color:T.ink, display:'flex', alignItems:'center', justifyContent:'center', padding:0 }}>
            <PGear sz={18}/>
          </button>
        )}
      </div>
    )}
  </div>
);

/* Screen viewport: fixed height so the frame never resizes between screens. */
const PhoneShell = ({ children, pad = '40px 14px 14px' }) => (
  <div style={{ position:'absolute', inset:0, background:T.cream, borderRadius:30, overflow:'hidden',
                animation:'tabIn .32s cubic-bezier(.16,1,.3,1) both' }}>
    <StatusBar/>
    <div style={{ position:'absolute', inset:0, padding:pad, overflowY:'auto', overflowX:'hidden' }}>
      {children}
    </div>
  </div>
);

/* ══════════════ STATUS SCREENS ══════════════
   tracking / paused / stopped differ only in this table. */

const STATUS = {
  tracking: { color:T.brand, label:'RASTREANDO', sub:() => `Desde: ${PHONE.since}`, pulse:true },
  paused:   { color:T.amber, label:'PAUSADO',    sub:() => 'Pausado manualmente',   pulse:false },
  stopped:  { color:T.muted, label:'PARADO',     sub:() => null,                    pulse:false },
};

const StatusScreen = ({ id, stats, setView }) => {
  const s = STATUS[id];
  const live = id === 'tracking';
  return (
    <PhoneShell>
      <AppHeader
        title={PHONE.driver}
        subtitle={`${PHONE.company} · ${PHONE.shift}`}
        onDiag={() => setView('diagnostics')}
        onGear={() => setView('settings')}
      />

      {/* status block */}
      <div style={{ textAlign:'center', margin:'2px 0 12px' }}>
        <div style={{ display:'inline-flex', flexDirection:'column', alignItems:'center' }}>
          <div style={{ width:18, height:18, borderRadius:'50%', background:s.color, marginBottom:10,
                        animation: s.pulse ? 'trackPulse 1.9s ease-out infinite' : 'none' }}/>
          <div style={{ fontSize:21, fontWeight:700, letterSpacing:'.18em', color:s.color }}>{s.label}</div>
          {s.sub() && <div style={{ fontSize:11.5, color:T.muted, marginTop:5 }}>{s.sub()}</div>}
        </div>
      </div>

      {/* controls */}
      {live && <>
        <PillButton variant="neutral" icon={<PPause sz={16}/>} label="PAUSAR" onClick={() => setView('paused')}/>
        <PillButton variant="danger"  icon={<PStop sz={14}/>}  label="PARAR"  onClick={() => setView('stopped')} mt={9}/>
      </>}
      {id === 'paused' && <>
        <PillButton variant="go"     icon={<PPlay sz={15}/>} label="RETOMAR" onClick={() => setView('tracking')}/>
        <PillButton variant="danger" icon={<PStop sz={14}/>} label="PARAR"   onClick={() => setView('stopped')} mt={9}/>
      </>}
      {id === 'stopped' &&
        <PillButton variant="go" icon={<PPlay sz={15}/>} label="INICIAR RASTREAMENTO" onClick={() => setView('tracking')}/>}

      {/* stats */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:7, margin:'10px 0 7px' }}>
        <StatCard icon={<PPin sz={17}/>}       tint={T.brandTint} color={T.brand} value={Number(stats.points).toLocaleString('pt-BR')} label="Pontos coletados"/>
        <StatCard icon={<PClock sz={17}/>}     tint={T.brandTint} color={T.brand} value={live ? stats.lastSend : 'sem envio'} label="Último envio"/>
        <StatCard icon={<PGauge sz={17}/>}     tint={T.blueTint}  color={T.blue}  value={`${stats.km} km`}                   label="Distância"/>
        <StatCard icon={<PHourglass sz={17}/>} tint={T.amberTint} color={T.amber} value={stats.dur}                          label="Duração"/>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:6, marginBottom:8 }}>
        <MiniCard icon={<PBattery sz={16}/>} value="63%" label="Bateria"/>
        {/* the app grades GPS: "Preciso" (green) while actively tracking,
            "Bom" (amber) when idle — both appear in the reference shots */}
        <MiniCard icon={<PNav sz={16}/>} value={live ? 'Preciso' : 'Bom'} color={live ? T.green : T.amber} label="GPS"/>
        <MiniCard icon={<PWifi sz={16}/>} value="Online" label="Rede"/>
      </div>

      <div style={{ background:T.surface, border:`1px solid ${T.line}`, borderRadius:T.rChip, padding:'10px 12px' }}>
        <div style={{ display:'flex', alignItems:'center', gap:7, fontSize:11, color:T.muted, marginBottom:5 }}>
          <PCal sz={14}/> Resumo de hoje
        </div>
        <div style={{ fontSize:11.5, color:T.inkSoft, fontWeight:600 }}>
          {stats.dur} rastreando &nbsp;|&nbsp; {stats.km} km percorridos
        </div>
      </div>
    </PhoneShell>
  );
};

/* ══════════════ LIST SCREENS ══════════════ */

const SettingsScreen = ({ setView }) => (
  <PhoneShell>
    <AppHeader title="Configurações" onBack={() => setView('tracking')}/>

    <SectionLabel>CONTA</SectionLabel>
    <div style={{ background:T.surface, border:`1px solid ${T.line}`, borderRadius:T.rCard, padding:12,
                  display:'flex', gap:11, alignItems:'center' }}>
      <IconTile size={38} r={11} tint={T.brandTint} color={T.brand}><PUser sz={20}/></IconTile>
      <div style={{ minWidth:0 }}>
        <div style={{ fontSize:12.5, fontWeight:700, color:T.ink }}>{PHONE.driver}</div>
        <div style={{ fontSize:10, color:T.muted, marginTop:2, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{PHONE.email}</div>
        <div style={{ fontSize:9.5, color:T.muted, marginTop:1 }}>{PHONE.company}</div>
      </div>
    </div>

    <SectionLabel>AGENDAMENTO</SectionLabel>
    <div style={{ background:T.surface, border:`1px solid ${T.line}`, borderRadius:T.rCard }}>
      <Row icon={<PClock sz={16}/>} label="Horário" right="07:00 - 19:00"/>
      <Row icon={<PCal sz={16}/>}   label="Dias"    right="Seg-Sex"/>
      <Row icon={<PBldg sz={16}/>}  label="Origem"  right="Padrão (empresa)" last/>
    </div>

    <SectionLabel>SOBRE</SectionLabel>
    <div style={{ background:T.surface, border:`1px solid ${T.line}`, borderRadius:T.rCard }}>
      <Row icon={<PInfo sz={16}/>} label="Versão" right={PHONE.version} last/>
    </div>

    <div style={{ marginTop:18 }}>
      <PillButton variant="danger" icon={<PLogout sz={15}/>} label="SAIR"/>
    </div>
  </PhoneShell>
);

/* The health checklist. `ok:false` rows are informational in the app
   (they expand to show a value), not failures. */
const DIAG_ITEMS = [
  { icon:<PCrosshair sz={15}/>, label:'Localização do aparelho',              ok:true },
  { icon:<PPin sz={15}/>,       label:'Permissão de localização',             ok:true },
  { icon:<PNav sz={15}/>,       label:'Localização "Sempre permitir"',        ok:true },
  { icon:<PBell sz={15}/>,      label:'Notificações habilitadas',             ok:true },
  { icon:<PBattChg sz={15}/>,   label:'Otimização de bateria desligada',      ok:true },
  { icon:<PAlarm sz={15}/>,     label:'Inicialização em segundo plano',        ok:true },
  { icon:<PDownload sz={15}/>,  label:'Versão do app',                        ok:true },
  { icon:<PTool sz={15}/>,      label:'Ajuste extra do fabricante',           ok:false },
  { icon:<PGauge sz={15}/>,     label:'Parâmetros de coleta da empresa',      ok:false },
  { icon:<PActivity sz={15}/>,  label:'Modo de coleta atual',                 ok:false },
  { icon:<PCrosshair sz={15}/>, label:'GPS de fundo',                         ok:false },
  { icon:<PUpload sz={15}/>,    label:'Envio em segundo plano',               ok:false },
  { icon:<PShield sz={15}/>,    label:'Vigilância do rastreamento',           ok:false },
  { icon:<PClock sz={15}/>,     label:'Data e hora do aparelho',              ok:false },
  { icon:<PMobile sz={15}/>,    label:'Dicas para seu aparelho',              ok:false },
];

const DiagnosticsScreen = ({ setView }) => (
  <PhoneShell>
    <AppHeader title="Diagnóstico" onBack={() => setView('tracking')}/>

    <div style={{ background:T.greenTint, border:`1px solid ${T.green}`, borderRadius:T.rCard,
                  padding:'13px 13px', display:'flex', gap:11, alignItems:'flex-start', marginBottom:14 }}>
      <span style={{ width:24, height:24, borderRadius:'50%', background:T.green, color:'#fff', flexShrink:0,
                     display:'flex', alignItems:'center', justifyContent:'center', marginTop:1 }}><PCheck sz={13}/></span>
      <div>
        <div style={{ fontSize:13.5, fontWeight:700, color:T.ink }}>Tudo certo!</div>
        <div style={{ fontSize:11, color:T.inkSoft, marginTop:3, lineHeight:1.45 }}>
          Seu rastreamento está funcionando do jeito certo.
        </div>
      </div>
    </div>

    {DIAG_ITEMS.map((d, i) => <DiagRow key={i} {...d}/>)}

    <div style={{ textAlign:'center', marginTop:14, fontSize:9.5, color:T.muted, lineHeight:1.7 }}>
      {PHONE.company} · {PHONE.driver}<br/>
      {PHONE.email}<br/>
      App v{PHONE.version.split(' ')[0]} · Android 16
    </div>
  </PhoneShell>
);

/* ══════════════ REGISTRY ══════════════
   Evaluated at load time — must stay below the definitions above. */

const SCREENS = {
  tracking:    p => <StatusScreen id="tracking" {...p}/>,
  paused:      p => <StatusScreen id="paused"   {...p}/>,
  stopped:     p => <StatusScreen id="stopped"  {...p}/>,
  settings:    p => <SettingsScreen {...p}/>,
  diagnostics: p => <DiagnosticsScreen {...p}/>,
};
