/* Sidebar — themed for both directions */

const navItems = [
  { group: 'OPERAÇÃO', items: [
    { id: 'chat', label: 'Conversas', icon: 'Chat' },
    { id: 'dashboard', label: 'Painel de Leads', icon: 'Dashboard' },
    { id: 'kanban', label: 'Kanban CRM', icon: 'Kanban' },
    { id: 'customers', label: 'Banco de Clientes', icon: 'Users' },
    { id: 'appointments', label: 'Compromissos', icon: 'Calendar' },
  ]},
  { group: 'INTELIGÊNCIA', items: [
    { id: 'dna', label: 'DNA da Assistente', icon: 'Sparkles' },
    { id: 'knowledge', label: 'Base de Conhecimento', icon: 'Book' },
  ]},
  { group: 'CONTA', items: [
    { id: 'settings', label: 'Configurações', icon: 'Settings' },
  ]},
];

const Logo = ({ onNavigate }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
      <div 
        onClick={() => onNavigate && onNavigate('dashboard')}
        style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: onNavigate ? 'pointer' : 'default' }}>
        <div style={{
          width: 38, height: 38, borderRadius: isBloom ? 10 : 9,
          background: `linear-gradient(135deg, ${t.green} 0%, ${t.primary} 100%)`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: isBloom ? `1.5px solid ${t.border}` : 'none',
          boxShadow: isBloom ? '3px 3px 0 0 #14131A' : '0 6px 24px -6px rgba(91,141,239,0.5)',
          position: 'relative',
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
            <path d="M14 3 L4 14 L11 14 L10 21 L20 10 L13 10 Z" fill="#fff" stroke="#fff" strokeWidth="1.2" strokeLinejoin="round"/>
          </svg>
        </div>
        <div style={{ lineHeight: 1.05 }}>
          <div style={{ fontFamily: t.fontDisplay, fontSize: 17, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
            FLUXO<span style={{ color: t.green }}>ZAP</span>
          </div>
          <div style={{ fontSize: 10, color: t.textMuted, letterSpacing: '0.12em', fontFamily: t.fontMono, marginTop: 2 }}>
            CRM × IA × WHATSAPP
          </div>
        </div>
      </div>
      <button onClick={() => t.setTheme(isBloom ? 'PULSE' : 'BLOOM')} style={{
        background: 'transparent', border: 'none', cursor: 'pointer', color: t.textMuted,
        padding: 6, borderRadius: t.radiusMd, display: 'flex', alignItems: 'center', justifyContent: 'center',
      }} onMouseEnter={(e) => e.currentTarget.style.color = t.text} onMouseLeave={(e) => e.currentTarget.style.color = t.textMuted}>
        {isBloom ? <Icons.Moon size={18} /> : <Icons.Sun size={18} />}
      </button>
    </div>
  );
};

const WhatsappModal = ({ isOpen, onClose, status, qrCode, onConnect }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  
  if (!isOpen) return null;
  
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center'
    }}>
      <div style={{
        background: t.surface, borderRadius: t.radiusLg,
        border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
        width: 400, padding: 24, boxShadow: isBloom ? '8px 8px 0 0 #14131A' : '0 10px 40px -10px rgba(0,0,0,0.5)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
          <h2 style={{ margin: 0, fontSize: 18, fontFamily: t.fontDisplay, color: t.text }}>Conectar WhatsApp</h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: t.textMuted, cursor: 'pointer' }}>
            <Icons.X size={20} />
          </button>
        </div>
        
        {status === 'INITIALIZING' && (
          <div style={{ textAlign: 'center', padding: '40px 0', color: t.textMuted }}>
            <Icons.Clock size={40} style={{ margin: '0 auto 16px', opacity: 0.5 }} />
            <p>Inicializando o motor do WhatsApp...</p>
            <p style={{ fontSize: 12 }}>Isso pode levar alguns segundos.</p>
          </div>
        )}

        {status === 'QR_READY' && qrCode && (
          <div style={{ textAlign: 'center' }}>
            <p style={{ color: t.textMuted, marginBottom: 16, fontSize: 14 }}>
              Abra o WhatsApp no seu celular, vá em Aparelhos Conectados e aponte a câmera para o QR Code abaixo:
            </p>
            <div style={{ background: '#fff', padding: 16, borderRadius: 12, display: 'inline-block' }}>
              <img src={qrCode} alt="QR Code" style={{ width: 200, height: 200, display: 'block' }} />
            </div>
            <p style={{ marginTop: 16, fontSize: 12, color: t.orange, fontWeight: 600 }}>
              O QR Code expira rapidamente. Aguardando leitura...
            </p>
          </div>
        )}

        {status === 'CONNECTED' && (
          <div style={{ textAlign: 'center', padding: '40px 0', color: t.green }}>
            <Icons.CheckDouble size={48} style={{ margin: '0 auto 16px' }} />
            <p style={{ fontSize: 18, fontWeight: 700, fontFamily: t.fontDisplay }}>Conectado com Sucesso!</p>
            <p style={{ fontSize: 14, color: t.textMuted, marginTop: 8 }}>
              O sistema agora está ouvindo e respondendo através do seu WhatsApp.
            </p>
          </div>
        )}

        {status === 'DISCONNECTED' && (
          <div style={{ textAlign: 'center', padding: '30px 0' }}>
            <Icons.Power size={48} style={{ margin: '0 auto 16px', color: t.red, opacity: 0.8 }} />
            <p style={{ fontSize: 16, fontWeight: 700, color: t.text, fontFamily: t.fontDisplay }}>WhatsApp Desconectado</p>
            <p style={{ fontSize: 13, color: t.textMuted, marginTop: 8, marginBottom: 20 }}>
              Sua instância do WhatsApp Business está atualmente offline.
            </p>
            <Btn 
              variant="primary" 
              style={{ width: '100%' }}
              icon={<Icons.Whatsapp size={16}/>}
              onClick={onConnect}
            >
              Conectar / Gerar QR Code
            </Btn>
          </div>
        )}
      </div>
    </div>
  );
};

const Sidebar = ({ current, onNavigate }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const { showToast } = useToast();
  const { data: waData } = useWhatsappStatus();
  const { data: apiLeads } = useLeads();
  const { data: aiConfig } = useAiConfig();
  const updateAiConfig = useUpdateAiConfig();
  const [modalOpen, setModalOpen] = React.useState(false);

  const status = waData?.status || 'DISCONNECTED';
  const isConnected = status === 'CONNECTED';
  const botActive = aiConfig?.botActive !== false; // default true
  
  // Obter perfil do usuário logado para liberar menu administrativo
  const user = React.useMemo(() => {
    try {
      const u = localStorage.getItem('fluxo_user');
      return u ? JSON.parse(u) : null;
    } catch(e) { return null; }
  }, []);

  const isAdmin = user?.role === 'owner' || user?.role === 'admin' || user?.email === 'admin@fluxozap.com';

  const fullNavItems = React.useMemo(() => {
    const items = [...navItems];
    if (isAdmin) {
      items.push({
        group: 'PROPRIETÁRIO (SAAS)',
        items: [
          { id: 'admin-panel', label: 'Super Administração', icon: 'Settings' }
        ]
      });
    }
    return items;
  }, [isAdmin]);

  // Calculate unread badge from API safely (handles array or {data: []} response)
  const leadsArray = Array.isArray(apiLeads) ? apiLeads : (apiLeads?.data || []);
  const unreadCount = leadsArray.reduce((acc, l) => acc + (l.unread || 0), 0);

  const toggleBot = async (e) => {
    e.stopPropagation();
    try {
      await updateAiConfig({ botActive: !botActive });
      window.FluxoApi.post('/ai/toggle', { active: !botActive });
    } catch(e) {}
  };

  return (
    <aside style={{
      width: 260, flexShrink: 0, height: '100%',
      background: isBloom ? t.surface : '#0A0E1A',
      borderRight: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      <div style={{ padding: '20px 18px 18px',
        borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
      }}>
        <Logo onNavigate={onNavigate} />
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '14px 12px' }}>
        {fullNavItems.map((group, gi) => (
          <div key={gi} style={{ marginBottom: 18 }}>
            <div style={{
              padding: '0 8px 8px', fontSize: 10, fontWeight: 700, color: t.textMuted,
              letterSpacing: '0.14em', fontFamily: t.fontMono,
            }}>{group.group}</div>
            {group.items.map(item => {
              const I = Icons[item.icon];
              const active = current === item.id;
              // Override badge dynamically for 'chat'
              const badgeCount = item.id === 'chat' ? unreadCount : item.badge;
              
              return (
                <button key={item.id} onClick={() => onNavigate(item.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 11, width: '100%',
                  padding: '9px 10px', marginBottom: 2,
                  background: active ? (isBloom ? t.text : 'rgba(91,141,239,0.13)') : 'transparent',
                  color: active ? (isBloom ? t.surface : t.text) : t.textMuted,
                  border: isBloom ? `1.5px solid ${active ? t.border : 'transparent'}` : (active ? `1px solid rgba(91,141,239,0.3)` : '1px solid transparent'),
                  borderRadius: t.radiusMd, fontFamily: t.fontBody, fontSize: 13.5, fontWeight: 600,
                  textAlign: 'left', letterSpacing: '-0.01em', position: 'relative',
                  boxShadow: isBloom && active ? '3px 3px 0 0 #14131A' : 'none',
                }}>
                  <I size={17} stroke={active ? (isBloom ? t.surface : t.primary) : t.textMuted}/>
                  <span style={{ flex: 1 }}>{item.label}</span>
                  {badgeCount > 0 && (
                    <span style={{
                      padding: typeof badgeCount === 'number' ? '1px 6px' : '2px 7px',
                      borderRadius: 99, fontSize: 10, fontWeight: 700,
                      background: typeof badgeCount === 'number' ? t.green : t.pink,
                      color: '#fff', fontFamily: t.fontMono, letterSpacing: '0.04em',
                    }}>{badgeCount}</span>
                  )}
                  {active && !isBloom && (
                    <span style={{ position: 'absolute', left: -12, top: '50%', transform: 'translateY(-50%)',
                      width: 3, height: 18, borderRadius: 2, background: t.primary }}/>
                  )}
                </button>
              );
            })}
          </div>
        ))}
      </div>

      {/* Connection status footer */}
      <div style={{ padding: 12,
        borderTop: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
      }}>
        <div 
          onClick={() => setModalOpen(true)}
          style={{
            padding: 12, borderRadius: t.radiusMd, cursor: 'pointer',
            background: isConnected ? (isBloom ? t.greenSoft : 'rgba(16,185,129,0.08)') : (isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.03)'),
            border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${isConnected ? 'rgba(16,185,129,0.2)' : 'rgba(255,255,255,0.08)'}`,
            boxShadow: isBloom ? '3px 3px 0 0 #14131A' : 'none',
          }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icons.Whatsapp size={16} stroke={isConnected ? t.green : t.textMuted} fill={isConnected ? t.green : 'none'}/>
              <span style={{ fontSize: 12, fontWeight: 700, color: t.text, fontFamily: t.fontBody }}>WhatsApp Business</span>
            </div>
            <button onClick={toggleBot} style={{
              background: botActive ? t.green : (isBloom ? t.surfaceAlt : 'rgba(239,68,68,0.15)'),
              border: `1px solid ${botActive ? t.green : (isBloom ? t.border : 'rgba(239,68,68,0.4)')}`,
              borderRadius: 99, padding: '2px 8px', fontSize: 10, fontWeight: 700,
              color: botActive ? '#fff' : (isBloom ? t.textMuted : '#f87171'),
              cursor: 'pointer', fontFamily: t.fontMono,
              transition: 'all 0.2s ease'
            }}>
              {botActive ? 'IA ON' : 'IA OFF'}
            </button>
          </div>
          <Status 
            ok={isConnected} 
            color={status === 'QR_READY' ? t.orange : (isConnected ? t.green : t.textMuted)}
            label={
              isConnected ? (botActive ? "Assistente ativa" : "Assistente pausada") :
              status === 'QR_READY' ? "Aguardando QR Code..." :
              status === 'INITIALIZING' ? "Iniciando motor..." : "Desconectado"
            }
          />
        </div>
      </div>
      
      <WhatsappModal 
        isOpen={modalOpen} 
        onClose={() => setModalOpen(false)} 
        status={status} 
        qrCode={waData?.qrCode} 
        onConnect={async () => {
          try {
            const token = localStorage.getItem('fluxo_token');
            const res = await fetch('/api/whatsapp/connect', {
              method: 'POST',
              headers: { 'Authorization': `Bearer ${token}` }
            });
            if (res.ok) {
              showToast('Solicitada a geração do QR Code. Inicializando...', 'success');
            } else {
              showToast('Erro ao iniciar conexão com o WhatsApp.', 'error');
            }
          } catch(e) {
            showToast('Erro de rede ao conectar.', 'error');
          }
        }}
      />
    </aside>
  );
};

window.Sidebar = Sidebar;
window.Logo = Logo;
