// ============================================================
// SCREENS — Compartilhadas (S) + auxiliares
// ============================================================
const { useState: useStateS } = React;

// ============ S1 — PERFIL ============
function ProfileScreen({ go, dark, setDark, mode, setMode }) {
  return (
    <div className="screen-enter" style={{paddingBottom:24}}>
      <ScreenHeader title="Perfil" large/>
      <div style={{padding:'4px 16px 0'}}>
        {/* User card */}
        <div style={{
          display:'flex', alignItems:'center', gap:14,
          background:'var(--surface)', border:'1px solid var(--border)', borderRadius:16, padding:14,
          marginBottom:18,
        }}>
          <Avatar tone="#1F3864" name="Pedro Mendes" size={56}/>
          <div style={{flex:1, minWidth:0}}>
            <div style={{fontSize:17, fontWeight:700, color:'var(--text)', letterSpacing:-.3}}>Pedro Mendes</div>
            <div style={{fontSize:12.5, color:'var(--text-muted)'}}>pedro.mendes@email.com</div>
            <div style={{display:'inline-flex', alignItems:'center', gap:5, marginTop:6,
              background:'var(--accent-soft)', border:'1px solid #E9DDC2',
              padding:'3px 9px', borderRadius:999, fontSize:11, fontWeight:600, color:'#3A2D14'}}>
              <Icon name="Crown" size={11} color="#7D6A47" strokeWidth={2}/> Proprietário Convés desde 2025
            </div>
          </div>
        </div>

        {/* Mode toggle */}
        <SectionHeader title="Modo do app"/>
        <div style={{
          display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginBottom:18,
          background:'#EDEFF3', padding:4, borderRadius:12,
        }}>
          {[
            { key:'owner', label:'Proprietário', icon:'Anchor' },
            { key:'pro', label:'Prestador', icon:'Wrench' },
          ].map(m=>{
            const on = mode === m.key;
            return (
              <button key={m.key} onClick={()=>setMode(m.key)} className="ripple" style={{
                display:'inline-flex', alignItems:'center', justifyContent:'center', gap:8,
                background: on ? 'var(--surface)' : 'transparent', border:'none', borderRadius:8,
                padding:'10px 0', fontSize:13, fontWeight: on?600:500,
                color: on ? 'var(--text)' : 'var(--text-muted)', cursor:'pointer',
                boxShadow: on ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
              }}>
                <Icon name={m.icon} size={15} strokeWidth={2}/> {m.label}
              </button>
            );
          })}
        </div>

        <SectionHeader title="Conta"/>
        <div style={{background:'var(--surface)', border:'1px solid var(--border)', borderRadius:14, overflow:'hidden', marginBottom:18}}>
          {[
            { icon:'User', label:'Dados pessoais' },
            { icon:'CreditCard', label:'Métodos de pagamento', sub:'•••• 4242' },
            { icon:'Bell', label:'Notificações' },
            { icon:'Lock', label:'Segurança' },
          ].map((r,i,arr)=>(
            <button key={r.label} className="ripple" style={{
              display:'flex', alignItems:'center', gap:12, padding:'12px 14px', cursor:'pointer',
              width:'100%', textAlign:'left', background:'transparent', border:'none',
              borderBottom: i<arr.length-1 ? '1px solid var(--border)' : 'none',
            }}>
              <div style={{width:30, height:30, borderRadius:8, background:'var(--accent-soft)', border:'1px solid #E9DDC2', display:'flex', alignItems:'center', justifyContent:'center'}}>
                <Icon name={r.icon} size={15} color="#7D6A47" strokeWidth={1.8}/>
              </div>
              <span style={{flex:1, fontSize:14, color:'var(--text)'}}>{r.label}</span>
              {r.sub && <span style={{fontSize:12, color:'var(--text-subtle)'}}>{r.sub}</span>}
              <Icon name="ChevronRight" size={16} color="var(--text-subtle)" strokeWidth={1.8}/>
            </button>
          ))}
        </div>

        <SectionHeader title="Aparência"/>
        <div style={{background:'var(--surface)', border:'1px solid var(--border)', borderRadius:14, padding:'12px 14px', marginBottom:18, display:'flex', alignItems:'center'}}>
          <Icon name={dark?'Moon':'Sun'} size={18} strokeWidth={1.8} style={{marginRight:12}}/>
          <span style={{flex:1, fontSize:14, color:'var(--text)'}}>Modo escuro</span>
          <button onClick={()=>setDark(!dark)} style={{
            width:42, height:24, borderRadius:24, border:'none', position:'relative',
            background: dark ? 'var(--primary)' : '#D7DBE3', cursor:'pointer',
            transition:'background .15s',
          }}>
            <span style={{
              position:'absolute', top:2, left: dark ? 20 : 2, width:20, height:20, borderRadius:20,
              background:'#fff', transition:'left .15s', boxShadow:'0 1px 2px rgba(0,0,0,0.2)',
            }}/>
          </button>
        </div>

        <SectionHeader title="Suporte"/>
        <div style={{background:'var(--surface)', border:'1px solid var(--border)', borderRadius:14, overflow:'hidden', marginBottom:18}}>
          {[
            { icon:'Sparkles', label:'Concierge IA', sub:'Disponível 24/7', action:()=>go('concierge') },
            { icon:'BookOpen', label:'Central de ajuda' },
            { icon:'FileText', label:'Termos e privacidade' },
          ].map((r,i,arr)=>(
            <button key={r.label} onClick={r.action} className="ripple" style={{
              display:'flex', alignItems:'center', gap:12, padding:'12px 14px', cursor:'pointer',
              width:'100%', textAlign:'left', background:'transparent', border:'none',
              borderBottom: i<arr.length-1 ? '1px solid var(--border)' : 'none',
            }}>
              <div style={{width:30, height:30, borderRadius:8, background:'var(--accent-soft)', border:'1px solid #E9DDC2', display:'flex', alignItems:'center', justifyContent:'center'}}>
                <Icon name={r.icon} size={15} color="#7D6A47" strokeWidth={1.8}/>
              </div>
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontSize:14, color:'var(--text)'}}>{r.label}</div>
                {r.sub && <div style={{fontSize:11.5, color:'var(--text-subtle)', marginTop:1}}>{r.sub}</div>}
              </div>
              <Icon name="ChevronRight" size={16} color="var(--text-subtle)" strokeWidth={1.8}/>
            </button>
          ))}
        </div>

        <SectionHeader title="Acesso interno"/>
        <button onClick={()=>go('admin')} className="ripple" style={{
          width:'100%', textAlign:'left', background:'#15171C', color:'#fff',
          border:'none', borderRadius:14, padding:'12px 14px', marginBottom:18,
          display:'flex', alignItems:'center', gap:12, cursor:'pointer',
        }}>
          <div style={{width:30, height:30, borderRadius:8, background:'rgba(255,255,255,0.08)', display:'flex', alignItems:'center', justifyContent:'center'}}>
            <Icon name="ShieldCheck" size={15} color="#C5A572" strokeWidth={1.8}/>
          </div>
          <div style={{flex:1, minWidth:0}}>
            <div style={{fontSize:13.5, fontWeight:600}}>Painel de curadoria</div>
            <div style={{fontSize:11.5, color:'rgba(255,255,255,0.55)', marginTop:1}}>Time interno · validação e disputas</div>
          </div>
          <Icon name="ChevronRight" size={16} color="rgba(255,255,255,0.5)" strokeWidth={1.8}/>
        </button>

        <Btn variant="danger" full icon="LogOut">Sair</Btn>
        <div style={{textAlign:'center', marginTop:18, fontSize:11, color:'var(--text-subtle)'}} className="mono">
          CONVÉS · v1.4.0 · build 2826
        </div>
      </div>
    </div>
  );
}

// ============ S2 — NOTIFICAÇÕES ============
function NotifScreen({ go }) {
  const icons = {
    aviso:'Gauge', os:'MessageSquare', cotacao:'FileText', pagamento:'ShieldCheck', logbook:'BookOpen',
  };
  return (
    <div className="screen-enter" style={{paddingBottom:24}}>
      <ScreenHeader title="Notificações" large
        right={<button className="ripple" style={{
          background:'none', border:'none', color:'var(--primary)', fontSize:13, fontWeight:600, cursor:'pointer',
        }}>Marcar como lidas</button>}/>
      <div style={{padding:'4px 16px 0'}}>
        <div style={{display:'flex', flexDirection:'column', gap:8}}>
          {NOTIFICATIONS.map(n=>(
            <div key={n.id} style={{
              display:'flex', gap:12, padding:'12px 14px',
              background:'var(--surface)', border:'1px solid ' + (n.unread ? 'var(--primary)' : 'var(--border)'),
              borderRadius:14, position:'relative',
            }}>
              <div style={{
                width:36, height:36, borderRadius:10, flexShrink:0,
                background: n.unread ? 'rgba(31,56,100,0.08)' : '#F4F5F8',
                display:'flex', alignItems:'center', justifyContent:'center',
              }}>
                <Icon name={icons[n.kind]} size={17} color={n.unread?'var(--primary)':'var(--text-muted)'} strokeWidth={1.8}/>
              </div>
              <div style={{flex:1, minWidth:0}}>
                <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', gap:8}}>
                  <span style={{fontSize:13.5, fontWeight:600, color:'var(--text)'}}>{n.title}</span>
                  <span style={{fontSize:11, color:'var(--text-subtle)', flexShrink:0}}>{n.at}</span>
                </div>
                <div style={{fontSize:12.5, color:'var(--text-muted)', marginTop:3, lineHeight:1.4}}>{n.body}</div>
              </div>
              {n.unread && (
                <span style={{
                  position:'absolute', top:14, right:-4, width:8, height:8, borderRadius:8, background:'var(--primary)',
                }}/>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ============ S3 — CONCIERGE IA ============
function ConciergeScreen({ go }) {
  const [offline, setOffline] = useStateS(true);
  const [thread, setThread] = useStateS([
    { role:'assistant', text:'Olá, Pedro. Sou o concierge do Convés. Posso explicar como funciona o escrow, ajudar a abrir uma disputa ou encaminhar para um especialista humano. Como posso ajudar hoje?' },
  ]);
  const suggestions = [
    'Como funciona o escrow?',
    'Quero abrir uma disputa',
    'Quando o pagamento é liberado?',
    'Falar com humano',
  ];
  const replies = {
    'Como funciona o escrow?':'O pagamento fica retido pelo Convés até você confirmar a conclusão do serviço. Em até 24h após sua aprovação, o valor (descontada a comissão) é repassado ao prestador. Caso haja divergência, abrimos uma disputa antes de qualquer liberação.',
    'Quero abrir uma disputa':'Posso te ajudar a abrir uma disputa. Antes, preciso saber: qual OS está em questão e qual é a sua descrição do problema? Você também pode anexar fotos como evidência.',
    'Quando o pagamento é liberado?':'O pagamento é liberado em até 24h após você confirmar a conclusão do serviço na tela da OS. Antes disso, ele permanece retido na conta-escrow do Convés.',
    'Falar com humano':'Sem problema, Pedro. Vou encaminhar sua conversa para o time de Suporte Humano do Convés. Tempo médio de resposta neste horário: 4 minutos.',
  };

  function ask(q) {
    setThread([...thread, { role:'user', text:q }]);
    setTimeout(()=>{
      setThread(t=>[...t, { role:'assistant', text: replies[q] || 'Posso te ajudar com isso. Pode me dar um pouco mais de contexto?' }]);
    }, 600);
  }

  return (
    <div className="screen-enter" style={{height:'100%', display:'flex', flexDirection:'column'}}>
      <ScreenHeader title="Concierge IA" subtitle="Respostas geradas por IA, sujeitas a verificação." onBack={()=>go('home')}/>
      {offline && (
        <div style={{paddingTop:12}}>
          <NetBanner onRetry={()=>setOffline(false)} message="Conexão instável. Tentando restabelecer…"/>
        </div>
      )}
      <div className="scroll-clean" style={{flex:1, overflowY:'auto', padding:'12px 16px', display:'flex', flexDirection:'column', gap:10}}>
        {thread.map((m,i)=>(
          <div key={i} style={{display:'flex', justifyContent: m.role==='user' ? 'flex-end' : 'flex-start'}}>
            <div style={{
              maxWidth:'82%',
              background: m.role==='user' ? 'var(--primary)' : 'var(--surface)',
              color: m.role==='user' ? '#fff' : 'var(--text)',
              border: m.role==='user' ? 'none' : '1px solid var(--border)',
              padding:'10px 14px', borderRadius:16,
              borderBottomRightRadius: m.role==='user' ? 5 : 16,
              borderBottomLeftRadius: m.role==='user' ? 16 : 5,
              fontSize:14, lineHeight:1.5,
            }}>
              {m.role==='assistant' && (
                <div style={{display:'inline-flex', alignItems:'center', gap:5, marginBottom:6, fontSize:11, fontWeight:600, color:'var(--accent)'}}>
                  <Icon name="Sparkles" size={11} color="var(--accent)" strokeWidth={2.2}/>
                  CONCIERGE IA
                </div>
              )}
              <div>{m.text}</div>
            </div>
          </div>
        ))}
      </div>
      <div style={{padding:'8px 16px 28px', borderTop:'1px solid var(--border)', background:'rgba(250,250,250,0.96)'}}>
        <div className="scroll-clean" style={{display:'flex', gap:8, overflowX:'auto', marginBottom:10, paddingBottom:4}}>
          {suggestions.map(s=>(
            <button key={s} onClick={()=>ask(s)} className="ripple" style={{
              background:'var(--surface)', border:'1px solid var(--border)', color:'var(--text)',
              borderRadius:999, padding:'7px 13px', fontSize:12.5, fontWeight:500, cursor:'pointer',
              whiteSpace:'nowrap', flexShrink:0,
            }}>{s}</button>
          ))}
        </div>
        <div style={{display:'flex', gap:8, alignItems:'center'}}>
          <input placeholder="Pergunte ao concierge…" style={{
            flex:1, padding:'10px 14px', borderRadius:999, border:'1px solid var(--border-strong)',
            fontFamily:'inherit', fontSize:14, outline:'none', background:'var(--surface)',
          }}/>
          <button className="ripple" style={{
            width:38, height:38, borderRadius:38, border:'none', background:'var(--primary)',
            display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer',
          }}><Icon name="ArrowUp" size={17} color="#fff" strokeWidth={2.4}/></button>
        </div>
      </div>
    </div>
  );
}

// ============ MESSAGES LIST ============
function MessagesList({ go }) {
  const [loading, setLoading] = useStateS(true);
  React.useEffect(()=>{
    const t = setTimeout(()=>setLoading(false), 700);
    return ()=>clearTimeout(t);
  }, []);
  const threads = [
    { proId:'p1', os:'OS-2826', preview:'Recebi, tudo certo. Te aviso quando estiver chegando…', at:'14:44', unread:2 },
    { proId:'p3', os:'OS-2814', preview:'Vou começar pelo polimento na sexta, conforme combinado.', at:'Ontem', unread:0 },
    { proId:'p2', os:'OS-2790', preview:'Preciso passar amanhã para diagnosticar o sistema elétrico.', at:'Ter', unread:1 },
  ];
  return (
    <div className="screen-enter" style={{paddingBottom:24}}>
      <ScreenHeader title="Mensagens" large/>
      <div style={{padding:'4px 16px 0'}}>
        <div style={{position:'relative', marginBottom:12}}>
          <Icon name="Search" size={16} color="var(--text-subtle)" strokeWidth={2} style={{position:'absolute', left:12, top:11}}/>
          <input placeholder="Buscar conversa ou OS" style={{
            width:'100%', padding:'10px 14px 10px 36px', borderRadius:10,
            border:'1px solid var(--border-strong)', background:'var(--surface)',
            fontSize:13.5, outline:'none', fontFamily:'inherit',
          }}/>
        </div>
        {loading ? (
          <div style={{background:'var(--surface)', border:'1px solid var(--border)', borderRadius:14, overflow:'hidden'}}>
            {[0,1,2].map(i=>(
              <div key={i} style={{
                display:'flex', gap:12, alignItems:'center', padding:'12px 14px',
                borderBottom: i<2 ? '1px solid var(--border)' : 'none',
              }}>
                <Skel w={44} h={44} r={44}/>
                <div style={{flex:1, display:'flex', flexDirection:'column', gap:6}}>
                  <Skel w="60%" h={12}/>
                  <Skel w="85%" h={11}/>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{background:'var(--surface)', border:'1px solid var(--border)', borderRadius:14, overflow:'hidden'}}>
            {threads.map((t,i,arr)=>{
              const pro = PROS.find(p=>p.id===t.proId);
              return (
                <button key={t.proId} onClick={()=>go('chat')} className="ripple" style={{
                  display:'flex', gap:12, alignItems:'center', padding:'12px 14px',
                  width:'100%', textAlign:'left', background:'transparent', border:'none',
                  borderBottom: i<arr.length-1 ? '1px solid var(--border)' : 'none', cursor:'pointer',
                }}>
                  <Avatar tone={pro.avatarTone} name={pro.short} size={44}/>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', gap:8}}>
                      <span style={{fontSize:14, fontWeight:600, color:'var(--text)'}}>{pro.short}</span>
                      <span style={{fontSize:11.5, color:'var(--text-subtle)'}}>{t.at}</span>
                    </div>
                    <div style={{display:'flex', alignItems:'center', gap:6, marginTop:1}}>
                      <span className="mono" style={{fontSize:10.5, color:'var(--text-subtle)', fontWeight:600}}>{t.os}</span>
                      <span style={{fontSize:11, color:'var(--text-subtle)'}}>·</span>
                      <span style={{fontSize:12.5, color:'var(--text-muted)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{t.preview}</span>
                    </div>
                  </div>
                  {t.unread > 0 && (
                    <span style={{
                      width:20, height:20, borderRadius:20, background:'var(--primary)', color:'#fff',
                      fontSize:11, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
                    }}>{t.unread}</span>
                  )}
                </button>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

// ============ PROS LIST (compass / explore) ============
function ProsList({ go }) {
  const [cat, setCat] = useStateS('mecanica');
  return (
    <div className="screen-enter" style={{paddingBottom:24}}>
      <ScreenHeader title="Explorar prestadores" large/>
      <div className="scroll-clean" style={{display:'flex', gap:8, padding:'4px 16px 12px', overflowX:'auto'}}>
        {CATEGORIES.map(c=>(
          <CategoryChip key={c.id} icon={c.icon} label={c.label} active={cat===c.id} onClick={()=>setCat(c.id)}/>
        ))}
      </div>
      <div style={{padding:'0 16px', display:'flex', flexDirection:'column', gap:10}}>
        {PROS.map(p=>(
          <ProCard key={p.id} pro={p} onClick={()=>go('pro-detail')}/>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ProfileScreen, NotifScreen, ConciergeScreen, MessagesList, ProsList });
