'use client';

import { useState, useEffect, useRef } from 'react';
import { Eye, EyeOff, Loader, RefreshCcw, Check, X, ChevronDown } from 'lucide-react';
import Link from 'next/link';
import Image from 'next/image';
import { useAppDispatch } from '@/hooks/useRedux';
import { signUpStart, signUpFailure } from '@/lib/store/slices/userSlice';
import { createBusinessProfile, getVerificationCaptcha, verifyCaptcha, getAllBusinessTypes, getLabelsByScreenAndType } from '@/lib/api/client';
import { validateEmail, validatePhone, validateName, calculateAge } from '@/lib/utils/helpers';
import { detectLocation } from '@/lib/utils/ipDetection';
import { toast } from 'sonner';

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

interface BusinessProfileFormProps {
  logoImage?: any;
  countries?: any[];
  onSuccess: (userData: any) => void;
  loading: boolean;
}

export function BusinessProfileForm({ logoImage, countries = [], onSuccess, loading }: BusinessProfileFormProps) {
  const dispatch = useAppDispatch();
  
  // Dynamic Labels
  const [labels, setLabels] = useState({
    personalInfo: {} as Record<string, string>,
    businessInfo: {} as Record<string, string>,
    formButtons: {} as Record<string, string>,
  });
  const [isLoadingLabels, setIsLoadingLabels] = useState(true);
  
  // UI States
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [selectedCountryFlag, setSelectedCountryFlag] = useState('');
  const [selectedBusinessPhoneFlag, setSelectedBusinessPhoneFlag] = useState('');
  const [showCountryDropdown, setShowCountryDropdown] = useState(false);
  const [showBusinessPhoneDropdown, setShowBusinessPhoneDropdown] = useState(false);
  
  // Dynamic business types
  const [businessTypes, setBusinessTypes] = useState<any[]>([]);
  const [isLoadingBusinessTypes, setIsLoadingBusinessTypes] = useState(true);
  
  // Password validation states
  const [passwordStrength, setPasswordStrength] = useState({
    hasSpecialChar: false,
    hasNumber: false,
    hasAlphabet: false,
    hasUppercase: false,
    hasMinLength: false,
  });
  
  const [confirmPassword, setConfirmPassword] = useState("");
  const [confirmPasswordStrength, setConfirmPasswordStrength] = useState({
    hasSpecialChar: false,
    hasNumber: false,
    hasAlphabet: false,
    hasUppercase: false,
    hasMinLength: false,
  });
  const [isPasswordFieldTouched, setIsPasswordFieldTouched] = useState(false);
  const [isConfirmPasswordFieldTouched, setIsConfirmPasswordFieldTouched] = useState(false);
  
  // Refs for tooltips
  const passwordRef = useRef<HTMLDivElement>(null);
  const confirmPasswordRef = useRef<HTMLDivElement>(null);
  const passwordTooltipRef = useRef<HTMLDivElement>(null);
  const confirmPasswordTooltipRef = useRef<HTMLDivElement>(null);
  const countryDropdownRef = useRef<HTMLDivElement>(null);
  const businessPhoneDropdownRef = useRef<HTMLDivElement>(null);
  
  // CAPTCHA
  const [captchaData, setCaptchaData] = useState({ svg: '' });
  const [captchaInput, setCaptchaInput] = useState('');
  const [captchaError, setCaptchaError] = useState('');
  
  // Form Data
  const [formData, setFormData] = useState({
    fullName: '',
    email: '',
    password: '',
    phone: '',
    dateOfBirth: '',
    countryCode: '+91',
    businessCountryCode: '+91',
    country: 'India',
    countryId: '',
    organizationName: '',
    businessType: '',
    businessEmail: '',
    businessPhone: '',
    address: '',
    website: '',
    ipAddress: '',
    timezone: 'Asia/Kolkata',
    currency: 'INR',
    termsAccepted: false,
  });

  const isPasswordValid = Object.values(passwordStrength).every(Boolean);
  const doPasswordsMatch = formData.password && confirmPassword && formData.password === confirmPassword;

  // Fetch dynamic labels
  useEffect(() => {
    const fetchLabels = async () => {
      try {
        const result = await getLabelsByScreenAndType('beforlogin', 'business', logoImage?.securityKey);
        
        if (result.success && result.data) {
          const labelsData = {
            personalInfo: {} as Record<string, string>,
            businessInfo: {} as Record<string, string>,
            formButtons: {} as Record<string, string>,
          };
          
          result.data.forEach((item: any) => {
            if (item.section === 'personal_information') {
              labelsData.personalInfo[item.label] = item.value;
            } else if (item.section === 'business_details') {
              labelsData.businessInfo[item.label] = item.value;
            } else if (item.section === 'form_buttons') {
              labelsData.formButtons[item.label] = item.value;
            }
          });
          
          setLabels(labelsData);
        }
        setIsLoadingLabels(false);
      } catch (error) {
        console.error('Failed to fetch labels:', error);
        setIsLoadingLabels(false);
      }
    };
    
    fetchLabels();
  }, [logoImage?.securityKey]);

  // Handle click outside to close tooltips and dropdown
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        passwordTooltipRef.current &&
        !passwordTooltipRef.current.contains(event.target as Node) &&
        passwordRef.current &&
        !passwordRef.current.contains(event.target as Node)
      ) {
        setIsPasswordFieldTouched(false);
      }

      if (
        confirmPasswordTooltipRef.current &&
        !confirmPasswordTooltipRef.current.contains(event.target as Node) &&
        confirmPasswordRef.current &&
        !confirmPasswordRef.current.contains(event.target as Node)
      ) {
        setIsConfirmPasswordFieldTouched(false);
      }

      if (
        countryDropdownRef.current &&
        !countryDropdownRef.current.contains(event.target as Node)
      ) {
        setShowCountryDropdown(false);
      }

      if (
        businessPhoneDropdownRef.current &&
        !businessPhoneDropdownRef.current.contains(event.target as Node)
      ) {
        setShowBusinessPhoneDropdown(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);
  
  // Fetch business types from API
 // Fetch business types from API
useEffect(() => {
  const fetchBusinessTypes = async () => {
    try {
      const result = await getAllBusinessTypes(logoImage?.securityKey);
      
      if (result.success && result.data) {
        // Now result.data should be the array directly
        const businessTypesData = Array.isArray(result.data) ? result.data : [];
        setBusinessTypes(businessTypesData);
      } else {
        console.error('Failed to fetch business types:', result.message);
        setBusinessTypes([]);
      }
      setIsLoadingBusinessTypes(false);
    } catch (error) {
      console.error('Failed to fetch business types:', error);
      setBusinessTypes([]);
      setIsLoadingBusinessTypes(false);
    }
  };

  fetchBusinessTypes();
}, [logoImage?.securityKey]);
  
  // Password strength checker
  const checkPasswordStrength = (password: string) => {
    setPasswordStrength({
      hasSpecialChar: /[\W_]/.test(password),
      hasNumber: /\d/.test(password),
      hasAlphabet: /[a-zA-Z]/.test(password),
      hasUppercase: /[A-Z]/.test(password),
      hasMinLength: password.length >= 8,
    });
  };
  
  const checkConfirmPasswordStrength = (password: string) => {
    setConfirmPasswordStrength({
      hasSpecialChar: /[\W_]/.test(password),
      hasNumber: /\d/.test(password),
      hasAlphabet: /[a-zA-Z]/.test(password),
      hasUppercase: /[A-Z]/.test(password),
      hasMinLength: password.length >= 8,
    });
  };
  
  // Fetch location and CAPTCHA
  useEffect(() => {
    const init = async () => {
      try {
        const location = await detectLocation(logoImage?.securityKey);
        setFormData(prev => ({
          ...prev,
          ipAddress: location.ip,
          country: location.country,
          countryCode: location.countryCode,
          businessCountryCode: location.countryCode,
          timezone: location.timezone,
          currency: location.currency,
        }));
        
        const matchedCountry = countries.find(c => c.scode === location.countrySortname);
        if (matchedCountry) {
          const countryCodeValue = `+${matchedCountry.phonecode}`;
          setFormData(prev => ({ 
            ...prev, 
            countryId: matchedCountry._id,
            countryCode: countryCodeValue,
            businessCountryCode: countryCodeValue,
            country: matchedCountry.billcountry || matchedCountry.countryName || location.country
          }));
          setSelectedCountryFlag(matchedCountry.countryFlag || '');
          setSelectedBusinessPhoneFlag(matchedCountry.countryFlag || '');
        }
      } catch (err) {
        console.error('Location detection failed:', err);
      }
      
      await fetchCaptcha();
    };
    if (countries.length > 0) {
      init();
    } else {
      fetchCaptcha();
    }
  }, [countries]);
  
  const fetchCaptcha = async () => {
    try {
      const result = await getVerificationCaptcha(logoImage?.securityKey);
      if (result.success && result.data?.captcha) {
        setCaptchaData({ svg: result.data.captcha });
        setCaptchaInput('');
        setCaptchaError('');
      }
    } catch (err) {
      toast.error('Failed to load CAPTCHA');
    }
  };
  
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : name === 'email' || name === 'businessEmail' ? value.toLowerCase() : value,
    }));
  };
  
  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    checkPasswordStrength(value);
    if (value) {
      setIsPasswordFieldTouched(true);
    }
  };
  
  const handleConfirmPasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setConfirmPassword(e.target.value);
    checkConfirmPasswordStrength(e.target.value);
    if (e.target.value) {
      setIsConfirmPasswordFieldTouched(true);
    }
  };
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

     if (isSubmitting) {
    return;
  }
    
    // Personal validations
    if (!formData.fullName || !formData.email || !formData.password || !formData.phone || !formData.dateOfBirth) {
      toast.error('Please fill all personal details');
      return;
    }
    
    if (!validateName(formData.fullName)) {
      toast.error('Full name can only contain letters and spaces');
      return;
    }
    
    if (!validateEmail(formData.email)) {
      toast.error('Invalid email format');
      return;
    }
    
    if (!isPasswordValid) {
      toast.error('Password must be at least 8 characters with uppercase, lowercase, number and special character');
      return;
    }
    
    if (!doPasswordsMatch) {
      toast.error('Passwords do not match');
      return;
    }
    
    if (!validatePhone(formData.phone)) {
      toast.error('Phone number must be 10-12 digits');
      return;
    }
    
    const age = calculateAge(formData.dateOfBirth);
    if (age < 18) {
      toast.error('You must be at least 18 years old');
      return;
    }
    
    // Business validations
    if (!formData.organizationName) {
      toast.error('Organization name is required');
      return;
    }
    
    if (!formData.businessType) {
      toast.error('Business type is required');
      return;
    }
    
    if (!formData.businessEmail) {
      toast.error('Business email is required');
      return;
    }
    
    if (!validateEmail(formData.businessEmail)) {
      toast.error('Invalid business email format');
      return;
    }
    
  
    
    if (!formData.termsAccepted) {
      toast.error('Please accept terms and conditions');
      return;
    }
    
    if (!captchaInput) {
      setCaptchaError('Please enter CAPTCHA');
      return;
    }
    
    setIsSubmitting(true);
    dispatch(signUpStart());
    
    try {
    const captchaResult = await verifyCaptcha(captchaInput, logoImage?.securityKey);
    
    if (!captchaResult.success) {
      toast.error(captchaResult.message || 'CAPTCHA is incorrect!');
      fetchCaptcha();
      setCaptchaInput('');
      setCaptchaError('CAPTCHA is incorrect!');
      setIsSubmitting(false);
       dispatch(signUpFailure(captchaResult.message || 'CAPTCHA is incorrect!')); // ✅ ADD THIS
      return;
    }
      
      const result = await createBusinessProfile(formData, logoImage?.securityKey);
      
     if (result.success) {
      toast.success(result.message);
      // ✅ Store email for OTP verification
  localStorage.setItem('email', formData.email);
  localStorage.setItem('message', 'signup')
      onSuccess(result.data?.customer);
    } else {
      dispatch(signUpFailure(result.message));
      toast.error(result.message);
    }
    setIsSubmitting(false);
  } catch (error) {
    console.error('❌ Catch block error:', error);
    dispatch(signUpFailure('Failed to create business profile'));
    toast.error('Failed to create business profile');
    setIsSubmitting(false);
  }
  };
  
  const isFormValid = formData.fullName && formData.email && isPasswordValid && doPasswordsMatch &&
    formData.phone && formData.dateOfBirth && formData.organizationName && formData.businessType &&
    formData.businessEmail  && formData.termsAccepted && captchaInput;
  
  // Show skeleton while loading labels
  if (isLoadingLabels) {
    return (
      <div className="w-full max-h-[70vh] overflow-y-auto pr-1 ">
        <div className="space-y-3 animate-pulse">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-2">
            <div><div className="h-2 w-16 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
            <div><div className="h-2 w-20 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-2">
            <div><div className="h-2 w-14 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
            <div><div className="h-2 w-20 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-2">
            <div><div className="h-2 w-20 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
            <div><div className="h-2 w-16 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
            <div><div className="h-2 w-28 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
            <div><div className="h-2 w-20 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
            <div><div className="h-2 w-24 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
            <div><div className="h-2 w-24 bg-gray-200 rounded mb-1"></div><div className="h-9 bg-gray-200 rounded-lg"></div></div>
          </div>
        </div>
      </div>
    );
  }
  
  return (
<div className="w-full max-h-[70vh] overflow-y-auto pr-1 custom-scrollbar">
      <form onSubmit={handleSubmit} className="space-y-1">
        {/* ===== PERSONAL DETAILS ===== */}
        <div>
          <h3 className="text-[13px] font-semibold text-[#1E222A] mb-3 flex items-center gap-2">
            <span className="w-1 h-4 bg-[#0084a5] rounded-full"></span>
            {labels.personalInfo.section_title || 'Personal Information'}
          </h3>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
            <div>
              <label className="text-[13px] text-[#1E222A]">
                {labels.personalInfo.full_name || 'Full Name'} <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                name="fullName"
                value={formData.fullName}
                onChange={handleChange}
                disabled={loading || isSubmitting}
                placeholder={labels.personalInfo.full_name_placeholder || 'Enter your full name'}
                className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm"
              />
            </div>
            
            <div>
              <label className="text-[13px] text-[#1E222A]">
                {labels.personalInfo.email || 'Email Address'} <span className="text-red-500">*</span>
              </label>
              <input
                type="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                disabled={loading || isSubmitting}
                placeholder={labels.personalInfo.email_placeholder || 'Enter your email'}
                className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm"
              />
            </div>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
            <div className="relative">
              <label className="text-[13px] text-[#1E222A]">
                {labels.personalInfo.password || 'Password'} <span className="text-red-500">*</span>
              </label>
              <div className="relative" ref={passwordRef}>
                <input
                  type={showPassword ? "text" : "password"}
                  name="password"
                  value={formData.password}
                  onChange={handlePasswordChange}
                  onFocus={() => setIsPasswordFieldTouched(true)}
                  disabled={loading || isSubmitting}
                  placeholder="********"
                  className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm pr-10"
                />
                <span
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute inset-y-0 right-3 flex items-center text-[#77829D] cursor-pointer"
                >
                  {showPassword ? <Eye size={18} /> : <EyeOff size={18} />}
                </span>
              </div>

              {isPasswordFieldTouched && formData.password && (
                <div
                  ref={passwordTooltipRef}
                  className="absolute z-50 w-full mt-1 p-3 rounded-lg bg-white shadow-lg border border-gray-200"
                >
                  <div className="mb-2">
                    <div className="w-full bg-gray-200 rounded-full h-1.5">
                      <div
                        className={`h-1.5 rounded-full transition-all duration-300 ${
                          Object.values(passwordStrength).filter(Boolean).length === 5
                            ? "bg-green-500"
                            : Object.values(passwordStrength).filter(Boolean).length >= 3
                            ? "bg-yellow-500"
                            : "bg-red-500"
                        }`}
                        style={{
                          width: `${(Object.values(passwordStrength).filter(Boolean).length / 5) * 100}%`,
                        }}
                      ></div>
                    </div>
                  </div>
                  {[
                    { key: "hasMinLength", label: "At least 8 characters" },
                    { key: "hasSpecialChar", label: "Contains special character" },
                    { key: "hasNumber", label: "Contains number" },
                    { key: "hasAlphabet", label: "Contains alphabet" },
                    { key: "hasUppercase", label: "Contains uppercase" },
                  ].map((item) => (
                    <div key={item.key} className="flex gap-2 items-center mb-1">
                      <div
                        className={`w-4 h-4 p-0.5 rounded-full flex justify-center border ${
                          passwordStrength[item.key as keyof typeof passwordStrength]
                            ? "border-green-600"
                            : "border-red-500"
                        }`}
                      >
                        {passwordStrength[item.key as keyof typeof passwordStrength] ? (
                          <Check className="w-3 h-3 text-green-600" />
                        ) : (
                          <X className="w-3 h-3 text-red-500" />
                        )}
                      </div>
                      <p className="text-xs text-gray-700">{item.label}</p>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div className="relative">
              <label className="text-[13px] text-[#1E222A]">
                {labels.personalInfo.confirm_password || 'Confirm Password'} <span className="text-red-500">*</span>
              </label>
              <div className="relative" ref={confirmPasswordRef}>
                <input
                  type={showConfirmPassword ? "text" : "password"}
                  value={confirmPassword}
                  onChange={handleConfirmPasswordChange}
                  onFocus={() => setIsConfirmPasswordFieldTouched(true)}
                  disabled={loading || isSubmitting}
                  placeholder="********"
                  className={`w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm pr-10 ${
                    confirmPassword && !doPasswordsMatch ? "border border-red-500" : ""
                  }`}
                />
                <span
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute inset-y-0 right-3 flex items-center text-[#77829D] cursor-pointer"
                >
                  {showConfirmPassword ? <Eye size={18} /> : <EyeOff size={18} />}
                </span>
              </div>

              {isConfirmPasswordFieldTouched && confirmPassword && (
                <div
                  ref={confirmPasswordTooltipRef}
                  className={`absolute z-50 w-full mt-1 p-3 rounded-lg bg-white shadow-lg border ${
                    !doPasswordsMatch ? "border-red-500" : "border-gray-200"
                  }`}
                >
                  <div className="mb-2">
                    <div className="w-full bg-gray-200 rounded-full h-1.5">
                      <div
                        className={`h-1.5 rounded-full transition-all duration-300 ${
                          Object.values(confirmPasswordStrength).filter(Boolean).length === 5
                            ? "bg-green-500"
                            : Object.values(confirmPasswordStrength).filter(Boolean).length >= 3
                            ? "bg-yellow-500"
                            : "bg-red-500"
                        }`}
                        style={{
                          width: `${(Object.values(confirmPasswordStrength).filter(Boolean).length / 5) * 100}%`,
                        }}
                      ></div>
                    </div>
                  </div>
                  {[
                    { key: "hasMinLength", label: "At least 8 characters" },
                    { key: "hasSpecialChar", label: "Contains special character" },
                    { key: "hasNumber", label: "Contains number" },
                    { key: "hasAlphabet", label: "Contains alphabet" },
                    { key: "hasUppercase", label: "Contains uppercase" },
                    { key: "match", label: "Passwords match", custom: doPasswordsMatch },
                  ].map((item) => (
                    <div key={item.key} className="flex gap-2 items-center mb-1">
                      <div
                        className={`w-4 h-4 p-0.5 rounded-full flex justify-center border ${
                          item.custom !== undefined
                            ? item.custom
                              ? "border-green-600"
                              : "border-red-500"
                            : confirmPasswordStrength[item.key as keyof typeof confirmPasswordStrength]
                            ? "border-green-600"
                            : "border-red-500"
                        }`}
                      >
                        {item.custom !== undefined ? (
                          item.custom ? (
                            <Check className="w-3 h-3 text-green-600" />
                          ) : (
                            <X className="w-3 h-3 text-red-500" />
                          )
                        ) : confirmPasswordStrength[item.key as keyof typeof confirmPasswordStrength] ? (
                          <Check className="w-3 h-3 text-green-600" />
                        ) : (
                          <X className="w-3 h-3 text-red-500" />
                        )}
                      </div>
                      <p className="text-xs text-gray-700">{item.label}</p>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
            <div ref={countryDropdownRef}>
              <label className="text-[13px] text-[#1E222A]">
                {labels.personalInfo.mobile_number || 'Mobile Number'} <span className="text-red-500">*</span>
              </label>
              <div className="flex items-center bg-[#F8FAFC] rounded-lg h-[50px]">
                <div className="relative flex-shrink-0">
                  <div
                    className="flex items-center gap-2 px-1 h-full cursor-pointer hover:bg-gray-50 rounded-l-lg transition-colors"
                    onClick={() => setShowCountryDropdown(!showCountryDropdown)}
                  >
                    <div className="flex items-center gap-2 shrink-0">
                      {selectedCountryFlag ? (
                        <Image
                          src={`${BASE_URL}/uploads/${selectedCountryFlag}`}
                          alt="Country Flag"
                          width={16}
                          height={12}
                          className=" object-contain"
                        />
                      ) : (
                        <div className="w-6 h-4 bg-gray-200 rounded-sm flex items-center justify-center">
                          <span className="text-[10px] text-gray-500"></span>
                        </div>
                      )}
                      <span className="text-[#1E222A] text-xs font-medium leading-none">
                        {formData.countryCode}
                      </span>
                      <ChevronDown className="w-4 h-4 text-gray-500" />
                    </div>
                  </div>

                  {showCountryDropdown && (
                    <div className="absolute z-50 top-full left-0 mt-1 bg-white rounded-lg shadow-lg border border-gray-200 max-h-60 overflow-y-auto w-[180px]">
                      {countries?.map((country: any) => {
                        const displayCode = country.phonecode ? `+${country.phonecode}` : (country.countryCode || "");
                        const displayName = country.billcountry || country.countryName || "";
                        const flag = country.countryFlag || "";
                        
                        return (
                          <div
                            key={country._id}
                            className={`flex items-center gap-3 px-3 py-2 cursor-pointer hover:bg-gray-100 transition-colors ${
                              formData.countryCode === displayCode ? "bg-blue-50" : ""
                            }`}
                            onClick={() => {
                              setFormData(prev => ({
                                ...prev,
                                countryCode: displayCode,
                                country: displayName,
                                countryId: country._id,
                              }));
                              setSelectedCountryFlag(flag);
                              setShowCountryDropdown(false);
                            }}
                          >
                            {flag ? (
                              <Image
                                src={`${BASE_URL}/uploads/${flag}`}
                                alt={displayName}
                                width={15}
                                height={12}
                                className=" object-contain"
                              />
                            ) : (
                              <div className="w-6 h-4 bg-gray-200 rounded-sm flex items-center justify-center">
                                <span className="text-[10px] text-gray-500"></span>
                              </div>
                            )}
                            <div className="flex flex-col">
                              <span className="text-sm text-gray-700 font-medium">
                                {displayCode}
                              </span>
                              <span className="text-xs text-gray-500">
                                {displayName}
                              </span>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>

                <span className="h-5 w-px bg-gray-300" />

                <input
                  type="tel"
                  name="phone"
                  value={formData.phone}
                  onChange={handleChange}
                  disabled={loading || isSubmitting}
                  placeholder={labels.personalInfo.mobile_placeholder || 'Mobile number'}
                  maxLength={12}
                  className="w-full bg-transparent outline-none text-[#1E222A] text-sm px-3"
                />
              </div>
            </div>
            
            <div>
  <label className="text-[13px] text-[#1E222A]">
    {labels.personalInfo.dob || 'Date of Birth'} <span className="text-red-500">*</span>
  </label>
  <div className="relative">
    <input
      type="date"
      name="dateOfBirth"
      id="business-dob-input"
      value={formData.dateOfBirth}
      onChange={handleChange}
      disabled={loading || isSubmitting}
      max={new Date(new Date().setFullYear(new Date().getFullYear() - 18)).toISOString().split('T')[0]}
      className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm pr-10"
    />
    <button
      type="button"
      onClick={() => {
        const dateInput = document.getElementById('business-dob-input');
        if (dateInput && dateInput.showPicker) {
          dateInput.showPicker();
        }
      }}
      className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700"
      style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 0 }}
    >
      <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
        <line x1="16" y1="2" x2="16" y2="6"></line>
        <line x1="8" y1="2" x2="8" y2="6"></line>
        <line x1="3" y1="10" x2="21" y2="10"></line>
      </svg>
    </button>
  </div>
</div>
          </div>
        </div>
        
        {/* ===== BUSINESS DETAILS ===== */}
        <div>
          <h3 className="text-[13px] font-semibold text-[#1E222A] mb-3 flex items-center gap-2">
            <span className="w-1 h-4 bg-[#0084a5] rounded-full"></span>
            {labels.businessInfo.section_title || 'Business Information'}
          </h3>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
            <div>
              <label className="text-[13px] text-[#1E222A]">
                {labels.businessInfo.organization_name || 'Organization Name'} <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                name="organizationName"
                value={formData.organizationName}
                onChange={handleChange}
                disabled={loading || isSubmitting}
                placeholder={labels.businessInfo.org_name_placeholder || 'Organization name'}
                className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm"
              />
            </div>
            
            <div>
              <label className="text-[13px] text-[#1E222A]">
                {labels.businessInfo.business_type || 'Business Type'} <span className="text-red-500">*</span>
              </label>
              <select
                name="businessType"
                value={formData.businessType}
                onChange={handleChange}
                disabled={loading || isSubmitting || isLoadingBusinessTypes}
                className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm"
              >
                <option value="">{labels.businessInfo.select_type || 'Select type'}</option>
                {isLoadingBusinessTypes ? (
                  <option disabled>{labels.businessInfo.loading || 'Loading...'}</option>
                ) : (
                  businessTypes.map((type) => (
                    <option key={type._id || type.businessTypeId} value={type.businessTypeSlug}>
                      {type.businessTypeName}
                    </option>
                  ))
                )}
              </select>
            </div>
            
            <div>
              <label className="text-[13px] text-[#1E222A]">
                {labels.businessInfo.business_email || 'Business Email'} <span className="text-red-500">*</span>
              </label>
              <input
                type="email"
                name="businessEmail"
                value={formData.businessEmail}
                onChange={handleChange}
                disabled={loading || isSubmitting}
                placeholder={labels.businessInfo.business_email_placeholder || 'Business email'}
                className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm"
              />
            </div>
            
            <div ref={businessPhoneDropdownRef}>
              <label className="text-[13px] text-[#1E222A]">
                {labels.businessInfo.business_phone || 'Business Phone'}
              </label>
              <div className="flex items-center bg-[#F8FAFC] rounded-lg h-[50px]">
                <div className="relative flex-shrink-0">
                  <div
                    className="flex items-center gap-2 px-1 h-full cursor-pointer hover:bg-gray-50 rounded-l-lg transition-colors"
                    onClick={() => setShowBusinessPhoneDropdown(!showBusinessPhoneDropdown)}
                  >
                    <div className="flex items-center gap-2 shrink-0">
                      {selectedBusinessPhoneFlag ? (
                        <Image
                          src={`${BASE_URL}/uploads/${selectedBusinessPhoneFlag}`}
                          alt="Country Flag"
                          width={15}
                          height={12}
                          className=" object-contain"
                        />
                      ) : (
                        <div className="w-6 h-4 bg-gray-200 rounded-sm flex items-center justify-center">
                          <span className="text-[10px] text-gray-500">🌍</span>
                        </div>
                      )}
                      <span className="text-[#1E222A] text-xs font-medium leading-none">
                        {formData.businessCountryCode}
                      </span>
                      <ChevronDown className="w-4 h-4 text-gray-500" />
                    </div>
                  </div>

                  {showBusinessPhoneDropdown && (
                    <div className="absolute z-50 top-full left-0 mt-1 bg-white rounded-lg shadow-lg border border-gray-200 max-h-60 overflow-y-auto w-[150px]">
                      {countries?.map((country: any) => {
                        const displayCode = country.phonecode ? `+${country.phonecode}` : (country.countryCode || "");
                        const displayName = country.billcountry || country.countryName || "";
                        const flag = country.countryFlag || "";
                        
                        return (
                          <div
                            key={country._id}
                            className={`flex items-center gap-3 px-3 py-2 cursor-pointer hover:bg-gray-100 transition-colors ${
                              formData.businessCountryCode === displayCode ? "bg-blue-50" : ""
                            }`}
                            onClick={() => {
                              setFormData(prev => ({
                                ...prev,
                                businessCountryCode: displayCode,
                              }));
                              setSelectedBusinessPhoneFlag(flag);
                              setShowBusinessPhoneDropdown(false);
                            }}
                          >
                            {flag ? (
                              <Image
                                src={`${BASE_URL}/uploads/${flag}`}
                                alt={displayName}
                                width={15}
                                height={12}
                                className=" object-contain "
                              />
                            ) : (
                              <div className="w-6 h-4 bg-gray-200 rounded-sm flex items-center justify-center">
                                <span className="text-[10px] text-gray-500"></span>
                              </div>
                            )}
                            <div className="flex flex-col">
                              <span className="text-sm text-gray-700 font-medium">
                                {displayCode}
                              </span>
                              <span className="text-xs text-gray-500">
                                {displayName}
                              </span>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  )}
                </div>

                <span className="h-5 w-px bg-gray-300" />

                <input
                  type="tel"
                  name="businessPhone"
                  value={formData.businessPhone}
                  onChange={handleChange}
                  disabled={loading || isSubmitting}
                  placeholder={labels.businessInfo.business_phone_placeholder || 'Business phone'}
                  maxLength={12}
                  className="w-full bg-transparent outline-none text-[#1E222A] text-sm px-3"
                />
              </div>
            </div>
            
            <div>
              <label className="text-[13px] text-[#1E222A]">
                {labels.businessInfo.website || 'Website'}
              </label>
              <input
                type="url"
                name="website"
                value={formData.website}
                onChange={handleChange}
                disabled={loading || isSubmitting}
                placeholder={labels.businessInfo.website_placeholder || 'https://example.com'}
                className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm"
              />
            </div>
            
            <div className="md:col-span-2">
              <label className="text-[13px] text-[#1E222A]">
                {labels.businessInfo.address || 'Address'}
              </label>
              <textarea
                name="address"
                value={formData.address}
                onChange={handleChange}
                disabled={loading || isSubmitting}
                placeholder={labels.businessInfo.address_placeholder || 'Business address'}
                rows={1}
                className="w-full p-3 bg-[#F8FAFC] rounded-lg outline-none text-[#1E222A] text-sm resize-none"
              />
            </div>
          </div>
        </div>
        
        {/* ===== CAPTCHA SECTION ===== */}
        <div>
          <label className="text-[13px] text-[#1E222A]">
            {labels.formButtons.captcha_label || 'Captcha'} <span className="text-red-500">*</span>
          </label>
          <div className="flex items-center gap-3 mt-1">
            <div className="flex gap-2 items-center">
              <div
                className="captcha-wrapper"
                dangerouslySetInnerHTML={{ __html: captchaData.svg }}
              />
            </div>

            <input
              type="text"
              name="captchaInput"
              value={captchaInput}
              onChange={(e) => setCaptchaInput(e.target.value)}
              placeholder={labels.formButtons.captcha_placeholder || 'Enter result'}
              className="flex-1 px-3 py-2 bg-[#F8FAFC] outline-none rounded-lg text-sm text-[#1E222A] placeholder:text-[#77829D]"
            />

            <button
              type="button"
              onClick={fetchCaptcha}
              disabled={loading || isSubmitting}
              className="p-2 bg-gray-200 cursor-pointer text-black rounded-lg hover:bg-gray-300 transition-colors"
            >
              <RefreshCcw size={16} />
            </button>
          </div>

          {captchaError && (
            <p className="text-red-500 text-xs mt-1">{captchaError}</p>
          )}
        </div>
        
        {/* Hidden fields */}
        <input type="hidden" name="ipAddress" value={formData.ipAddress} />
        <input type="hidden" name="timezone" value={formData.timezone} />
        <input type="hidden" name="currency" value={formData.currency} />
        <input type="hidden" name="countryId" value={formData.countryId} />
        
        {/* Terms and Submit */}
        <div className="flex items-center gap-2 mt-4">
          <input
            type="checkbox"
            name="termsAccepted"
            checked={formData.termsAccepted}
            onChange={handleChange}
            disabled={loading || isSubmitting}
            className="w-4 h-4"
          />
          <span className="text-xs text-gray-700">
            {labels.formButtons.terms_text || 'I agree to the'}{" "}
            <Link
              href="/terms-and-conditions"
               target="_blank"
            rel="noopener noreferrer"
              className="text-[#0084a5] font-medium"
            >
              {labels.formButtons.terms_link || 'Terms and Conditions'}
            </Link>{" "}
            &{" "}
            <Link
              href="/privacy-policy"
               target="_blank"
            rel="noopener noreferrer"
              className="text-[#0084a5] font-medium"
            >
              {labels.formButtons.privacy_link || 'Privacy Policy'}
            </Link>
          </span>
        </div>
        
        <button
          type="submit"
          disabled={loading || !isFormValid || isSubmitting}
          className={`w-full py-1 mt-2 rounded-lg text-white font-medium text-sm ${
            loading || !isFormValid || isSubmitting
              ? "bg-gray-400 cursor-not-allowed"
              : "bg-[#0084a5] hover:bg-[#006a85] cursor-pointer"
          }`}
        >
          {loading || isSubmitting ? (
            <Loader size={20} className="animate-spin mx-auto" />
          ) : (
            labels.formButtons.submit_button || "Create Business Account"
          )}
        </button>

          <p className="text-center text-sm text-[#1E222A]">
                  Already Registered?{" "}
                  <Link
                    href="/login"
                    className="text-[#0084a5] font-medium cursor-pointer"
                  >
                    Login Now
                  </Link>
                </p>
      </form>
    </div>
  );
}