import React, { useState, useMemo, useEffect } from 'react';
import { 
    X, User, DollarSign, Calendar, MapPin, Phone, Mail, 
    Briefcase, FileText, Calculator, AlertTriangle, 
    CheckCircle2, Wallet, Plus, Minus, Power, PowerOff, 
    ShieldCheck, Smartphone, Laptop, Globe, HardDrive, 
    Folder, UserCheck, UserMinus, Hash, Fingerprint, Clock,
    RefreshCw, UserCircle, ClipboardList
} from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { generatePayslip, calculateFGTS } from '../utils/dpCalculations';
import { useEmployees } from '../hooks/useEmployees';
import { useCalculos } from '../hooks/useCalculos';
import { useDescontos } from '../hooks/useDescontos';
import { usePassagem } from '../hooks/usePassagem';
import { useProventos } from '../hooks/useProventos';
import { useBeneficios } from '../hooks/useBeneficios';
import { useRecisao } from '../hooks/useRecisao';
import { usePagamento } from '../hooks/usePagamento';
import { useRhFeedback } from './RhFeedbackNotification';
import { ExperienceContractFormSidebar } from './ExperienceContractFormSidebar';
import { useExperienceContracts } from '../hooks/useExperienceContracts';

export const EmployeeDetailPanel = ({ employee: initialEmployee, onClose, onEdit, onUpdate }) => {
  const { fetchEmployeeById, inactivateEmployee, reactivateEmployee } = useEmployees();
  const { calcularCompleto, salvarCalculo, fetchCalculosByColaborador, loading: calculosLoading } = useCalculos();
  const { descontos, fetchDescontosByColaborador, createOrUpdateDescontos, loading: descontosLoading } = useDescontos();
  const { passagens, fetchPassagemByColaborador, createOrUpdatePassagem, loading: passagemLoading } = usePassagem();
  const { proventos, fetchProventosByColaborador, createOrUpdateProventos, loading: proventosLoading } = useProventos();
  const { beneficios, fetchBeneficios, loading: beneficiosLoading } = useBeneficios();
  const { recisoes, fetchRecisoesByColaborador, salvarRecisao, loading: recisaoLoading } = useRecisao();
  const { pagamento, fetchPagamentoByColaborador, loading: pagamentoLoading } = usePagamento();
  const { success, error, handleBackendError } = useRhFeedback();
  const { handleCreateContract, rawContracts, fetchContracts } = useExperienceContracts();
  
  const [employee, setEmployee] = useState(initialEmployee);
  const [loading, setLoading] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);
  const [calculosResult, setCalculosResult] = useState(null);
  const [savingCalculo, setSavingCalculo] = useState(false);
  const [activeDpTab, setActiveDpTab] = useState('calculos');
  const [isExperienceFormOpen, setIsExperienceFormOpen] = useState(false);

  // Estados para Simulação de Folha
  const [config, setConfig] = useState({
      hasVT: true,
      hasVR: false,
      hasUnionContribution: false,
      hasPericulosidade: false,
      insalubrityLevel: 0, 
      workDays: 22,
      numChildren: 0,
      extraHours50: 0,
      extraHours100: 0,
      mes: new Date().getMonth() + 1,
      ano: new Date().getFullYear()
  });

  // Carregar dados completos do colaborador
  useEffect(() => {
    const loadFullData = async () => {
      if (initialEmployee?.id) {
        setLoading(true);
        const fullData = await fetchEmployeeById(initialEmployee.id);
        if (fullData) {
          // Normalizar campos do backend para o estado local (preservar todos os campos originais)
          setEmployee({
            ...fullData,
            id: fullData.idcolaborador || fullData.id,
            name: fullData.colaboradores || fullData.nome || fullData.name,
            email: fullData.email_corporativo || fullData.email,
            phone: fullData.telefone,
            role: fullData.cargo || fullData.role,
            status: fullData.status_contrato || fullData.status || 'Ativo',
            salary: Number(fullData.salario || 0)
            // Todos os outros campos do objeto original são preservados automaticamente pelo spread
          });
        }
        setLoading(false);
      }
    };
    loadFullData();
    // Carregar contratos de experiência para validar visibilidade de botões
    fetchContracts();
  }, [initialEmployee, fetchEmployeeById, fetchContracts]);

  // Verificar se já possui contrato de experiência
  const hasExperienceContract = useMemo(() => {
    return rawContracts.some(c => Number(c.idcolaborador) === Number(employee?.id));
  }, [rawContracts, employee?.id]);

  // Carregar cálculos salvos ao mudar mês/ano ou ao abrir a aba
  useEffect(() => {
    const loadCalculos = async () => {
      if (employee?.id && config.mes && config.ano) {
        try {
          const response = await fetchCalculosByColaborador(employee.id, {
            mes: config.mes,
            ano: config.ano
          });
          if (response?.calculos && response.calculos.length > 0) {
            // Carregar último cálculo salvo
            const ultimoCalculo = response.calculos[0];
            setCalculosResult({
              salario_bruto: ultimoCalculo.salario_bruto || ultimoCalculo.salario_bruto,
              descontos: {
                inss: {
                  valor: ultimoCalculo.valor_inss || 0,
                  aliquota: ultimoCalculo.aliquota_inss || 0
                },
                irrf: {
                  valor: ultimoCalculo.valor_irrf || 0,
                  aliquota: ultimoCalculo.aliquota_irrf || 0
                }
              },
              fgts: {
                valor: ultimoCalculo.valor_fgts || 0,
                aliquota: 8
              },
              resumo: {
                total_descontos: ultimoCalculo.total_descontos || 0,
                salario_liquido: ultimoCalculo.salario_liquido || 0
              }
            });
          }
        } catch (error) {
          console.error('Erro ao carregar cálculos:', error);
        }
      }
    };
    loadCalculos();
  }, [employee?.id, config.mes, config.ano, fetchCalculosByColaborador]);

  // Carregar dados de Departamento Pessoal automaticamente quando a aba é aberta ou mês/ano mudam
  useEffect(() => {
    if (employee?.id && config.mes && config.ano) {
      const params = { mes: config.mes, ano: config.ano };
      
      console.log('🔄 Carregando dados DP:', { activeDpTab, params, employeeId: employee.id });
      
      // Carregar dados baseado na aba ativa
      if (activeDpTab === 'descontos') {
        fetchDescontosByColaborador(employee.id, params);
      } else if (activeDpTab === 'proventos') {
        fetchProventosByColaborador(employee.id, params);
      } else if (activeDpTab === 'passagem') {
        fetchPassagemByColaborador(employee.id, params);
      }
    }
  }, [employee?.id, config.mes, config.ano, activeDpTab, fetchDescontosByColaborador, fetchProventosByColaborador, fetchPassagemByColaborador]);

  // Logs de debug para verificar dados carregados
  useEffect(() => {
    if (proventos.length > 0) {
      console.log('✅ Proventos carregados:', proventos);
    }
  }, [proventos]);

  useEffect(() => {
    if (descontos.length > 0) {
      console.log('✅ Descontos carregados:', descontos);
    }
  }, [descontos]);

  useEffect(() => {
    if (passagens.length > 0) {
      console.log('✅ Passagens carregadas:', passagens);
    }
  }, [passagens]);

  // Cálculos (Memoizado)
  const payslip = useMemo(() => {
      return generatePayslip(employee || {}, config);
  }, [employee, config]);

  const fgtsData = useMemo(() => calculateFGTS(employee?.salary || 0, 12), [employee?.salary]); 
  const vacationValue = (employee?.salary || 0) + ((employee?.salary || 0) / 3);

  const handleConfigChange = (key, value) => {
      setConfig(prev => ({ ...prev, [key]: value }));
  };

  // Calcular folha usando a API
  const handleCalcularFolha = async () => {
    if (!employee?.id || !employee?.salary) {
      error('Dados Incompletos', 'O colaborador precisa ter um salário cadastrado para realizar a simulação.');
      return;
    }

    try {
      setLoading(true);
      
      // Preparar payload para cálculo completo
      const salarioBruto = employee.salary || employee.salario || 0;
      
      // Calcular proventos adicionais
      let proventosAdicionais = 0;
      if (config.hasPericulosidade) {
        proventosAdicionais += salarioBruto * 0.30; // Periculosidade 30%
      }
      if (config.insalubrityLevel > 0) {
        proventosAdicionais += salarioBruto * (config.insalubrityLevel / 100); // Insalubridade
      }
      
      // Calcular horas extras
      const valorHora = salarioBruto / 220;
      const he50Value = valorHora * 1.5 * (config.extraHours50 || 0);
      const he100Value = valorHora * 2.0 * (config.extraHours100 || 0);
      
      const salarioBrutoTotal = salarioBruto + proventosAdicionais + he50Value + he100Value;
      
      // Calcular outros descontos (VT, VR, etc)
      let outrosDescontos = 0;
      if (config.hasVT) {
        outrosDescontos += salarioBruto * 0.06; // Vale Transporte 6%
      }
      if (config.hasVR) {
        // Assumindo VR de R$ 30/dia * 22 dias * 20% = R$ 132
        outrosDescontos += 30 * config.workDays * 0.20;
      }

      const payload = {
        salario_bruto: salarioBrutoTotal,
        num_dependentes: config.numChildren || 0,
        outros_descontos: outrosDescontos,
        calcular_fgts: true
      };

      const resultado = await calcularCompleto(payload);
      setCalculosResult(resultado);
      success('Cálculo Realizado', 'A simulação da folha de pagamento foi processada.');
    } catch (err) {
      handleBackendError(err);
    } finally {
      setLoading(false);
    }
  };

  // Salvar cálculo no banco
  const handleSalvarCalculo = async () => {
    if (!employee?.id || !calculosResult) {
      error('Ação Negada', 'Realize a simulação do cálculo antes de tentar salvar os dados.');
      return;
    }

    try {
      setSavingCalculo(true);
      
      const salarioBruto = employee.salary || employee.salario || 0;
      let proventosAdicionais = 0;
      if (config.hasPericulosidade) {
        proventosAdicionais += salarioBruto * 0.30;
      }
      if (config.insalubrityLevel > 0) {
        proventosAdicionais += salarioBruto * (config.insalubrityLevel / 100);
      }
      
      const valorHora = salarioBruto / 220;
      const he50Value = valorHora * 1.5 * (config.extraHours50 || 0);
      const he100Value = valorHora * 2.0 * (config.extraHours100 || 0);
      
      const salarioBrutoTotal = salarioBruto + proventosAdicionais + he50Value + he100Value;
      
      let outrosDescontos = 0;
      if (config.hasVT) {
        outrosDescontos += salarioBruto * 0.06;
      }
      if (config.hasVR) {
        outrosDescontos += 30 * config.workDays * 0.20;
      }

      const payload = {
        idcolaborador: employee.id || employee.idcolaborador,
        mes: config.mes,
        ano: config.ano,
        salario_bruto: salarioBrutoTotal,
        num_dependentes: config.numChildren || 0,
        outros_descontos: outrosDescontos,
        calcular_fgts: true
      };

      await salvarCalculo(payload);
      success('Cálculo Salvo', 'As informações da folha foram registradas no histórico do colaborador.');
      onUpdate?.();
    } catch (err) {
      handleBackendError(err);
    } finally {
      setSavingCalculo(false);
    }
  };


  const handleToggleStatus = async () => {
    setActionLoading(true);
    const success = employee.status === 'Inativo' 
        ? await reactivateEmployee(employee.id)
        : await inactivateEmployee(employee.id);
    
    if (success) {
        // Atualizar estado local para refletir a mudança imediata
        setEmployee(prev => ({ 
            ...prev, 
            status: prev.status === 'Inativo' ? 'Ativo' : 'Inativo' 
        }));
        onUpdate?.();
    }
    setActionLoading(false);
  };

  if (!employee && loading) return (
    <div className="h-full w-full flex items-center justify-center bg-white dark:bg-[#1b1b1b]">
        <RefreshCw className="animate-spin text-emerald-500" size={32} />
    </div>
  );

  return (
    <div className="h-full w-full bg-white dark:bg-[#1b1b1b] flex flex-col overflow-hidden shadow-2xl rounded-xl">
        {/* Header Ultra Premium com Iluminação Refinada */}
        <div className="p-4 sm:p-6 md:p-8 pb-4 relative overflow-hidden flex-shrink-0 border-b border-slate-100 dark:border-white/5 bg-gradient-to-br from-white to-slate-50/50 dark:from-[#1b1b1b] dark:to-[#1e1e1e]">
            
            <div className="flex items-start justify-between relative z-10 flex-wrap gap-4">
                <div className="flex items-center gap-3 sm:gap-5 min-w-0 flex-1">
                    <div className="w-12 h-12 sm:w-14 sm:h-14 md:w-16 md:h-16 rounded-3xl bg-emerald-500/10 flex items-center justify-center text-emerald-600 flex-shrink-0">
                        <User size={24} className="sm:w-7 sm:h-7 md:w-8 md:h-8" />
                    </div>
                    <div className="min-w-0 flex-1">
                        <h2 className="text-[clamp(1.125rem,2.4vw,1.875rem)] font-semibold text-slate-800 dark:text-white tracking-tight leading-tight truncate">
                            {employee.name}
                        </h2>
                        <div className="flex items-center gap-2 mt-1">
                            <Briefcase size={12} className="text-slate-400 flex-shrink-0" />
                            <p className="text-slate-500 dark:text-slate-400 font-medium text-[clamp(1rem,1.1vw,1.0625rem)] uppercase tracking-wider truncate">
                                {employee.role}
                            </p>
                        </div>
                    </div>
                </div>
                <button 
                    onClick={onClose} 
                    className="p-3 bg-slate-100 dark:bg-white/5 rounded-3xl hover:bg-slate-200 dark:hover:bg-white/10 transition-all text-slate-500"
                >
                    <X size={20} />
                </button>
            </div>
            
            <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 mt-6 sm:mt-8 relative z-10">
                <div className="flex items-center gap-3 sm:gap-4 flex-wrap">
                    <div className="flex flex-col items-center bg-slate-100 dark:bg-white/5 px-3 sm:px-4 py-2 rounded-xl border border-slate-200 dark:border-white/10">
                        <Hash size={10} className="text-slate-400 mb-0.5" />
                        <span className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-700 dark:text-slate-300 font-mono tracking-tighter">{employee.id}</span>
                    </div>
                    <Badge className={`rounded-xl px-3 sm:px-4 py-2 text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase tracking-widest border-2 h-auto sm:h-11 ${
                        employee.status === 'Ativo' 
                        ? 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20' 
                        : 'bg-rose-500/10 text-rose-600 border-rose-500/20'
                    }`}>
                        {employee.status}
                    </Badge>
                </div>

               <div className="flex gap-2 sm:gap-3 flex-wrap">
                   <Button 
                    variant="outline" 
                    size="sm" 
                    onClick={() => onEdit && onEdit(employee)}
                    className="rounded-xl h-10 sm:h-11 px-4 sm:px-6 text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase tracking-widest gap-2 bg-white dark:bg-transparent border-slate-200 dark:border-white/10 hover:border-emerald-500/50 transition-all flex-1 sm:flex-initial"
                   >
                       <User size={12} className="sm:w-3.5 sm:h-3.5 text-emerald-500" /> 
                       <span className="hidden sm:inline">Editar Registro</span>
                       <span className="sm:hidden">Editar</span>
                   </Button>
                   {!hasExperienceContract && (
                       <Button 
                        variant="outline" 
                        size="sm" 
                        onClick={() => setIsExperienceFormOpen(true)}
                        className="rounded-xl h-10 sm:h-11 px-4 sm:px-6 text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase tracking-widest gap-2 bg-white dark:bg-transparent border-indigo-200 dark:border-indigo-500/20 text-indigo-600 hover:bg-indigo-500/5 transition-all flex-1 sm:flex-initial"
                       >
                           <ClipboardList size={12} className="sm:w-3.5 sm:h-3.5" />
                           <span className="hidden sm:inline">Iniciar Experiência</span>
                           <span className="sm:hidden">Experiência</span>
                       </Button>
                   )}
                   <Button 
                    variant="outline" 
                    size="sm" 
                    disabled={actionLoading}
                    onClick={handleToggleStatus}
                    className={`rounded-xl h-10 sm:h-11 px-4 sm:px-6 text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase tracking-widest gap-2 transition-all shadow-sm flex-1 sm:flex-initial ${
                        employee.status === 'Inativo' 
                        ? 'border-emerald-500/30 text-emerald-600 hover:bg-emerald-500/5' 
                        : 'border-rose-500/30 text-rose-600 hover:bg-rose-500/5'
                    }`}
                   >
                       {employee.status === 'Inativo' ? <UserCheck size={14} className="sm:w-4 sm:h-4" /> : <UserMinus size={14} className="sm:w-4 sm:h-4" />}
                       <span className="hidden sm:inline">{employee.status === 'Inativo' ? 'Ativar Colaborador' : 'Inativar Registro'}</span>
                       <span className="sm:hidden">{employee.status === 'Inativo' ? 'Ativar' : 'Inativar'}</span>
                   </Button>
               </div>
            </div>
        </div>

        {/* Abas Estilo Pastinha Premium */}
        <div className="flex-1 flex flex-col min-h-0 bg-slate-50 dark:bg-[#0a0a0a] relative p-3 sm:p-4 md:p-6 pt-2">
            <Tabs defaultValue="dados" className="flex flex-col h-full w-full">
                
                <TabsList className="bg-transparent p-0 w-full justify-start gap-2 h-auto mb-0 overflow-x-auto flex-nowrap scrollbar-hide [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
                    {['Dados Pessoais', 'Administrativo', 'Infraestrutura', 'Nextcloud', 'DP Simulação'].map((label, i) => {
                        const isFirst = i === 0;
                        const isLast = i === 4;
                        return (
                        <TabsTrigger 
                            key={i}
                            value={label.toLowerCase().split(' ')[0]}
                            className={`
                                relative
                                ${isFirst ? 'rounded-tl-3xl' : 'rounded-tl-2xl'} 
                                ${isLast ? 'rounded-tr-3xl' : 'rounded-tr-2xl'} 
                                rounded-b-none 
                                border-t border-l border-r border-transparent 
                                data-[state=active]:border-slate-200 dark:data-[state=active]:border-white/10 
                                data-[state=active]:bg-white dark:data-[state=active]:bg-[#1b1b1b] 
                                data-[state=active]:border-b-0
                                data-[state=inactive]:bg-slate-200/40 dark:data-[state=inactive]:bg-[#151515]
                                data-[state=active]:text-emerald-600 dark:data-[state=active]:text-emerald-400
                                data-[state=inactive]:text-slate-400
                                px-5 sm:px-6 md:px-8 py-3 sm:py-4 md:py-5 text-[clamp(1rem,1.2vw,1.125rem)] font-semibold uppercase tracking-widest whitespace-nowrap
                                transition-all z-10 hover:text-slate-600 flex-shrink-0
                                ${isFirst ? 'ml-0' : ''}
                            `}
                        >
                            <span className="hidden sm:inline">{label}</span>
                            <span className="sm:hidden">{label.split(' ')[0]}</span>
                        </TabsTrigger>
                    )})}
                </TabsList>

                {/* Conteúdo da Pasta */}
                <div className="flex-1 overflow-hidden bg-white dark:bg-[#1b1b1b] border border-slate-200 dark:border-white/10 border-t-0 rounded-b-2xl shadow-sm relative z-0 mt-[-1px]">
                    <ScrollArea className="h-full">
                        <div className="p-8">
                            <TabsContent value="dados" className="mt-0 space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-300">
                                {/* Seção: Identificação */}
                                <div className="space-y-4">
                                    <h3 className="text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase tracking-[0.2em] text-slate-400 flex items-center gap-2 px-1">
                                        <Fingerprint size={14} className="text-emerald-500" /> Identificação Civil
                                    </h3>
                                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                                        {[
                                            { label: 'CPF', value: employee.cpf_validado || employee.cpf || 'Não informado', icon: FileText },
                                            { label: 'RG', value: employee.rg || 'Não informado', icon: FileText },
                                            { label: 'PIS', value: employee.pis || 'Não informado', icon: Hash },
                                            { label: 'Nascimento', value: employee.data_nascimento ? new Date(employee.data_nascimento).toLocaleDateString('pt-BR') : 'Não informado', icon: Calendar },
                                        ].map((item, idx) => (
                                            <div key={idx} className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5 transition-all hover:border-emerald-500/20">
                                                <span className="text-[clamp(1rem,1.1vw,1.0625rem)] text-slate-400 font-medium uppercase tracking-wider flex items-center gap-2 mb-1">
                                                    <item.icon size={12} /> {item.label}
                                                </span>
                                                <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-slate-200 break-words">{item.value}</p>
                                            </div>
                                        ))}
                                    </div>
                                </div>

                                {/* Seção: Contato */}
                                <div className="space-y-4">
                                    <h3 className="text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase tracking-[0.2em] text-slate-400 flex items-center gap-2 px-1">
                                        <Phone size={14} className="text-blue-500" /> Contato e Localização
                                    </h3>
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-4">
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase tracking-wider flex items-center gap-2 mb-1">
                                                <Mail size={12} /> Email Corporativo
                                            </span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-slate-200 break-words">{employee.email_corporativo || 'Não informado'}</p>
                                        </div>
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase tracking-wider flex items-center gap-2 mb-1">
                                                <Mail size={12} /> Email Pessoal
                                            </span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-slate-200 break-words">{employee.email_pessoal_em_uso || 'Não informado'}</p>
                                        </div>
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase tracking-wider flex items-center gap-2 mb-1">
                                                <Phone size={12} /> Telefone Principal
                                            </span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-slate-200">{employee.telefone || 'Não informado'}</p>
                                        </div>
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase tracking-wider flex items-center gap-2 mb-1">
                                                <MapPin size={12} /> CEP
                                            </span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-slate-200 font-mono">{employee.cep || 'Não informado'}</p>
                                        </div>
                                        <div className="col-span-1 md:col-span-2 bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase tracking-wider flex items-center gap-2 mb-1">
                                                <MapPin size={12} /> Endereço Residencial
                                            </span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-slate-200 leading-relaxed break-words">
                                                {employee.endereco || 'Endereço não cadastrado'}
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </TabsContent>

                            <TabsContent value="administrativo" className="mt-0 space-y-6 sm:space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-300">
                                {/* Gestão e Contrato */}
                                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                                    {[
                                        { label: 'Responsável Direto', value: employee.responsavel_direto_validado || employee.responsavel_direto || 'N/A', icon: UserCheck },
                                        { label: 'Empresa', value: employee.empresas || (employee.empresa ? `ID: ${employee.empresa}` : 'N/A'), icon: Globe },
                                        { label: 'Cliente', value: employee.cliente_nome && employee.cliente_nome !== '[]' ? employee.cliente_nome : (employee.cliente || 'N/A'), icon: Briefcase },
                                        { label: 'Base Operacional', value: employee.base_validada && employee.base_validada !== '[]' ? employee.base_validada : (employee.base || 'N/A'), icon: MapPin },
                                        { label: 'Realmente Subalterno', value: employee.realmente_e_subordinado ? 'Sim' : 'Não', icon: UserCircle },
                                        { label: 'Contratos Ativos', value: employee.contratos_operacionais_ativos || '---', icon: FileText },
                                        { label: 'Data Admissão', value: employee.data_admissao ? new Date(employee.data_admissao).toLocaleDateString('pt-BR') : 'Não informado', icon: Calendar },
                                        { label: 'CBO', value: employee.cbo || '---', icon: Briefcase },
                                        { label: 'Função', value: employee.funcao || '---', icon: Briefcase },
                                        { label: 'Ponto Eletrônico', value: employee.id_prl ? `ID: ${employee.id_prl}` : 'Não vinculado', icon: Clock },
                                        { label: 'Salário Base', value: employee.salario ? `R$ ${Number(employee.salario).toLocaleString('pt-BR', { minimumFractionDigits: 2 })}` : 'Não informado', icon: DollarSign },
                                        { label: 'Carga Horária', value: employee.carga_horaria || 'Não informado', icon: Clock },
                                        { label: 'Jornada', value: employee.jornada || employee.jornada_1 || 'Não informado', icon: Clock },
                                        { label: 'Tipo Contratação', value: employee.contratacao_validada || employee.contratacao || 'Não informado', icon: FileText },
                                    ].map((item, idx) => (
                                        <div key={idx} className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase tracking-wider flex items-center gap-2 mb-1">
                                                <item.icon size={12} /> {item.label}
                                            </span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-slate-200 break-words">{item.value}</p>
                                        </div>
                                    ))}
                                </div>

                                <Separator className="bg-slate-100 dark:bg-white/5" />

                                {/* Documentação Adicional */}
                                <div className="space-y-4">
                                    <h3 className="text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase tracking-[0.2em] text-slate-400 flex items-center gap-2 px-1">
                                        <ShieldCheck size={14} className="text-emerald-500" /> Documentação Técnica
                                    </h3>
                                    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3 sm:gap-4">
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase mb-1 block">CNH Número</span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold break-words font-mono text-slate-800 dark:text-slate-200">{employee.cnh || '---'}</p>
                                        </div>
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase mb-1 block">Data Expedição CNH</span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold break-words text-slate-800 dark:text-slate-200">
                                                {employee.data_expedicao_cnh ? new Date(employee.data_expedicao_cnh).toLocaleDateString('pt-BR') : '---'}
                                            </p>
                                        </div>
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase mb-1 block">Validade CNH</span>
                                            <p className={`text-[clamp(1rem,1.2vw,1.125rem)] font-semibold break-words ${employee.cnh_status === 'vencida' ? 'text-rose-500' : 'text-slate-800 dark:text-slate-200'}`}>
                                                {employee.validade_cnh ? new Date(employee.validade_cnh).toLocaleDateString('pt-BR') : '---'}
                                            </p>
                                        </div>
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase mb-1 block">Data Limite Férias</span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold break-words text-slate-800 dark:text-slate-200">
                                                {employee.data_limite_ferias ? new Date(employee.data_limite_ferias).toLocaleDateString('pt-BR') : '---'}
                                            </p>
                                        </div>
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase mb-1 block">Últimas Férias</span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold break-words text-slate-800 dark:text-slate-200">
                                                {employee.data_ultimas_ferias ? new Date(employee.data_ultimas_ferias).toLocaleDateString('pt-BR') : '---'}
                                            </p>
                                        </div>
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-4 sm:p-5 rounded-xl border border-slate-100 dark:border-white/5">
                                            <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase mb-1 block">Contratação</span>
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold break-words text-slate-800 dark:text-slate-200">
                                                {employee.contratacao_validada || employee.contratacao || '---'}
                                            </p>
                                        </div>
                                    </div>
                                </div>

                                {/* Operacional & Suporte */}
                                <div className="space-y-4">
                                    <h3 className="text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase tracking-[0.2em] text-slate-400 flex items-center gap-2 px-1">
                                        <Briefcase size={14} className="text-amber-500" /> Vínculos Operacionais
                                    </h3>
                                    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3 sm:gap-4">
                                        {[
                                            { label: 'Oficina', value: employee.oficina || (employee.id_oficina ? `ID: ${employee.id_oficina}` : '---'), icon: Briefcase },
                                            { label: 'Almoxarifado', value: employee.almoxarifado || (employee.id_almoxarifado ? `ID: ${employee.id_almoxarifado}` : '---'), icon: Briefcase },
                                            { label: 'Apoio/Setor', value: employee.apoio_setor || (employee.id_apoio ? `ID: ${employee.id_apoio}` : '---'), icon: Briefcase },
                                            { label: 'ID B2B', value: employee.id_b2b || '---', icon: Briefcase },
                                            { label: 'Cargo ADM', value: employee.cargo_adm || '---', icon: Briefcase },
                                            { label: 'ADM Validado', value: employee.cargo_administrativo_validado ? 'Sim' : 'Não', icon: UserCheck },
                                            { label: 'Classificação CBO', value: employee.classificacao_cbo || '---', icon: Hash },
                                            { label: 'Risco', value: employee.risco || 'N/A', icon: AlertTriangle },
                                        ].map((item, idx) => (
                                            <div key={idx} className="bg-slate-50 dark:bg-white/[0.03] p-4 rounded-xl border border-slate-100 dark:border-white/5">
                                                <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium uppercase mb-1 block">{item.label}</span>
                                                <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-slate-200">{item.value}</p>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            </TabsContent>

                            <TabsContent value="infraestrutura" className="mt-0 space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-300">
                                <div className="grid grid-cols-2 gap-6">
                                    {/* Notebook / Desktop */}
                                    <div className="space-y-6">
                                        <div className={`p-6 rounded-xl border ${employee.usa_notebook_empresa === 'Sim' ? 'border-emerald-500/20 bg-emerald-500/5' : 'border-slate-100 dark:border-white/5 bg-slate-50 dark:bg-white/[0.03]'}`}>
                                            <div className="flex items-center gap-4">
                                                <div className={`p-3 rounded-3xl ${employee.usa_notebook_empresa === 'Sim' ? 'bg-emerald-500 text-white' : 'bg-slate-200 dark:bg-white/10 text-slate-400'}`}>
                                                    <Laptop size={24} />
                                                </div>
                                                <div>
                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 tracking-wider">Notebook Empresa</p>
                                                    <p className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-slate-800 dark:text-slate-200">{employee.usa_notebook_empresa || 'Não'}</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div className={`p-6 rounded-xl border ${employee.usa_desktop_empresa === 'Sim' ? 'border-blue-500/20 bg-blue-500/5' : 'border-slate-100 dark:border-white/5 bg-slate-50 dark:bg-white/[0.03]'}`}>
                                            <div className="flex items-center gap-4">
                                                <div className={`p-3 rounded-3xl ${employee.usa_desktop_empresa === 'Sim' ? 'bg-blue-500 text-white' : 'bg-slate-200 dark:bg-white/10 text-slate-400'}`}>
                                                    <Smartphone size={24} />
                                                </div>
                                                <div>
                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 tracking-wider">Desktop Empresa</p>
                                                    <p className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-slate-800 dark:text-slate-200">{employee.usa_desktop_empresa || 'Não'}</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Conectividade */}
                                    <div className="bg-slate-50 dark:bg-white/[0.03] p-6 sm:p-8 rounded-xl border border-slate-100 dark:border-white/5 space-y-6">
                                        <h4 className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase tracking-widest text-slate-400 flex items-center gap-2">
                                            <ShieldCheck size={16} className="text-emerald-500" /> Acessos e Máquina
                                        </h4>
                                        <div className="space-y-4 text-[clamp(1rem,1.2vw,1.125rem)] font-medium">
                                            <div className="flex justify-between items-center py-3 border-b border-slate-100 dark:border-white/5">
                                                <span className="text-slate-500">Email Corporativo</span>
                                                <span className="text-slate-800 dark:text-slate-200 font-mono text-[clamp(1rem,1.1vw,1.0625rem)] break-words text-right max-w-[60%]">{employee.email_corporativo || 'N/A'}</span>
                                            </div>
                                            <div className="flex justify-between items-center py-3 border-b border-slate-100 dark:border-white/5">
                                                <span className="text-slate-500">Conta AD</span>
                                                <span className="px-2 py-1 bg-white dark:bg-white/10 rounded-xl text-[clamp(1rem,1.1vw,1.0625rem)] font-mono break-words">{employee.conta_ad || 'N/A'}</span>
                                            </div>
                                            <div className="flex justify-between items-center py-3 border-b border-slate-100 dark:border-white/5">
                                                <span className="text-slate-500">Modelo Dispositivo</span>
                                                <span className="text-slate-800 dark:text-slate-200 underline decoration-emerald-500/30 break-words text-right max-w-[60%]">{employee.modelo_dispositivo || 'N/A'}</span>
                                            </div>
                                            <div className="flex justify-between items-center py-3 border-b border-slate-100 dark:border-white/5">
                                                <span className="text-slate-500">Máquina Registrada</span>
                                                <span className="text-slate-800 dark:text-slate-200 break-words text-right max-w-[60%]">{employee.maquina_registrada || 'N/A'}</span>
                                            </div>
                                            <div className="flex justify-between items-center py-3 border-b border-slate-100 dark:border-white/5">
                                                <span className="text-slate-500">Máquina Cliente</span>
                                                <span className="text-slate-800 dark:text-slate-200 break-words text-right max-w-[60%]">{employee.maquina_registrada_cliente || 'N/A'}</span>
                                            </div>
                                            <div className="flex justify-between items-center py-3">
                                                <span className="text-slate-500">Escritório Remoto</span>
                                                <span className={`px-2 py-1 rounded-xl text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold ${employee.escritorio_remoto === 'Sim' ? 'bg-emerald-500/10 text-emerald-600' : 'bg-slate-500/10 text-slate-600'}`}>
                                                    {employee.escritorio_remoto === 'Sim' ? 'Habilitado' : 'Desativado'}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </TabsContent>

                            <TabsContent value="nextcloud" className="mt-0 space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-300">
                                <div className="space-y-4">
                                    <h3 className="text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase tracking-[0.2em] text-slate-400 flex items-center gap-2 px-1">
                                        <HardDrive size={14} className="text-emerald-500" /> Permissões Nextcloud
                                    </h3>
                                    <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                                        {Object.entries(employee || {})
                                            .filter(([k]) => k.startsWith('pasta_'))
                                            .map(([key, value], idx) => (
                                                <div 
                                                    key={idx} 
                                                    className={`p-4 rounded-xl border transition-all flex items-center gap-3 ${
                                                        value === 1 || value === '1' || value === 'Sim' 
                                                        ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-600' 
                                                        : 'bg-slate-50 dark:bg-white/5 border-slate-100 dark:border-white/5 text-slate-400 opacity-60'
                                                    }`}
                                                >
                                                    <Folder size={16} />
                                                    <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase truncate">
                                                        {key.replace('pasta_', '').replace(/_/g, ' ')}
                                                    </span>
                                                </div>
                                            ))
                                        }
                                    </div>
                                </div>
                            </TabsContent>

                            <TabsContent value="dp" className="mt-0 space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-300">
                                {/* DEPARTAMENTO PESSOAL - SUB-ABAS */}
                                <Tabs value={activeDpTab} onValueChange={setActiveDpTab} className="w-full">
                                    <TabsList className="grid w-full grid-cols-4 lg:grid-cols-7 gap-2 mb-6 bg-transparent p-0 h-auto">
                                        <TabsTrigger value="calculos" className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-semibold uppercase px-4 py-2 rounded-xl data-[state=active]:bg-blue-500 data-[state=active]:text-white data-[state=inactive]:bg-slate-200/40 dark:data-[state=inactive]:bg-white/5">
                                            Cálculos
                                        </TabsTrigger>
                                        <TabsTrigger value="descontos" className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-semibold uppercase px-4 py-2 rounded-xl data-[state=active]:bg-rose-500 data-[state=active]:text-white data-[state=inactive]:bg-slate-200/40 dark:data-[state=inactive]:bg-white/5">
                                            Descontos
                                        </TabsTrigger>
                                        <TabsTrigger value="proventos" className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-semibold uppercase px-4 py-2 rounded-xl data-[state=active]:bg-emerald-500 data-[state=active]:text-white data-[state=inactive]:bg-slate-200/40 dark:data-[state=inactive]:bg-white/5">
                                            Proventos
                                        </TabsTrigger>
                                        <TabsTrigger value="passagem" className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-semibold uppercase px-4 py-2 rounded-xl data-[state=active]:bg-amber-500 data-[state=active]:text-white data-[state=inactive]:bg-slate-200/40 dark:data-[state=inactive]:bg-white/5">
                                            Passagem
                                        </TabsTrigger>
                                        <TabsTrigger value="beneficios" className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-semibold uppercase px-4 py-2 rounded-xl data-[state=active]:bg-purple-500 data-[state=active]:text-white data-[state=inactive]:bg-slate-200/40 dark:data-[state=inactive]:bg-white/5">
                                            Benefícios
                                        </TabsTrigger>
                                        <TabsTrigger value="recisao" className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-semibold uppercase px-4 py-2 rounded-xl data-[state=active]:bg-red-500 data-[state=active]:text-white data-[state=inactive]:bg-slate-200/40 dark:data-[state=inactive]:bg-white/5">
                                            Recisão
                                        </TabsTrigger>
                                        <TabsTrigger value="pagamento" className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-semibold uppercase px-4 py-2 rounded-xl data-[state=active]:bg-indigo-500 data-[state=active]:text-white data-[state=inactive]:bg-slate-200/40 dark:data-[state=inactive]:bg-white/5">
                                            Pagamento
                                        </TabsTrigger>
                                    </TabsList>

                                    {/* ABA: CÁLCULOS */}
                                    <TabsContent value="calculos" className="mt-0">
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-8 rounded-xl border border-slate-100 dark:border-white/5">
                                    <div className="flex items-center justify-between mb-8">
                                        <h3 className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-slate-800 dark:text-white flex items-center gap-3">
                                            <Calculator size={24} className="text-blue-500" /> Simulador de Folha
                                        </h3>
                                        <div className="flex items-center gap-4">
                                            <div className="flex items-center gap-2">
                                                <Label className="text-[clamp(1rem,1.1vw,1.0625rem)] font-medium text-slate-500">Mês:</Label>
                                                <Input 
                                                    type="number" 
                                                    min="1" 
                                                    max="12" 
                                                    className="w-20 h-9 rounded-xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 text-center"
                                                    value={config.mes}
                                                    onChange={e => handleConfigChange('mes', Number(e.target.value))}
                                                />
                                            </div>
                                            <div className="flex items-center gap-2">
                                                <Label className="text-[clamp(1rem,1.1vw,1.0625rem)] font-medium text-slate-500">Ano:</Label>
                                                <Input 
                                                    type="number" 
                                                    min="2020" 
                                                    max="2100"
                                                    className="w-24 h-9 rounded-xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 text-center"
                                                    value={config.ano}
                                                    onChange={e => handleConfigChange('ano', Number(e.target.value))}
                                                />
                                            </div>
                                        </div>
                                    </div>

                                    <div className="grid grid-cols-2 gap-8 mb-8">
                                        <div className="space-y-4">
                                            <div className="flex items-center justify-between p-3 rounded-xl hover:bg-white dark:hover:bg-white/5 transition-colors">
                                                <Label className="text-[clamp(1rem,1.1vw,1.0625rem)] font-medium text-slate-600 dark:text-slate-400 cursor-pointer">Vale Transporte (6%)</Label>
                                                <Switch checked={config.hasVT} onCheckedChange={v => handleConfigChange('hasVT', v)} />
                                            </div>
                                            <div className="flex items-center justify-between p-3 rounded-xl hover:bg-white dark:hover:bg-white/5 transition-colors">
                                                <Label className="text-[clamp(1rem,1.1vw,1.0625rem)] font-medium text-slate-600 dark:text-slate-400 cursor-pointer">Vale Refeição</Label>
                                                <Switch checked={config.hasVR} onCheckedChange={v => handleConfigChange('hasVR', v)} />
                                            </div>
                                            <div className="flex items-center justify-between p-3 rounded-xl hover:bg-white dark:hover:bg-white/5 transition-colors">
                                                <Label className="text-[clamp(1rem,1.1vw,1.0625rem)] font-medium text-slate-600 dark:text-slate-400 cursor-pointer">Periculosidade (30%)</Label>
                                                <Switch checked={config.hasPericulosidade} onCheckedChange={v => handleConfigChange('hasPericulosidade', v)} />
                                            </div>
                                            <div className="space-y-2">
                                                <Label className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 tracking-wider">Nº Dependentes</Label>
                                                <Input 
                                                    type="number" 
                                                    min="0"
                                                    className="h-11 rounded-xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10" 
                                                    value={config.numChildren} 
                                                    onChange={e => handleConfigChange('numChildren', Number(e.target.value))} 
                                                />
                                            </div>
                                        </div>
                                        <div className="space-y-4">
                                            <div className="space-y-2">
                                                <Label className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 tracking-wider">Insalubridade</Label>
                                                <select 
                                                    className="w-full h-11 bg-white dark:bg-white/5 border border-slate-200 dark:border-white/10 rounded-xl px-4 text-[clamp(1rem,1.1vw,1.0625rem)] font-medium outline-none ring-blue-500/20 focus:ring-4 transition-all text-slate-700 dark:text-slate-200"
                                                    value={config.insalubrityLevel}
                                                    onChange={(e) => handleConfigChange('insalubrityLevel', Number(e.target.value))}
                                                >
                                                    <option value={0} className="dark:bg-[#1b1b1b]">Isento</option>
                                                    <option value={10} className="dark:bg-[#1b1b1b]">Mínimo (10%)</option>
                                                    <option value={20} className="dark:bg-[#1b1b1b]">Médio (20%)</option>
                                                    <option value={40} className="dark:bg-[#1b1b1b]">Máximo (40%)</option>
                                                </select>
                                            </div>
                                            <div className="grid grid-cols-2 gap-4">
                                                <div className="space-y-2">
                                                    <Label className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 tracking-wider">HE 50%</Label>
                                                    <Input type="number" min="0" className="h-11 rounded-xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10" value={config.extraHours50} onChange={e => handleConfigChange('extraHours50', Number(e.target.value))} />
                                                </div>
                                                <div className="space-y-2">
                                                    <Label className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 tracking-wider">HE 100%</Label>
                                                    <Input type="number" min="0" className="h-11 rounded-xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10" value={config.extraHours100} onChange={e => handleConfigChange('extraHours100', Number(e.target.value))} />
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Botões de Ação */}
                                    <div className="flex gap-4 mb-8">
                                        <Button 
                                            onClick={handleCalcularFolha}
                                            disabled={loading || calculosLoading}
                                            className="flex-1 h-12 rounded-xl bg-blue-600 hover:bg-blue-700 text-white font-semibold uppercase tracking-widest shadow-lg shadow-blue-500/20 text-[clamp(1rem,1.1vw,1.0625rem)]"
                                        >
                                            {loading || calculosLoading ? 'Calculando...' : 'Calcular Folha'}
                                        </Button>
                                        <Button 
                                            onClick={handleSalvarCalculo}
                                            disabled={!calculosResult || savingCalculo}
                                            variant="outline"
                                            className="flex-1 h-12 rounded-xl border-2 border-emerald-500 text-emerald-600 hover:bg-emerald-500 hover:text-white font-semibold uppercase tracking-widest text-[clamp(1rem,1.1vw,1.0625rem)]"
                                        >
                                            {savingCalculo ? 'Salvando...' : 'Salvar Cálculo'}
                                        </Button>
                                    </div>

                                    {/* HOLERITE SIMULADO PREMIUM */}
                                    {calculosResult ? (
                                        <div className="bg-white dark:bg-[#121212] rounded-xl p-8 border border-slate-200 dark:border-white/5 shadow-xl shadow-slate-200/20 dark:shadow-none">
                                            <div className="flex justify-between items-end mb-8">
                                                <div className="flex items-center gap-4">
                                                    <div className="p-4 bg-emerald-500 rounded-3xl text-white">
                                                        <Wallet size={24} />
                                                    </div>
                                                    <div>
                                                        <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-emerald-600 dark:text-emerald-400 tracking-[0.2em]">Salário Líquido</p>
                                                        <p className="text-[clamp(1.75rem,3.8vw,2.625rem)] font-semibold text-slate-800 dark:text-white">
                                                            {calculosResult.resumo?.salario_liquido?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) || 'R$ 0,00'}
                                                        </p>
                                                    </div>
                                                </div>
                                                <div className="text-right">
                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 tracking-widest mb-1">Salário Bruto</p>
                                                    <p className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-slate-600 dark:text-slate-300">
                                                        {calculosResult.salario_bruto?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) || employee.salario?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                    </p>
                                                </div>
                                            </div>

                                            <div className="grid grid-cols-3 gap-4 mb-6">
                                                <div className="p-4 bg-slate-50 dark:bg-white/5 rounded-xl border border-slate-100 dark:border-white/5">
                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 mb-1">INSS</p>
                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-rose-500">
                                                        - {calculosResult.descontos?.inss?.valor?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) || 'R$ 0,00'}
                                                    </p>
                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-normal mt-1">Alíquota: {calculosResult.descontos?.inss?.aliquota || 0}%</p>
                                                </div>
                                                <div className="p-4 bg-slate-50 dark:bg-white/5 rounded-xl border border-slate-100 dark:border-white/5">
                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 mb-1">IRRF</p>
                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-rose-500">
                                                        - {calculosResult.descontos?.irrf?.valor?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) || 'R$ 0,00'}
                                                    </p>
                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-normal mt-1">Alíquota: {calculosResult.descontos?.irrf?.aliquota || 0}%</p>
                                                </div>
                                                <div className="p-4 bg-slate-50 dark:bg-white/5 rounded-xl border border-slate-100 dark:border-white/5">
                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 mb-1">FGTS Mensal</p>
                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-blue-500">
                                                        {calculosResult.fgts?.valor?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) || 'R$ 0,00'}
                                                    </p>
                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-normal mt-1">Alíquota: {calculosResult.fgts?.aliquota || 8}%</p>
                                                </div>
                                            </div>

                                            {/* Detalhamento de Descontos */}
                                            <div className="border-t border-slate-100 dark:border-white/5 pt-6">
                                                <h4 className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium uppercase text-slate-400 tracking-widest mb-4 flex items-center gap-2">
                                                    <Minus size={12} className="text-rose-500" /> Detalhamento de Descontos
                                                </h4>
                                                <div className="space-y-3">
                                                    {calculosResult.descontos?.inss?.valor > 0 && (
                                                        <div className="flex justify-between items-center group">
                                                            <div className="flex items-center gap-2">
                                                                <div className="w-1 h-1 rounded-full bg-rose-400/50 group-hover:bg-rose-500 transition-colors"></div>
                                                                <span className="text-[clamp(1rem,1.2vw,1.125rem)] font-medium text-slate-600 dark:text-slate-400">INSS ({calculosResult.descontos.inss.aliquota}%)</span>
                                                            </div>
                                                            <span className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-rose-500">
                                                                - {calculosResult.descontos.inss.valor.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                            </span>
                                                        </div>
                                                    )}
                                                    {calculosResult.descontos?.irrf?.valor > 0 && (
                                                        <div className="flex justify-between items-center group">
                                                            <div className="flex items-center gap-2">
                                                                <div className="w-1 h-1 rounded-full bg-rose-400/50 group-hover:bg-rose-500 transition-colors"></div>
                                                                <span className="text-[clamp(1rem,1.2vw,1.125rem)] font-medium text-slate-600 dark:text-slate-400">IRRF ({calculosResult.descontos.irrf.aliquota}%)</span>
                                                            </div>
                                                            <span className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-rose-500">
                                                                - {calculosResult.descontos.irrf.valor.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                            </span>
                                                        </div>
                                                    )}
                                                    {config.hasVT && (
                                                        <div className="flex justify-between items-center group">
                                                            <div className="flex items-center gap-2">
                                                                <div className="w-1 h-1 rounded-full bg-rose-400/50 group-hover:bg-rose-500 transition-colors"></div>
                                                                <span className="text-[clamp(1rem,1.2vw,1.125rem)] font-medium text-slate-600 dark:text-slate-400">Vale Transporte (6%)</span>
                                                            </div>
                                                            <span className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-rose-500">
                                                                - {((employee.salary || employee.salario || 0) * 0.06).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                            </span>
                                                        </div>
                                                    )}
                                                    {config.hasVR && (
                                                        <div className="flex justify-between items-center group">
                                                            <div className="flex items-center gap-2">
                                                                <div className="w-1 h-1 rounded-full bg-rose-400/50 group-hover:bg-rose-500 transition-colors"></div>
                                                                <span className="text-[clamp(1rem,1.2vw,1.125rem)] font-medium text-slate-600 dark:text-slate-400">Vale Refeição (20%)</span>
                                                            </div>
                                                            <span className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-rose-500">
                                                                - {(30 * config.workDays * 0.20).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                            </span>
                                                        </div>
                                                    )}
                                                    {calculosResult.resumo?.total_descontos === 0 && (
                                                        <p className="text-[clamp(0.875rem,1vw,0.9375rem)] text-slate-400 italic font-medium pl-3">Nenhum desconto aplicado.</p>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    ) : (
                                        <div className="bg-white dark:bg-[#121212] rounded-xl p-8 border border-slate-200 dark:border-white/5 shadow-xl shadow-slate-200/20 dark:shadow-none text-center py-16">
                                            <Calculator size={48} className="mx-auto text-slate-300 dark:text-slate-600 mb-4" />
                                            <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-medium text-slate-400">Configure os parâmetros e clique em "Calcular Folha" para ver os resultados</p>
                                        </div>
                                    )}
                                        </div>
                                    </TabsContent>

                                    {/* ABA: DESCONTOS */}
                                    <TabsContent value="descontos" className="mt-0">
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-8 rounded-xl border border-slate-100 dark:border-white/5">
                                            <div className="flex items-center justify-between mb-6">
                                                <h3 className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-slate-800 dark:text-white flex items-center gap-3">
                                                    <Minus size={24} className="text-rose-500" /> Descontos
                                                </h3>
                                                <Button 
                                                    onClick={() => {
                                                        console.log('🔘 Botão Carregar Descontos clicado');
                                                        if (employee?.id) {
                                                            fetchDescontosByColaborador(employee.id, { mes: config.mes, ano: config.ano });
                                                        }
                                                    }}
                                                    disabled={descontosLoading}
                                                    className="h-9 rounded-xl bg-rose-600 hover:bg-rose-700 text-white text-[clamp(0.875rem,1vw,0.9375rem)] font-semibold uppercase"
                                                >
                                                    {descontosLoading ? 'Carregando...' : 'Carregar'}
                                                </Button>
                                            </div>
                                            {descontos.length > 0 ? (
                                                <div className="space-y-3">
                                                    {descontos.map((desc, idx) => {
                                                        // Mapear campos de descontos para exibição
                                                        const descontosItems = [
                                                            { label: 'Vale', valor: desc.vale },
                                                            { label: 'Vale Transporte', valor: desc.vale_transporte },
                                                            { label: 'Plano Odontológico', valor: desc.plano_odonto },
                                                            { label: 'Pensão', valor: desc.pensao },
                                                            { label: 'Falta', valor: desc.falta }
                                                        ].filter(item => {
                                                            const valor = item.valor;
                                                            if (valor === null || valor === undefined || valor === '') {
                                                                console.log(`❌ Item filtrado (vazio): ${item.label} = ${valor}`);
                                                                return false;
                                                            }
                                                            // Converter string para número, tratando tanto ',' quanto '.' como separador decimal
                                                            const valorNum = typeof valor === 'string' 
                                                                ? parseFloat(valor.replace(',', '.')) 
                                                                : Number(valor);
                                                            const isValid = !isNaN(valorNum) && valorNum > 0;
                                                            if (isValid) {
                                                                console.log(`✅ Item válido: ${item.label} = "${valor}" (${valorNum})`);
                                                            } else {
                                                                console.log(`❌ Item filtrado: ${item.label} = "${valor}" (${valorNum}) - não é > 0`);
                                                            }
                                                            return isValid;
                                                        });

                                                        return (
                                                            <div key={idx} className="bg-white dark:bg-[#121212] p-4 rounded-xl border border-slate-200 dark:border-white/5">
                                                                <div className="mb-3 pb-3 border-b border-slate-100 dark:border-white/5">
                                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium text-slate-400 uppercase">Mês/Ano: {desc.mes}/{desc.ano}</p>
                                                                </div>
                                                                {descontosItems.length > 0 ? (
                                                                    <div className="space-y-2">
                                                                        {descontosItems.map((item, itemIdx) => (
                                                                            <div key={itemIdx} className="flex justify-between items-center">
                                                                                <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-white">{item.label}</p>
                                                                                <p className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-rose-500">
                                                                                    - {Number(item.valor || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                                                </p>
                                                                            </div>
                                                                        ))}
                                                                    </div>
                                                                ) : (
                                                                    <p className="text-sm text-slate-400">Nenhum desconto registrado para este período</p>
                                                                )}
                                                            </div>
                                                        );
                                                    })}
                                                </div>
                                            ) : (
                                                <div className="text-center py-12">
                                                    <Minus size={48} className="mx-auto text-slate-300 dark:text-slate-600 mb-4" />
                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-400">Nenhum desconto encontrado</p>
                                                    <p className="text-[clamp(0.875rem,1vw,0.9375rem)] text-slate-500 font-medium mt-2">Total de registros: {descontos.length}</p>
                                                </div>
                                            )}
                                        </div>
                                    </TabsContent>

                                    {/* ABA: PROVENTOS */}
                                    <TabsContent value="proventos" className="mt-0">
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-8 rounded-xl border border-slate-100 dark:border-white/5">
                                            <div className="flex items-center justify-between mb-6">
                                                <h3 className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-slate-800 dark:text-white flex items-center gap-3">
                                                    <Plus size={24} className="text-emerald-500" /> Proventos
                                                </h3>
                                                <Button 
                                                    onClick={() => employee?.id && fetchProventosByColaborador(employee.id, { mes: config.mes, ano: config.ano })}
                                                    disabled={proventosLoading}
                                                    className="h-9 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-[clamp(0.875rem,1vw,0.9375rem)] font-semibold uppercase"
                                                >
                                                    {proventosLoading ? 'Carregando...' : 'Carregar'}
                                                </Button>
                                            </div>
                                            {proventos.length > 0 ? (
                                                <div className="space-y-3">
                                                    {proventos.map((prov, idx) => {
                                                        // Mapear campos de proventos para exibição
                                                        const proventosItems = [
                                                            { label: 'Vale Alimentação', valor: prov.vale_alimentacao },
                                                            { label: 'Domingo', valor: prov.domingo },
                                                            { label: 'Feriado', valor: prov.feriado },
                                                            { label: 'Sábado', valor: prov.sabado },
                                                            { label: 'Insalubridade', valor: prov.insalubridade },
                                                            { label: 'Benefício Assistencial', valor: prov.beneficio_assistencial },
                                                            { label: 'Reembolso', valor: prov.reembolso }
                                                        ].filter(item => {
                                                            const valor = item.valor;
                                                            if (valor === null || valor === undefined || valor === '') return false;
                                                            const valorNum = typeof valor === 'string' 
                                                                ? parseFloat(valor.replace(',', '.')) 
                                                                : Number(valor);
                                                            // Aceitar apenas valores > 0 (exclui 0.00)
                                                            return !isNaN(valorNum) && valorNum > 0;
                                                        });

                                                        return (
                                                            <div key={idx} className="bg-white dark:bg-[#121212] p-4 rounded-xl border border-slate-200 dark:border-white/5">
                                                                <div className="mb-3 pb-3 border-b border-slate-100 dark:border-white/5">
                                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium text-slate-400 uppercase">Mês/Ano: {prov.mes}/{prov.ano}</p>
                                                                </div>
                                                                {proventosItems.length > 0 ? (
                                                                    <div className="space-y-2">
                                                                        {proventosItems.map((item, itemIdx) => {
                                                                            const valorNum = typeof item.valor === 'string' 
                                                                                ? parseFloat(item.valor.replace(',', '.')) 
                                                                                : Number(item.valor || 0);
                                                                            return (
                                                                                <div key={itemIdx} className="flex justify-between items-center">
                                                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-white">{item.label}</p>
                                                                                    <p className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-emerald-500">
                                                                                        + {valorNum.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                                                    </p>
                                                                                </div>
                                                                            );
                                                                        })}
                                                                    </div>
                                                                ) : (
                                                                    <p className="text-sm text-slate-400">Nenhum provento registrado para este período</p>
                                                                )}
                                                            </div>
                                                        );
                                                    })}
                                                </div>
                                            ) : (
                                                <div className="text-center py-12">
                                                    <Plus size={48} className="mx-auto text-slate-300 dark:text-slate-600 mb-4" />
                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-400">Nenhum provento encontrado</p>
                                                    <p className="text-[clamp(0.875rem,1vw,0.9375rem)] text-slate-500 font-medium mt-2">Total de registros: {proventos.length}</p>
                                                </div>
                                            )}
                                        </div>
                                    </TabsContent>

                                    {/* ABA: PASSAGEM */}
                                    <TabsContent value="passagem" className="mt-0">
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-8 rounded-xl border border-slate-100 dark:border-white/5">
                                            <div className="flex items-center justify-between mb-6">
                                                <h3 className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-slate-800 dark:text-white flex items-center gap-3">
                                                    <Calendar size={24} className="text-amber-500" /> Passagem
                                                </h3>
                                                <Button 
                                                    onClick={() => {
                                                        console.log('🔘 Botão Carregar Passagens clicado');
                                                        if (employee?.id) {
                                                            fetchPassagemByColaborador(employee.id, { mes: config.mes, ano: config.ano });
                                                        }
                                                    }}
                                                    disabled={passagemLoading}
                                                    className="h-9 rounded-xl bg-amber-600 hover:bg-amber-700 text-white text-[clamp(0.875rem,1vw,0.9375rem)] font-semibold uppercase"
                                                >
                                                    {passagemLoading ? 'Carregando...' : 'Carregar'}
                                                </Button>
                                            </div>
                                            {passagens.length > 0 ? (
                                                <div className="space-y-3">
                                                    {passagens.map((pass, idx) => {
                                                        // Mapear campos de passagens para exibição
                                                        const passagensItems = [
                                                            { label: 'JAE', valor: pass.jae_valor_receber, original: pass.jae },
                                                            { label: 'Riocard', valor: pass.riocard_valor_receber, original: pass.riocard },
                                                            { label: 'Combustível', valor: pass.combustivel_valor_receber, original: pass.combustivel }
                                                        ].filter(item => {
                                                            const valor = item.valor;
                                                            if (valor === null || valor === undefined || valor === '') {
                                                                console.log(`❌ Item filtrado (vazio): ${item.label} = ${valor}`);
                                                                return false;
                                                            }
                                                            // Converter string para número, tratando tanto ',' quanto '.' como separador decimal
                                                            const valorNum = typeof valor === 'string' 
                                                                ? parseFloat(valor.replace(',', '.')) 
                                                                : Number(valor);
                                                            const isValid = !isNaN(valorNum) && valorNum > 0;
                                                            if (isValid) {
                                                                console.log(`✅ Item válido: ${item.label} = "${valor}" (${valorNum})`);
                                                            } else {
                                                                console.log(`❌ Item filtrado: ${item.label} = "${valor}" (${valorNum}) - não é > 0`);
                                                            }
                                                            return isValid;
                                                        });

                                                        return (
                                                            <div key={idx} className="bg-white dark:bg-[#121212] p-4 rounded-xl border border-slate-200 dark:border-white/5">
                                                                <div className="mb-3 pb-3 border-b border-slate-100 dark:border-white/5">
                                                                    <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-medium text-slate-400 uppercase">Mês/Ano: {pass.mes}/{pass.ano}</p>
                                                                    {pass.porcentagem_desconto && (
                                                                        <p className="text-[clamp(0.875rem,1vw,0.9375rem)] text-slate-500 font-medium mt-1">Desconto: {pass.porcentagem_desconto}</p>
                                                                    )}
                                                                </div>
                                                                {passagensItems.length > 0 ? (
                                                                    <div className="space-y-2">
                                                                        {passagensItems.map((item, itemIdx) => {
                                                                            const valorNum = typeof item.valor === 'string' 
                                                                                ? parseFloat(item.valor.replace(',', '.')) 
                                                                                : Number(item.valor || 0);
                                                                            const originalNum = item.original 
                                                                                ? (typeof item.original === 'string' 
                                                                                    ? parseFloat(item.original.replace(',', '.')) 
                                                                                    : Number(item.original || 0))
                                                                                : null;
                                                                            return (
                                                                                <div key={itemIdx} className="flex justify-between items-center">
                                                                                    <div>
                                                                                        <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-white">{item.label}</p>
                                                                                        {originalNum && originalNum > 0 && (
                                                                                            <p className="text-[clamp(0.75rem,0.9vw,0.875rem)] text-slate-400 font-medium">Original: {originalNum.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}</p>
                                                                                        )}
                                                                                    </div>
                                                                                    <p className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-amber-500">
                                                                                        {valorNum.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                                                    </p>
                                                                                </div>
                                                                            );
                                                                        })}
                                                                    </div>
                                                                ) : (
                                                                    <p className="text-sm text-slate-400">Nenhuma passagem registrada para este período</p>
                                                                )}
                                                            </div>
                                                        );
                                                    })}
                                                </div>
                                            ) : (
                                                <div className="text-center py-12">
                                                    <Calendar size={48} className="mx-auto text-slate-300 dark:text-slate-600 mb-4" />
                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-400">Nenhuma passagem encontrada</p>
                                                    <p className="text-[clamp(0.875rem,1vw,0.9375rem)] text-slate-500 font-medium mt-2">Total de registros: {passagens.length}</p>
                                                </div>
                                            )}
                                        </div>
                                    </TabsContent>

                                    {/* ABA: BENEFÍCIOS */}
                                    <TabsContent value="beneficios" className="mt-0">
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-8 rounded-xl border border-slate-100 dark:border-white/5">
                                            <div className="flex items-center justify-between mb-6">
                                                <h3 className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-slate-800 dark:text-white flex items-center gap-3">
                                                    <CheckCircle2 size={24} className="text-purple-500" /> Benefícios
                                                </h3>
                                                <Button 
                                                    onClick={() => fetchBeneficios({ idcolaborador: employee?.id })}
                                                    disabled={beneficiosLoading}
                                                    className="h-9 rounded-xl bg-purple-600 hover:bg-purple-700 text-white text-[clamp(0.875rem,1vw,0.9375rem)] font-semibold uppercase"
                                                >
                                                    {beneficiosLoading ? 'Carregando...' : 'Carregar'}
                                                </Button>
                                            </div>
                                            {beneficios.length > 0 ? (
                                                <div className="space-y-3">
                                                    {beneficios.map((ben, idx) => (
                                                        <div key={idx} className="bg-white dark:bg-[#121212] p-4 rounded-2xl border border-slate-200 dark:border-white/5">
                                                            <div className="flex justify-between items-center">
                                                                <div>
                                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-white">{ben.nome || ben.tipo || 'Benefício'}</p>
                                                                    <p className="text-[clamp(0.875rem,1vw,0.9375rem)] text-slate-400 font-normal">{ben.descricao || ''}</p>
                                                                </div>
                                                                <p className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-purple-500">
                                                                    {Number(ben.valor || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                                </p>
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                            ) : (
                                                <div className="text-center py-12">
                                                    <CheckCircle2 size={48} className="mx-auto text-slate-300 dark:text-slate-600 mb-4" />
                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-400">Nenhum benefício encontrado</p>
                                                </div>
                                            )}
                                        </div>
                                    </TabsContent>

                                    {/* ABA: RECISÃO */}
                                    <TabsContent value="recisao" className="mt-0">
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-8 rounded-xl border border-slate-100 dark:border-white/5">
                                            <div className="flex items-center justify-between mb-6">
                                                <h3 className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-slate-800 dark:text-white flex items-center gap-3">
                                                    <FileText size={24} className="text-red-500" /> Recisão
                                                </h3>
                                                <Button 
                                                    onClick={() => employee?.id && fetchRecisoesByColaborador(employee.id)}
                                                    disabled={recisaoLoading}
                                                    className="h-9 rounded-xl bg-red-600 hover:bg-red-700 text-white text-[clamp(0.875rem,1vw,0.9375rem)] font-semibold uppercase"
                                                >
                                                    {recisaoLoading ? 'Carregando...' : 'Carregar'}
                                                </Button>
                                            </div>
                                            {recisoes.length > 0 ? (
                                                <div className="space-y-3">
                                                    {recisoes.map((rec, idx) => (
                                                        <div key={idx} className="bg-white dark:bg-[#121212] p-4 rounded-2xl border border-slate-200 dark:border-white/5">
                                                            <div className="flex justify-between items-center">
                                                                <div>
                                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-white">Recisão {rec.tipo || ''}</p>
                                                                    <p className="text-[clamp(0.875rem,1vw,0.9375rem)] text-slate-400 font-normal">Data: {rec.data_rescisao || rec.data}</p>
                                                                </div>
                                                                <p className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-red-500">
                                                                    {Number(rec.valor_total || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                                </p>
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                            ) : (
                                                <div className="text-center py-12">
                                                    <FileText size={48} className="mx-auto text-slate-300 dark:text-slate-600 mb-4" />
                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-400">Nenhuma recisão encontrada</p>
                                                </div>
                                            )}
                                        </div>
                                    </TabsContent>

                                    {/* ABA: PAGAMENTO */}
                                    <TabsContent value="pagamento" className="mt-0">
                                        <div className="bg-slate-50 dark:bg-white/[0.03] p-8 rounded-xl border border-slate-100 dark:border-white/5">
                                            <div className="flex items-center justify-between mb-6">
                                                <h3 className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-slate-800 dark:text-white flex items-center gap-3">
                                                    <DollarSign size={24} className="text-indigo-500" /> Apresentação de Pagamento
                                                </h3>
                                                <Button 
                                                    onClick={() => employee?.id && fetchPagamentoByColaborador(employee.id, { mes: config.mes, ano: config.ano })}
                                                    disabled={pagamentoLoading}
                                                    className="h-9 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-[clamp(0.875rem,1vw,0.9375rem)] font-semibold uppercase"
                                                >
                                                    {pagamentoLoading ? 'Carregando...' : 'Carregar'}
                                                </Button>
                                            </div>
                                            {pagamento ? (
                                                <div className="bg-white dark:bg-[#121212] p-6 rounded-xl border border-slate-200 dark:border-white/5">
                                                    <div className="space-y-4">
                                                        <div className="flex justify-between items-center">
                                                            <div>
                                                                <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-white">Pagamento {pagamento.mes}/{pagamento.ano}</p>
                                                                <p className="text-xs text-slate-400">Status: {pagamento.status || 'Processado'}</p>
                                                            </div>
                                                            <p className="text-[clamp(1.125rem,1.6vw,1.375rem)] font-semibold text-indigo-500">
                                                                {Number(pagamento.valor_liquido || pagamento.salario_liquido || 0).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                                                            </p>
                                                        </div>
                                                        {pagamento.detalhes && (
                                                            <div className="border-t border-slate-100 dark:border-white/5 pt-4">
                                                                <p className="text-[clamp(0.875rem,1vw,0.9375rem)] text-slate-400 font-medium mb-2">Detalhes:</p>
                                                                <pre className="text-[clamp(0.875rem,1vw,0.9375rem)] text-slate-600 dark:text-slate-300 font-normal whitespace-pre-wrap">
                                                                    {JSON.stringify(pagamento.detalhes, null, 2)}
                                                                </pre>
                                                            </div>
                                                        )}
                                                    </div>
                                                </div>
                                            ) : (
                                                <div className="text-center py-12">
                                                    <DollarSign size={48} className="mx-auto text-slate-300 dark:text-slate-600 mb-4" />
                                                    <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-400">Nenhum pagamento encontrado</p>
                                                </div>
                                            )}
                                        </div>
                                    </TabsContent>
                                </Tabs>
                            </TabsContent>
                        </div>
                    </ScrollArea>
                </div>
            </Tabs>
        </div>

        {/* Formulário de Contrato de Experiência - pré-populado com dados do colaborador */}
        <ExperienceContractFormSidebar
            isOpen={isExperienceFormOpen}
            onClose={() => setIsExperienceFormOpen(false)}
            onSubmit={async (data) => {
                const success = await handleCreateContract({
                    ...data,
                    idcolaborador: employee?.id || employee?.idcolaborador,
                    empresa: data.empresa || employee?.empresas || employee?.empresa,
                    data_admissao: data.data_admissao || employee?.data_admissao,
                    global_status: 'Admissão'
                });
                if (success) setIsExperienceFormOpen(false);
            }}
            initialData={null}
            prefillData={{
                idcolaborador: employee?.id || employee?.idcolaborador,
                empresa: employee?.empresas || '',
                data_admissao: employee?.data_admissao
                    ? new Date(employee.data_admissao).toISOString().split('T')[0]
                    : ''
            }}
        />
    </div>
  );
};
