"use client";

import { useState, useEffect } from "react";
import Image from "next/image";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import {
  User, Mail, Calendar, Briefcase, Phone, MapPin,
  Building, Globe, Lock, ShieldCheck, Zap, ChevronDown, Eye,
  UploadCloud, CheckCircle2, X, FileText
} from "lucide-react";
import { api } from "@/services/api";
import { useAuthStore } from "@/store/auth.store";
import { useCurrentUser } from "@/hooks/useCurrentUser";

// 1. Zod Schema
const registerSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters"),
  email: z.string().email("Please enter a valid email"),
  dob: z.string().min(1, "Date of birth is required"),
  role: z.string().min(1, "Please select a preferred role"),
  phone: z.string().min(10, "Phone number is required"),
  gender: z.enum(["Male", "Female", "Others"]),
  address: z.string().min(5, "Address is required"),
  pincode: z.string().min(6, "Valid pincode required"),
  area: z.string().min(2, "Area is required"),
  city: z.string().min(2, "City is required"),
  state: z.string().min(2, "State is required"),
  country: z.string().min(2, "Country is required"),
  highestQualification: z.string().optional(),
  jobTitle: z.string().optional(),
  experience: z.string().optional(),
});

type RegisterFormValues = z.infer<typeof registerSchema>;

// Reusable Input Wrapper matching the design
const InputWrapper = ({ icon: Icon, children, error }: { icon: any, children: React.ReactNode, error?: string }) => (
  <div className="flex flex-col gap-1 w-full">
    <div className={`flex items-center px-3 py-2.5 rounded-md border ${error ? 'border-red-400' : 'border-gray-200'} bg-white focus-within:border-[#ff6b00] focus-within:ring-1 focus-within:ring-[#ff6b00]/30 transition-all`}>
      <Icon className="w-4 h-4 text-gray-400 mr-2 flex-shrink-0" />
      <div className="flex-1">
        {children}
      </div>
    </div>
    {error && <span className="text-red-500 text-xs">{error}</span>}
  </div>
);

export default function RegisterPage() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const pathname = usePathname();
  const { user, refetch } = useCurrentUser();
  const phoneParam = searchParams.get("phone") || user?.phone || "";

  // React State for multi-step
  const stepParamValue = searchParams.get("step");
  const initialStep = stepParamValue ? parseInt(stepParamValue, 10) : 1;
  const totalSteps = 2;
  const [step, setStep] = useState(initialStep >= 1 && initialStep <= totalSteps ? initialStep : 1);

  useEffect(() => {
    if (stepParamValue) {
      const parsed = parseInt(stepParamValue, 10);
      if (parsed >= 1 && parsed <= totalSteps) {
        setStep(parsed);
      }
    } else {
      setStep(1);
    }
  }, [stepParamValue, totalSteps]);

  const handleStepChange = (newStep: number) => {
    setStep(newStep);
    if (newStep === 1) {
      router.push(phoneParam ? `${pathname}?phone=${phoneParam}` : pathname, { scroll: false });
    } else {
      router.push(`${pathname}?step=${newStep}${phoneParam ? `&phone=${phoneParam}` : ''}`, { scroll: false });
    }
  };

  const [roles, setRoles] = useState<{ _id?: string; id?: string; name: string }[]>([]);
  const [educationLevels, setEducationLevels] = useState<{ _id?: string; id?: string; name: string }[]>([]);
  const [experiences, setExperiences] = useState<any[]>([]);
  const [allSkills, setAllSkills] = useState<{ _id?: string; id?: string; skill_name: string; name?: string }[]>([]);
  const [loading, setLoading] = useState(false);
  const [skillsList, setSkillsList] = useState<string[]>([]);
  const [skillInput, setSkillInput] = useState("");
  const [showSkillDropdown, setShowSkillDropdown] = useState(false);
  const [resumeFile, setResumeFile] = useState<File | null>(null);

  const [allPincodes, setAllPincodes] = useState<string[]>([]);
  const [pincodeResults, setPincodeResults] = useState<any[]>([]);
  const [showPincodeDropdown, setShowPincodeDropdown] = useState(false);

  const handleAddSkill = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      const newSkill = skillInput.trim().replace(',', '');
      
      // Only allow skills that exist in the database (case-insensitive match)
      const matchedSkill = allSkills.find(
        (s) => (s.skill_name || s.name || "").toLowerCase() === newSkill.toLowerCase()
      );

      if (matchedSkill) {
        const skillName = matchedSkill.skill_name || matchedSkill.name || "";
        if (!skillsList.includes(skillName)) {
          setSkillsList([...skillsList, skillName]);
        }
      }
      setSkillInput("");
    }
  };

  const removeSkill = (skillToRemove: string) => {
    setSkillsList(skillsList.filter(s => s !== skillToRemove));
  };

  const {
    register,
    handleSubmit,
    control,
    setValue,
    watch,
    formState: { errors },
  } = useForm<RegisterFormValues>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      name: "",
      email: "",
      dob: "",
      phone: phoneParam,
      gender: "Male",
      role: "",
      address: "",
      pincode: "",
      area: "",
      city: "",
      state: "",
      country: "",
      highestQualification: "",
      jobTitle: "",
      experience: "",
    },
  });

  // Hydrate user data from context and localStorage
  useEffect(() => {
    if (user?.phone) {
      setValue("phone", user.phone);
    }
    if (user?.name) {
      setValue("name", user.name);
    }
    if (user?.email) {
      setValue("email", user.email);
    }
    
    // Load from localStorage to persist across step transitions
    if (typeof window !== "undefined") {
      const saved = localStorage.getItem('seeker_onboarding_data');
      if (saved) {
        try {
          const parsed = JSON.parse(saved);
          Object.keys(parsed).forEach(key => {
            if (parsed[key] && !['phone', 'email', 'name'].includes(key)) {
              setValue(key as any, parsed[key]);
            }
          });
        } catch (e) {}
      }
      
      const savedSkills = localStorage.getItem('seeker_onboarding_skills');
      if (savedSkills) {
        try {
          const parsedSkills = JSON.parse(savedSkills);
          if (Array.isArray(parsedSkills) && parsedSkills.length > 0) {
            setSkillsList(parsedSkills);
          }
        } catch (e) {}
      }
    }
  }, [user, setValue]);

  // Save form data to localStorage
  useEffect(() => {
    const subscription = watch((value) => {
      localStorage.setItem('seeker_onboarding_data', JSON.stringify(value));
    });
    return () => subscription.unsubscribe();
  }, [watch]);

  // Save skills to localStorage
  useEffect(() => {
    if (skillsList.length > 0) {
      localStorage.setItem('seeker_onboarding_skills', JSON.stringify(skillsList));
    }
  }, [skillsList]);

  // Initial Data Load (Roles & All Pincodes)
  useEffect(() => {
    const fetchInitialData = async () => {
      try {
        const [rolesRes, pincodesRes, educationRes, experiencesRes, skillsRes] = await Promise.all([
          api.get('/roles'),
          api.get('/area/pincodes'),
          api.get('/education_levels'),
          api.get('/experiences'),
          api.get('/skills')
        ]);
        if (rolesRes.data) setRoles(rolesRes.data);
        if (educationRes.data) setEducationLevels(educationRes.data);
        if (experiencesRes.data) setExperiences(experiencesRes.data);
        if (skillsRes.data) setAllSkills(skillsRes.data);
        if (pincodesRes.data) {
          const flatPincodes = pincodesRes.data.map((item: any) => item.pincode);
          setAllPincodes(flatPincodes);
        }
      } catch (error) {
        console.error("Failed to fetch initial data", error);
      }
    };
    fetchInitialData();
  }, []);

  const pincode = watch('pincode');

  // Auto-Suggesting as User Types
  useEffect(() => {
    const fetchPincodeSuggestions = async () => {
      if (!pincode || pincode.length < 3) {
        setPincodeResults([]);
        setShowPincodeDropdown(false);
        return;
      }

      // Step 2: Search allPincodes in memory for top 5 matches
      const matches = allPincodes
        .filter((p) => p && p.includes(pincode))
        .slice(0, 5);

      if (matches.length === 0) {
        setPincodeResults([]);
        setShowPincodeDropdown(false);
        return;
      }

      // Step 3: Fetch Deep Data concurrently
      try {
        const promises = matches.map((match) => 
          api.get(`/area/by_pincode?pincode=${match}&status=1`)
        );
        
        const responses = await Promise.all(promises);
        
        // Step 4: Formatting flattened array
        const suggestions: any[] = [];
        responses.forEach((res) => {
          if (res.data && Array.isArray(res.data)) {
            res.data.forEach((item: any) => {
              suggestions.push({
                pincode: item.pincode,
                area: item.area,
                cityName: item.city_name,
                stateName: item.state_name,
                countryName: item.country_name,
              });
            });
          }
        });

        setPincodeResults(suggestions);
        setShowPincodeDropdown(suggestions.length > 0);

      } catch (error) {
        console.error("Failed to fetch deep data for pincodes", error);
      }
    };
    
    const timeoutId = setTimeout(() => {
      fetchPincodeSuggestions();
    }, 400); // 400ms debounce

    return () => clearTimeout(timeoutId);
  }, [pincode, allPincodes]);

  const handleSelectPincodeResult = (result: any) => {
    if (result.cityName) setValue('city', result.cityName, { shouldValidate: true });
    if (result.stateName) setValue('state', result.stateName, { shouldValidate: true });
    if (result.countryName) setValue('country', result.countryName, { shouldValidate: true });
    if (result.area) setValue('area', result.area, { shouldValidate: true });
    if (result.pincode) setValue('pincode', result.pincode, { shouldValidate: true });
    
    setShowPincodeDropdown(false);
  };

  const onSubmit = async (data: RegisterFormValues) => {
    setLoading(true);

    try {
      if (step === 1) {
        if (data.email) {
          try {
            const emailCheck = await api.post('/users/check_email', { email: data.email });
            if (emailCheck.data.exists) {
              alert("Email is already registered. Please use a different email.");
              setLoading(false);
              return;
            }
          } catch (e: any) {
            console.error("Email check failed:", e);
            // Optionally alert if it explicitly returns a 400 with message
            if (e.response?.data?.message) {
              alert(e.response.data.message);
              setLoading(false);
              return;
            }
          }
        }

        // Save Step 1 data to backend incrementally
        try {
          await api.post('/users/save_onboarding_step_1', {
            userId: user?.id,
            phone: user?.phone || phoneParam,
            role: 'seeker',
            full_name: data.name,
            email: data.email,
            dateOfBirth: data.dob,
            gender: data.gender
          });
        } catch (e: any) {
          console.error("Failed to save step 1 data:", e);
          alert(e.response?.data?.message || "Failed to save data. Please try again.");
          setLoading(false);
          return;
        }

        handleStepChange(2);
        window.scrollTo({ top: 0, behavior: 'smooth' });
        setLoading(false);
      } else {
        console.log("Final Submit Data:", { ...data, skillsList, resumeFile });
        const basicsStr = localStorage.getItem('seeker_onboarding_basics');
        let fullData = { ...data };
        if (basicsStr) {
          try {
            const basics = JSON.parse(basicsStr);
            fullData = { ...basics, ...data };
            // React Hook Form might pass empty strings for unmounted fields. We must override them with our saved basics.
            if (basics.name && !data.name) fullData.name = basics.name;
            if (basics.role && !data.role) fullData.role = basics.role;
            if (basics.email && !data.email) fullData.email = basics.email;
            if (basics.dob && !data.dob) fullData.dob = basics.dob;
            if (basics.gender && !data.gender) fullData.gender = basics.gender;
          } catch (e) {
            console.error("Failed to parse basic data");
          }
        }
        
        const formData = new FormData();
        
        // Add basic user info
        if (user?.id) formData.append('userId', user.id.toString());
        if (user?.phone) formData.append('phone', user.phone);
        formData.append('role', 'seeker');
        formData.append('full_name', fullData.name || '');
        formData.append('email', fullData.email || '');
        if (fullData.dob) formData.append('dateOfBirth', fullData.dob);
        if (fullData.gender) formData.append('gender', fullData.gender);
        
        // Address info
        if (fullData.address) formData.append('communicationAddress', fullData.address);
        if (fullData.pincode) formData.append('communicationPincode', fullData.pincode);
        if (fullData.area) formData.append('communicationArea', fullData.area);
        if (fullData.city) formData.append('communicationCity', fullData.city);
        if (fullData.state) formData.append('communicationState', fullData.state);
        if (fullData.country) formData.append('communicationCountry', fullData.country);

        // Required by backend to save experience/profession IDs
        formData.append('selectedRoleCategory', 'white_collar');

        // Map step 2 dropdowns to IDs if possible
        const educationMatch = educationLevels.find(e => e.id == data.highestQualification || e._id == data.highestQualification || e.name === data.highestQualification);
        if (educationMatch?.id || educationMatch?._id) {
          formData.append('educationId', (educationMatch.id || educationMatch._id)!.toString());
        }

        const roleMatch = roles.find(r => r.id == fullData.role || r._id == fullData.role || r.name === fullData.role);
        if (roleMatch?.id || roleMatch?._id) {
          formData.append('professionId', (roleMatch.id || roleMatch._id)!.toString());
        }

        const experienceMatch = experiences.find(e => e.id == data.experience || e._id == data.experience || `${e.level} (${e.duration})` === data.experience);
        if (experienceMatch?.id || experienceMatch?._id) {
          formData.append('experienceId', (experienceMatch.id || experienceMatch._id).toString());
        }

        // Skills (pass array of IDs or names based on backend capability, we send names as string and IDs as array)
        const selectedSkillIds = allSkills
          .filter(s => skillsList.includes(s.skill_name || s.name || ""))
          .map(s => s.id || s._id)
          .filter(Boolean);
          
        selectedSkillIds.forEach(id => {
          if (id) formData.append('skillsIds', id.toString());
        });
        formData.append('skills', JSON.stringify(skillsList));

        if (resumeFile) formData.append('resume', resumeFile);

        // Submit to complete onboarding
        const res = await api.post('/users/complete_onboarding', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        
        console.log("Onboarding complete response:", res.data);

        // Clear local storage on success
        localStorage.removeItem('seeker_onboarding_data');
        localStorage.removeItem('seeker_onboarding_skills');

        // After API updates onboarding_status to completed in database, we refetch to update cookies and UI
        await refetch();
        
        // Redirect to dashboard
        router.push("/seeker/dashboard");
      }
    } catch (error: any) {
      console.error("Failed to complete onboarding:", error?.response?.data || error);
      alert(error?.response?.data?.message || "Failed to complete onboarding. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex bg-gray-50/50">

      {/* Left Column - Visuals (Hidden on smaller screens) */}
      <div className="hidden lg:flex lg:w-[400px] xl:w-[480px] bg-[#fff2ed] flex-col relative overflow-hidden">
        {/* Background gradient overlay to simulate the orange circle */}
        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[400px] h-[400px] bg-[#ff7a29] rounded-full blur-[80px] opacity-20 pointer-events-none"></div>

        {/* Content Container */}
        <div className="flex-1 flex flex-col p-8 z-10 relative">

          {/* Logo */}
          <div className="mb-10">
            <Image src="/images/jobvumi-logo.png" alt="Jobvumi" width={130} height={42} className="object-contain" />
          </div>

          {/* Step Badge */}
          <div className="bg-orange-100/80 text-[#ff6b00] text-xs font-semibold px-3 py-1.5 rounded-full inline-flex items-center w-fit mb-6">
            <span className="mr-1"></span> Step {step} of {totalSteps}
          </div>

          {/* Heading */}
          <h1 className="text-4xl font-bold leading-[1.15] text-[#111] mb-4">
            Let's set up<br />
            your <span className="text-[#ff6b00]">profile</span>
          </h1>
          <p className="text-gray-600 text-sm max-w-[280px] mb-8">
            This helps employers find the right opportunities for you.
          </p>

          {/* Main Image */}
          <div className="relative flex-1 min-h-[300px] flex items-end justify-center -mb-8 -mx-8 mt-auto">
            <Image
              src="/images/register-seeker.png"
              alt="Professional Professionals"
              fill
              className="object-contain object-bottom"
              priority
            />
          </div>
        </div>

        {/* Bottom Trust Badges */}
        <div className="bg-white border-t border-gray-100 py-4 px-6 flex justify-between items-center z-10 relative">
          <div className="flex items-center gap-1.5 text-[11px] font-medium text-gray-700">
            <Lock className="w-3.5 h-3.5 text-[#ff6b00]" />
            100% Secure
          </div>
          <div className="flex items-center gap-1.5 text-[11px] font-medium text-gray-700">
            <ShieldCheck className="w-3.5 h-3.5 text-[#ff6b00]" />
            <div className="leading-tight">Trusted by<br />Top Employers</div>
          </div>
          <div className="flex items-center gap-1.5 text-[11px] font-medium text-gray-700">
            <Zap className="w-3.5 h-3.5 text-[#ff6b00]" />
            <div className="leading-tight">Quick & Easy<br />Setup</div>
          </div>
        </div>
      </div>

      {/* Right Column - Form */}
      <div className="flex-1 flex flex-col justify-center items-center p-4 sm:p-6 lg:p-10 overflow-y-auto">
        <div className="w-full max-w-[700px]">

          {step === 1 ? (
            <form onSubmit={handleSubmit(onSubmit)} className="animate-in fade-in slide-in-from-right-4 duration-300">

              {/* Basic Details Section */}
              <div className="mb-6">
                <h2 className="text-lg font-semibold text-gray-900 mb-3">Basic Details</h2>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-3">

                  {/* Name */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Name</label>
                    <InputWrapper icon={User} error={errors.name?.message}>
                      <input
                        {...register("name")}
                        placeholder="Enter your name"
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400"
                      />
                    </InputWrapper>
                  </div>

                  {/* Preferred Role */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Preferred Role</label>
                    <InputWrapper icon={Briefcase} error={errors.role?.message}>
                      <select
                        {...register("role")}
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400 appearance-none cursor-pointer"
                      >
                        <option value="" disabled>Choose a role</option>
                        {roles.map((r, idx) => (
                          <option key={r.id || r._id || idx} value={r.id || r._id || r.name}>{r.name}</option>
                        ))}
                      </select>
                    </InputWrapper>
                  </div>

                  {/* Email */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Email</label>
                    <InputWrapper icon={Mail} error={errors.email?.message}>
                      <input
                        type="email"
                        {...register("email")}
                        placeholder="Enter your email"
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400"
                      />
                    </InputWrapper>
                  </div>

                  {/* Phone */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Phone Number</label>
                    <InputWrapper icon={Phone} error={errors.phone?.message}>
                      <Controller
                        name="phone"
                        control={control}
                        render={({ field }) => (
                          <input
                            {...field}
                            type="tel"
                            value={field.value || ""}
                            placeholder="+91 Enter your number"
                            readOnly
                            className="w-full text-sm outline-none bg-gray-50/50 text-gray-500 cursor-not-allowed placeholder:text-gray-400"
                          />
                        )}
                      />
                    </InputWrapper>
                  </div>

                  {/* DOB */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Date of Birth</label>
                    <InputWrapper icon={Calendar} error={errors.dob?.message}>
                      <input
                        type="date"
                        {...register("dob")}
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400 cursor-text"
                      />
                    </InputWrapper>
                  </div>

                  {/* Gender (Radio Group) */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Gender</label>
                    <Controller
                      name="gender"
                      control={control}
                      render={({ field }) => (
                        <div className="flex items-center gap-3">
                          {["Male", "Female", "Others"].map((g) => {
                            const isSelected = field.value === g;
                            return (
                              <button
                                key={g}
                                type="button"
                                onClick={() => field.onChange(g)}
                                className={`flex-1 py-2.5 rounded-md border text-sm flex items-center justify-center gap-2 transition-colors ${isSelected
                                    ? 'border-[#ff6b00] bg-orange-50 text-[#ff6b00] shadow-sm'
                                    : 'border-gray-200 bg-white text-gray-500 hover:bg-gray-50'
                                  }`}
                              >
                                {g === "Male" && <span className="text-base">♂</span>}
                                {g === "Female" && <span className="text-base">♀</span>}
                                {g === "Others" && <span className="text-base">⚥</span>}
                                {g}
                              </button>
                            );
                          })}
                        </div>
                      )}
                    />
                    {errors.gender && <span className="text-red-500 text-xs mt-1 block">{errors.gender.message}</span>}
                  </div>

                </div>
              </div>

              {/* Address Details Section */}
              <div>
                <h2 className="text-lg font-semibold text-gray-900 mb-3">Address Details</h2>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-3">

                  {/* Current Address */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Current Address</label>
                    <InputWrapper icon={MapPin} error={errors.address?.message}>
                      <input
                        {...register("address")}
                        placeholder="Enter your address"
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400"
                      />
                    </InputWrapper>
                  </div>

                  {/* Pincode */}
                  <div className="relative">
                    <label className="block text-sm text-gray-600 mb-1">Pincode</label>
                    <InputWrapper icon={MapPin} error={errors.pincode?.message}>
                      <input
                        {...register("pincode")}
                        placeholder="Enter your pincode"
                        autoComplete="off"
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400"
                        onFocus={() => {
                          if (pincodeResults.length > 0) setShowPincodeDropdown(true);
                        }}
                      />
                    </InputWrapper>

                    {/* Dropdown */}
                    {showPincodeDropdown && pincodeResults.length > 0 && (
                      <div className="absolute top-[105%] left-0 w-full bg-white border border-gray-200 rounded-md shadow-lg z-50 max-h-60 overflow-y-auto">
                        {pincodeResults.map((result, idx) => (
                          <div 
                            key={idx}
                            className="p-3 border-b border-gray-100 cursor-pointer hover:bg-gray-50 transition-colors last:border-0"
                            onClick={() => handleSelectPincodeResult(result)}
                          >
                            <div className="font-bold text-gray-900 text-[13px]">{result.pincode}</div>
                            <div className="text-gray-500 text-[12px] mt-0.5">{result.area}</div>
                            <div className="text-gray-400 text-[11px] mt-0.5">{result.cityName}, {result.stateName}, {result.countryName}</div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>

                  {/* Area */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Area</label>
                    <InputWrapper icon={MapPin} error={errors.area?.message}>
                      <input
                        {...register("area")}
                        placeholder="Enter your area"
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400"
                      />
                    </InputWrapper>
                  </div>

                  {/* State */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">State</label>
                    <InputWrapper icon={Building} error={errors.state?.message}>
                      <input
                        {...register("state")}
                        placeholder="State"
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400"
                      />
                    </InputWrapper>
                  </div>

                  {/* City */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">City</label>
                    <InputWrapper icon={Building} error={errors.city?.message}>
                      <input
                        {...register("city")}
                        placeholder="City"
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400"
                      />
                    </InputWrapper>
                  </div>

                  {/* Country */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1.5">Country</label>
                    <InputWrapper icon={Globe} error={errors.country?.message}>
                      <input
                        {...register("country")}
                        placeholder="Country"
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400"
                      />
                    </InputWrapper>
                  </div>

                </div>
              </div>

              {/* Submit Button */}
              <div className="mt-6 flex justify-end">
                <button
                  type="submit"
                  disabled={loading}
                  className="w-full md:w-auto md:min-w-[240px] px-8 py-3 bg-[#e2e2e2] text-gray-500 hover:text-white font-medium rounded-md hover:bg-[#ff6b00] focus:ring-4 focus:ring-gray-200 transition-colors flex justify-center items-center shadow-sm disabled:opacity-70 disabled:cursor-not-allowed"
                >
                  {loading ? (
                    <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  ) : (
                    "Continue"
                  )}
                </button>
              </div>
            </form>
          ) : (
            <form onSubmit={handleSubmit(onSubmit)} className="animate-in fade-in slide-in-from-right-4 duration-300">
              {/* Professional Details Section */}
              <div className="mb-6">
                <h2 className="text-lg font-semibold text-gray-900 mb-3">Professional Details</h2>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-3">

                  {/* Highest Qualification */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Highest Qualification</label>
                    <InputWrapper icon={User} error={errors.highestQualification?.message}>
                      <select
                        {...register("highestQualification")}
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400 appearance-none cursor-pointer"
                      >
                        <option value="" disabled>Select Qualification</option>
                        {educationLevels.map((ed, idx) => (
                          <option key={ed.id || ed._id || idx} value={ed.id || ed._id || ed.name}>
                            {ed.name}
                          </option>
                        ))}
                      </select>
                    </InputWrapper>
                  </div>

                  {/* Job Title */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Job Title</label>
                    <InputWrapper icon={Briefcase} error={errors.jobTitle?.message}>
                      <select
                        {...register("jobTitle")}
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400 appearance-none cursor-pointer"
                      >
                        <option value="" disabled>Select Job Title</option>
                        {roles.map((r, idx) => (
                          <option key={r.id || r._id || idx} value={r.id || r._id || r.name}>
                            {r.name}
                          </option>
                        ))}
                      </select>
                    </InputWrapper>
                  </div>

                  {/* Experience */}
                  <div>
                    <label className="block text-sm text-gray-600 mb-1">Experience</label>
                    <InputWrapper icon={Briefcase} error={errors.experience?.message}>
                      <select
                        {...register("experience")}
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400 appearance-none cursor-pointer"
                      >
                        <option value="" disabled>Select Experience</option>
                        {experiences.map((exp, idx) => {
                          const displayValue = `${exp.level} (${exp.duration})`;
                          return (
                            <option key={exp.id || exp._id || idx} value={exp.id || exp._id || displayValue}>
                              {displayValue}
                            </option>
                          );
                        })}
                      </select>
                    </InputWrapper>
                  </div>

                  {/* Skills */}
                  <div className="relative">
                    <label className="block text-sm text-gray-600 mb-1">Skills</label>
                    <InputWrapper icon={User} error={undefined}>
                      <input
                        value={skillInput}
                        onChange={(e) => {
                          setSkillInput(e.target.value);
                          setShowSkillDropdown(true);
                        }}
                        onFocus={() => setShowSkillDropdown(true)}
                        onBlur={() => setTimeout(() => setShowSkillDropdown(false), 200)}
                        onKeyDown={handleAddSkill}
                        placeholder="Search & add skills"
                        className="w-full text-sm outline-none bg-transparent text-gray-800 placeholder:text-gray-400"
                      />
                    </InputWrapper>
                    
                    {/* Skills Dropdown */}
                    {showSkillDropdown && (
                      <div className="absolute top-[105%] left-0 w-full bg-white border border-gray-200 rounded-md shadow-lg z-50 max-h-48 overflow-y-auto">
                        {allSkills
                          .filter(s => {
                            const nameToMatch = s.skill_name || s.name || "";
                            return nameToMatch.toLowerCase().includes(skillInput.toLowerCase()) && !skillsList.includes(nameToMatch);
                          })
                          .map((skill, idx) => {
                            const displayName = skill.skill_name || skill.name || "";
                            return (
                              <div 
                                key={skill.id || skill._id || idx}
                                className="p-3 border-b border-gray-100 cursor-pointer hover:bg-gray-50 transition-colors last:border-0 text-[13px] text-gray-800"
                                onClick={() => {
                                  setSkillsList([...skillsList, displayName]);
                                  setSkillInput("");
                                  setShowSkillDropdown(false);
                                }}
                              >
                                {displayName}
                              </div>
                            );
                          })}
                      </div>
                    )}

                    {skillsList.length > 0 && (
                      <div className="flex flex-wrap gap-2 mt-3">
                        {skillsList.map((skill) => (
                          <div key={skill} className="flex items-center gap-1.5 px-3 py-1 bg-white border border-[#ff6b00]/30 rounded-full text-xs text-[#ff6b00] font-medium shadow-sm">
                            {skill}
                            <button type="button" onClick={() => removeSkill(skill)} className="hover:text-red-500 focus:outline-none">
                              <X className="w-3 h-3" />
                            </button>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Resume Section */}
              <div className="mb-6">
                <h2 className="text-lg font-semibold text-gray-900 mb-3">Resume</h2>
                <div className="border border-dashed border-gray-400 rounded-lg p-6 bg-white flex flex-col items-center justify-center text-center relative hover:bg-gray-50 transition-colors">
                  <input
                    type="file"
                    className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                    accept=".pdf,.doc,.docx"
                    onChange={(e) => {
                      if (e.target.files && e.target.files[0]) {
                        setResumeFile(e.target.files[0]);
                      }
                    }}
                  />
                  <UploadCloud className="w-8 h-8 text-gray-800 mb-3" />
                  <p className="text-sm font-medium text-gray-900 mb-1">Update your resume</p>
                  <p className="text-xs text-gray-500 mb-4">PDF, DOC, DOCX (Max 5MB)</p>
                  <button type="button" className="px-6 py-2 border border-[#ff6b00] text-[#ff6b00] rounded-md text-sm font-medium hover:bg-orange-50 transition-colors pointer-events-none">
                    Browse File
                  </button>
                </div>

                {resumeFile && (
                  <div className="mt-4 flex items-center justify-between p-4 bg-white border border-gray-200 rounded-lg shadow-sm">
                    <div className="flex items-center gap-4">
                      <div className="w-10 h-10 bg-red-500 rounded-md flex items-center justify-center text-white flex-shrink-0">
                        <FileText className="w-5 h-5" />
                      </div>
                      <div className="flex flex-col text-left">
                        <span className="text-sm font-semibold text-gray-900 truncate max-w-[200px] sm:max-w-[300px]">{resumeFile.name}</span>
                        <span className="text-xs text-gray-500">{(resumeFile.size / (1024 * 1024)).toFixed(1)} MB</span>
                      </div>
                    </div>
                    <CheckCircle2 className="w-6 h-6 text-green-500 flex-shrink-0" />
                  </div>
                )}
              </div>

              {/* Navigation Buttons */}
              <div className="flex gap-4">
                <button
                  type="button"
                  onClick={() => {
                    handleStepChange(1);
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                  }}
                  disabled={loading}
                  className="flex-1 py-3 bg-transparent border border-gray-900 text-gray-900 font-medium rounded-md hover:bg-gray-50 transition-colors focus:ring-4 focus:ring-gray-100 disabled:opacity-70 text-sm"
                >
                  Previous
                </button>
                <button
                  type="submit"
                  disabled={loading}
                  className="flex-[2] py-3 bg-[#ff6b00] text-white font-medium rounded-md hover:bg-[#e66000] focus:ring-4 focus:ring-[#ff6b00]/30 transition-colors flex justify-center items-center shadow-sm disabled:opacity-70 disabled:cursor-not-allowed text-sm"
                >
                  {loading ? (
                    <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  ) : (
                    "Continue"
                  )}
                </button>
              </div>
            </form>
          )}

        </div>
      </div>
    </div>
  );
}
