import { useState, useMemo, useEffect } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { registrationSchema } from './schema';
import { submitDriverRegistration } from '../../services/driverService';
import { updateDriverRegistration, submitInternalDriverRegistration, getBases } from '../../services/grService';
import { handleGrError } from '../../utils/grErrorHandler';
import { useGrStore } from '../../services/useGrStore';
import { toast } from 'sonner';
import { motion, AnimatePresence } from 'framer-motion';
import { Check, ChevronRight, ChevronLeft, Upload, FileText, AlertCircle, Loader2, Info, Building2, Car, User2, MapPin, ClipboardList } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { cn } from '@/lib/utils';

// Constantes de opções
const WORK_MODES = [
  { value: 'proprio', label: 'Com meu veículo próprio' },
  { value: 'motorista', label: 'Como motorista (veículo da empresa)' },
];

const VEHICLE_TYPES = [
  { value: 'carro_passeio', label: 'Carro de Passeio' },
  { value: 'utilitario', label: 'Utilitário' },
  { value: 'van', label: 'Van' },
  { value: 'vuc', label: 'VUC (Veículo Urbano de Carga)' },
  { value: 'caminhao', label: 'Caminhão' },
  { value: 'cavalo', label: 'Cavalo' },
  { value: 'carreta', label: 'Carreta' },
  { value: 'moto', label: 'Moto' },
];

const MODALITIES = [
  { value: 'Agregado', label: 'Agregado' },
  { value: 'Rentals', label: 'Rentals' },
  { value: 'Frota Fixa Diarista', label: 'Frota Fixa Diarista' },
  { value: 'Frota Fixa Mensal', label: 'Frota Fixa Mensal' },
];

const RENTAL_TYPES = [
  { id: 'carro_passeio', label: 'Carro de Passeio (Cronos, Polo, etc.)', price: 'R$2.850,00', example: 'CRONOS/Polo' },
  { id: 'utilitario_leve', label: 'Utilitário Leve (Fiorino, Saveiro, etc.)', price: 'R$2.600,00', example: 'FIORINO/SAVEIROS' },
  { id: 'vuc_van', label: 'VUC / Van (Iveco Daily, Kia Bongo, etc.)', price: 'R$5.000,00', example: 'IVECO DAILY, VW Delivery, KIA BONGO', extra: true },
];

const RENTAL_TERMS_BASE = `
    <div class="mt-4 space-y-4">
        <p><strong>2. Abastecimento Facilitado:</strong> Para agilizar seu dia a dia, disponibilizamos o app PROFROTAS. O valor consumido é descontado automaticamente do seu repasse.</p>
        <div>
            <strong>3. Política de Manutenção:</strong>
            <ul class="list-disc list-inside ml-4 mt-1 space-y-1">
                <li><strong class="text-emerald-600 dark:text-emerald-400">Por conta do Grupo Pralog:</strong> Manutenções preventivas (troca de óleo e filtros) e serviço de reboque/guincho.</li>
                <li><strong class="text-red-500">Por conta do CONDUTOR:</strong> Custos de reparo por avarias, desgastes de pneus, reparos de funilaria/pintura e manutenções corretivas.</li>
            </ul>
        </div>
        <p><strong>4. Infrações:</strong> Todas as multas de trânsito são de responsabilidade integral do motorista.</p>
        <p><strong>5. Uso do Veículo:</strong> Você tem liberdade para utilizar o veículo para outras atividades quando não estiver em rota, mantendo o zelo.</p>
        <p className="text-red-600 dark:text-red-400"><strong>6. Requisito para Contratação:</strong> É imprescindível possuir um <u>CNPJ (MEI) ativo e válido</u>.</p>
    </div>
`;

export const DriverRegistrationForm = ({ onSuccess, isInternal = false }) => {
  const [step, setStep] = useState(1);
  const [submissionId, setSubmissionId] = useState(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [filePreviews, setFilePreviews] = useState({});

  const { register, handleSubmit, watch, setValue, trigger, control, setError, formState: { errors }, reset } = useForm({
    resolver: zodResolver(registrationSchema),
    defaultValues: {
      forma_trab: '',
      forma_trabalho: '',
      tipos_aluguel: [],
      is_third_party_vehicle: false,
      terms: false,
      coordenador: '',
      modalidade: '',
      base: '',
      is_internal: isInternal
    }
  });

  const { userData } = useGrStore();
  const currentUser = userData?.usuario;

  // Pre-fill form if 'info' exists in sessionStorage
  useEffect(() => {
    // Se não for interno, limpa qualquer resíduo de edição anterior
    if (!isInternal) {
        sessionStorage.removeItem('info');
        return;
    }

    const infoStr = sessionStorage.getItem('info');
    if (infoStr) {
      try {
        const info = JSON.parse(infoStr);
        console.log("GR [DEBUG]: Objeto 'info' recuperado para preenchimento:", info);
        
        // Helper to convert DD/MM/YYYY to YYYY-MM-DD
        const parseDateForInput = (dateStr) => {
          if (!dateStr || typeof dateStr !== 'string') return '';
          if (dateStr.includes('/')) {
            const parts = dateStr.split('/');
            if (parts.length === 3) {
                const [d, m, y] = parts;
                return `${y}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`;
            }
          }
          return dateStr;
        };

        // Map internal API work modes to form values
        let mappedFormaTrabalho = info.forma_trabalho || '';
        if (mappedFormaTrabalho === 'veiculo_proprio' || mappedFormaTrabalho === 'proprio') mappedFormaTrabalho = 'proprio';
        if (mappedFormaTrabalho === 'veiculo_empresa' || mappedFormaTrabalho === 'motorista') mappedFormaTrabalho = 'motorista';

        console.log("GR [DEBUG]: Mapeamento de Forma de Trabalho:", { original: info.forma_trabalho, mapped: mappedFormaTrabalho });

        // Map fields from 'info' to form fields
        const mapping = {
          nome_completo: info.nome_completo || info.title || '',
          cpf: info.cpf || info.subtitle || '',
          telefone: info.telefone || '',
          data_nascimento: parseDateForInput(info.data_nascimento),
          email: info.email || '',
          cnh: info.cnh || '',
          validade_cnh: parseDateForInput(info.validade_cnh),
          placa_veiculo: info.placa_veiculo || '',
          coordenador: info.coordenador || '',
          modalidade: info.modalidade || '',
          forma_trabalho: mappedFormaTrabalho,
          tipo_veiculo: info.tipo_veiculo || '',
          cnpj: info.cnpj || '',
          cep: info.cep || '',
          endereco: info.endereco || '',
          bairro: info.bairro || '',
          cidade: info.cidade || '',
          observacao: info.obs_cliente || info.observacao || '',
          iddrivers: info.iddrivers || info.id || '',
          base: info.base || ''
        };

        console.log("GR [DEBUG]: Mapping final gerado:", mapping);
        console.log("GR [DEBUG]: Campo base no mapping:", mapping.base);

        reset(mapping);
        
        console.log("GR [DEBUG]: Após reset, valor de watch('base'):", watch('base'));
        
        // Shadcn UI (Radix) Selects as vezes precisam de um pequeno delay para registrar o valor se forem renderizados condicionalmente
        setTimeout(() => {
            if (mappedFormaTrabalho) {
                console.log("GR [DEBUG]: Configurando Select 'forma_trabalho' como:", mappedFormaTrabalho);
                setValue('forma_trabalho', mappedFormaTrabalho, { shouldValidate: true, shouldDirty: true });
            }
            if (info.tipo_veiculo) {
                console.log("GR [DEBUG]: Configurando Select 'tipo_veiculo' como:", info.tipo_veiculo);
                setValue('tipo_veiculo', info.tipo_veiculo, { shouldValidate: true, shouldDirty: true });
            }
            if (info.modalidade) {
                console.log("GR [DEBUG]: Configurando Select 'modalidade' como:", info.modalidade);
                setValue('modalidade', info.modalidade, { shouldValidate: true, shouldDirty: true });
            }
            if (info.base) {
                console.log("GR [DEBUG]: Tentando setValue para base:", info.base);
                setValue('base', info.base, { shouldValidate: true, shouldDirty: true });
                console.log("GR [DEBUG]: Após setValue, watch('base'):", watch('base'));
            }
        }, 100);

        // Pre-fill image previews from URLs
        const imagePreviews = {};
        const docFields = [
            { field: 'cnh_frente', key: 'cnh_frente' },
            { field: 'cnh_verso', key: 'cnh_verso' },
            { field: 'comprovante_residencia', key: 'comprovante_residencia' },
            { field: 'crlv', key: 'crlv' },
            { field: 'cartao_cnpj', key: 'cartao_cnpj' },
            { field: 'antt', key: 'antt' },
            { field: 'direcao_defensiva', key: 'direcao_defensiva' },
            { field: 'exame_toxico', key: 'exame_toxico' }
        ];

        docFields.forEach(doc => {
            if (info[doc.key] && typeof info[doc.key] === 'string' && info[doc.key].startsWith('http')) {
                imagePreviews[doc.field] = info[doc.key];
            }
        });

        if (Object.keys(imagePreviews).length > 0) {
            setFilePreviews(prev => ({ ...prev, ...imagePreviews }));
        }
        
      } catch (e) {
        console.error("GR [ERROR]: Erro ao processar pre-fill do formulário:", e);
      }
    }
  }, [reset, isInternal, setValue]);

  const workMode = watch('forma_trabalho');
  const isThirdParty = watch('is_third_party_vehicle');
  const selectedRentals = watch('tipos_aluguel') || [];
  const [basesList, setBasesList] = useState([]);

  const filteredBases = useMemo(() => {
    if (!basesList) return [];
    
    // Logic matched with GrRegistrationDetails: Admin or 'Todas' gets full access
    const isAdmin = currentUser?.grupo === 'Administrador';
    const hasFullAccess = currentUser?.base === 'Todas' || currentUser?.base?.includes('Todas');

    if (isAdmin || hasFullAccess) {
        return basesList;
    }

    if (!currentUser?.base) return basesList || [];
    const userAllowedBases = currentUser.base.split(',').map(b => b.trim());
    const filtered = basesList.filter(b => userAllowedBases.includes((b.base || b.nome)?.trim()));
    console.log('GR [FILTER]: Bases filtradas:', filtered);
    return filtered;
  }, [basesList, currentUser]);

  useEffect(() => {
    if (isInternal) {
        getBases().then(response => {
             const list = response.Base_Dados_API || response.dados || response || [];
             setBasesList(Array.isArray(list) ? list : []);
        }).catch(err => console.error("Erro ao carregar bases:", err));
    }
  }, [isInternal]);

  // Auto-fill base field only when editing (info.base exists)
  // Removed auto-fill for new registrations - user must select manually
  // useEffect(() => {
  //   if (isInternal && filteredBases.length > 0) {
  //     const currentBase = watch('base');
  //     if (!currentBase && filteredBases.length === 1) {
  //       setValue('base', filteredBases[0].base || filteredBases[0].nome);
  //       console.log('GR [AUTO-FILL]: Base auto-preenchida com única opção:', filteredBases[0].base || filteredBases[0].nome);
  //     }
  //   }
  // }, [filteredBases, isInternal, setValue, watch]);

  // --- Handlers ---

  const handleFileChange = (e, fieldName) => {
    const file = e.target.files[0];
    if (file) {
      setFilePreviews(prev => ({
        ...prev,
        [fieldName]: URL.createObjectURL(file)
      }));
      // Converte FileList para array para facilitar o acesso posterior
      setValue(fieldName, Array.from(e.target.files));
    }
  };

  // Registra os campos de arquivo manualmente
  useEffect(() => {
    const fileFields = ['cnh_verso', 'cnh_frente', 'comprovante_residencia', 'crlv', 'antt', 'direcao_defensiva', 'exame_toxico', 'cartao_cnpj', 'owner_cnh_file'];
    fileFields.forEach(field => register(field));
  }, [register]);

  const handleNextStep = async () => {
    let fieldsToValidate = [];
    
    if (step === 1) {
      // Validate common fields first
      fieldsToValidate = ['forma_trabalho', 'nome_completo', 'data_nascimento', 'cpf', 'telefone', 'cnh', 'validade_cnh', 'email'];
      
      if (watch('forma_trabalho') === 'proprio') {
        fieldsToValidate.push('tipo_veiculo', 'placa_veiculo');
      }
    } else if (step === 2) {
      const requiredFiles = ['cnh_verso', 'cnh_frente', 'comprovante_residencia', 'cartao_cnpj', 'crlv'];
      if (watch('is_third_party_vehicle')) requiredFiles.push('owner_cnh_file');

      const missingFiles = requiredFiles.filter(field => {
        const hasFile = watch(field) && watch(field).length > 0;
        const hasPreview = !!filePreviews[field];
        return !hasFile && !hasPreview;
      });

      if (missingFiles.length > 0) {
        toast.error("Por favor, anexe todos os documentos obrigatórios.");
        return;
      }
    } else if (step === 3) {
      fieldsToValidate = ['cnpj', 'cep', 'endereco', 'cidade'];
    }

    const isValid = await trigger(fieldsToValidate);

    // Validação manual dos campos internos obrigatórios (superRefine não roda no trigger parcial)
    if (isInternal && step === 1) {
      let hasInternalErrors = false;

      if (!watch('coordenador') || watch('coordenador').trim() === '') {
        setError('coordenador', { type: 'manual', message: 'Nome do Coordenador é obrigatório' });
        hasInternalErrors = true;
      }
      if (!watch('modalidade') || watch('modalidade').trim() === '') {
        setError('modalidade', { type: 'manual', message: 'Modalidade é obrigatória' });
        hasInternalErrors = true;
      }
      if (!watch('base') || watch('base').trim() === '') {
        setError('base', { type: 'manual', message: 'Base de Operação é obrigatória' });
        hasInternalErrors = true;
      }

      if (hasInternalErrors) {
        toast.error("Por favor, preencha todos os campos obrigatórios.", {
          description: "Verifique os avisos em vermelho no formulário."
        });
        return;
      }
    }

    if (isValid || step === 2) {
       setStep(prev => prev + 1);
       window.scrollTo(0, 0);
    } else {
       const missingFields = fieldsToValidate.filter(field => !!errors[field]);
       if (missingFields.length > 0) {
           toast.error("Por favor, preencha todos os campos obrigatórios.", {
               description: "Verifique os avisos em vermelho no formulário."
           });
       }
    }
  };


  // Funções de máscara
  const maskCPF = (value) => value.replace(/\D/g, '').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d{1,2})$/, '$1-$2').slice(0, 14);
  const maskPhone = (value) => {
    const v = value.replace(/\D/g, '');
    if (v.length <= 10) return v.replace(/(\d{2})(\d)/, '($1) $2').replace(/(\d{4})(\d)/, '$1-$2').slice(0, 14);
    return v.replace(/(\d{2})(\d)/, '($1) $2').replace(/(\d{5})(\d)/, '$1-$2').slice(0, 15);
  };
  const maskCEP = (value) => value.replace(/\D/g, '').replace(/(\d{5})(\d)/, '$1-$2').slice(0, 9);
  const maskCNPJ = (value) => value.replace(/\D/g, '').replace(/^(\d{2})(\d)/, '$1.$2').replace(/^(\d{2})\.(\d{3})(\d)/, '$1.$2.$3').replace(/\.(\d{3})(\d)/, '.$1/$2').replace(/(\d{4})(\d)/, '$1-$2').slice(0, 18);

  const handlePrevStep = () => {
    setStep(prev => prev - 1);
    window.scrollTo(0, 0);
  };

  const onSubmit = async (data) => {
    setIsSubmitting(true);
    try {
      console.log('GR Form: Iniciando submissão', data);
      
      if (!data) throw new Error("Dados do formulário vazios.");

      const isEdit = !!data.iddrivers;
      const fileFields = ['cnh_verso', 'cnh_frente', 'comprovante_residencia', 'crlv', 'antt', 'direcao_defensiva', 'exame_toxico', 'cartao_cnpj', 'owner_cnh_file'];
      
      const payload = { ...data };

      console.log('GR [DEBUG]: ========== INÍCIO DA SUBMISSÃO ==========');
      console.log('GR [DEBUG]: Dados do formulário (data):', data);
      console.log('GR [DEBUG]: Campo base no data:', data.base);
      console.log('GR [DEBUG]: Valor atual do watch(base):', watch('base'));

      // Ajustes específicos para cadastro interno ou edição
      if (isInternal || isEdit) {
         if (payload.observacao) {
             payload.obs_cliente = payload.observacao;
             delete payload.observacao;
         }

         payload.setor = "Gestão de Risco"; 
         payload.grupo = currentUser?.grupo || 'Despachante';
         payload.base_usuario = payload.base || 'Sem resposta';
         payload.despachante = currentUser?.nome || 'Despachante';
         payload.email_despachante = currentUser?.email || 'despacho@pralog.com.br';

         if (!payload.base) {
           console.warn('GR [WARNING]: Base não selecionada. Usuário deve escolher manualmente.');
           payload.base = 'Sem resposta'; 
         }

         try {
            payload.data_envio = new Date().toLocaleDateString('pt-BR').split('/').reverse().join('-') + ' ';
         } catch (e) {
            console.error("GR Form: Erro ao formatar data_envio", e);
            payload.data_envio = new Date().toISOString().split('T')[0] + ' ';
         }
      } else {
         payload.setor = "Gestão de Risco";
         payload.grupo = "Candidato Externo";
         payload.base = "Sem Registro"; 
         payload.despachante = "Auto-Cadastro";
         payload.email_despachante = "externo@pralog.com.br";
         try {
            payload.data_envio = new Date().toLocaleDateString('pt-BR').split('/').reverse().join('-') + ' ';
         } catch (e) {
            payload.data_envio = new Date().toISOString().split('T')[0] + ' ';
         }
      }

      fileFields.forEach(field => delete payload[field]);

      console.log('GR [DEBUG]: ========== APÓS PROCESSAMENTO ==========');
      console.log('GR [DEBUG]: Payload.base:', payload.base);

      const workMode = payload.forma_trabalho;
      if (workMode === 'proprio') payload.forma_trabalho = 'veiculo_proprio';
      if (workMode === 'motorista') payload.forma_trabalho = 'veiculo_empresa';

      payload.forma_trab = payload.forma_trabalho;
      payload.placa_veiculo = payload.placa_veiculo || '';
      
      const selectedRentals = data.tipos_aluguel || [];
      if (Array.isArray(selectedRentals) && selectedRentals.length > 0) {
          payload.tipos_aluguel = selectedRentals.join(', ');
          
          if (workMode === 'motorista' && !payload.tipo_veiculo) {
              const firstRental = selectedRentals[0];
              if (firstRental === 'utilitario_leve') payload.tipo_veiculo = 'utilitario';
              else if (firstRental === 'vuc_van') payload.tipo_veiculo = 'vuc';
              else payload.tipo_veiculo = firstRental; 
          }
      } else {
          payload.tipos_aluguel = '';
      }

      payload.tipo_veiculo = payload.tipo_veiculo || '';

      console.log("GR [DEBUG]: Payload final para envio:", payload);

      const formDataObj = new FormData();
      formDataObj.append('dados_json', JSON.stringify(payload));
      
      let filesAttached = 0;
      fileFields.forEach(fieldName => {
         const files = data[fieldName];
         if (files && Array.isArray(files) && files.length > 0) {
             formDataObj.append(fieldName, files[0]);
             filesAttached++;
             console.log(`GR Form: Arquivo anexado - ${fieldName}:`, files[0].name, files[0].size, 'bytes');
         }
      });

      console.log(`GR Form: Total de arquivos anexados: ${filesAttached}`);

      let res;
      if (isEdit) {
          console.log('GR Form: Fluxo -> EDIÇÃO DE CADASTRO EXISTENTE');
          res = await updateDriverRegistration(formDataObj);
      } else if (isInternal) {
          console.log('GR Form: Fluxo -> NOVO CADASTRO INTERNO');
          res = await submitInternalDriverRegistration(formDataObj);
      } else {
          console.log('GR Form: Fluxo -> NOVO CADASTRO EXTERNO');
          res = await submitDriverRegistration(formDataObj);
      }
      
      console.log('GR Form: Resposta do servidor:', res);
      
      toast.success(isEdit ? "Cadastro atualizado!" : "Cadastro realizado com sucesso!", {
        description: isEdit ? "As alterações foram salvas com sucesso." : "Seus dados foram enviados para análise."
      });
      
      sessionStorage.removeItem('info');
      
      setSubmitted(true);
      if (onSuccess && typeof onSuccess === 'function') {
        setTimeout(() => {
            try {
                onSuccess();
            } catch (err) {
                console.error("GR Form: Erro no callback onSuccess:", err);
            }
        }, 3000);
      }

    } catch (error) {
      // Uso do handler centralizado para garantir consistência e redirecionamento
      handleGrError(error, "Não foi possível concluir o cadastro.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const onInvalid = (errors) => {
    console.warn("GR Form: Erros de validação encontrados:", errors);
    toast.error("Campos obrigatórios faltando ou inválidos", {
      description: "Por favor, revise as etapas do formulário."
    });
  };

  // Cálculo dos detalhes do aluguel
  const rentalDetailsContent = useMemo(() => {
    if (selectedRentals.length === 0) return null;
    
    const selectedData = RENTAL_TYPES.filter(t => selectedRentals.includes(t.id));
    const titles = selectedData.map(d => d.label);
    
    return (
      <div className="space-y-4 text-xs sm:text-sm animate-in fade-in slide-in-from-top-2">
        <div className="p-4 bg-emerald-50 dark:bg-emerald-900/20 border-l-4 border-emerald-500 rounded-r-xl">
            <h4 className="font-bold text-emerald-800 dark:text-emerald-400 mb-2 underline tracking-tight uppercase">Termos e Condições de Locação</h4>
            <div className="space-y-2 text-slate-700 dark:text-zinc-300">
                <p><strong>1. Modalidades Selecionadas:</strong> {titles.join(', ')}</p>
                <ul className="list-disc list-inside space-y-1">
                    {selectedData.map(d => (
                        <li key={d.id}><strong>Custo Mensal ({d.name} - Ex: {d.example}):</strong> <span className="font-bold text-emerald-700 dark:text-emerald-400">{d.price}</span></li>
                    ))}
                </ul>
                <div dangerouslySetInnerHTML={{ __html: RENTAL_TERMS_BASE }} />
                {selectedData.some(d => d.extra) && (
                    <div className="mt-3 p-3 bg-amber-50 dark:bg-amber-900/30 border-l-4 border-amber-400 text-amber-800 dark:text-amber-400 rounded-r-md text-xs italic">
                        <strong>Obs:</strong> Para VUC/Van, é obrigatória a presença de ajudante e uso de EPI (responsabilidade do locatário).
                    </div>
                )}
            </div>
        </div>
      </div>
    );
  }, [selectedRentals]);

  if (submitted) {
    return (
      <motion.div 
        initial={{ opacity: 0, scale: 0.9 }} 
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-xl mx-auto"
      >
        <Card className="border-0 shadow-2xl rounded-[40px] bg-white dark:bg-[#1a1a1a] overflow-hidden text-center p-12 space-y-6">
            <div className="w-20 h-20 bg-emerald-500 rounded-full mx-auto flex items-center justify-center shadow-lg shadow-emerald-500/20">
                <Check className="text-white" size={40} strokeWidth={3} />
            </div>
            <div className="space-y-2">
                <h2 className="text-3xl font-bold text-slate-800 dark:text-white tracking-tight leading-tight uppercase">Cadastro Recebido!</h2>
                <p className="text-slate-500 dark:text-zinc-400 font-medium leading-relaxed">
                    Obrigado por se cadastrar. Nossa equipe analisará seus dados e entrará em contato em até <strong className="text-emerald-600">72 horas</strong> com os próximos passos.
                </p>
            </div>
            <Button 
                variant="outline" 
                onClick={() => window.location.reload()}
                className="rounded-2xl px-8 h-12 uppercase text-[10px] font-bold tracking-widest"
            >
                Fazer outro cadastro
            </Button>
        </Card>
      </motion.div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      {/* Header Informativo */
      isInternal && (
      <div className="text-center space-y-4">
        <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-emerald-500 to-emerald-700 rounded-2xl shadow-xl shadow-emerald-500/20 mb-2">
             <ClipboardList className="text-white" size={32} />
        </div>
        <h1 className="text-3xl md:text-5xl font-bold text-slate-800 dark:text-white tracking-tighter leading-none">
          Cadastro de <span className="text-emerald-600">Motorista Parceiro</span>
        </h1>
        <p className="text-slate-500 dark:text-zinc-400 max-w-lg mx-auto font-medium">
          Preencha seus dados com atenção. Este processo iniciará sua análise de perfil e viabilidade operacional.
        </p>
      </div>
      )}
        
        {/* Progress Tracker */}
        <div className="flex items-center justify-center gap-4 pt-6">
            {[1, 2, 3, 4].map(num => (
                <div key={num} className="flex items-center">
                    <div className={cn(
                        "w-10 h-10 rounded-full flex items-center justify-center font-bold transition-all duration-500",
                        step >= num ? "bg-emerald-600 text-white shadow-lg shadow-emerald-500/30 scale-110" : "bg-slate-100 dark:bg-white/5 text-slate-400"
                    )}>
                        {step > num ? <Check size={20} strokeWidth={3} /> : num}
                    </div>
                    {num < 4 && <div className={cn("w-8 md:w-16 h-1 mx-2 rounded-full transition-colors duration-500", step > num ? "bg-emerald-600" : "bg-slate-100 dark:bg-white/5")}></div>}
                </div>
            ))}
        </div>


      <Card className="border-0 shadow-[0_32px_64px_-16px_rgba(0,0,0,0.1)] dark:shadow-[0_32px_64px_-16px_rgba(0,0,0,0.5)] overflow-hidden bg-white dark:bg-[#1a1a1a] rounded-[40px] border-slate-100 dark:border-white/5">
        <CardContent className="p-8 md:p-14">
            <form onSubmit={handleSubmit(onSubmit, onInvalid)}>
                <AnimatePresence mode="wait">
                    
                    {/* STEP 1: Identificação */}
                    {step === 1 && (
                        <motion.div
                            key="step1"
                            initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}
                            className="space-y-8"
                        >
                            <div className="flex items-center gap-3 border-b border-slate-100 dark:border-white/5 pb-6">
                                <div className="p-2 bg-emerald-500/10 rounded-xl"><User2 className="text-emerald-600" size={24} /></div>
                                <h2 className="text-xl font-bold text-slate-800 dark:text-zinc-100 uppercase tracking-tight">Etapa 1: Identificação</h2>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                <div className="md:col-span-2 space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Como você deseja trabalhar conosco?</Label>
                                    <Select onValueChange={(val) => setValue('forma_trabalho', val)} value={workMode}>
                                        <SelectTrigger className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 border-slate-200 dark:border-white/10 focus:ring-[var(--gr-primary)]/20 shadow-sm", errors.forma_trabalho && "border-red-500")}>
                                            <SelectValue placeholder="Selecione uma opção..." />
                                        </SelectTrigger>
                                        <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10 bg-white dark:bg-[#151515] shadow-2xl">
                                            {WORK_MODES.map(m => <SelectItem key={m.value} value={m.value} className="focus:bg-slate-100 dark:focus:bg-white/5">{m.label}</SelectItem>)}
                                        </SelectContent>
                                    </Select>
                                    {errors.forma_trabalho && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.forma_trabalho.message}</span>}
                                </div>

                                {workMode === 'proprio' && (
                                    <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} className="md:col-span-2 space-y-6">
                                        <div className="space-y-3">
                                            <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Tipo de Veículo</Label>
                                            <Select onValueChange={(val) => setValue('tipo_veiculo', val)} value={watch('tipo_veiculo')}>
                                                <SelectTrigger className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 border-slate-200 dark:border-white/10 shadow-sm", errors.tipo_veiculo && "border-red-500")}>
                                                    <SelectValue placeholder="Selecione o tipo..." />
                                                </SelectTrigger>
                                                <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10 bg-white dark:bg-[#151515] shadow-2xl">
                                                    {VEHICLE_TYPES.map(t => <SelectItem key={t.value} value={t.value} className="focus:bg-slate-100 dark:focus:bg-white/5">{t.label}</SelectItem>)}
                                                </SelectContent>
                                            </Select>
                                            {errors.tipo_veiculo && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.tipo_veiculo.message}</span>}
                                        </div>

                                        <div className="p-6 bg-emerald-50/50 dark:bg-emerald-900/10 border border-emerald-200/50 dark:border-emerald-500/20 rounded-3xl space-y-3">
                                            <div className="flex items-center gap-2 text-emerald-700 dark:text-emerald-400 font-bold text-sm uppercase">
                                                <Info size={18} /> Requisitos para Parceria:
                                            </div>
                                            <ul className="list-disc list-inside text-xs md:text-sm text-slate-600 dark:text-zinc-400 space-y-2 font-medium">
                                                <li>Ter <strong className="text-red-500 underline">CNPJ ACTIVE (MEI)</strong>.</li>
                                                <li>Veículo dentro do perfil exigido pela operação.</li>
                                                <li>Comprometimento com as rotinas e horários.</li>
                                            </ul>
                                        </div>
                                    </motion.div>
                                )}

                                {workMode === 'motorista' && (
                                    <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} className="md:col-span-2 space-y-6">
                                        <div className="p-8 bg-slate-50 dark:bg-black/20 border border-slate-200 dark:border-white/5 rounded-[32px] space-y-6">
                                            <div className="space-y-1">
                                                <h4 className="text-sm font-bold text-slate-800 dark:text-white uppercase tracking-tight">Interesse em Aluguel (Opcional)</h4>
                                                <p className="text-[11px] text-slate-400 font-medium italic">Marque as opções desejadas. Detalhes aparecerão abaixo.</p>
                                            </div>
                                            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                                                {RENTAL_TYPES.map(type => (
                                                    <div key={type.id} 
                                                        className={cn(
                                                            "flex flex-col gap-3 p-4 rounded-2xl border transition-all cursor-pointer",
                                                            selectedRentals.includes(type.id) ? "bg-emerald-500 text-white border-emerald-600 shadow-lg shadow-emerald-500/20" : "bg-white dark:bg-black/20 border-slate-200 dark:border-white/10 hover:border-emerald-500/50"
                                                        )}
                                                        onClick={() => {
                                                            const current = watch('tipos_aluguel') || [];
                                                            if (current.includes(type.id)) setValue('tipos_aluguel', current.filter(x => x !== type.id));
                                                            else setValue('tipos_aluguel', [...current, type.id]);
                                                        }}
                                                    >
                                                        <div className="flex justify-between items-start">
                                                            <div className={cn("w-6 h-6 rounded-full border-2 flex items-center justify-center", selectedRentals.includes(type.id) ? "border-white bg-white/20" : "border-slate-300")}>
                                                                {selectedRentals.includes(type.id) && <Check size={14} strokeWidth={4} />}
                                                            </div>
                                                        </div>
                                                        <div className="space-y-0.5">
                                                            <p className="text-[11px] font-bold uppercase leading-tight">{type.label}</p>
                                                            <p className={cn("text-xs font-medium", selectedRentals.includes(type.id) ? "text-white/80" : "text-emerald-600")}>{type.price}/mês</p>
                                                        </div>
                                                    </div>
                                                ))}
                                            </div>
                                            {rentalDetailsContent}
                                        </div>
                                    </motion.div>
                                )}

                                <div className="space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Nome Completo</Label>
                                    <Input {...register('nome_completo')} className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 shadow-sm", errors.nome_completo && "border-red-500")} />
                                    {errors.nome_completo && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.nome_completo.message}</span>}
                                </div>
                                <div className="space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">CPF</Label>
                                    <Input 
                                        {...register('cpf')} placeholder="000.000.000-00" 
                                        onChange={(e) => setValue('cpf', maskCPF(e.target.value))}
                                        className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 shadow-sm", errors.cpf && "border-red-500")}
                                    />
                                    {errors.cpf && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.cpf.message}</span>}
                                </div>
                                <div className="space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Telefone / WhatsApp</Label>
                                    <Input 
                                        {...register('telefone')} placeholder="(21) 99999-9999" 
                                        onChange={(e) => setValue('telefone', maskPhone(e.target.value))}
                                        className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 shadow-sm", errors.telefone && "border-red-500")}
                                    />
                                    {errors.telefone && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.telefone.message}</span>}
                                </div>
                                <div className="space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Data de Nascimento</Label>
                                    <Input type="date" {...register('data_nascimento')} className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 shadow-sm", errors.data_nascimento && "border-red-500")} />
                                    {errors.data_nascimento && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.data_nascimento.message}</span>}
                                </div>
                                <div className="space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">CNH</Label>
                                    <Input {...register('cnh')} className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 shadow-sm", errors.cnh && "border-red-500")} />
                                    {errors.cnh && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.cnh.message}</span>}
                                </div>
                                <div className="space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Validade CNH</Label>
                                    <Input type="date" {...register('validade_cnh')} className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 shadow-sm", errors.validade_cnh && "border-red-500")} />
                                    {errors.validade_cnh && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.validade_cnh.message}</span>}
                                </div>
                                <div className="md:col-span-2 grid grid-cols-1 md:grid-cols-2 gap-8">
                                    <div className="space-y-3">
                                        <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Placa do Veículo</Label>
                                        <Input {...register('placa_veiculo')} className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 shadow-sm", errors.placa_veiculo && "border-red-500")} />
                                        {errors.placa_veiculo && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.placa_veiculo.message}</span>}
                                    </div>
                                    {isInternal && (
                                    <div className="space-y-3">
                                        <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Modalidade <span className="text-red-500">*</span></Label>
                                        <Select onValueChange={(val) => setValue('modalidade', val)} value={watch('modalidade')}>
                                            <SelectTrigger className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 border-slate-200 dark:border-white/10 shadow-sm", errors.modalidade && "border-red-500")}>
                                                <SelectValue placeholder="Selecione..." />
                                            </SelectTrigger>
                                            <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10 bg-white dark:bg-[#151515] shadow-2xl">
                                                {MODALITIES.map(m => <SelectItem key={m.value} value={m.value} className="focus:bg-slate-100 dark:focus:bg-white/5">{m.label}</SelectItem>)}
                                            </SelectContent>
                                        </Select>
                                        {errors.modalidade && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.modalidade.message}</span>}
                                    </div>
                                    )}
                                </div>
                                {isInternal && (
                                <>
                                <div className="md:col-span-2 space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Nome Coordenador <span className="text-red-500">*</span></Label>
                                    <Input {...register('coordenador')} className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 shadow-sm", errors.coordenador && "border-red-500")} />
                                    {errors.coordenador && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.coordenador.message}</span>}
                                </div>
                                 <div className="md:col-span-2 space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Base de Operação <span className="text-red-500">*</span></Label>
                                    <Controller
                                      name="base"
                                      control={control}
                                      defaultValue=""
                                      render={({ field }) => (
                                        <Select 
                                          onValueChange={(val) => {
                                            console.log('GR [SELECT]: Base selecionada:', val);
                                            if (val && val !== field.value) {
                                              field.onChange(val);
                                            }
                                          }} 
                                          value={field.value || ""}
                                        >
                                            <SelectTrigger className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 border-slate-200 dark:border-white/10 shadow-sm", errors.base && "border-red-500")}>
                                                <SelectValue placeholder="Selecione a base..." />
                                            </SelectTrigger>
                                            <SelectContent className="rounded-2xl border-slate-200 dark:border-white/10 bg-white dark:bg-[#151515] shadow-2xl max-h-[200px]">
                                                {filteredBases.map(b => {
                                                  const baseValue = b.base || b.nome;
                                                  return (
                                                    <SelectItem key={b.id || b.base || b.nome} value={baseValue}>
                                                        {baseValue}
                                                    </SelectItem>
                                                  );
                                                })}
                                            </SelectContent>
                                        </Select>
                                      )}
                                    />
                                    {errors.base && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.base.message}</span>}
                                </div>
                                </>
                                )}
                                <div className="md:col-span-2 space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">E-mail</Label>
                                    <Input type="email" {...register('email')} placeholder="seu.email@exemplo.com" className={cn("h-14 rounded-2xl bg-slate-100 dark:bg-black/20 shadow-sm", errors.email && "border-red-500")} />
                                    {errors.email && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.email.message}</span>}
                                </div>
                                <div className="md:col-span-2 space-y-3">
                                    <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Observações Adicionais</Label>
                                    <Textarea {...register('observacao')} className="min-h-[120px] rounded-[32px] bg-slate-100 dark:bg-black/20 py-4 shadow-sm" />
                                </div>
                            </div>
                        </motion.div>
                    )}

                    {/* STEP 2: Documentos */}
                    {step === 2 && (
                        <motion.div
                            key="step2"
                            initial={{ opacity: 0, scale: 0.98 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.98 }}
                            className="space-y-10"
                        >
                            <div className="flex flex-col gap-2 border-b border-slate-100 dark:border-white/5 pb-8 text-center md:text-left">
                                <div className="flex items-center justify-center md:justify-start gap-3">
                                    <div className="p-2 bg-emerald-500/10 rounded-xl"><Car className="text-emerald-600" size={24} /></div>
                                    <h2 className="text-xl font-bold text-slate-800 dark:text-zinc-100 uppercase tracking-tight">Etapa 2: Documentação</h2>
                                </div>
                                <p className="text-sm text-slate-500 font-medium italic">Tire fotos nítidas ou envie arquivos em alta resolução. Formatos: PDF, JPG ou PNG.</p>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                <FileUploadField label="CNH (FRENTE)" name="cnh_frente" onChange={handleFileChange} preview={filePreviews.cnh_frente} />
                                <FileUploadField label="CNH (VERSO)" name="cnh_verso" onChange={handleFileChange} preview={filePreviews.cnh_verso} />
                                <FileUploadField label="COMPROVANTE RESIDÊNCIA" name="comprovante_residencia" onChange={handleFileChange} preview={filePreviews.comprovante_residencia} note="Água, luz ou gás (deve estar em seu nome)." />
                                
                                    <div className="md:col-span-2 p-8 bg-slate-50 dark:bg-black/20 border border-slate-200 dark:border-white/5 rounded-[40px] space-y-8">
                                        <FileUploadField label="DOCUMENTO DO VEÍCULO (CRLV)" name="crlv" onChange={handleFileChange} preview={filePreviews.crlv} />
                                        <Separator className="bg-slate-200 dark:bg-white/10" />
                                        <div className="flex items-center space-x-4 p-4 bg-white dark:bg-black/40 rounded-3xl border border-slate-100 dark:border-white/5">
                                            <Checkbox id="tpv" onCheckedChange={(c) => setValue('is_third_party_vehicle', c)} className="h-6 w-6 rounded-lg" />
                                            <Label htmlFor="tpv" className="text-sm font-bold text-slate-700 dark:text-zinc-300">O VEÍCULO ESTÁ EM NOME DE TERCEIROS?</Label>
                                        </div>
                                        {isThirdParty && (
                                            <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="pt-4">
                                                <FileUploadField label="CNH DO PROPRIETÁRIO DO VEÍCULO" name="owner_cnh_file" onChange={handleFileChange} preview={filePreviews.owner_cnh_file} />
                                            </motion.div>
                                        )}
                                    </div>
                                
                                <FileUploadField label="CARTÃO CNPJ (MEI)" name="cartao_cnpj" onChange={handleFileChange} preview={filePreviews.cartao_cnpj} note="Comprovante de inscrição e de situação cadastral." />
                                
                                <div className="md:col-span-2 pt-8">
                                    <div className="flex items-center gap-3 mb-6">
                                        <h4 className="text-xs font-bold uppercase tracking-widest text-slate-400">Documentos Adicionais (Opcionais)</h4>
                                        <div className="flex-1 h-px bg-slate-100 dark:bg-white/5"></div>
                                    </div>
                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                                        <FileUploadField label="ANTT" name="antt" onChange={handleFileChange} preview={filePreviews.antt} optional />
                                        <FileUploadField label="CURSO DIR. DEFENSIVA" name="direcao_defensiva" onChange={handleFileChange} preview={filePreviews.direcao_defensiva} optional />
                                        <FileUploadField label="EXAME TOXICOLÓGICO" name="exame_toxico" onChange={handleFileChange} preview={filePreviews.exame_toxico} optional />
                                    </div>
                                </div>
                            </div>
                        </motion.div>
                    )}

                    {/* STEP 3: Complementar */}
                    {step === 3 && (
                        <motion.div
                            key="step3"
                            initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} exit={{ opacity: 0, x: -20 }}
                            className="space-y-10"
                        >
                            <div className="flex items-center gap-3 border-b border-slate-100 dark:border-white/5 pb-6">
                                <div className="p-2 bg-emerald-500/10 rounded-xl"><MapPin className="text-emerald-600" size={24} /></div>
                                <h2 className="text-xl font-bold text-slate-800 dark:text-zinc-100 uppercase tracking-tight">Etapa 3: Dados Complementares</h2>
                            </div>

                            <div className="space-y-10">
                                <div className="space-y-6">
                                    <div className="p-4 bg-slate-50 dark:bg-black/20 rounded-[32px] border border-slate-200 dark:border-white/10 space-y-3">
                                        <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">CNPJ (MESMO QUE TERCEIRO PARA AGREGADOS)</Label>
                                        <Input 
                                            {...register('cnpj')} placeholder="00.000.000/0001-00" 
                                            onChange={(e) => setValue('cnpj', maskCNPJ(e.target.value))}
                                            className={cn("h-14 rounded-2xl bg-white dark:bg-black/10 px-6 font-bold", errors.cnpj && "border-red-500")}
                                        />
                                        {errors.cnpj && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.cnpj.message}</span>}
                                    </div>
                                </div>

                                <div className="space-y-8">
                                    <div className="flex items-center gap-3">
                                        <h4 className="text-sm font-bold text-slate-700 dark:text-zinc-300 uppercase tracking-tight">Endereço Residencial</h4>
                                        <div className="flex-1 h-px bg-slate-100 dark:bg-white/5"></div>
                                    </div>
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                         <div className="md:col-span-2 space-y-3">
                                            <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">CEP</Label>
                                            <Input 
                                                {...register('cep')} placeholder="00000-000" 
                                                onChange={(e) => setValue('cep', maskCEP(e.target.value))}
                                                onBlur={async (e) => {
                                                    const cep = e.target.value.replace(/\D/g, '');
                                                    if (cep.length === 8) {
                                                        try {
                                                            const res = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
                                                            const data = await res.json();
                                                            if (!data.erro) {
                                                                setValue('endereco', data.logradouro);
                                                                setValue('cidade', data.localidade);
                                                                setValue('bairro', data.bairro);
                                                                toast.success("Endereço localizado!");
                                                            }
                                                        } catch (err) {}
                                                    }
                                                }}
                                                className={cn("h-14 rounded-2xl bg-slate-50 dark:bg-black/20 px-6", errors.cep && "border-red-500")}
                                            />
                                            {errors.cep && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.cep.message}</span>}
                                         </div>
                                         <div className="md:col-span-2 space-y-3">
                                            <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Rua / Logradouro</Label>
                                             <Input {...register('endereco')} className={cn("h-14 rounded-2xl bg-slate-50 dark:bg-black/20 px-6", errors.endereco && "border-red-500")} />
                                             {errors.endereco && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.endereco.message}</span>}
                                         </div>
                                         <div className="space-y-3">
                                            <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Cidade</Label>
                                            <Input {...register('cidade')} className={cn("h-14 rounded-2xl bg-slate-50 dark:bg-black/20 px-6", errors.cidade && "border-red-500")} />
                                            {errors.cidade && <span className="text-[10px] text-red-500 font-bold uppercase">{errors.cidade.message}</span>}
                                         </div>
                                         <div className="space-y-3">
                                            <Label className="text-xs font-bold uppercase tracking-widest text-slate-400">Bairro</Label>
                                            <Input {...register('bairro')} className="h-14 rounded-2xl bg-slate-50 dark:bg-black/20 px-6" />
                                         </div>
                                    </div>
                                </div>
                            </div>
                        </motion.div>
                    )}

                    {/* STEP 4: Review */}
                    {step === 4 && (
                        <motion.div
                            key="step4"
                            initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.95 }}
                            className="space-y-10"
                        >
                            <div className="flex items-center gap-3 border-b border-slate-100 dark:border-white/5 pb-6">
                                <div className="p-2 bg-emerald-500/10 rounded-xl"><Building2 className="text-emerald-600" size={24} /></div>
                                <h2 className="text-xl font-bold text-slate-800 dark:text-zinc-100 uppercase tracking-tight">Etapa 4: Revisão & Envio</h2>
                            </div>

                            <div className="p-8 bg-slate-50 dark:bg-black/20 border border-slate-200 dark:border-white/5 rounded-[40px] space-y-6">
                                <h4 className="text-xs font-bold uppercase tracking-widest text-slate-400">Resumo dos Dados</h4>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-12 gap-y-4 text-sm font-medium">
                                    <p className="flex justify-between border-b border-slate-200 dark:border-white/10 pb-2">
                                        <span className="text-slate-400">Nome:</span> <span className="text-slate-900 dark:text-white font-bold uppercase">{watch('nome_completo')}</span>
                                    </p>
                                    <p className="flex justify-between border-b border-slate-200 dark:border-white/10 pb-2">
                                        <span className="text-slate-400">CPF:</span> <span className="text-slate-900 dark:text-white font-bold">{watch('cpf')}</span>
                                    </p>
                                    <p className="flex justify-between border-b border-slate-200 dark:border-white/10 pb-2">
                                        <span className="text-slate-400">Forma Trab:</span> <span className="text-emerald-600 dark:text-emerald-400 font-bold uppercase">{workMode}</span>
                                    </p>
                                    <p className="flex justify-between border-b border-slate-200 dark:border-white/10 pb-2">
                                        <span className="text-slate-400">E-mail:</span> <span className="text-slate-900 dark:text-white font-bold truncate ml-4">{watch('email')}</span>
                                    </p>
                                </div>
                            </div>

                            <div className="flex items-center space-x-4 p-8 bg-white dark:bg-black/40 border border-slate-200 dark:border-white/5 rounded-[32px] shadow-sm">
                                <Checkbox id="terms" onCheckedChange={(c) => setValue('terms', c)} className="h-8 w-8 rounded-xl" />
                                <Label htmlFor="terms" className={cn("text-sm font-bold leading-tight", errors.terms ? "text-red-500" : "text-slate-600 dark:text-zinc-400")}>
                                    Li e concordo com os <span className="text-emerald-600 underline">termos de uso</span> e a <span className="text-emerald-600 underline">política de privacidade</span>.
                                </Label>
                            </div>
                            {errors.terms && <span className="text-xs text-red-500 font-bold uppercase block text-center">Aceitação obrigatória</span>}
                        </motion.div>
                    )}
                </AnimatePresence>

                {/* Footer Buttons */}
                <div className="flex flex-col md:flex-row justify-between items-center gap-4 mt-14 pt-8 border-t border-slate-100 dark:border-white/5">
                    {step > 1 ? (
                        <Button type="button" variant="outline" onClick={handlePrevStep} disabled={isSubmitting} className="w-full md:w-auto px-10 h-14 rounded-2xl font-bold uppercase text-[10px] tracking-widest">
                            <ChevronLeft size={16} className="mr-2" /> Voltar
                        </Button>
                    ) : <div className="hidden md:block"></div>}

                    {step < 4 ? (
                        <Button type="button" onClick={handleNextStep} className="w-full md:w-auto px-12 h-14 rounded-2xl bg-emerald-600 hover:bg-emerald-700 text-white font-bold uppercase text-[10px] tracking-widest shadow-xl shadow-emerald-600/20">
                            Avançar <ChevronRight size={16} className="ml-2" />
                        </Button>
                    ) : (
                        <Button type="submit" disabled={isSubmitting || !watch('terms')} className="w-full md:w-[300px] h-14 rounded-2xl bg-emerald-600 hover:bg-emerald-700 text-white font-bold uppercase text-[10px] tracking-widest shadow-xl shadow-emerald-600/20">
                            {isSubmitting ? <><Loader2 className="animate-spin mr-2" /> Enviando Dados...</> : "Finalizar Cadastro"}
                        </Button>
                    )}
                </div>
            </form>
        </CardContent>
      </Card>
      
      {/* Footer Branding */}
      <div className="text-center space-y-2 pb-10">
        <p className="text-[10px] font-bold uppercase tracking-[0.3em] text-slate-400">Integra Finance | GR Cockpit</p>
        <p className="text-[9px] text-slate-300 dark:text-zinc-600">&copy; 2025 Pralog Logística Integrada - Todos os direitos reservados.</p>
      </div>
    </div>
  );
};

const FileUploadField = ({ label, name, onChange, preview, optional, note }) => (
    <div className="space-y-4">
        <div className="flex justify-between items-end px-1">
            <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400">{label}</Label>
            {optional && <span className="text-[9px] bg-slate-100 dark:bg-white/5 px-2 py-0.5 rounded-full text-slate-400 font-bold">OPT</span>}
        </div>
        <div className="group relative border-2 border-dashed border-slate-200 dark:border-white/5 rounded-[32px] p-6 hover:bg-emerald-50/50 dark:hover:bg-emerald-900/10 hover:border-emerald-500/50 transition-all cursor-pointer text-center h-[180px] flex flex-col justify-center overflow-hidden">
            <input 
                type="file" 
                className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10" 
                onChange={(e) => onChange(e, name)} 
                accept=".jpg,.jpeg,.png,.pdf"
            />
            {preview ? (
                <div className="h-full w-full relative">
                    <img src={preview} alt="Preview" className="h-full w-full object-contain rounded-xl" />
                    <div className="absolute inset-0 bg-black/60 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity rounded-xl">
                        <p className="text-white text-[10px] font-bold uppercase tracking-widest">Clique para Alterar</p>
                    </div>
                </div>
            ) : (
                <div className="space-y-3">
                    <div className="w-12 h-12 bg-slate-50 dark:bg-white/5 rounded-2xl mx-auto flex items-center justify-center text-slate-300 dark:text-zinc-600 group-hover:text-emerald-500 group-hover:scale-110 transition-all">
                        <Upload size={24} />
                    </div>
                    <div className="space-y-1">
                        <p className="text-[11px] font-bold text-slate-400 uppercase tracking-tight">Anexar Documento</p>
                        <p className="text-[9px] text-slate-300 dark:text-zinc-700 font-medium italic">PDF, JPG ou PNG de até 5MB</p>
                    </div>
                </div>
            )}
        </div>
        {note && <p className="text-[10px] text-slate-400 dark:text-zinc-600 font-medium italic px-2">{note}</p>}
    </div>
);
