/* Main app — routing, theme switching, tweaks panel */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "direction": "PULSE",
  "accent": "blue-green",
  "compactKanban": true
}/*EDITMODE-END*/;

const App = () => {
  const { showToast } = useToast();
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  
  // Auth state
  const [token, setToken] = React.useState(() => localStorage.getItem('fluxo_token'));
  const [user, setUser] = React.useState(() => {
    try {
      const u = localStorage.getItem('fluxo_user');
      return u ? JSON.parse(u) : null;
    } catch(e) { return null; }
  });

  const [route, setRoute] = React.useState('dashboard');
  const [activeLeadId, setActiveLeadId] = React.useState(1);

  // SaaS Billing states
  const [activePlan, setActivePlan] = React.useState(() => localStorage.getItem('fluxo_active_plan') || 'Pro');
  const [cardLastDigits, setCardLastDigits] = React.useState(() => localStorage.getItem('fluxo_card_last') || '4321');
  const [cardHolder, setCardHolder] = React.useState(() => localStorage.getItem('fluxo_card_holder') || (user ? user.name.toUpperCase() : 'ADMINISTRADOR'));
  const [billingDay, setBillingDay] = React.useState(() => parseInt(localStorage.getItem('fluxo_billing_day') || '10'));
  const [billingMonthOffset, setBillingMonthOffset] = React.useState(() => parseInt(localStorage.getItem('fluxo_billing_offset') || '0'));
  
  // Card Editor states
  const [isEditingCard, setIsEditingCard] = React.useState(false);
  const [editCardNum, setEditCardNum] = React.useState('');
  const [editCardHolder, setEditCardHolder] = React.useState('');
  const [editCardExpiry, setEditCardExpiry] = React.useState('');
  const [editCardCvv, setEditCardCvv] = React.useState('');
  const [isProcessingPayment, setIsProcessingPayment] = React.useState(false);

  const getBillingDate = () => {
    const date = new Date();
    date.setMonth(date.getMonth() + billingMonthOffset);
    let targetMonth = date.getMonth();
    let targetYear = date.getFullYear();
    
    if (new Date().getDate() > billingDay && billingMonthOffset === 0) {
      targetMonth += 1;
    }
    
    if (targetMonth > 11) {
      targetMonth = targetMonth - 12;
      targetYear += 1;
    }
    
    const monthStr = String(targetMonth + 1).padStart(2, '0');
    return `${String(billingDay).padStart(2, '0')}/${monthStr}/${targetYear}`;
  };

  const getPlanPrice = () => {
    if (activePlan === 'Starter') return 'R$ 147,00';
    if (activePlan === 'Enterprise') return 'R$ 799,00';
    return 'R$ 297,00';
  };
  
  // Interface/Spotlight UI states
  const [searchOpen, setSearchOpen] = React.useState(false);
  const [searchQuery, setSearchQuery] = React.useState('');
  const [notificationsOpen, setNotificationsOpen] = React.useState(false);
  const [notifications, setNotifications] = React.useState([
    {
      id: 'notif_1',
      title: '⚡ Qualificação de Lead',
      desc: 'Assistente IA qualificou o lead João Silva como Proposta.',
      time: '1h atrás',
      unread: true,
      targetRoute: 'crm',
      targetLeadId: 1
    },
    {
      id: 'notif_2',
      title: '📲 WhatsApp Business',
      desc: 'Conexão com o WhatsApp +55 (41) 99876-5432 ativa.',
      time: '3h atrás',
      unread: true,
      targetRoute: 'settings',
      targetLeadId: null
    },
    {
      id: 'notif_3',
      title: '💳 Faturamento',
      desc: 'Mensalidade do Plano Pro processada com sucesso.',
      time: '1d atrás',
      unread: true,
      targetRoute: 'payment_modal',
      targetLeadId: null
    },
    {
      id: 'notif_4',
      title: '📢 Alerta de Ausência',
      desc: 'Você tem uma mensagem de contato sem resposta de Maria Oliveira.',
      time: '2d atrás',
      unread: true,
      targetRoute: 'chat',
      targetLeadId: 2
    }
  ]);

  const hasUnreadNotifications = notifications.some(n => n.unread);
  const [profileMenuOpen, setProfileMenuOpen] = React.useState(false);
  const [profileSubModal, setProfileSubModal] = React.useState(null);

  // Keyboard shortcut listener for Global Search (Cmd+K / Ctrl+K) and Escape key
  React.useEffect(() => {
    const handleKeyDown = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setSearchOpen(prev => !prev);
      } else if (e.key === 'Escape') {
        setSearchOpen(false);
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  // Sync token errors
  React.useEffect(() => {
    window.FluxoConfig.ON_AUTH_ERROR = () => {
      localStorage.removeItem('fluxo_token');
      localStorage.removeItem('fluxo_user');
      setToken(null);
      setUser(null);
      showToast('Sessão expirada. Por favor, faça login novamente.', 'error');
    };
  }, [showToast]);

  // Fetch current user details on token change
  React.useEffect(() => {
    if (token) {
      fetch('/api/auth/me', {
        headers: { 'Authorization': `Bearer ${token}` }
      })
      .then(res => {
        if (res.status === 401) throw new Error('Unauthorized');
        return res.json();
      })
      .then(data => {
        setUser(data.user);
        localStorage.setItem('fluxo_user', JSON.stringify(data.user));
      })
      .catch(err => {
        console.warn('[AUTH] Token inválido:', err.message);
        localStorage.removeItem('fluxo_token');
        localStorage.removeItem('fluxo_user');
        setToken(null);
        setUser(null);
      });
    }
  }, [token]);

  // -- Dash Metrics Globais --
  const { data: apiLeads } = useLeads();
  const { data: kpiData } = useDashboardKpis();
  const leads = (apiLeads && apiLeads.data) ? apiLeads.data : window.mockLeads || [];
  
  const emAtendimento = leads.filter(l => l.stage === 'novo' || l.stage === 'qualificando' || l.stage === 'proposta').length;
  const aguardando = leads.filter(l => l.unread > 0).length;
  const revenue = kpiData ? (kpiData.pipeline.value_cents / 100).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) : '+R$ 0';

  // Pick theme
  const baseTheme = tweaks.direction === 'BLOOM' ? themeBloom : themePulse;

  // Accent variations
  const accentMap = {
    'blue-green': { primary: '#5B8DEF', primarySoft: tweaks.direction === 'BLOOM' ? '#C9D5FF' : 'rgba(91,141,239,0.14)' },
    'purple-pink': { primary: '#A78BFA', primarySoft: tweaks.direction === 'BLOOM' ? '#DEC8FF' : 'rgba(167,139,250,0.14)' },
    'orange-red': { primary: '#F59E0B', primarySoft: tweaks.direction === 'BLOOM' ? '#FFD2B0' : 'rgba(245,158,11,0.14)' },
  };
  const accent = accentMap[tweaks.accent] || accentMap['blue-green'];
  const theme = { 
    ...baseTheme, 
    ...accent, 
    name: tweaks.direction, 
    setTheme: (name) => setTweak('direction', name) 
  };

  React.useEffect(() => {
    document.body.style.background = theme.bg;
    document.body.style.color = theme.text;
    document.body.style.fontFamily = theme.fontBody;
  }, [theme.bg, theme.text]);

  const openLead = (id) => {
    setActiveLeadId(id);
    setRoute('crm');
  };

  const screens = {
    dashboard: <Dashboard onOpenLead={openLead}/>,
    kanban: <Kanban onOpenLead={openLead}/>,
    chat: <Chat activeLeadId={activeLeadId} onOpenCrm={openLead}/>,
    crm: <CrmDetail leadId={activeLeadId} onBack={() => setRoute('kanban')} onChat={() => setRoute('chat')}/>,
    dna: <DnaAssistente/>,
    customers: window.Customers ? <window.Customers onOpenLead={openLead}/> : null,
    appointments: window.Appointments ? <window.Appointments onOpenLead={openLead}/> : null,
    radar: <Radar/>,
    knowledge: <Knowledge/>,
    settings: <Settings/>,
    'admin-panel': window.AdminPanel ? <window.AdminPanel /> : null,
  };

  const isBloom = theme.name === 'BLOOM';

  if (!token) {
    return (
      <ThemeContext.Provider value={theme}>
        <LoginScreen onLoginSuccess={(tok, usr) => { setToken(tok); setUser(usr); }} />
      </ThemeContext.Provider>
    );
  }

  return (
    <ThemeContext.Provider value={theme}>
      <DialogProvider>
        <div style={{
          width: '100vw', height: '100vh', display: 'flex', overflow: 'hidden',
          background: theme.bg,
          backgroundImage: theme.bgGrid,
          backgroundSize: '24px 24px',
          color: theme.text, fontFamily: theme.fontBody,
        }}>
          <Sidebar current={route} onNavigate={setRoute}/>
          <main style={{ flex: 1, overflow: 'auto', minWidth: 0, background: theme.bg, position: 'relative' }}>
            {/* Top status strip — hidden on chat (which has its own header) */}
            {route !== 'chat' && (
              <div style={{
                position: 'sticky', top: 0, zIndex: 10,
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
                padding: '10px 28px',
                background: isBloom ? theme.bg + 'EE' : 'rgba(7,9,15,0.85)',
                backdropFilter: 'blur(10px)',
                borderBottom: isBloom ? `1.5px solid ${theme.border}` : `1px solid ${theme.border}`,
              }}>
                <div onClick={() => showToast('Configurações de status em breve!', 'info')} style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14, fontSize: 11.5, color: theme.textMuted, fontFamily: theme.fontMono, letterSpacing: '0.04em' }}>
                  <Status ok label="WhatsApp Business · online"/>
                  <span>·</span>
                  <span><strong style={{color: theme.text}}>{emAtendimento}</strong> em atendimento</span>
                  <span>·</span>
                  <span><strong style={{color: theme.text}}>{aguardando}</strong> aguardando</span>
                  <span>·</span>
                  <span style={{ color: theme.green, fontWeight: 700 }}>{revenue} hoje</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  {/* Busca Global */}
                  <div style={{ position: 'relative' }}>
                    <Icons.Search size={13} stroke={theme.textMuted} style={{ position: 'absolute', left: 9, top: 7 }}/>
                    <input 
                      placeholder="Buscar contato, conversa ou nota..." 
                      readOnly
                      onClick={() => setSearchOpen(true)}
                      style={{
                        width: 280, padding: '6px 10px 6px 28px',
                        background: isBloom ? theme.surface : 'rgba(255,255,255,0.04)',
                        border: isBloom ? `1.5px solid ${theme.border}` : `1px solid ${theme.border}`,
                        borderRadius: theme.radiusMd, color: theme.text, fontSize: 12, outline: 'none',
                        fontFamily: theme.fontBody, cursor: 'pointer'
                    }}/>
                    <span style={{
                      position: 'absolute', right: 8, top: 6, padding: '1px 6px', borderRadius: 4,
                      background: isBloom ? theme.surfaceAlt : 'rgba(255,255,255,0.06)',
                      fontFamily: theme.fontMono, fontSize: 10, color: theme.textMuted,
                      border: isBloom ? `1px solid ${theme.border}` : 'none',
                      cursor: 'pointer'
                    }} onClick={() => setSearchOpen(true)}>⌘K</span>
                  </div>

                  {/* Notificações */}
                  <div style={{ position: 'relative' }}>
                    <Btn 
                      variant="ghost" 
                      size="sm" 
                      style={{ padding: 7, position: 'relative' }} 
                      onClick={() => {
                        setNotificationsOpen(!notificationsOpen);
                        setProfileMenuOpen(false);
                      }}
                    >
                      <Icons.Bell size={15}/>
                      {hasUnreadNotifications && <span style={{ position: 'absolute', top: 5, right: 5, width: 7, height: 7, borderRadius: '50%', background: theme.orange }}/>}
                    </Btn>

                    {notificationsOpen && (
                      <div 
                        style={{
                          position: 'absolute',
                          top: 'calc(100% + 8px)',
                          right: 0,
                          width: 320,
                          background: isBloom ? '#FFFBF4' : '#0D111C',
                          border: isBloom ? `2px solid ${theme.border}` : '1px solid rgba(255, 255, 255, 0.08)',
                          borderRadius: theme.radiusMd,
                          boxShadow: isBloom ? '6px 6px 0 0 #14131A' : '0 10px 30px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.05)',
                          padding: '12px 0',
                          zIndex: 9999,
                          display: 'flex',
                          flexDirection: 'column',
                          animation: 'fadeInUp 0.2s cubic-bezier(0.16, 1, 0.3, 1)'
                        }}
                      >
                        <div style={{ padding: '4px 16px 10px', borderBottom: isBloom ? `1.5px solid ${theme.border}` : '1px solid rgba(255, 255, 255, 0.06)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                          <span style={{ fontWeight: 700, fontSize: 13, color: theme.text }}>Notificações</span>
                          {hasUnreadNotifications && (
                            <button 
                              onClick={() => {
                                setNotifications(prev => prev.map(notif => ({ ...notif, unread: false })));
                                showToast('Todas as notificações marcadas como lidas.', 'success');
                              }} 
                              style={{ background: 'transparent', border: 'none', color: theme.primary, fontSize: 11, fontWeight: 600, cursor: 'pointer', outline: 'none' }}
                            >
                              Limpar
                            </button>
                          )}
                        </div>
                        <div style={{ maxHeight: 280, overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
                          {notifications.map((n, i) => (
                            <div 
                              key={n.id || i} 
                              onClick={() => {
                                // 1. Marcar como lida
                                setNotifications(prev => prev.map(notif => notif.id === n.id ? { ...notif, unread: false } : notif));
                                setNotificationsOpen(false);

                                // 2. Redirecionar
                                if (n.targetRoute === 'crm') {
                                  openLead(n.targetLeadId);
                                } else if (n.targetRoute === 'settings') {
                                  setRoute('settings');
                                } else if (n.targetRoute === 'payment_modal') {
                                  setProfileSubModal('payment');
                                } else if (n.targetRoute === 'chat') {
                                  const leadList = (apiLeads && apiLeads.data) ? apiLeads.data : window.mockLeads || [];
                                  const maria = leadList.find(l => (l.name || '').includes('Maria')) || { id: n.targetLeadId };
                                  setActiveLeadId(maria.id);
                                  setRoute('chat');
                                }
                                showToast(`Redirecionando para: ${n.title}`, 'info');
                              }}
                              style={{
                                padding: '10px 16px',
                                borderBottom: i < notifications.length - 1 ? (isBloom ? `1.5px solid ${theme.border}` : '1px solid rgba(255, 255, 255, 0.04)') : 'none',
                                background: n.unread ? (isBloom ? 'rgba(91,141,239,0.08)' : 'rgba(91, 141, 239, 0.04)') : 'transparent',
                                display: 'flex',
                                flexDirection: 'column',
                                gap: 2,
                                cursor: 'pointer',
                                transition: 'background 0.2s'
                              }}
                              onMouseEnter={(e) => { e.currentTarget.style.background = isBloom ? theme.bg : 'rgba(255, 255, 255, 0.06)'; }}
                              onMouseLeave={(e) => { e.currentTarget.style.background = n.unread ? (isBloom ? 'rgba(91,141,239,0.08)' : 'rgba(91, 141, 239, 0.04)') : 'transparent'; }}
                            >
                              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <span style={{ fontWeight: 700, fontSize: 12, color: n.unread ? theme.primary : theme.text }}>{n.title}</span>
                                <span style={{ fontSize: 10, color: theme.textMuted, fontFamily: theme.fontMono }}>{n.time}</span>
                              </div>
                              <p style={{ margin: '2px 0 0', fontSize: 11.5, color: theme.textMuted, lineHeight: 1.4 }}>{n.desc}</p>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>

                  {/* Painel do Administrador Dropdown */}
                  <div style={{ position: 'relative' }}>
                    <div 
                      onClick={() => {
                        setProfileMenuOpen(!profileMenuOpen);
                        setNotificationsOpen(false);
                      }}
                      style={{
                        display: 'flex', alignItems: 'center', gap: 8, padding: '4px 10px 4px 4px',
                        background: isBloom ? theme.surface : 'rgba(255,255,255,0.04)',
                        border: isBloom ? `1.5px solid ${theme.border}` : `1px solid ${theme.border}`,
                        borderRadius: theme.radiusPill, cursor: 'pointer',
                        transition: 'opacity 0.2s',
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.opacity = 0.8}
                      onMouseLeave={(e) => e.currentTarget.style.opacity = 1}
                    >
                      <div style={{
                        width: 26, height: 26, borderRadius: '50%',
                        background: `linear-gradient(135deg, ${theme.orange}, ${theme.pink})`,
                        color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 11, fontWeight: 700,
                      }}>
                        {user?.avatar || (user?.name ? user.name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2) : 'US')}
                      </div>
                      <span style={{ fontSize: 12, fontWeight: 600, color: theme.text }}>
                        {user?.name || 'Usuário'}
                      </span>
                      <Icons.Logout size={12} stroke={theme.textMuted} style={{ marginLeft: 2 }} />
                    </div>

                    {profileMenuOpen && (
                      <div 
                        style={{
                          position: 'absolute',
                          top: 'calc(100% + 8px)',
                          right: 0,
                          width: 280,
                          background: isBloom ? '#FFFBF4' : '#0D111C',
                          border: isBloom ? `2px solid ${theme.border}` : '1px solid rgba(255, 255, 255, 0.08)',
                          borderRadius: theme.radiusMd,
                          boxShadow: isBloom ? '6px 6px 0 0 #14131A' : '0 10px 30px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.05)',
                          padding: '12px 0',
                          zIndex: 9999,
                          display: 'flex',
                          flexDirection: 'column',
                          animation: 'fadeInUp 0.2s cubic-bezier(0.16, 1, 0.3, 1)'
                        }}
                      >
                        <div style={{ padding: '4px 16px 12px', borderBottom: isBloom ? `1.5px solid ${theme.border}` : '1px solid rgba(255, 255, 255, 0.06)', marginBottom: 8 }}>
                          <div style={{ fontWeight: 700, fontSize: 13.5, color: theme.text }}>{user?.name || 'Admin'}</div>
                          <div style={{ fontSize: 11, color: theme.textMuted, marginTop: 2 }}>{user?.email || 'admin@fluxozap.com'}</div>
                          <div style={{ fontSize: 10, fontFamily: theme.fontMono, color: theme.green, fontWeight: 700, marginTop: 4, textTransform: 'uppercase' }}>
                            Plano {activePlan}
                          </div>
                        </div>

                        {[
                          { label: '👤 Informações Pessoais', value: 'personal' },
                          { label: '🔐 Trocar Senha, E-mail e Tel', value: 'access' },
                          { label: '💳 Pagamento de Mensalidade', value: 'payment' },
                          { label: '📈 Mudança de Plano', value: 'plan' },
                        ].map((item, idx) => (
                          <button
                            key={idx}
                            onClick={() => {
                              setProfileSubModal(item.value);
                              setProfileMenuOpen(false);
                            }}
                            style={{
                              width: '100%', padding: '9px 16px', background: 'transparent',
                              border: 'none', color: theme.text, fontSize: 12.5, fontWeight: 600,
                              textAlign: 'left', cursor: 'pointer', display: 'flex', alignItems: 'center',
                              fontFamily: theme.fontBody, transition: 'all 0.15s'
                            }}
                            onMouseEnter={(e) => { e.currentTarget.style.background = isBloom ? theme.bg : 'rgba(255, 255, 255, 0.04)'; }}
                            onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
                          >
                            {item.label}
                          </button>
                        ))}

                        <div style={{ height: 1, background: isBloom ? theme.border : 'rgba(255, 255, 255, 0.06)', margin: '8px 0' }} />

                        <div style={{ padding: '6px 16px', fontSize: 11, color: theme.textMuted, fontFamily: theme.fontMono }}>
                          ⚙️ Versão: v1.8.5 stable
                        </div>

                        <button
                          onClick={async () => {
                            setProfileMenuOpen(false);
                            if (window.confirm('Deseja realmente sair da sua conta no FluxoZap?')) {
                              localStorage.removeItem('fluxo_token');
                              localStorage.removeItem('fluxo_user');
                              setToken(null);
                              setUser(null);
                              showToast('Sessão encerrada com sucesso.', 'info');
                            }
                          }}
                          style={{
                            width: '100%', padding: '9px 16px', background: 'transparent',
                            border: 'none', color: theme.red, fontSize: 12.5, fontWeight: 700,
                            textAlign: 'left', cursor: 'pointer', display: 'flex', alignItems: 'center',
                            fontFamily: theme.fontBody, transition: 'all 0.15s'
                          }}
                          onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(239, 68, 68, 0.06)'; }}
                          onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
                        >
                          🚪 Sair do Sistema
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
            
            {/* Screen content */}
            <div style={{ position: 'relative', minHeight: 'calc(100vh - 54px)' }}>
              {screens[route] || screens.dashboard}
            </div>
          </main>

        {/* Tweaks Panel */}
        <TweaksPanel>
          <TweakSection label="Direção visual">
            <TweakRadio
              label="Estilo"
              value={tweaks.direction}
              options={[
                { label: 'PULSE', value: 'PULSE' },
                { label: 'BLOOM', value: 'BLOOM' },
              ]}
              onChange={(v) => setTweak('direction', v)}
            />
            <div style={{ fontSize: 11, color: '#888', marginTop: 4, lineHeight: 1.5, padding: '0 14px 8px' }}>
              <strong>PULSE</strong> · cockpit profissional, navy + neon, denso.<br/>
              <strong>BLOOM</strong> · neo-brutalismo cremoso, vibrante, alegre.
            </div>
          </TweakSection>

          <TweakSection label="Acento">
            <TweakSelect
              label="Paleta"
              value={tweaks.accent}
              options={[
                { label: 'Azul + Verde', value: 'blue-green' },
                { label: 'Roxo + Rosa', value: 'purple-pink' },
                { label: 'Laranja + Vermelho', value: 'orange-red' },
              ]}
              onChange={(v) => setTweak('accent', v)}
            />
          </TweakSection>

          <TweakSection label="Navegação rápida">
            <div style={{ padding: '0 14px 8px', display: 'flex', flexDirection: 'column', gap: 3 }}>
              {[
                { id: 'dashboard', l: 'Painel de Leads' },
                { id: 'kanban', l: 'Kanban CRM' },
                { id: 'chat', l: 'Conversa WhatsApp' },
                { id: 'dna', l: 'DNA da Assistente' },
                { id: 'knowledge', l: 'Base de Conhecimento' },
                { id: 'settings', l: 'Configurações' },
              ].map(s => (
                <button key={s.id} onClick={() => setRoute(s.id)} style={{
                  display: 'block', width: '100%', padding: '6px 10px',
                  background: route === s.id ? '#3a3a4a' : 'transparent',
                  color: route === s.id ? '#fff' : '#aaa',
                  border: '1px solid ' + (route === s.id ? '#555' : 'transparent'),
                  borderRadius: 6, fontSize: 12, textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit',
                }}>{s.l}</button>
              ))}
            </div>
          </TweakSection>
        </TweaksPanel>
      {/* Spotlight Search Modal (Command+K) */}
      {searchOpen && (
        <div 
          onClick={() => setSearchOpen(false)}
          style={{
            position: 'fixed', inset: 0, zIndex: 100000,
            background: 'rgba(0, 0, 0, 0.65)', backdropFilter: 'blur(5px)',
            display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
            paddingTop: '10vh', animation: 'fadeIn 0.2s ease-out'
          }}
        >
          <div 
            onClick={(e) => e.stopPropagation()}
            style={{
              width: '100%', maxWidth: 550,
              background: isBloom ? '#FFFBF4' : '#0D111C',
              border: isBloom ? `2px solid ${theme.border}` : '1px solid rgba(255, 255, 255, 0.08)',
              borderRadius: 16,
              boxShadow: isBloom ? '8px 8px 0 0 #14131A' : '0 25px 50px -12px rgba(0, 0, 0, 0.7)',
              overflow: 'hidden', display: 'flex', flexDirection: 'column',
              animation: 'scaleIn 0.25s cubic-bezier(0.16, 1, 0.3, 1)'
            }}
          >
            {/* Search Header */}
            <div style={{ display: 'flex', alignItems: 'center', padding: '14px 18px', borderBottom: isBloom ? `1.5px solid ${theme.border}` : '1px solid rgba(255, 255, 255, 0.06)', gap: 10 }}>
              <Icons.Search size={18} stroke={theme.textMuted} />
              <input 
                autoFocus
                placeholder="Buscar leads por nome, telefone, canal ou tag..." 
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                style={{
                  flex: 1, border: 'none', background: 'transparent',
                  color: theme.text, fontSize: 14.5, outline: 'none', fontFamily: theme.fontBody
                }}
              />
              <span style={{ fontSize: 10, fontFamily: theme.fontMono, color: theme.textMuted }}>ESC para fechar</span>
            </div>

            {/* Search Results */}
            <div style={{ maxHeight: 360, overflowY: 'auto', padding: 8, display: 'flex', flexDirection: 'column', gap: 2 }}>
              {leads.filter(l => {
                if (!searchQuery) return true;
                const q = searchQuery.toLowerCase();
                return (l.name || '').toLowerCase().includes(q) || 
                       (l.phone || '').includes(q) || 
                       (l.city || '').toLowerCase().includes(q) ||
                       (l.tags && l.tags.some(t => t.toLowerCase().includes(q)));
              }).slice(0, 8).map((l, i) => (
                <div 
                  key={l.id || i}
                  onClick={() => {
                    openLead(l.id);
                    setSearchOpen(false);
                    setSearchQuery('');
                  }}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px',
                    borderRadius: theme.radiusMd, cursor: 'pointer', transition: 'all 0.15s'
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.background = isBloom ? theme.bg : 'rgba(255, 255, 255, 0.04)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
                >
                  <Avatar name={l.avatar} color={l.color} size={32} ai={l.aiActive} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 13, color: theme.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{l.name}</div>
                    <div style={{ fontSize: 11, color: theme.textMuted, fontFamily: theme.fontMono }}>{l.phone} · {l.city}</div>
                  </div>
                  <Pill soft={theme.primarySoft} color={theme.primary} style={{ fontSize: 10, padding: '1px 6px' }}>{l.stage}</Pill>
                </div>
              ))}

              {leads.filter(l => {
                if (!searchQuery) return true;
                const q = searchQuery.toLowerCase();
                return (l.name || '').toLowerCase().includes(q) || (l.phone || '').includes(q) || (l.city || '').toLowerCase().includes(q);
              }).length === 0 && (
                <div style={{ padding: '24px 16px', textAlign: 'center', color: theme.textMuted, fontSize: 13 }}>
                  Nenhum contato encontrado para "{searchQuery}"
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Profile settings submodals */}
      {/* 👤 Informações Pessoais */}
      {profileSubModal === 'personal' && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 101000, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Card style={{ width: '100%', maxWidth: 420, padding: 24, background: isBloom ? theme.surface : theme.surfaceAlt }}>
            <h3 style={{ margin: '0 0 16px', fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text }}>👤 Informações Pessoais</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <label style={{ fontSize: 11, fontWeight: 700, color: theme.textMuted }}>NOME COMPLETO</label>
                <input type="text" value={user?.name || ''} onChange={(e) => setUser({ ...user, name: e.target.value })} style={{ width: '100%', padding: '10px 12px', marginTop: 4, background: isBloom ? '#FFF' : 'rgba(255,255,255,0.03)', border: `1.5px solid ${theme.border}`, borderRadius: theme.radiusMd, color: theme.text, fontSize: 13, outline: 'none' }} />
              </div>
              <div>
                <label style={{ fontSize: 11, fontWeight: 700, color: theme.textMuted }}>FUNÇÃO / ROLE</label>
                <input type="text" value="Proprietário (Owner)" disabled style={{ width: '100%', padding: '10px 12px', marginTop: 4, background: 'rgba(255,255,255,0.02)', border: `1.5px solid ${theme.border}`, borderRadius: theme.radiusMd, color: theme.textMuted, fontSize: 13 }} />
              </div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
                <Btn variant="ghost" onClick={() => setProfileSubModal(null)}>Cancelar</Btn>
                <Btn variant="primary" onClick={() => { localStorage.setItem('fluxo_user', JSON.stringify(user)); setProfileSubModal(null); showToast('Nome alterado com sucesso!', 'success'); }}>Salvar Alterações</Btn>
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* 🔐 Trocar Senha, E-mail e Tel */}
      {profileSubModal === 'access' && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 101000, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Card style={{ width: '100%', maxWidth: 420, padding: 24, background: isBloom ? theme.surface : theme.surfaceAlt }}>
            <h3 style={{ margin: '0 0 16px', fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text }}>🔐 Trocar Senha, E-mail e Tel</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <label style={{ fontSize: 11, fontWeight: 700, color: theme.textMuted }}>NOVO E-MAIL</label>
                <input type="email" placeholder="seu-email@fluxozap.com" style={{ width: '100%', padding: '10px 12px', marginTop: 4, background: isBloom ? '#FFF' : 'rgba(255,255,255,0.03)', border: `1.5px solid ${theme.border}`, borderRadius: theme.radiusMd, color: theme.text, fontSize: 13, outline: 'none' }} />
              </div>
              <div>
                <label style={{ fontSize: 11, fontWeight: 700, color: theme.textMuted }}>NOVO TELEFONE</label>
                <input type="text" placeholder="+55 (41) 99999-9999" style={{ width: '100%', padding: '10px 12px', marginTop: 4, background: isBloom ? '#FFF' : 'rgba(255,255,255,0.03)', border: `1.5px solid ${theme.border}`, borderRadius: theme.radiusMd, color: theme.text, fontSize: 13, outline: 'none' }} />
              </div>
              <div>
                <label style={{ fontSize: 11, fontWeight: 700, color: theme.textMuted }}>NOVA SENHA</label>
                <input type="password" placeholder="Mínimo 6 caracteres" style={{ width: '100%', padding: '10px 12px', marginTop: 4, background: isBloom ? '#FFF' : 'rgba(255,255,255,0.03)', border: `1.5px solid ${theme.border}`, borderRadius: theme.radiusMd, color: theme.text, fontSize: 13, outline: 'none' }} />
              </div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
                <Btn variant="ghost" onClick={() => setProfileSubModal(null)}>Cancelar</Btn>
                <Btn variant="primary" onClick={() => { setProfileSubModal(null); showToast('Dados de acesso atualizados com sucesso!', 'success'); }}>Atualizar Acesso</Btn>
              </div>
            </div>
          </Card>
        </div>
      )}

      {/* 💳 Pagamento de Mensalidade */}
      {profileSubModal === 'payment' && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 101000, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Card style={{ width: '100%', maxWidth: 440, padding: 24, background: isBloom ? theme.surface : theme.surfaceAlt }}>
            <h3 style={{ margin: '0 0 16px', fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text }}>💳 Pagamento de Mensalidade</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {isEditingCard ? (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  <div style={{ fontSize: 11.5, fontWeight: 700, color: theme.textMuted, letterSpacing: '0.04em' }}>📝 ALTERAR CARTÃO DE CRÉDITO</div>
                  <div>
                    <label style={{ fontSize: 10, fontWeight: 700, color: theme.textMuted }}>NÚMERO DO CARTÃO</label>
                    <input 
                      type="text" 
                      placeholder="**** **** **** 4321" 
                      value={editCardNum}
                      onChange={e => setEditCardNum(e.target.value.replace(/\D/g, '').slice(0, 16))}
                      style={{ width: '100%', padding: '10px 12px', marginTop: 4, background: isBloom ? '#FFF' : 'rgba(255,255,255,0.03)', border: `1.5px solid ${theme.border}`, borderRadius: theme.radiusMd, color: theme.text, fontSize: 13, outline: 'none' }}
                    />
                  </div>
                  <div>
                    <label style={{ fontSize: 10, fontWeight: 700, color: theme.textMuted }}>NOME IMPRESSO</label>
                    <input 
                      type="text" 
                      placeholder={user?.name ? user.name.toUpperCase() : "ADMINISTRADOR"} 
                      value={editCardHolder}
                      onChange={e => setEditCardHolder(e.target.value.toUpperCase())}
                      style={{ width: '100%', padding: '10px 12px', marginTop: 4, background: isBloom ? '#FFF' : 'rgba(255,255,255,0.03)', border: `1.5px solid ${theme.border}`, borderRadius: theme.radiusMd, color: theme.text, fontSize: 13, outline: 'none' }}
                    />
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                    <div>
                      <label style={{ fontSize: 10, fontWeight: 700, color: theme.textMuted }}>VALIDADE (MM/AA)</label>
                      <input 
                        type="text" 
                        placeholder="12/29" 
                        value={editCardExpiry}
                        onChange={e => setEditCardExpiry(e.target.value.slice(0, 5))}
                        style={{ width: '100%', padding: '10px 12px', marginTop: 4, background: isBloom ? '#FFF' : 'rgba(255,255,255,0.03)', border: `1.5px solid ${theme.border}`, borderRadius: theme.radiusMd, color: theme.text, fontSize: 13, outline: 'none' }}
                      />
                    </div>
                    <div>
                      <label style={{ fontSize: 10, fontWeight: 700, color: theme.textMuted }}>CVV</label>
                      <input 
                        type="password" 
                        placeholder="***" 
                        value={editCardCvv}
                        onChange={e => setEditCardCvv(e.target.value.replace(/\D/g, '').slice(0, 3))}
                        style={{ width: '100%', padding: '10px 12px', marginTop: 4, background: isBloom ? '#FFF' : 'rgba(255,255,255,0.03)', border: `1.5px solid ${theme.border}`, borderRadius: theme.radiusMd, color: theme.text, fontSize: 13, outline: 'none' }}
                      />
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
                    <Btn variant="ghost" onClick={() => setIsEditingCard(false)}>Cancelar</Btn>
                    <Btn variant="primary" onClick={() => {
                      if (editCardNum.length < 4) {
                        showToast('Digite pelo menos os 4 últimos dígitos do cartão.', 'error');
                        return;
                      }
                      const lastDigits = editCardNum.slice(-4);
                      setCardLastDigits(lastDigits);
                      localStorage.setItem('fluxo_card_last', lastDigits);
                      if (editCardHolder) {
                        setCardHolder(editCardHolder);
                        localStorage.setItem('fluxo_card_holder', editCardHolder);
                      }
                      setIsEditingCard(false);
                      showToast('Cartão de crédito atualizado com sucesso!', 'success');
                    }}>Salvar Cartão</Btn>
                  </div>
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <div style={{ padding: 16, background: 'rgba(255,255,255,0.03)', borderRadius: 12, border: `1px solid ${theme.border}` }}>
                    <div style={{ fontSize: 11, fontWeight: 700, color: theme.textMuted, fontFamily: theme.fontMono }}>STATUS DA ASSINATURA</div>
                    <div style={{ fontSize: 16, fontWeight: 700, color: theme.green, marginTop: 4 }}>✓ Ativo · Renovação automática</div>
                    <div style={{ fontSize: 13, color: theme.text, marginTop: 8 }}>
                      Plano: <strong style={{ color: theme.primary }}>Plano {activePlan}</strong>
                    </div>
                    <div style={{ fontSize: 13, color: theme.text, marginTop: 4 }}>
                      Próxima mensalidade vence em: <strong>{getBillingDate()}</strong>
                    </div>
                    <div style={{ fontSize: 13, color: theme.text, marginTop: 4 }}>
                      Valor: <strong>{getPlanPrice()} / mês</strong>
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 14px', background: 'rgba(255,255,255,0.02)', borderRadius: 8, border: `1px solid ${theme.border}` }}>
                    <span style={{ fontSize: 13 }}>💳 Cartão final <strong>**** {cardLastDigits}</strong> ({cardHolder})</span>
                    <button onClick={() => {
                      setEditCardNum('');
                      setEditCardHolder(cardHolder);
                      setEditCardExpiry('');
                      setEditCardCvv('');
                      setIsEditingCard(true);
                    }} style={{ background: 'transparent', border: 'none', color: theme.primary, fontWeight: 600, fontSize: 12, cursor: 'pointer', outline: 'none' }}>Alterar</button>
                  </div>
                  <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 8 }}>
                    <Btn variant="ghost" onClick={() => setProfileSubModal(null)}>Fechar</Btn>
                    <Btn 
                      variant="primary" 
                      loading={isProcessingPayment}
                      onClick={() => {
                        setIsProcessingPayment(true);
                        setTimeout(() => {
                          setIsProcessingPayment(false);
                          setBillingMonthOffset(prev => prev + 1);
                          localStorage.setItem('fluxo_billing_offset', String(billingMonthOffset + 1));
                          showToast(`Fatura de ${getPlanPrice()} processada com sucesso no cartão **** ${cardLastDigits}! Próximo vencimento atualizado.`, 'success');
                        }, 2000);
                      }}
                    >
                      Pagar Fatura Agora
                    </Btn>
                  </div>
                </div>
              )}
            </div>
          </Card>
        </div>
      )}

      {/* 📈 Mudança de Plano */}
      {profileSubModal === 'plan' && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 101000, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Card style={{ width: '100%', maxWidth: 500, padding: 24, background: isBloom ? theme.surface : theme.surfaceAlt }}>
            <h3 style={{ margin: '0 0 16px', fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text }}>📈 Mudança de Plano</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {[
                { name: 'Starter', price: 'R$ 147', desc: '1 número de WhatsApp e 500 leads ativos.', active: activePlan === 'Starter' },
                { name: 'Pro', price: 'R$ 297', desc: 'Até 3 números, Assistente IA ilimitada e CRM avançado.', active: activePlan === 'Pro' },
                { name: 'Enterprise', price: 'R$ 799', desc: 'Números ilimitados, APIs customizadas e SLA dedicado.', active: activePlan === 'Enterprise' },
              ].map((plan, i) => (
                <div 
                  key={i} 
                  style={{
                    padding: 14, borderRadius: 12,
                    border: plan.active ? `2px solid ${theme.primary}` : `1px solid ${theme.border}`,
                    background: plan.active ? 'rgba(91,141,239,0.06)' : 'rgba(255,255,255,0.02)',
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center'
                  }}
                >
                  <div style={{ flex: 1, paddingRight: 10 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ fontWeight: 700, fontSize: 14, color: theme.text }}>Plano {plan.name}</span>
                      {plan.active && <Pill soft={theme.primarySoft} color={theme.primary} style={{ fontSize: 9, padding: '1px 6px' }}>Atual</Pill>}
                    </div>
                    <p style={{ margin: '4px 0 0', fontSize: 12, color: theme.textMuted, lineHeight: 1.35 }}>{plan.desc}</p>
                  </div>
                  <div style={{ textAlign: 'right', flexShrink: 0 }}>
                    <div style={{ fontSize: 16, fontWeight: 700, color: theme.text }}>{plan.price}<span style={{ fontSize: 10, fontWeight: 500 }}>/mês</span></div>
                    {!plan.active && (
                      <button 
                        onClick={() => {
                          setActivePlan(plan.name);
                          localStorage.setItem('fluxo_active_plan', plan.name);
                          setProfileSubModal('payment');
                          showToast(`Plano alterado para ${plan.name} com sucesso!`, 'success');
                        }}
                        style={{ marginTop: 6, padding: '4px 10px', background: theme.primary, border: 'none', borderRadius: 6, color: '#fff', fontSize: 11, fontWeight: 600, cursor: 'pointer', outline: 'none' }}
                      >
                        Selecionar
                      </button>
                    )}
                  </div>
                </div>
              ))}
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 8 }}>
                <Btn variant="ghost" onClick={() => setProfileSubModal(null)}>Fechar</Btn>
              </div>
            </div>
          </Card>
        </div>
      )}
      </div>
      </DialogProvider>
    </ThemeContext.Provider>
  );
};

// Wait for all components to load before mounting
const mount = () => {
  if (!window.Dashboard || !window.Kanban || !window.Chat || !window.CrmDetail ||
      !window.DnaAssistente || !window.Knowledge || !window.Settings ||
      !window.Sidebar || !window.TweaksPanel || !window.useTweaks || !window.ToastProvider ||
      !window.Customers || !window.Appointments || !window.AdminPanel) {
    setTimeout(mount, 30);
    return;
  }
  ReactDOM.createRoot(document.getElementById('root')).render(
    <ToastProvider>
      <App/>
    </ToastProvider>
  );
};
mount();
