// GuinchoFlow — Layout (Sidebar + Topbar)

const NAV_ITEMS = [
  { id: 'dashboard',    label: 'Dashboard',       icon: 'home' },
  { id: 'assistencias', label: 'Assistências',     icon: 'truck' },
  { id: 'vistoria',     label: 'Vistoria Digital', icon: 'search' },
  { id: 'frota',        label: 'Frota de Guinchos',icon: 'wrench' },
  { id: 'motoristas',   label: 'Motoristas',       icon: 'users' },
  { id: 'seguradoras',  label: 'Seguradoras',       icon: 'shield' },
  { id: 'financeiro',   label: 'Financeiro',        icon: 'dollar' },
  { id: 'relatorios',   label: 'Relatórios',        icon: 'fileText' },
  { id: 'configuracoes',label: 'Configurações',     icon: 'settings' },
];

const Sidebar = ({ active, onNav, collapsed, onToggle, session, onLogout }) => {
  const [hov, setHov] = React.useState(null);
  const [userInfo, setUserInfo] = React.useState(null);
  React.useEffect(() => {
    if (!session?.user) { setUserInfo(null); return; }
    db.one('usuarios', session.user.id).then(u => setUserInfo(u));
  }, [session?.user?.id]);
  const userNome = userInfo?.nome || session?.user?.email?.split('@')[0] || 'Usuário';
  const userCargo = userInfo?.cargo || '—';
  const userInits = userNome.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase();
  return (
    <aside style={{
      width: collapsed ? 0 : 260, minWidth: collapsed ? 0 : 260,
      background: '#1E293B', display: 'flex', flexDirection: 'column',
      height: '100vh', position: 'sticky', top: 0,
      overflowX: 'hidden', transition: 'width 0.3s ease, min-width 0.3s ease',
      flexShrink: 0, zIndex: 200
    }}>
      {/* Logo */}
      <div style={{
        padding: 'max(env(safe-area-inset-top), 24px) 20px 20px',
        borderBottom: '1px solid rgba(255,255,255,0.07)',
        display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0
      }}>
        <img src="logo.png" alt="Caririaçu Guincho" style={{
          width: 44, height: 44, borderRadius: '50%', objectFit: 'cover',
          flexShrink: 0, transform: 'scale(1.08)',
          boxShadow: '0 0 0 2px rgba(245,158,11,0.6), 0 4px 10px rgba(0,0,0,0.3)'
        }} />
        <div>
          <div style={{ fontSize: 15, fontWeight: 700, color: '#fff', fontFamily: 'DM Sans, sans-serif', letterSpacing: '-0.3px', lineHeight: 1.1 }}>Caririaçu Guincho</div>
          <div style={{ fontSize: 10, color: '#F59E0B', marginTop: 2, fontWeight: 600, letterSpacing: '0.5px' }}>RAPIDEZ · SEGURANÇA</div>
        </div>
      </div>

      {/* Nav Items */}
      <nav style={{ flex: 1, padding: '12px 12px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 2 }}>
        {NAV_ITEMS.map(item => {
          const isActive = active === item.id;
          return (
            <button key={item.id}
              onClick={() => onNav(item.id)}
              onMouseEnter={() => setHov(item.id)}
              onMouseLeave={() => setHov(null)}
              style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
                borderRadius: 10, border: 'none', cursor: 'pointer', width: '100%',
                background: isActive ? 'rgba(245,158,11,0.15)' : hov === item.id ? 'rgba(255,255,255,0.07)' : 'transparent',
                color: isActive ? '#F59E0B' : '#CBD5E1',
                borderLeft: `3px solid ${isActive ? '#F59E0B' : 'transparent'}`,
                transition: 'all 0.15s', textAlign: 'left',
                fontFamily: 'Inter, sans-serif', fontSize: 14, fontWeight: isActive ? 600 : 400,
                whiteSpace: 'nowrap', overflow: 'hidden'
              }}>
              <Icon name={item.icon} size={18} color={isActive ? '#F59E0B' : hov === item.id ? '#CBD5E1' : '#64748B'} />
              <span>{item.label}</span>
            </button>
          );
        })}
      </nav>

      {/* User Footer */}
      <div style={{
        padding: '16px 16px max(env(safe-area-inset-bottom), 16px) 16px',
        borderTop: '1px solid rgba(255,255,255,0.07)',
        display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0
      }}>
        <Avatar initials={userInits} size={36} />
        <div style={{ flex: 1, overflow: 'hidden' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: '#F1F5F9', fontFamily: 'DM Sans, sans-serif', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{userNome}</div>
          <div style={{ fontSize: 11, color: '#64748B' }}>{userCargo}</div>
        </div>
        <button onClick={onLogout} title="Sair" style={{
          background: 'none', border: 'none', cursor: 'pointer', color: '#64748B',
          padding: 6, borderRadius: 6, display: 'flex',
          transition: 'color 0.15s'
        }}
        onMouseEnter={e=>e.currentTarget.style.color='#EF4444'}
        onMouseLeave={e=>e.currentTarget.style.color='#64748B'}>
          <Icon name="logout" size={16} />
        </button>
      </div>
    </aside>
  );
};

const BREADCRUMBS = {
  dashboard:     ['Dashboard'],
  assistencias:  ['Assistências'],
  vistoria:      ['Vistoria Digital'],
  frota:         ['Frota de Guinchos'],
  motoristas:    ['Cadastros', 'Motoristas'],
  seguradoras:   ['Cadastros', 'Seguradoras'],
  financeiro:    ['Financeiro'],
  relatorios:    ['Relatórios'],
  configuracoes: ['Configurações'],
};

const Topbar = ({ active, onMenuToggle, isMobile, onNav, session }) => {
  const [searchOpen, setSearchOpen] = React.useState(false);
  const [searchVal, setSearchVal] = React.useState('');
  const [notifOpen, setNotifOpen] = React.useState(false);
  const [alerts, setAlerts] = React.useState([]);
  const crumbs = BREADCRUMBS[active] || ['Dashboard'];

  React.useEffect(() => {
    if (!notifOpen) return;
    (async () => {
      const abertas = await db.list('assistencias', { eq: { status: 'aberta' } });
      const manut = await db.list('frota', { eq: { status: 'manutencao' } });
      const list = [
        ...abertas.slice(0, 3).map(a => ({ id: 'a' + a.id, type: 'danger', msg: `Assistência ${a.numero || '#' + a.id} aberta`, link: 'assistencias' })),
        ...manut.slice(0, 2).map(g => ({ id: 'f' + g.id, type: 'warning', msg: `Guincho ${g.code} (${g.placa}) em manutenção`, link: 'frota' })),
      ];
      setAlerts(list);
    })();
  }, [notifOpen]);

  const userEmail = session?.user?.email || '';
  const userInits = userEmail.split('@')[0].slice(0, 2).toUpperCase() || 'U';
  const userShort = userEmail.split('@')[0];

  return (
    <header style={{
      background: '#fff', borderBottom: '1px solid #E2E8F0',
      padding: `max(env(safe-area-inset-top), 0px) ${isMobile ? 16 : 24}px 0 ${isMobile ? 16 : 24}px`,
      height: `calc(60px + max(env(safe-area-inset-top), 0px))`,
      display: 'flex', alignItems: 'center',
      gap: 12, position: 'sticky', top: 0, zIndex: 100, flexShrink: 0
    }}>
      {isMobile && (
        <button onClick={onMenuToggle} style={{
          background: 'none', border: 'none', cursor: 'pointer', padding: 6,
          borderRadius: 8, color: '#64748B', display: 'flex'
        }}>
          <Icon name="menu" size={20} />
        </button>
      )}

      {/* Breadcrumb */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 6 }}>
        {crumbs.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <Icon name="chevronRight" size={14} color="#CBD5E1" />}
            <span style={{
              fontSize: 14, color: i < crumbs.length - 1 ? '#94A3B8' : '#0F172A',
              fontWeight: i < crumbs.length - 1 ? 400 : 600,
              fontFamily: 'DM Sans, sans-serif'
            }}>{c}</span>
          </React.Fragment>
        ))}
      </div>

      {/* Search */}
      <div style={{ position: 'relative' }}>
        {searchOpen ? (
          <input autoFocus value={searchVal} onChange={e => setSearchVal(e.target.value)}
            onBlur={() => { setSearchOpen(false); setSearchVal(''); }}
            placeholder="Buscar placa, ID, cliente... (Ctrl+K)"
            style={{
              width: 280, padding: '7px 12px', borderRadius: 8, fontSize: 13,
              border: '1px solid #3B82F6', outline: 'none', color: '#0F172A',
              fontFamily: 'Inter, sans-serif', boxShadow: '0 0 0 3px rgba(59,130,246,0.12)'
            }} />
        ) : (
          <button onClick={() => setSearchOpen(true)} style={{
            background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 8,
            padding: '7px 12px', cursor: 'pointer', display: 'flex', alignItems: 'center',
            gap: 8, color: '#94A3B8', fontSize: 13, fontFamily: 'Inter, sans-serif'
          }}>
            <Icon name="search" size={15} color="#94A3B8" />
            <span style={{ display: isMobile ? 'none' : 'inline' }}>Buscar...</span>
            <kbd style={{ background: '#E2E8F0', borderRadius: 4, padding: '1px 5px', fontSize: 11, display: isMobile ? 'none' : 'inline' }}>Ctrl+K</kbd>
          </button>
        )}
      </div>

      {/* Badge global de lembretes da frota */}
      <BadgeLembreteGlobal onClick={() => onNav && onNav('lembretes')} />

      {/* Notif */}
      <div style={{ position: 'relative' }}>
        <button onClick={() => setNotifOpen(!notifOpen)} style={{
          background: 'none', border: 'none', cursor: 'pointer', padding: 6,
          borderRadius: 8, color: '#64748B', display: 'flex', position: 'relative',
          transition: 'background 0.15s'
        }}
        onMouseEnter={e=>e.currentTarget.style.background='#F1F5F9'}
        onMouseLeave={e=>e.currentTarget.style.background='none'}>
          <Icon name="bell" size={20} />
          <span style={{
            position: 'absolute', top: 4, right: 4, width: 8, height: 8,
            background: '#EF4444', borderRadius: '50%', border: '2px solid #fff'
          }} />
        </button>
        {notifOpen && (
          <div style={{
            position: 'absolute', right: 0, top: '100%', marginTop: 8,
            background: '#fff', borderRadius: 14, border: '1px solid #E2E8F0',
            boxShadow: '0 8px 30px rgba(0,0,0,0.12)', width: 320, zIndex: 500
          }}>
            <div style={{ padding: '14px 16px', borderBottom: '1px solid #F1F5F9', fontWeight: 700, fontSize: 14, color: '#0F172A' }}>
              Notificações {alerts.length > 0 && <span style={{ background: '#EF4444', color: '#fff', borderRadius: 10, padding: '1px 7px', fontSize: 11, marginLeft: 4 }}>{alerts.length}</span>}
            </div>
            {alerts.length === 0 ? (
              <div style={{ padding: '24px 16px', textAlign: 'center', color: '#94A3B8', fontSize: 13 }}>Nenhum alerta no momento</div>
            ) : alerts.map(a => (
              <div key={a.id}
                onClick={() => { setNotifOpen(false); onNav && onNav(a.link); }}
                style={{
                  padding: '12px 16px', borderBottom: '1px solid #F8FAFC',
                  display: 'flex', gap: 10, alignItems: 'flex-start',
                  cursor: 'pointer', transition: 'background 0.15s'
                }}
                onMouseEnter={e => e.currentTarget.style.background = '#FFF7ED'}
                onMouseLeave={e => e.currentTarget.style.background = ''}>
                <Icon name="alert" size={15} color={a.type === 'danger' ? '#EF4444' : '#F59E0B'} />
                <span style={{ fontSize: 13, color: '#374151', lineHeight: 1.4, flex: 1 }}>{a.msg}</span>
                <Icon name="chevronRight" size={13} color="#CBD5E1" />
              </div>
            ))}
          </div>
        )}
      </div>

      {/* User */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }} title={userEmail}>
        <Avatar initials={userInits} size={32} />
        {!isMobile && <span style={{ fontSize: 13, fontWeight: 600, color: '#374151' }}>{userShort}</span>}
      </div>
    </header>
  );
};

// Mobile overlay
const SidebarOverlay = ({ open, onClose, active, onNav, session, onLogout }) => {
  if (!open) return null;
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 300 }} onClick={onClose}>
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.4)' }} />
      <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 260 }} onClick={e => e.stopPropagation()}>
        <Sidebar active={active} onNav={(id) => { onNav(id); onClose(); }} collapsed={false} session={session} onLogout={onLogout} />
      </div>
    </div>
  );
};

Object.assign(window, { Sidebar, Topbar, SidebarOverlay, NAV_ITEMS });
