// SGAB v2 — App Shell: Login, Sidebar, Header, Router
const { useState, useEffect, useCallback } = React;

// Mobile detection hook
function useIsMobile(breakpoint = 900) {
  const [mobile, setMobile] = useState(() => typeof window !== 'undefined' && window.innerWidth < breakpoint);
  useEffect(() => {
    const onResize = () => setMobile(window.innerWidth < breakpoint);
    window.addEventListener('resize', onResize);
    window.addEventListener('orientationchange', onResize);
    return () => {
      window.removeEventListener('resize', onResize);
      window.removeEventListener('orientationchange', onResize);
    };
  }, [breakpoint]);
  return mobile;
}

const NAV_GROUPS = [
  { label:'GERAL', items:[
    { id:'dashboard',    label:'Dashboard',      icon:'dashboard' },
    { id:'agenda',       label:'Agenda',         icon:'agenda' },
  ]},
  { label:'OPERAÇÃO', items:[
    { id:'clientes',     label:'Clientes',         icon:'clientes' },
    { id:'equipamentos', label:'Equipamentos',     icon:'equipamentos' },
    { id:'ordens',       label:'Ordens de Serviço',icon:'ordens' },
    { id:'calibracao',   label:'Calibração',       icon:'calibracao' },
    { id:'propostas',    label:'Propostas (PTC)',  icon:'propostas' },
  ]},
  { label:'GESTÃO', items:[
    { id:'financeiro',   label:'Financeiro',  icon:'financeiro' },
    { id:'estoque',      label:'Estoque',     icon:'estoque' },
    { id:'relatorios',   label:'Relatórios',  icon:'relatorios' },
  ]},
  { label:'SISTEMA', items:[
    { id:'config',       label:'Configurações', icon:'config' },
  ]},
];
const NAV_ITEMS = NAV_GROUPS.flatMap(g => g.items);

// ── LOGIN SCREEN ─────────────────────────────────────────────────
function LoginScreen({ onLogin, mobile }) {
  const [email, setEmail]   = useState('');
  const [senha, setSenha]   = useState('');
  const [err, setErr]       = useState('');
  const [loading, setLoading] = useState(false);

  async function handleLogin(e) {
    e.preventDefault(); setErr(''); setLoading(true);
    if (!window.SGAB_SB) {
      setErr('Cliente Supabase não carregou. Verifique sua conexão.');
      setLoading(false); return;
    }
    const { error } = await window.SGAB_SB.signIn(email, senha);
    if (error) {
      const msg = (error.message || '').toLowerCase().includes('invalid')
        ? 'E-mail ou senha incorretos.'
        : (error.message || 'Falha no login.');
      setErr(msg); setLoading(false); return;
    }
    const profile = await window.SGAB_SB.currentProfile();
    if (!profile) {
      setErr('Login OK, mas o perfil não foi encontrado. Avise o administrador.');
      setLoading(false); return;
    }
    if (!profile.ativo) {
      setErr('Usuário desativado. Avise o administrador.');
      await window.SGAB_SB.signOut();
      setLoading(false); return;
    }
    // Carrega snapshot de todas as tabelas antes de entrar no app
    try {
      await window.SGAB_SB.loadAll();
    } catch (err) {
      console.error('[SGAB] Falha ao carregar dados:', err);
      setErr('Login OK, mas falha ao carregar dados. ' + (err.message || ''));
      setLoading(false); return;
    }
    onLogin(profile);
  }

  return (
    <div style={{ minHeight:'100vh', display:'flex', background:'#0D1B2A', fontFamily:"'DM Sans',sans-serif", paddingTop:'env(safe-area-inset-top)', paddingBottom:'env(safe-area-inset-bottom)' }}>
      {/* LEFT PANEL */}
      <div style={{ flex:1, display: mobile?'none':'flex', flexDirection:'column', justifyContent:'center', alignItems:'center', padding:48, position:'relative', overflow:'hidden' }}>
        {/* BG circles */}
        <div style={{position:'absolute',inset:0,overflow:'hidden',pointerEvents:'none'}}>
          <div style={{position:'absolute',top:'-15%',left:'-10%',width:500,height:500,borderRadius:'50%',background:'rgba(30,111,217,0.08)',filter:'blur(60px)'}}></div>
          <div style={{position:'absolute',bottom:'-10%',right:'-5%',width:400,height:400,borderRadius:'50%',background:'rgba(22,163,74,0.07)',filter:'blur(60px)'}}></div>
        </div>
        <div style={{ position:'relative', maxWidth:460, textAlign:'center' }}>
          {/* LOGO */}
          <div style={{ display:'flex', justifyContent:'center', marginBottom:36 }}>
            <div style={{
              background:'#fff', borderRadius:16, padding:'14px 22px',
              boxShadow:'0 16px 40px rgba(30,111,217,0.3)', display:'inline-block'
            }}>
              <img src="sgab/logo.png" alt="Levi Balanças" style={{ height:90, display:'block' }}/>
            </div>
          </div>
          <h1 style={{ margin:'0 0 16px', fontSize:34, fontWeight:800, color:'#fff', lineHeight:1.2, letterSpacing:'-0.02em' }}>
            Sistema de Gestão para<br/>
            <span style={{ background:'linear-gradient(90deg,#1E6FD9,#0EA5E9)', WebkitBackgroundClip:'text', WebkitTextFillColor:'transparent' }}>Assistência Técnica</span>
          </h1>
          <p style={{ margin:'0 0 40px', fontSize:16, color:'rgba(255,255,255,0.5)', lineHeight:1.6 }}>
            Agenda, Calibrações RBC, Certificados, Propostas e Financeiro — tudo em um só lugar.
          </p>
          {/* Feature pills */}
          {[['calibracao','Calibrações RBC e Rastreada'],['propostas','Propostas PDF automáticas'],['financeiro','Controle financeiro em tempo real'],['agenda','Agenda mensal visual']].map(([icon,txt])=>(
            <div key={icon} style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 16px', borderRadius:10, background:'rgba(255,255,255,0.05)', border:'1px solid rgba(255,255,255,0.08)', marginBottom:8 }}>
              <div style={{ width:28, height:28, borderRadius:7, background:'rgba(30,111,217,0.25)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <Icon name={icon} size={15} color="#60A5FA"/>
              </div>
              <span style={{ fontSize:14, color:'rgba(255,255,255,0.7)', fontWeight:500 }}>{txt}</span>
            </div>
          ))}
          <p style={{ margin:'32px 0 0', fontSize:12, color:'rgba(255,255,255,0.25)', letterSpacing:'0.02em' }}>
            Acreditação CGCRE • CAL 0830 • ABNT NBR ISO/IEC 17025:2017
          </p>
        </div>
      </div>

      {/* RIGHT PANEL */}
      <div style={{ width: mobile?'100%':440, background:'#fff', display:'flex', flexDirection:'column', justifyContent:'center', padding: mobile?'24px 20px':48, boxShadow: mobile?'none':'-20px 0 60px rgba(0,0,0,0.3)' }}>
        {mobile && (
          <div style={{ display:'flex', justifyContent:'center', marginBottom:24 }}>
            <img src="sgab/logo.png" alt="Levi Balanças" style={{ maxWidth:200, width:'100%', height:'auto' }}/>
          </div>
        )}
        <h2 style={{ margin:'0 0 6px', fontSize: mobile?22:26, fontWeight:800, color:'#0D1B2A', textAlign: mobile?'center':'left' }}>Bem-vindo de volta</h2>
        <p style={{ margin:'0 0 32px', fontSize:14, color:'#6B7280', textAlign: mobile?'center':'left' }}>Acesse sua conta para continuar</p>

        <form onSubmit={handleLogin}>
          <div style={{ marginBottom:16 }}>
            <label style={{ display:'block', marginBottom:6, fontSize:12, fontWeight:700, color:'#374151', textTransform:'uppercase', letterSpacing:'0.05em' }}>E-mail</label>
            <Inp value={email} onChange={setEmail} type="email" placeholder="seu@email.com.br" />
          </div>
          <div style={{ marginBottom:24 }}>
            <label style={{ display:'block', marginBottom:6, fontSize:12, fontWeight:700, color:'#374151', textTransform:'uppercase', letterSpacing:'0.05em' }}>Senha</label>
            <Inp value={senha} onChange={setSenha} type="password" placeholder="••••••••" />
          </div>
          {err && <div style={{ padding:'10px 14px', background:'#FEE2E2', borderRadius:8, fontSize:13, color:'#B91C1C', marginBottom:16, display:'flex', gap:8, alignItems:'center' }}>
            <Icon name="alert" size={15} color="#B91C1C"/>{err}
          </div>}
          <Btn type="submit" full size="lg" disabled={loading}>
            {loading ? 'Entrando...' : 'Entrar no Sistema'}
          </Btn>
        </form>

        <p style={{ margin:'32px 0 0', textAlign:'center', fontSize:11, color:'#9CA3AF', letterSpacing:'0.02em' }}>
          Desenvolvido por <a href="https://juflowdigital.com.br" target="_blank" rel="noopener" style={{ color:'#1E6FD9', fontWeight:600, textDecoration:'none' }}>JuFlow Digital</a> · 2026
        </p>
      </div>
    </div>
  );
}

// ── SIDEBAR ──────────────────────────────────────────────────────
function Sidebar({ route, onNav, user, onLogout, collapsed, onToggle, mobile, mobileOpen }) {
  const perms = {
    administrador: NAV_ITEMS.map(n=>n.id),
    tecnico: ['dashboard','agenda','clientes','equipamentos','ordens','calibracao'],
    administrativo: ['dashboard','agenda','clientes','equipamentos','ordens','propostas','config'],
    financeiro: ['dashboard','financeiro','relatorios'],
    visualizador: ['dashboard','relatorios']
  };
  const allowed = perms[user.perfil] || [];
  const visible = NAV_ITEMS.filter(n => allowed.includes(n.id));

  return (
    <div style={{
      width: mobile ? 280 : (collapsed ? 72 : 244),
      background: 'linear-gradient(180deg, #0B1428 0%, #0F1E36 50%, #0D1B2A 100%)',
      height: '100vh', display: 'flex', flexDirection: 'column', flexShrink: 0,
      transition: mobile ? 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)' : 'width 0.28s cubic-bezier(0.4, 0, 0.2, 1)',
      overflow: 'hidden',
      position: mobile ? 'fixed' : 'relative',
      top: 0, left: 0, zIndex: mobile ? 200 : 1,
      transform: mobile ? (mobileOpen ? 'translateX(0)' : 'translateX(-100%)') : 'none',
      boxShadow: mobile && mobileOpen
        ? '8px 0 40px rgba(0,0,0,0.5)'
        : '4px 0 24px rgba(0,0,0,0.15), inset -1px 0 0 rgba(255,255,255,0.04)',
      paddingTop: mobile ? 'env(safe-area-inset-top)' : 0,
      paddingBottom: mobile ? 'env(safe-area-inset-bottom)' : 0
    }}>
      {/* Decorative gradient blob */}
      <div style={{ position:'absolute', top:-80, right:-60, width:200, height:200, borderRadius:'50%', background:'radial-gradient(circle, rgba(30,111,217,0.25) 0%, transparent 70%)', pointerEvents:'none' }}></div>
      <div style={{ position:'absolute', bottom:80, left:-40, width:160, height:160, borderRadius:'50%', background:'radial-gradient(circle, rgba(14,165,233,0.12) 0%, transparent 70%)', pointerEvents:'none' }}></div>

      {/* LOGO */}
      <div style={{ padding: collapsed ? '14px 8px' : '14px 12px', flexShrink:0, position:'relative', zIndex:1 }}>
        {collapsed ? (
          <div style={{
            width:52, height:52, borderRadius:12, background:'#fff',
            display:'flex', alignItems:'center', justifyContent:'center', padding:4,
            margin:'0 auto', boxShadow:'0 6px 18px rgba(0,0,0,0.3)', position:'relative'
          }}>
            <img src="sgab/logo.png" alt="Levi Balanças" style={{ width:'100%', height:'100%', objectFit:'contain', objectPosition:'left' }}/>
            <div style={{ position:'absolute', bottom:-3, right:-3, width:11, height:11, borderRadius:6, background:'#22C55E', border:'2.5px solid #0B1428' }}></div>
          </div>
        ) : (
          <div style={{ position:'relative' }}>
            <div style={{
              width:'100%', borderRadius:12, padding:'8px 10px',
              background:'#fff',
              boxShadow:'0 8px 20px rgba(0,0,0,0.35)',
              display:'flex', alignItems:'center', justifyContent:'center',
              minHeight:84
            }}>
              <img src="sgab/logo.png" alt="Levi Balanças" style={{ width:'100%', height:'auto', display:'block', objectFit:'contain', maxHeight:80 }}/>
            </div>
            <div style={{ position:'absolute', top:-4, right:-4, width:13, height:13, borderRadius:7, background:'#22C55E', border:'3px solid #0B1428', boxShadow:'0 0 10px rgba(34,197,94,0.7)' }}></div>
          </div>
        )}
        {!collapsed && (
          <div style={{ display:'flex', alignItems:'center', gap:5, marginTop:10, padding:'0 2px', whiteSpace:'nowrap' }}>
            <span style={{ fontSize:9, color:'#60A5FA', fontWeight:800, letterSpacing:'0.12em', background:'rgba(30,111,217,0.15)', padding:'2px 7px', borderRadius:4 }}>SGAB v2</span>
            <span style={{ fontSize:9, color:'rgba(255,255,255,0.4)', fontWeight:600 }}>● Online</span>
          </div>
        )}
      </div>

      {/* DIVIDER */}
      <div style={{ height:1, margin:'4px 16px 8px', background:'linear-gradient(90deg, transparent, rgba(255,255,255,0.08), transparent)' }}></div>

      {/* NAV with groups */}
      <nav className="sgab-sidebar-nav" style={{ flex:1, overflowY:'auto', padding:'4px 10px 12px', position:'relative', zIndex:1, scrollbarWidth:'none', msOverflowStyle:'none' }}>
        {NAV_GROUPS.map((group, gi) => {
          const groupItems = group.items.filter(it => allowed.includes(it.id));
          if (groupItems.length === 0) return null;
          return (
            <div key={group.label} style={{ marginBottom: 12 }}>
              {!collapsed && (
                <div style={{ padding:'8px 12px 4px', fontSize:9, fontWeight:800, color:'rgba(255,255,255,0.28)', letterSpacing:'0.14em' }}>
                  {group.label}
                </div>
              )}
              {collapsed && gi > 0 && (
                <div style={{ height:1, margin:'8px 12px', background:'rgba(255,255,255,0.06)' }}></div>
              )}
              {groupItems.map(item => {
                const active = route === item.id;
                return (
                  <button key={item.id} onClick={() => onNav(item.id)}
                    title={collapsed ? item.label : undefined}
                    style={{
                      width:'100%', display:'flex', alignItems:'center', gap:11,
                      padding: collapsed ? '11px' : '10px 12px',
                      border:'none', borderRadius:10,
                      background: active
                        ? 'linear-gradient(135deg, rgba(37,99,235,0.35) 0%, rgba(30,111,217,0.18) 100%)'
                        : 'transparent',
                      color: active ? '#fff' : 'rgba(255,255,255,0.55)',
                      cursor:'pointer', marginBottom:2,
                      transition:'all 0.18s cubic-bezier(0.4, 0, 0.2, 1)',
                      fontFamily:'inherit', justifyContent: collapsed ? 'center' : 'flex-start',
                      position:'relative', overflow:'hidden',
                      boxShadow: active ? 'inset 0 1px 0 rgba(255,255,255,0.08), 0 2px 8px rgba(30,111,217,0.2)' : 'none'
                    }}
                    onMouseEnter={e => {
                      if (!active) {
                        e.currentTarget.style.background = 'rgba(255,255,255,0.06)';
                        e.currentTarget.style.color = 'rgba(255,255,255,0.92)';
                      }
                    }}
                    onMouseLeave={e => {
                      if (!active) {
                        e.currentTarget.style.background = 'transparent';
                        e.currentTarget.style.color = 'rgba(255,255,255,0.55)';
                      }
                    }}>
                    {active && <div style={{ position:'absolute', left:0, top:6, bottom:6, width:3, borderRadius:'0 3px 3px 0', background:'linear-gradient(180deg, #60A5FA, #0EA5E9)', boxShadow:'0 0 8px rgba(96,165,250,0.6)' }}></div>}
                    <div style={{
                      width:26, height:26, borderRadius:7, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
                      background: active ? 'linear-gradient(135deg, #2563EB, #0EA5E9)' : 'rgba(255,255,255,0.04)',
                      boxShadow: active ? '0 3px 10px rgba(30,111,217,0.4), inset 0 1px 0 rgba(255,255,255,0.2)' : 'none',
                      transition:'all 0.18s'
                    }}>
                      <Icon name={item.icon} size={15} color={active ? '#fff' : 'rgba(255,255,255,0.6)'}/>
                    </div>
                    {!collapsed && <span style={{ fontSize:13, fontWeight: active ? 700 : 500, whiteSpace:'nowrap', letterSpacing: active ? '0' : '0.01em' }}>{item.label}</span>}
                    {!collapsed && active && (
                      <div style={{ marginLeft:'auto', display:'flex', alignItems:'center', gap:4 }}>
                        <div style={{ width:5, height:5, borderRadius:3, background:'#60A5FA', boxShadow:'0 0 6px #60A5FA' }}></div>
                      </div>
                    )}
                  </button>
                );
              })}
            </div>
          );
        })}
      </nav>

      {/* USER FOOTER */}
      <div style={{ padding: collapsed ? '10px' : '12px 12px 14px', flexShrink:0, position:'relative', zIndex:1, borderTop:'1px solid rgba(255,255,255,0.06)' }}>
        {/* Collapse toggle (desktop only) */}
        {!mobile && (
          <button onClick={onToggle}
            style={{
              width:'100%', display:'flex', alignItems:'center',
              justifyContent: collapsed ? 'center' : 'flex-start',
              gap:8, padding: collapsed ? '7px' : '7px 10px',
              border:'none', borderRadius:8, background:'rgba(255,255,255,0.03)',
              color:'rgba(255,255,255,0.45)', cursor:'pointer', marginBottom:10,
              transition:'all 0.15s', fontFamily:'inherit'
            }}
            onMouseEnter={e => { e.currentTarget.style.background='rgba(255,255,255,0.08)'; e.currentTarget.style.color='rgba(255,255,255,0.85)'; }}
            onMouseLeave={e => { e.currentTarget.style.background='rgba(255,255,255,0.03)'; e.currentTarget.style.color='rgba(255,255,255,0.45)'; }}>
            <Icon name={collapsed ? 'chevR' : 'chevL'} size={14}/>
            {!collapsed && <span style={{ fontSize:11, fontWeight:600, letterSpacing:'0.02em' }}>Recolher menu</span>}
          </button>
        )}

        {/* User card */}
        <div style={{
          display:'flex', alignItems:'center', gap:10,
          padding: collapsed ? '6px' : '8px 10px',
          borderRadius:10,
          background: collapsed ? 'transparent' : 'linear-gradient(135deg, rgba(37,99,235,0.12), rgba(14,165,233,0.06))',
          border: collapsed ? 'none' : '1px solid rgba(255,255,255,0.06)',
          cursor:'default'
        }}>
          <div style={{ position:'relative', flexShrink:0 }}>
            <div style={{
              width:32, height:32, borderRadius:9,
              background:`linear-gradient(135deg, ${user.cor || '#1E6FD9'}, ${user.cor || '#0EA5E9'}DD)`,
              display:'flex', alignItems:'center', justifyContent:'center',
              boxShadow:`0 4px 10px ${user.cor || '#1E6FD9'}55, inset 0 1px 0 rgba(255,255,255,0.2)`
            }}>
              <span style={{ fontSize:11, fontWeight:800, color:'#fff', letterSpacing:'0.02em' }}>{user.iniciais}</span>
            </div>
            <div style={{ position:'absolute', bottom:-1, right:-1, width:9, height:9, borderRadius:5, background:'#22C55E', border:'2px solid #0B1428' }}></div>
          </div>
          {!collapsed && (
            <>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:12, fontWeight:700, color:'#fff', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{user.nome}</div>
                <div style={{ fontSize:10, color:'rgba(255,255,255,0.45)', textTransform:'capitalize', fontWeight:500 }}>{user.perfil}</div>
              </div>
              <button onClick={onLogout}
                title="Sair"
                style={{ background:'none', border:'none', cursor:'pointer', color:'rgba(255,255,255,0.4)', display:'flex', padding:6, borderRadius:7, transition:'all 0.15s' }}
                onMouseEnter={e => { e.currentTarget.style.background='rgba(248,113,113,0.15)'; e.currentTarget.style.color='#F87171'; }}
                onMouseLeave={e => { e.currentTarget.style.background='transparent'; e.currentTarget.style.color='rgba(255,255,255,0.4)'; }}>
                <Icon name="logout" size={14}/>
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ── HEADER ───────────────────────────────────────────────────────
function AppHeader({ route, user, alertCount, mobile, onMenu, onNav, onLogout }) {
  const labels = { dashboard:'Dashboard', agenda:'Agenda Mensal', clientes:'Clientes', equipamentos:'Equipamentos',
    ordens:'Ordens de Serviço', calibracao:'Calibração RBC / Rastreada', propostas:'Propostas (PTC)',
    financeiro:'Financeiro', estoque:'Estoque', relatorios:'Relatórios', config:'Configurações' };
  const today = new Date();
  const todayStr = today.toLocaleDateString('pt-BR',{weekday:'long',day:'2-digit',month:'long',year:'numeric'});
  const shortDateStr = today.toLocaleDateString('pt-BR',{day:'2-digit',month:'short'});
  const [menuOpen, setMenuOpen]   = useState(false);
  const [bellOpen, setBellOpen]   = useState(false);
  const alertas = bellOpen ? SGAB.getAlertas(SGAB.getDB()) : [];

  // Fecha popovers ao clicar fora
  useEffect(() => {
    if (!menuOpen && !bellOpen) return;
    const onDoc = e => {
      if (!e.target.closest('[data-sgab-popover]')) { setMenuOpen(false); setBellOpen(false); }
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [menuOpen, bellOpen]);

  function handleNotifClick(al) {
    const target = {calibracao:'equipamentos',receber:'financeiro',pagar:'financeiro',estoque:'estoque'}[al.tipo];
    setBellOpen(false);
    if (target && onNav) onNav(target);
  }

  return (
    <div style={{
      minHeight: 60,
      background:'#fff', borderBottom:'1px solid #E8EDF4',
      display:'flex', alignItems:'center', justifyContent:'space-between',
      padding: mobile ? '0 14px' : '0 24px',
      paddingTop: mobile ? 'max(8px, env(safe-area-inset-top))' : 0,
      paddingLeft: mobile ? 'max(14px, env(safe-area-inset-left))' : 24,
      paddingRight: mobile ? 'max(14px, env(safe-area-inset-right))' : 24,
      flexShrink:0,
      boxShadow:'0 1px 3px rgba(0,0,0,0.04)',
      position:'relative', zIndex:50
    }}>
      <div style={{ display:'flex', alignItems:'center', gap:12, minWidth:0, flex:1 }}>
        {mobile && (
          <button onClick={onMenu} aria-label="Abrir menu"
            style={{ width:38, height:38, borderRadius:9, background:'#F1F5F9', border:'none', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink:0 }}>
            <Icon name="menu" size={20} color="#0D1B2A"/>
          </button>
        )}
        <div style={{ minWidth:0, overflow:'hidden' }}>
          <div style={{ fontSize: mobile ? 15 : 16, fontWeight:700, color:'#0D1B2A', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{labels[route]||route}</div>
          <div style={{ fontSize: mobile ? 10 : 12, color:'#9CA3AF', textTransform:'capitalize', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{mobile ? shortDateStr : todayStr}</div>
        </div>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap: mobile ? 8 : 16, flexShrink:0 }}>
        {/* Alert bell */}
        <div data-sgab-popover style={{ position:'relative' }}>
          <button onClick={()=>{setBellOpen(o=>!o); setMenuOpen(false);}} title="Notificações"
            style={{ width:36, height:36, borderRadius:9, background:bellOpen?'#EFF6FF':'#F1F5F9', border:'none', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', position:'relative', transition:'background 0.12s' }}>
            <Icon name="bell" size={18} color={bellOpen?'#1E6FD9':'#6B7280'}/>
            {alertCount > 0 && <div style={{ position:'absolute', top:-2, right:-2, minWidth:17, height:17, padding:'0 4px', borderRadius:9, background:'#DC2626', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <span style={{ fontSize:9, fontWeight:800, color:'#fff' }}>{alertCount}</span>
            </div>}
          </button>
          {bellOpen && (
            <div style={{ position:'absolute', top:46, right:0, width:360, maxHeight:480, background:'#fff', borderRadius:12, boxShadow:'0 12px 40px rgba(0,0,0,0.18)', border:'1px solid #E8EDF4', overflow:'hidden', display:'flex', flexDirection:'column', animation:'fadeIn 0.15s ease' }}>
              <div style={{ padding:'14px 16px', borderBottom:'1px solid #F1F5F9', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
                <div>
                  <div style={{ fontSize:14, fontWeight:800, color:'#0D1B2A' }}>Notificações</div>
                  <div style={{ fontSize:11, color:'#9CA3AF' }}>{alertas.length === 0 ? 'Nenhum alerta no momento' : `${alertas.length} alerta(s) ativos`}</div>
                </div>
                <button onClick={()=>setBellOpen(false)} style={{ background:'none', border:'none', cursor:'pointer', padding:4, color:'#9CA3AF', display:'flex' }}><Icon name="x" size={16}/></button>
              </div>
              <div style={{ overflowY:'auto', flex:1, maxHeight:380 }}>
                {alertas.length === 0 ? (
                  <div style={{ padding:'40px 20px', textAlign:'center', color:'#9CA3AF' }}>
                    <Icon name="check" size={32} color="#16A34A"/>
                    <p style={{ marginTop:10, fontSize:13 }}>Tudo em dia!</p>
                  </div>
                ) : alertas.map((al, i) => {
                  const cols = { danger:{ bg:'#FEF2F2', border:'#FECACA', ic:'#DC2626', c:'#991B1B' },
                                 warning:{ bg:'#FFFBEB', border:'#FDE68A', ic:'#D97706', c:'#92400E' },
                                 info:{ bg:'#EFF6FF', border:'#BFDBFE', ic:'#3B82F6', c:'#1E40AF' } };
                  const cc = cols[al.nivel] || cols.info;
                  const icons = { calibracao:'scale', receber:'financeiro', pagar:'arrowDown', estoque:'pkg' };
                  return (
                    <div key={i} onClick={()=>handleNotifClick(al)}
                      onMouseEnter={e=>e.currentTarget.style.background='#F8FAFF'}
                      onMouseLeave={e=>e.currentTarget.style.background='transparent'}
                      style={{ padding:'12px 16px', borderBottom: i<alertas.length-1?'1px solid #F1F5F9':'none', cursor:'pointer', display:'flex', gap:10, transition:'background 0.1s' }}>
                      <div style={{ width:32, height:32, borderRadius:8, background:cc.bg, border:`1px solid ${cc.border}`, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                        <Icon name={icons[al.tipo]||'alert'} size={16} color={cc.ic}/>
                      </div>
                      <div style={{ flex:1, minWidth:0 }}>
                        <div style={{ fontSize:13, color:cc.c, lineHeight:1.4 }}>{al.msg}</div>
                      </div>
                      <Icon name="chevR" size={14} color="#D1D5DB"/>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
        {/* User chip com dropdown */}
        <div data-sgab-popover style={{ position:'relative' }}>
          <button onClick={()=>{setMenuOpen(o=>!o); setBellOpen(false);}}
            style={{ background:menuOpen?'#EFF6FF':(mobile?(user.cor||'#1E6FD9'):'#F8FAFF'), border: mobile?'none':'1px solid #E8EDF4', borderRadius:mobile?9:10, padding: mobile?0:'6px 12px 6px 6px', display:'flex', alignItems:'center', gap:8, cursor:'pointer', fontFamily:'inherit', transition:'background 0.12s' }}>
            <div style={{ width: mobile?36:28, height: mobile?36:28, borderRadius:mobile?9:7, background:user.cor||'#1E6FD9', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
              <span style={{ fontSize:mobile?12:11, fontWeight:800, color:'#fff' }}>{user.iniciais}</span>
            </div>
            {!mobile && (
              <>
                <div style={{ textAlign:'left' }}>
                  <div style={{ fontSize:12, fontWeight:700, color:'#111827' }}>{user.nome}</div>
                  <div style={{ fontSize:10, color:'#9CA3AF', textTransform:'capitalize' }}>{user.perfil}</div>
                </div>
                <Icon name="chevD" size={14} color="#9CA3AF" style={{ marginLeft:2, transition:'transform 0.15s', transform: menuOpen?'rotate(180deg)':'none' }}/>
              </>
            )}
          </button>
          {menuOpen && (
            <div style={{ position:'absolute', top:46, right:0, width:240, background:'#fff', borderRadius:12, boxShadow:'0 12px 40px rgba(0,0,0,0.18)', border:'1px solid #E8EDF4', overflow:'hidden', animation:'fadeIn 0.15s ease' }}>
              {/* Cabeçalho com nome/email */}
              <div style={{ padding:'14px 16px', borderBottom:'1px solid #F1F5F9', display:'flex', alignItems:'center', gap:10 }}>
                <div style={{ width:38, height:38, borderRadius:10, background:user.cor||'#1E6FD9', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                  <span style={{ fontSize:13, fontWeight:800, color:'#fff' }}>{user.iniciais}</span>
                </div>
                <div style={{ minWidth:0, flex:1 }}>
                  <div style={{ fontSize:13, fontWeight:700, color:'#111827', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{user.nome}</div>
                  <div style={{ fontSize:11, color:'#9CA3AF', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{user.email || ''}</div>
                  <div style={{ fontSize:10, color:'#1E6FD9', textTransform:'capitalize', fontWeight:700, marginTop:2 }}>{user.perfil}</div>
                </div>
              </div>
              {/* Itens do menu */}
              {(user.perfil==='administrador' || user.perfil==='administrativo') && onNav && (
                <button onClick={()=>{ setMenuOpen(false); onNav('config'); }}
                  onMouseEnter={e=>e.currentTarget.style.background='#F8FAFF'}
                  onMouseLeave={e=>e.currentTarget.style.background='transparent'}
                  style={{ width:'100%', padding:'10px 16px', border:'none', background:'transparent', display:'flex', alignItems:'center', gap:10, cursor:'pointer', fontFamily:'inherit', fontSize:13, color:'#374151', transition:'background 0.1s' }}>
                  <Icon name="config" size={16} color="#6B7280"/>
                  <span>Configurações</span>
                </button>
              )}
              <div style={{ height:1, background:'#F1F5F9', margin:'4px 0' }}></div>
              <button onClick={()=>{ setMenuOpen(false); onLogout && onLogout(); }}
                onMouseEnter={e=>{e.currentTarget.style.background='#FEF2F2'; e.currentTarget.style.color='#B91C1C';}}
                onMouseLeave={e=>{e.currentTarget.style.background='transparent'; e.currentTarget.style.color='#374151';}}
                style={{ width:'100%', padding:'10px 16px', border:'none', background:'transparent', display:'flex', alignItems:'center', gap:10, cursor:'pointer', fontFamily:'inherit', fontSize:13, color:'#374151', transition:'all 0.1s' }}>
                <Icon name="logout" size={16}/>
                <span>Sair</span>
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── TOAST MANAGER ────────────────────────────────────────────────
function useToast() {
  const [toasts, setToasts] = useState([]);
  const show = useCallback((msg, type='success') => {
    const id = Date.now();
    setToasts(t => [...t, { id, msg, type }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 3500);
  }, []);
  const ToastContainer = () => (
    <div style={{ position:'fixed', bottom:24, right:24, zIndex:9999, display:'flex', flexDirection:'column', gap:8 }}>
      {toasts.map(t => <Toast key={t.id} msg={t.msg} type={t.type} onClose={() => setToasts(ts => ts.filter(x => x.id !== t.id))} />)}
    </div>
  );
  return { show, ToastContainer };
}

// ── APP SHELL ────────────────────────────────────────────────────
function App() {
  const [user, setUser]       = useState(null);
  const [route, setRoute]     = useState('dashboard');
  const [collapsed, setCollapsed] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [booting, setBooting] = useState(true);
  const [, forceRefresh]      = useState(0);
  const mobile = useIsMobile();
  const { show: toast, ToastContainer } = useToast();

  // Expor toast globalmente para o data.js mostrar erros de sync
  useEffect(() => { window.__SGAB_TOAST = toast; return () => { delete window.__SGAB_TOAST; }; }, [toast]);

  // Re-render quando o snapshot do Supabase atualizar
  useEffect(() => {
    if (!window.SGAB_SB) return;
    return window.SGAB_SB.onChange(() => forceRefresh(n => n + 1));
  }, []);

  // Boot: tenta restaurar sessão Supabase
  useEffect(() => {
    let cancelled = false;
    (async () => {
      if (!window.SGAB_SB) { if (!cancelled) setBooting(false); return; }
      try {
        const profile = await window.SGAB_SB.currentProfile();
        if (profile && profile.ativo) {
          await window.SGAB_SB.loadAll();
          if (!cancelled) setUser(profile);
        }
      } catch (e) {
        console.error('[SGAB] Boot:', e);
      } finally {
        if (!cancelled) setBooting(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  // Close drawer when leaving mobile
  useEffect(() => { if (!mobile) setMobileOpen(false); }, [mobile]);

  function handleLogin(u) { setUser(u); }
  async function handleLogout() {
    if (window.SGAB_SB) await window.SGAB_SB.signOut();
    setUser(null);
  }
  function handleNav(r) { setRoute(r); if (mobile) setMobileOpen(false); }

  const alertCount = user ? SGAB.getAlertas(SGAB.getDB()).length : 0;

  if (booting) {
    return (
      <div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center',background:'#0D1B2A',color:'#fff',fontFamily:"'DM Sans',sans-serif"}}>
        <div style={{textAlign:'center'}}>
          <div style={{width:48,height:48,border:'3px solid rgba(255,255,255,0.2)',borderTopColor:'#60A5FA',borderRadius:'50%',margin:'0 auto 16px',animation:'spin 0.8s linear infinite'}}></div>
          <p style={{fontSize:14,color:'rgba(255,255,255,0.6)'}}>Carregando...</p>
        </div>
        <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
      </div>
    );
  }

  if (!user) return <LoginScreen onLogin={handleLogin} mobile={mobile}/>;

  // Render module
  const moduleProps = { user, toast, onNav: handleNav };
  const modules = {
    dashboard:    window.Dashboard    && <Dashboard    {...moduleProps} />,
    agenda:       window.Agenda       && <Agenda       {...moduleProps} />,
    clientes:     window.Clientes     && <Clientes     {...moduleProps} />,
    equipamentos: window.Equipamentos && <Equipamentos {...moduleProps} />,
    ordens:       window.OrdemServico && <OrdemServico {...moduleProps} />,
    calibracao:   window.Calibracao   && <Calibracao   {...moduleProps} />,
    propostas:    window.Propostas    && <Propostas    {...moduleProps} />,
    financeiro:   window.Financeiro   && <Financeiro   {...moduleProps} />,
    estoque:      window.Estoque      && <Estoque      {...moduleProps} />,
    relatorios:   window.Relatorios   && <Relatorios   {...moduleProps} />,
    config:       window.Configuracoes && <Configuracoes {...moduleProps} />,
  };

  return (
    <div style={{ display:'flex', height:'100vh', overflow:'hidden', fontFamily:"'DM Sans',sans-serif", background:'#EEF2F7', position:'relative' }}>
      <style>{`
        @import url('https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700;0,9..40,800&display=swap');
        *{box-sizing:border-box;} body{margin:0;}
        ::-webkit-scrollbar{width:5px;height:5px} ::-webkit-scrollbar-track{background:#F1F5F9} ::-webkit-scrollbar-thumb{background:#CBD5E1;border-radius:10px}
        .sgab-sidebar-nav::-webkit-scrollbar{display:none;width:0;height:0}
        @keyframes slideUp{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:translateY(0)}}
        @keyframes fadeIn{from{opacity:0}to{opacity:1}}
        input[type=number]::-webkit-inner-spin-button{opacity:1}
        .sgab-backdrop{position:fixed;inset:0;background:rgba(13,27,42,0.55);z-index:150;animation:fadeIn 0.2s ease;backdrop-filter:blur(2px)}
        @media (max-width: 900px){
          .sgab-kpi-grid{grid-template-columns:repeat(2,1fr) !important}
          .sgab-main-grid{grid-template-columns:1fr !important}
          .sgab-2col-grid{grid-template-columns:1fr !important}
          .sgab-content{padding:14px !important}
          .sgab-page-header{flex-direction:column !important;align-items:flex-start !important;gap:10px !important}
        }
        @media (max-width: 640px){
          .sgab-form-grid{grid-template-columns:1fr !important}
        }
        @media (max-width: 560px){
          .sgab-kpi-grid{grid-template-columns:1fr !important}
        }
      `}</style>
      {mobile && mobileOpen && <div className="sgab-backdrop" onClick={()=>setMobileOpen(false)}/>}
      <Sidebar route={route} onNav={handleNav} user={user} onLogout={handleLogout}
        collapsed={collapsed} onToggle={() => setCollapsed(c => !c)}
        mobile={mobile} mobileOpen={mobileOpen}/>
      <div style={{ flex:1, display:'flex', flexDirection:'column', overflow:'hidden', minWidth:0 }}>
        <AppHeader route={route} user={user} alertCount={alertCount} mobile={mobile}
          onMenu={()=>setMobileOpen(true)} onNav={handleNav} onLogout={handleLogout}/>
        <div className="sgab-content" style={{ flex:1, overflowY:'auto', padding: mobile ? 14 : 24, paddingBottom: mobile ? 'max(14px, env(safe-area-inset-bottom))' : 24 }}>
          {modules[route] || <div style={{textAlign:'center',padding:80,color:'#9CA3AF'}}>Módulo em desenvolvimento</div>}
        </div>
      </div>
      <ToastContainer />
    </div>
  );
}

Object.assign(window, { App, useToast });
