/* Configurações */

const Settings = () => {
  const t = useTheme();
  const { showToast } = useToast();
  const isBloom = t.name === 'BLOOM';
  const [section, setSection] = React.useState('integracoes');

  const { data: integrationsData } = useIntegrations();
  const integrations = integrationsData || [];
  const { data: apiKeysData } = useApiKeys();
  const apiKeys = apiKeysData || [];
  
  const { data: notifsData } = typeof useNotifications !== 'undefined' ? useNotifications() : { data: null };
  const updateNotifs = typeof useUpdateNotifications !== 'undefined' ? useUpdateNotifications() : { run: async () => {} };

  const { data: teamData, loading: teamLoading } = typeof useTeam !== 'undefined' ? useTeam() : { data: null, loading: false };
  const team = Array.isArray(teamData) ? teamData : (teamData?.data || []);
  const inviteMember = typeof useInviteTeamMember !== 'undefined' ? useInviteTeamMember() : async () => {};
  const removeMember = typeof useRemoveTeamMember !== 'undefined' ? useRemoveTeamMember() : async () => {};

  // ── IA Config hooks ──
  const { data: aiConfigData } = typeof useAiConfig !== 'undefined' ? useAiConfig() : { data: null };
  const updateAiConfigFn = typeof useUpdateAiConfig !== 'undefined' ? useUpdateAiConfig() : async () => {};

  const [iaTone, setIaTone] = React.useState('Profissional e Direto');
  const [iaPrompt, setIaPrompt] = React.useState('');
  const [iaRestrictions, setIaRestrictions] = React.useState([true, true, false]);
  const [timezone, setTimezone] = React.useState(localStorage.getItem('fluxozap_tz') || 'America/Sao_Paulo');

  React.useEffect(() => {
    if (aiConfigData) {
      setIaTone(aiConfigData.tone || 'Profissional e Direto');
      setIaPrompt(aiConfigData.mission || '');
      try {
        const b = JSON.parse(aiConfigData.behavior || '{}');
        setIaRestrictions([b.allowLinks !== false, b.humanEscalation !== false, b.dynamicDiscounts === true]);
        if (b.timezone) {
          setTimezone(b.timezone);
          localStorage.setItem('fluxozap_tz', b.timezone);
        }
      } catch(e) {}
    }
  }, [aiConfigData]);

  const [tokensData, setTokensData] = React.useState({ used: 45200, limit: 100000 });
  React.useEffect(() => {
    fetch('/api/settings/tokens')
      .then(res => res.json())
      .then(data => {
        if(data && typeof data.used !== 'undefined') setTokensData(data);
      })
      .catch(err => console.error("Error fetching tokens:", err));
  }, []);

  // ── Estados e Handlers para Recarga Pré-paga de IA (Combustível Pix) ──
  const [rechargeModalOpen, setRechargeModalOpen] = React.useState(false);
  const [selectedPackage, setSelectedPackage] = React.useState(null); // { name, tokens, price }
  const [pixStep, setPixStep] = React.useState(1); // 1: Selecionar, 2: Pix QR, 3: Sucesso
  const [loadingPayment, setLoadingPayment] = React.useState(false);

  const handleConfirmRecharge = async () => {
    if (!selectedPackage) return;
    setLoadingPayment(true);
    showToast('Validando recebimento do Pix em tempo real...', 'info');
    
    try {
      const res = await fetch('/api/settings/recharge', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('fluxo_token')}`
        },
        body: JSON.stringify({ amount: selectedPackage.tokens })
      });
      
      if (res.ok) {
        const data = await res.json();
        // Atualiza o progresso local imediatamente
        setTokensData({ used: data.used, limit: data.limit });
        setPixStep(3);
        showToast('Combustível de IA recarregado com sucesso!', 'success');
      } else {
        showToast('Erro ao validar pagamento do Pix. Tente novamente.', 'error');
      }
    } catch(err) {
      showToast('Erro de conexão ao validar recarga.', 'error');
    } finally {
      setLoadingPayment(false);
    }
  };


  const connectIntegration = useConnectIntegration();
  const disconnectIntegration = useDisconnectIntegration();
  const createApiKey = useCreateApiKey();
  const revokeApiKey = useRevokeApiKey();
  const { prompt, confirm } = useDialog();

  return (
    <div style={{ padding: '24px 28px 40px', maxWidth: 1320, margin: '0 auto' }}>
      <div style={{ marginBottom: 20 }}>
        <div style={{ fontSize: 11, color: t.textMuted, letterSpacing: '0.14em', fontFamily: t.fontMono, marginBottom: 4 }}>
          CONTA
        </div>
        <h1 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em', color: t.text }}>
          Configurações
        </h1>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 18 }}>
        {/* Settings nav */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {[
            { id: 'integracoes', label: 'Integrações', icon: 'Plug' },
            { id: 'ia', label: 'Comportamento da IA', icon: 'Sparkles' },
            { id: 'time', label: 'Equipe e permissões', icon: 'Users' },
            { id: 'horario', label: 'Horários e SLA', icon: 'Clock' },
            { id: 'notif', label: 'Notificações', icon: 'Bell' },
            { id: 'plano', label: 'Plano e cobrança', icon: 'Money' },
            { id: 'seg', label: 'Segurança & LGPD', icon: 'Settings' },
          ].map(item => {
            const I = Icons[item.icon];
            const active = section === item.id;
            return (
              <button key={item.id} onClick={() => setSection(item.id)} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '10px 12px', textAlign: 'left',
                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'}` : '1px solid transparent',
                borderRadius: t.radiusMd, fontSize: 13, fontWeight: 600,
                fontFamily: t.fontBody, cursor: 'pointer', letterSpacing: '-0.01em',
                boxShadow: isBloom && active ? '3px 3px 0 0 #14131A' : 'none',
              }}>
                <I size={15} stroke={active ? (isBloom ? t.surface : t.primary) : t.textMuted}/>
                {item.label}
              </button>
            );
          })}
        </div>

        {/* Content */}
        <div>
          {section === 'integracoes' && (
            <>
              <Card style={{ padding: 0, overflow: 'hidden', marginBottom: 18 }}>
                <div style={{ padding: '18px 22px',
                  borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
                }}>
                  <h2 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 20, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                    Integrações
                  </h2>
                  <div style={{ fontSize: 13, color: t.textMuted, marginTop: 4 }}>
                    Conecte ferramentas que você já usa para a Assistente trabalhar com elas.
                  </div>
                </div>
                {integrations.map((ig, i) => {
                  const I = Icons[ig.icon];
                  return (
                    <div key={i} style={{
                      display: 'flex', alignItems: 'center', gap: 16,
                      padding: '16px 22px',
                      borderBottom: i < integrations.length - 1 ? (isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`) : 'none',
                    }}>
                      <div style={{
                        width: 42, height: 42, borderRadius: isBloom ? 10 : 10,
                        background: ig.logo, color: '#fff',
                        border: isBloom ? `1.5px solid ${t.border}` : 'none',
                        display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                        boxShadow: isBloom ? '3px 3px 0 0 #14131A' : 'none',
                      }}>
                        <I size={20} stroke="#fff" fill={ig.icon === 'Whatsapp' ? '#fff' : 'none'}/>
                      </div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{ig.name}</div>
                        <div style={{ fontSize: 12, color: t.textMuted, marginTop: 2 }}>{ig.desc}</div>
                      </div>
                      <Pill soft={ig.status === 'conectado' ? t.greenSoft : (isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.04)')} color={isBloom ? t.text : (ig.status === 'conectado' ? t.green : t.textMuted)}>
                        <span style={{width:6,height:6,borderRadius:'50%',background:ig.status === 'conectado' ? t.green : t.textMuted}}/>{ig.status}
                      </Pill>
                      <Btn variant={ig.status === 'conectado' ? 'secondary' : 'primary'} size="sm" onClick={async () => {
                        if (ig.status === 'conectado') {
                          if (await confirm(`Deseja revogar o acesso da ferramenta ${ig.name}? Isso irá pausar todas as operações da IA nela.`)) {
                            await disconnectIntegration(ig.provider);
                            showToast(`Integração com ${ig.name} desconectada.`);
                          }
                        } else {
                          const apiKey = await prompt(`Para conectar o ${ig.name}, cole aqui seu Token de Acesso (API Key):`);
                          if (apiKey) {
                            await connectIntegration(ig.provider, apiKey);
                            showToast(`${ig.name} conectado com sucesso!`, 'success');
                          }
                        }
                      }}>
                        {ig.status === 'conectado' ? 'Gerenciar' : 'Conectar'}
                      </Btn>
                    </div>
                  );
                })}
              </Card>

              {/* API + Webhooks */}
              <Card style={{ padding: 22 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
                  <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 17, fontWeight: 700, color: t.text, letterSpacing: '-0.02em' }}>
                    API & Webhooks
                  </h3>
                  <Btn variant="ghost" size="sm" icon={<Icons.Plus size={12}/>} onClick={async () => {
                    const label = await prompt("Dê um nome para a nova chave de API (Ex: Integração ERP, Zapier):");
                    if (label) {
                      await createApiKey(label);
                      showToast('Nova chave gerada com sucesso!', 'success');
                    }
                  }}>Nova chave</Btn>
                </div>
                {apiKeys.length === 0 && (
                  <div style={{ padding: 20, textAlign: 'center', color: t.textMuted, fontSize: 13 }}>
                    Nenhuma chave de API ativa.
                  </div>
                )}
                {apiKeys.map((k) => (
                  <div key={k.id} style={{
                    padding: 14, borderRadius: t.radiusMd, marginBottom: 8,
                    background: isBloom ? t.bg : 'rgba(255,255,255,0.025)',
                    border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
                    fontFamily: t.fontMono, fontSize: 12, color: t.text,
                    display: 'flex', alignItems: 'center', gap: 12,
                  }}>
                    <Icons.Plug size={14} stroke={t.green}/>
                    <span style={{ flex: 1, letterSpacing: '0.02em', wordBreak: 'break-all' }}>{k.key}</span>
                    <span style={{ fontSize: 10, color: t.textMuted, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                      CRIADA {new Date(k.createdAt).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' })}
                    </span>
                    <Btn variant="ghost" size="sm" onClick={() => {
                      navigator.clipboard.writeText(k.key);
                      showToast('Chave copiada para a área de transferência!');
                    }}>Copiar</Btn>
                    <Btn variant="ghost" size="sm" onClick={async () => {
                      if (await confirm(`Deseja revogar permanentemente a chave "${k.label}"? Sistemas dependentes irão parar de funcionar imediatamente.`)) {
                        await revokeApiKey(k.id);
                        showToast('Chave revogada e destruída.');
                      }
                    }}>Revogar</Btn>
                  </div>
                ))}
              </Card>
            </>
          )}

          {section === 'horario' && (
            <Card style={{ padding: 22 }}>
              <h2 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 20, fontWeight: 700, color: t.text }}>Fuso-Horário do Sistema</h2>
              <div style={{ marginTop: 10, color: t.textMuted, fontSize: 13, lineHeight: 1.5 }}>
                Este fuso-horário é a fonte de verdade (Source of Truth) e será utilizado em todas as interações da Inteligência Artificial, verificação de horário de expediente e gravação de datas nos Relatórios Gerenciais Exportados.
              </div>
              <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 10 }}>
                <label style={{ fontSize: 12, fontWeight: 600, color: t.text, fontFamily: t.fontMono }}>FUSO-HORÁRIO OFICIAL</label>
                <select value={timezone} onChange={(e) => setTimezone(e.target.value)} style={{ 
                  padding: '10px 14px', 
                  background: isBloom ? t.surface : 'rgba(255,255,255,0.04)', 
                  border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`, 
                  borderRadius: t.radiusMd, 
                  color: t.text, 
                  fontFamily: t.fontBody,
                  fontSize: 14,
                  width: '100%',
                  maxWidth: 400,
                  outline: 'none'
                }}>
                  <option value="America/Sao_Paulo" style={{ background: '#1A1A24', color: '#FFF' }}>Horário de Brasília (America/Sao_Paulo)</option>
                  <option value="America/Manaus" style={{ background: '#1A1A24', color: '#FFF' }}>Horário do Amazonas (America/Manaus)</option>
                  <option value="America/Rio_Branco" style={{ background: '#1A1A24', color: '#FFF' }}>Horário do Acre (America/Rio_Branco)</option>
                  <option value="America/Maceio" style={{ background: '#1A1A24', color: '#FFF' }}>Horário de Alagoas (America/Maceio)</option>
                  <option value="America/Recife" style={{ background: '#1A1A24', color: '#FFF' }}>Horário de Pernambuco (America/Recife)</option>
                </select>
                <div style={{ marginTop: 14 }}>
                  <Btn variant="primary" onClick={async () => {
                    try {
                      const currentBehavior = aiConfigData ? JSON.parse(aiConfigData.behavior || '{}') : {};
                      await updateAiConfigFn({
                        behavior: JSON.stringify({
                          ...currentBehavior,
                          timezone: timezone
                        })
                      });
                      localStorage.setItem('fluxozap_tz', timezone);
                      showToast('Preferências de fuso-horário salvas com sucesso!', 'success');
                    } catch(e) {
                      showToast('Erro ao salvar preferências de fuso-horário.', 'error');
                    }
                  }}>Salvar Preferências</Btn>
                </div>
              </div>
            </Card>
          )}

          {section === 'ia' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <Card style={{ padding: 22 }}>
                <h2 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 20, fontWeight: 700, color: t.text }}>Personalidade & Comportamento</h2>
                <div style={{ marginTop: 8, color: t.textMuted, fontSize: 13, lineHeight: 1.5 }}>
                  Ajuste como a Inteligência Artificial responde aos seus clientes, definindo seu comportamento e tom de voz.
                </div>
                
                <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 8 }}>
                  <label style={{ fontSize: 12, fontWeight: 600, color: t.text, fontFamily: t.fontMono }}>TOM DE VOZ</label>
                  <select value={iaTone} onChange={(e) => setIaTone(e.target.value)} style={{ padding: '10px 14px', background: isBloom ? t.surface : 'rgba(255,255,255,0.04)', border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`, borderRadius: t.radiusMd, color: t.text, fontFamily: t.fontBody, outline: 'none' }}>
                    <option value="Profissional e Direto" style={{ background: '#1A1A24', color: '#FFF' }}>Profissional e Direto</option>
                    <option value="Amigável e Descontraído" style={{ background: '#1A1A24', color: '#FFF' }}>Amigável e Descontraído</option>
                    <option value="Empático e Acolhedor" style={{ background: '#1A1A24', color: '#FFF' }}>Empático e Acolhedor</option>
                    <option value="Técnico e Especialista" style={{ background: '#1A1A24', color: '#FFF' }}>Técnico e Especialista</option>
                  </select>
                </div>

                <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 8 }}>
                  <label style={{ fontSize: 12, fontWeight: 600, color: t.text, fontFamily: t.fontMono }}>PROMPT DO SISTEMA (INSTRUÇÕES GERAIS)</label>
                  <textarea rows="4" value={iaPrompt} onChange={(e) => setIaPrompt(e.target.value)} style={{ padding: '12px 14px', background: isBloom ? t.surface : 'rgba(255,255,255,0.04)', border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`, borderRadius: t.radiusMd, color: t.text, fontFamily: t.fontBody, outline: 'none', resize: 'vertical' }} placeholder="Descreva as instruções gerais da IA..." />
                </div>

                <div style={{ marginTop: 20 }}>
                  <Btn variant="primary" onClick={async () => {
                    try {
                      await updateAiConfigFn({ tone: iaTone, mission: iaPrompt, behavior: JSON.stringify({ allowLinks: iaRestrictions[0], humanEscalation: iaRestrictions[1], dynamicDiscounts: iaRestrictions[2] }) });
                      showToast('Configurações da IA salvas com sucesso!', 'success');
                    } catch(e) { showToast('Erro ao salvar configurações.', 'error'); }
                  }}>Salvar Comportamento</Btn>
                </div>
              </Card>

              <Card style={{ padding: 22 }}>
                <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 17, fontWeight: 700, color: t.text }}>Restrições de Resposta</h3>
                <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 14 }}>
                  {[
                    { label: 'Permitir que a IA envie links externos', key: 0 },
                    { label: 'Recuar e chamar um humano se o cliente se irritar', key: 1 },
                    { label: 'Oferecer descontos dinâmicos', key: 2 },
                  ].map((rule) => (
                    <div key={rule.key} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', background: isBloom ? t.bg : 'rgba(255,255,255,0.02)', borderRadius: t.radiusMd, border: isBloom ? `1px solid ${t.border}` : 'none' }}>
                      <div style={{ fontSize: 14, color: t.text, fontWeight: 500 }}>{rule.label}</div>
                      <div style={{ width: 36, height: 20, background: iaRestrictions[rule.key] ? t.green : (isBloom ? t.border : 'rgba(255,255,255,0.1)'), borderRadius: 20, position: 'relative', cursor: 'pointer' }} onClick={() => { const copy = [...iaRestrictions]; copy[rule.key] = !copy[rule.key]; setIaRestrictions(copy); }}>
                        <div style={{ width: 16, height: 16, background: '#fff', borderRadius: '50%', position: 'absolute', top: 2, left: iaRestrictions[rule.key] ? 18 : 2, transition: '0.2s' }} />
                      </div>
                    </div>
                  ))}
                </div>
              </Card>
            </div>
          )}

          {section === 'time' && (
            <Card style={{ padding: 0, overflow: 'hidden' }}>
              <div style={{ padding: '22px', borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <h2 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 20, fontWeight: 700, color: t.text }}>Equipe e Permissões</h2>
                  <div style={{ fontSize: 13, color: t.textMuted, marginTop: 4 }}>Gerencie quem tem acesso ao sistema e defina seus papéis.</div>
                </div>
                <Btn variant="primary" onClick={async () => {
                  const email = await prompt('Digite o e-mail do novo membro para enviar o convite:');
                  if (email) {
                    const role = await prompt('Digite o papel (Vendedor, Operador):') || 'Vendedor';
                    const name = await prompt('Digite o nome do membro:') || email.split('@')[0];
                    try {
                      await inviteMember({ email, role, name });
                      showToast(`Convite enviado e membro adicionado!`, 'success');
                    } catch (e) {
                      showToast('Erro ao convidar membro. E-mail já existe?', 'error');
                    }
                  }
                }}>Convidar Membro</Btn>
              </div>
              
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                {teamLoading && <div style={{ padding: 22, color: t.textMuted }}>Carregando equipe...</div>}
                {!teamLoading && team.length === 0 && <div style={{ padding: 22, color: t.textMuted }}>Nenhum membro encontrado.</div>}
                {!teamLoading && team.map((user, i) => (
                  <div key={user.id} style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '16px 22px', borderBottom: i < team.length - 1 ? `1px solid ${t.border}` : 'none' }}>
                    <img src={user.avatar} alt="Avatar" style={{ width: 40, height: 40, borderRadius: '50%', border: `1px solid ${t.border}` }} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{user.name}</div>
                      <div style={{ fontSize: 13, color: t.textMuted }}>{user.email}</div>
                    </div>
                    <Pill soft color={t.textMuted}>{user.role}</Pill>
                    {user.role !== 'Proprietário' && (
                      <Btn variant="ghost" size="sm" onClick={async () => {
                        if (await confirm(`Tem certeza que deseja remover ${user.name} da equipe?`)) {
                          try {
                            await removeMember(user.id);
                            showToast('Usuário removido da equipe.', 'success');
                          } catch (e) {
                            showToast('Erro ao remover usuário.', 'error');
                          }
                        }
                      }}>Remover</Btn>
                    )}
                  </div>
                ))}
              </div>
            </Card>
          )}

          {section === 'notif' && (
            <Card style={{ padding: 22 }}>
              <h2 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 20, fontWeight: 700, color: t.text }}>Central de Notificações</h2>
              <div style={{ marginTop: 8, color: t.textMuted, fontSize: 13, lineHeight: 1.5, marginBottom: 24 }}>
                Controle onde e quando você deseja ser avisado sobre atualizações no CRM.
              </div>

              {notifsData && (
                <div style={{ marginBottom: 30, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <label style={{ fontSize: 12, fontWeight: 600, color: t.textMuted }}>E-mail para notificações</label>
                    <input 
                      type="email" 
                      value={notifsData.email} 
                      onChange={(e) => updateNotifs.run({ email: e.target.value })}
                      style={{ background: isBloom ? t.bg : '#14141A', border: `1px solid ${t.border}`, color: t.text, padding: '10px 14px', borderRadius: t.radiusMd, outline: 'none' }} 
                    />
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <label style={{ fontSize: 12, fontWeight: 600, color: t.textMuted }}>WhatsApp para notificações</label>
                    <input 
                      type="text" 
                      value={notifsData.whatsapp} 
                      onChange={(e) => updateNotifs.run({ whatsapp: e.target.value })}
                      style={{ background: isBloom ? t.bg : '#14141A', border: `1px solid ${t.border}`, color: t.text, padding: '10px 14px', borderRadius: t.radiusMd, outline: 'none' }} 
                    />
                  </div>
                </div>
              )}

              {notifsData && notifsData.preferences.map((item, i) => {
                const titles = {
                  "leads": { title: "Novos Leads Quentes", desc: "Notificar sempre que a IA classificar um chumbo como quente." },
                  "ai": { title: "IA não conseguiu responder", desc: "Seja avisado quando o motor da IA não souber a resposta e chamar um humano." },
                  "payment": { title: "Pagamento Concluído", desc: "Receber notificação quando uma cobrança for paga via integração." },
                  "summary": { title: "Resumo Semanal", desc: "Receber um relatório com estatísticas da semana toda sexta-feira." }
                };
                const meta = titles[item.id] || { title: item.id, desc: "" };
                
                const togglePref = (key) => {
                  const newPrefs = notifsData.preferences.map(p => p.id === item.id ? { ...p, [key]: !p[key] } : p);
                  updateNotifs.run({ preferences: newPrefs });
                  showToast('Preferência salva!');
                };

                return (
                  <div key={i} style={{ padding: '16px 0', borderBottom: i < 3 ? `1px solid ${t.border}` : 'none', display: 'flex', gap: 20, alignItems: 'center' }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{meta.title}</div>
                      <div style={{ fontSize: 13, color: t.textMuted, marginTop: 4 }}>{meta.desc}</div>
                    </div>
                    <div style={{ display: 'flex', gap: 12 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: t.text, cursor: 'pointer' }} onClick={() => togglePref('web')}>
                        <input type="checkbox" checked={item.web} readOnly style={{ accentColor: t.primary }}/> Web
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: t.text, cursor: 'pointer' }} onClick={() => togglePref('email')}>
                        <input type="checkbox" checked={item.email} readOnly style={{ accentColor: t.primary }}/> E-mail
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: t.text, cursor: 'pointer' }} onClick={() => togglePref('whatsapp')}>
                        <input type="checkbox" checked={item.whatsapp} readOnly style={{ accentColor: t.primary }}/> WhatsApp
                      </div>
                    </div>
                  </div>
                );
              })}
            </Card>
          )}

          {section === 'plano' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <Card style={{ padding: 0, overflow: 'hidden', background: isBloom ? t.bg : 'linear-gradient(135deg, rgba(20,20,25,1) 0%, rgba(30,30,40,1) 100%)', border: `1px solid ${t.primary}40` }}>
                <div style={{ padding: 24, position: 'relative' }}>
                  <div style={{ position: 'absolute', top: 0, right: 0, padding: 24, opacity: 0.1 }}><Icons.Sparkles size={100} /></div>
                  <h2 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 24, fontWeight: 700, color: t.primary, display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Icons.Star size={24} fill={t.primary} stroke={t.primary} />
                    SaaS Premium
                  </h2>
                  <div style={{ marginTop: 6, fontSize: 14, color: t.textMuted }}>Você está no plano mais avançado. Aproveite todos os recursos.</div>
                  <div style={{ marginTop: 24, display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ fontSize: 32, fontWeight: 800, fontFamily: t.fontDisplay, color: t.text }}>R$ 297<span style={{ fontSize: 14, color: t.textMuted, fontWeight: 500 }}>/mês</span></div>
                    <Pill soft={t.greenSoft} color={t.green}>Ativo e em dia</Pill>
                  </div>
                </div>
              </Card>

              <Card style={{ padding: 22 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                  <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 17, fontWeight: 700, color: t.text }}>Consumo de IA neste mês</h3>
                  <Btn variant="green" size="sm" icon={<Icons.Lightning size={12}/>} onClick={() => setRechargeModalOpen(true)}>Recarregar Combustível</Btn>
                </div>
                <div style={{ marginTop: 10 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8, fontSize: 13, fontWeight: 600, color: t.text }}>
                    <span>Franquia de Inteligência Artificial</span>
                    <span>{(tokensData.used / 1000).toFixed(1)}K / {(tokensData.limit / 1000).toFixed(0)}K</span>
                  </div>
                  <div style={{ width: '100%', height: 8, background: isBloom ? t.border : 'rgba(255,255,255,0.05)', borderRadius: 4, overflow: 'hidden' }}>
                    <div style={{ width: `${Math.min(100, (tokensData.used / tokensData.limit) * 100)}%`, height: '100%', background: t.primary, borderRadius: 4 }} />
                  </div>
                  <div style={{ marginTop: 8, fontSize: 12, color: t.textMuted, textAlign: 'right' }}>Renova em 14 dias</div>
                </div>
              </Card>

              {/* ⚡ CAÇA AO DESPERDÍCIO: ROI DO PLANO COMERCIAL ⚡ */}
              <Card style={{ 
                padding: 20, 
                background: isBloom ? t.greenSoft : 'linear-gradient(135deg, rgba(16,185,129,0.06) 0%, rgba(91,141,239,0.04) 100%)', 
                border: isBloom ? `2px solid ${t.border}` : `1px solid rgba(16,185,129,0.25)`,
                boxShadow: isBloom ? '3px 3px 0 0 #14131A' : 'none',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                  <div style={{ width: 32, height: 32, borderRadius: 8, background: isBloom ? t.surface : 'rgba(16,185,129,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icons.Lightning size={16} stroke={t.green} fill={t.green}/>
                  </div>
                  <span style={{ fontSize: 11, fontWeight: 700, color: isBloom ? t.text : t.green, letterSpacing: '0.08em', fontFamily: t.fontMono }}>MÉTRICAS DE ROI DO PLANO</span>
                </div>
                <div style={{ fontSize: 16, fontWeight: 700, color: t.text, lineHeight: 1.45 }}>
                  Até o momento, a assistente economizou cerca de <strong style={{ color: t.green }}>{Math.round(((tokensData.used * 0.07) * 2.5) / 60)} horas</strong> de trabalho comercial humano.
                </div>
                <div style={{ fontSize: 12.5, color: t.textMuted, marginTop: 8 }}>
                  Isso equivale a uma economia direta de folha de pagamento de mais de **R$ {Math.round((((tokensData.used * 0.07) * 2.5) / 60) * 15).toLocaleString('pt-BR')},00** reais neste mês. Pagar R$ 297,00 por um funcionário 24/7 é um ROI absoluto!
                </div>
              </Card>
            </div>
          )}


          {section === 'seg' && (
            <Card style={{ padding: 22 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
                <div style={{ width: 40, height: 40, background: 'rgba(255,60,60,0.1)', color: '#FF3C3C', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icons.ShieldAlert size={20} />
                </div>
                <div>
                  <h2 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 20, fontWeight: 700, color: t.text }}>Segurança e Privacidade (LGPD)</h2>
                  <div style={{ marginTop: 2, color: t.textMuted, fontSize: 13 }}>Configure autenticação de dois fatores e controle os dados dos seus leads.</div>
                </div>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 0', borderBottom: `1px solid ${t.border}`, borderTop: `1px solid ${t.border}` }}>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 600, color: t.text }}>Autenticação em Dois Fatores (2FA)</div>
                  <div style={{ fontSize: 13, color: t.textMuted, marginTop: 4 }}>Adicione uma camada extra de segurança usando o Google Authenticator.</div>
                </div>
                <Btn variant="primary" onClick={() => showToast('Redirecionando para setup do 2FA...', 'info')}>Ativar 2FA</Btn>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 0', borderBottom: `1px solid ${t.border}` }}>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 600, color: t.text }}>Exportação Completa de Dados</div>
                  <div style={{ fontSize: 13, color: t.textMuted, marginTop: 4 }}>Baixe um arquivo JSON com todas as conversas, clientes e chaves (Compliance LGPD).</div>
                </div>
                <Btn variant="secondary" onClick={() => showToast('Exportação iniciada. Você receberá um e-mail em breve.', 'info')}>Exportar</Btn>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 0' }}>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 600, color: '#FF3C3C' }}>Excluir Conta e Dados</div>
                  <div style={{ fontSize: 13, color: t.textMuted, marginTop: 4 }}>Esta ação é irreversível e apagará tudo permanentemente.</div>
                </div>
                <Btn variant="ghost" onClick={async () => {
                  if (await confirm('Você tem CERTEZA ABSOLUTA? Todo seu CRM será apagado.')) {
                    showToast('Você não pode excluir a conta de administrador primária.', 'error');
                  }
                }} style={{ color: '#FF3C3C', border: '1px solid rgba(255,60,60,0.2)' }}>Apagar Tudo</Btn>
              </div>
            </Card>
          )}
        </div>
      </div>

      {/* 💳 MODAL DE RECARGA DE COMBUSTÍVEL PIX (FASE BETA - HIGH FIDELITY) ── */}
      {rechargeModalOpen && (
        <div style={{
          position: 'fixed', inset: 0, zIndex: 101000,
          background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)',
          display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <Card style={{
            width: '100%', maxWidth: 440, padding: 24,
            background: isBloom ? t.surface : t.surfaceAlt,
            boxShadow: isBloom ? '8px 8px 0 0 #14131A' : '0 10px 45px rgba(0,0,0,0.6)',
            position: 'relative'
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
              <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 18, color: t.text }}>⚡ Recarga de IA (Combustível Pix)</h3>
              <button onClick={() => { setRechargeModalOpen(false); setPixStep(1); setSelectedPackage(null); }} style={{ background: 'transparent', border: 'none', color: t.textMuted, cursor: 'pointer' }}>
                <Icons.X size={20} />
              </button>
            </div>

            {pixStep === 1 && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                <p style={{ fontSize: 13, color: t.textMuted, lineHeight: 1.5, marginBottom: 6 }}>
                  Escolha um pacote de combustível para alimentar sua inteligência artificial. O robô consome tokens em tempo real de acordo com as conversas.
                </p>
                {[
                  { name: 'Franquia Compacta', tokens: 100000, price: 'R$ 15,00', desc: 'Ideal para testes e validar os primeiros leads.', badge: '100K tokens' },
                  { name: 'Franquia Pro (Melhor Valor)', tokens: 500000, price: 'R$ 50,00', desc: 'Perfeito para automação comercial ativa.', badge: '500K tokens' },
                  { name: 'Franquia Enterprise', tokens: 1000000, price: 'R$ 90,00', desc: 'Operação de alta volumetria e grandes campanhas.', badge: '1.0M tokens' }
                ].map((pkg, i) => (
                  <div 
                    key={i} 
                    onClick={() => setSelectedPackage(pkg)}
                    style={{
                      padding: 14, borderRadius: 12, cursor: 'pointer',
                      border: selectedPackage?.tokens === pkg.tokens ? `2px solid ${t.green}` : `1.5px solid ${t.border}`,
                      background: selectedPackage?.tokens === pkg.tokens ? (isBloom ? t.greenSoft : 'rgba(16,185,129,0.06)') : 'rgba(255,255,255,0.02)',
                      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                      transition: 'all 0.15s ease'
                    }}
                  >
                    <div style={{ flex: 1, paddingRight: 8 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span style={{ fontWeight: 700, fontSize: 13.5, color: t.text }}>{pkg.name}</span>
                        <Pill soft={t.greenSoft} color={t.green} style={{ fontSize: 9, padding: '1px 6px' }}>{pkg.badge}</Pill>
                      </div>
                      <p style={{ margin: '4px 0 0', fontSize: 12, color: t.textMuted, lineHeight: 1.35 }}>{pkg.desc}</p>
                    </div>
                    <div style={{ fontSize: 15, fontWeight: 800, color: t.text, flexShrink: 0 }}>{pkg.price}</div>
                  </div>
                ))}
                
                <Btn 
                  variant={selectedPackage ? 'green' : 'secondary'} 
                  style={{ marginTop: 14, width: '100%', padding: 12 }} 
                  disabled={!selectedPackage}
                  onClick={() => setPixStep(2)}
                >
                  Gerar QR Code Pix
                </Btn>
              </div>
            )}

            {pixStep === 2 && selectedPackage && (
              <div style={{ textAlign: 'center' }}>
                <p style={{ color: t.textMuted, fontSize: 13, marginBottom: 16 }}>
                  Pague o valor de <strong style={{color: t.text}}>{selectedPackage.price}</strong> para receber instantaneamente **{(selectedPackage.tokens / 1000).toFixed(0)}K tokens** na sua conta:
                </p>
                <div style={{ background: '#fff', padding: 14, borderRadius: 12, display: 'inline-block', border: `1.5px solid ${t.border}` }}>
                  <img src="https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=00020126580014br.gov.bcb.pix0136fluxozap-recarga-tokens-pix-key-real0215recarga-premium" alt="QR Code Pix" style={{ width: 160, height: 160, display: 'block' }} />
                </div>
                
                <div style={{ marginTop: 16, textAlign: 'left' }}>
                  <label style={{ fontSize: 10, fontWeight: 700, color: t.textMuted, fontFamily: t.fontMono }}>PIX COPIA E COLA</label>
                  <div style={{ 
                    display: 'flex', gap: 6, marginTop: 4, padding: 8, borderRadius: 8, 
                    background: 'rgba(0,0,0,0.15)', border: `1px solid ${t.border}`,
                    fontFamily: t.fontMono, fontSize: 11, color: t.text, wordBreak: 'break-all'
                  }}>
                    <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>00020126580014br.gov.bcb.pix0136fluxozap-recarga-tokens-pix-key-real0215recarga-premium</span>
                    <button 
                      onClick={() => {
                        navigator.clipboard.writeText("00020126580014br.gov.bcb.pix0136fluxozap-recarga-tokens-pix-key-real0215recarga-premium");
                        showToast('Chave Pix copiada com sucesso!');
                      }}
                      style={{ background: 'transparent', border: 'none', color: t.primary, cursor: 'pointer', fontWeight: 700 }}
                    >Copiar</button>
                  </div>
                </div>

                <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
                  <Btn variant="ghost" style={{ flex: 1 }} onClick={() => setPixStep(1)}>Voltar</Btn>
                  <Btn variant="green" style={{ flex: 1.5 }} loading={loadingPayment} onClick={handleConfirmRecharge}>Confirmar Pagamento</Btn>
                </div>
              </div>
            )}

            {pixStep === 3 && selectedPackage && (
              <div style={{ textAlign: 'center', padding: '20px 0' }}>
                <div style={{ fontSize: 60, marginBottom: 16 }}>⚡</div>
                <h3 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 20, color: t.green, fontWeight: 800 }}>Recarga Concluída!</h3>
                <p style={{ color: t.textMuted, fontSize: 13, marginTop: 8, lineHeight: 1.5 }}>
                  Seu Pix foi processado com sucesso! Adicionamos **{(selectedPackage.tokens / 1000).toFixed(0)}K tokens** ao seu limite e o robô de IA já pode continuar trabalhando 24/7.
                </p>
                <Btn variant="primary" style={{ marginTop: 24, width: '100%' }} onClick={() => { setRechargeModalOpen(false); setPixStep(1); setSelectedPackage(null); }}>
                  Entendi, Voltar ao Painel
                </Btn>
              </div>
            )}
          </Card>
        </div>
      )}
    </div>
  );
};

window.Settings = Settings;

