"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import AnimatedSection from "@/components/AnimatedSection";
import {
  Phone,
  Lock,
  UserPlus,
  Mail,
  User,
  Check,
  Clock,
  Edit2,
  Edit,
  EyeOff,
  Eye,
} from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { useRouter } from "next/navigation";
import {
  sendOtp,
  verifyOtp,
  getStates,
  getCities,
  registerUser,
  submitHearAboutUs,
  getCountry,
} from "@/lib/api/auth";
import Link from "next/link";
import Image from "next/image";
import { getStoredLanguage } from "@/lib/language";
import { getTranslation } from "@/src/hooks/useTranslation";
import { parsePhoneNumberFromString } from "libphonenumber-js";
import { countryList } from "@/lib/api/countries";
import { notifyAuthChange } from "@/lib/authEvents";

type Country = (typeof countryList)[number];

export default function Signup() {
  const { toast } = useToast();
  const router = useRouter();
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [loadingType, setLoadingType] = useState<"0" | "1" | null>(null);
  const [checkingAuth, setCheckingAuth] = useState(true);

  // Guard: if the user is already logged in, don't show the signup page.
  useEffect(() => {
    const token = localStorage.getItem("token");
    const storedUser = localStorage.getItem("user_data");
    if (token && storedUser) {
      router.replace("/");
    } else {
      setCheckingAuth(false);
    }
  }, []);

  const [otp, setOtp] = useState(["", "", "", ""]);

  const [userData, setUserData] = useState({
    name: "",
    // email: "",
    mobile: "",
    password: "",
    gender: "",
    // country: "",
    // state: "",
    // city: "",
  });
  const [confimPass, setConfirmPass] = useState("");
  const [hearAboutSource, setHearAboutSource] = useState<string>("");
  const [hearAboutOther, setHearAboutOther] = useState("");
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [passwordTouched, setPasswordTouched] = useState(false);

  const [states, setStates] = useState<any[]>([]);
  const [cities, setCities] = useState<any[]>([]);
  const [timer, setTimer] = useState(59);
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const [showDropdown, setShowDropdown] = useState(false);

  const [search, setSearch] = useState("");
  const countries = countryList;

  const [selectedCountry, setSelectedCountry] = useState<Country | null>(null);
  const [country, setCountry] = useState<any[]>([]);

  const isTimerFinished = timer === 0;
  const [lastOtpType, setLastOtpType] = useState<"0" | "1" | null>(null);

  const [mobileMaxLength, setMobileMaxLength] = useState(15);
  const passwordRules = {
    minLength: userData.password.length >= 8,
    upperCase: /[A-Z]/.test(userData.password),
    lowerCase: /[a-z]/.test(userData.password),
    number: /[0-9]/.test(userData.password),
    special: /[!@#$%^&*(),.?":{}|<>]/.test(userData.password),
  };

  const passwordStrength = Object.values(passwordRules).filter(Boolean).length;
  const isPasswordValid =
    passwordRules.minLength &&
    passwordRules.upperCase &&
    passwordRules.lowerCase &&
    passwordRules.number &&
    passwordRules.special;

  useEffect(() => {
    if (!selectedCountry) return;

    const testLengths = Array.from({ length: 15 }, (_, i) => i + 1);

    let max = 15;

    for (const len of testLengths) {
      const dummy = "9".repeat(len);

      const phone = parsePhoneNumberFromString(
        `${selectedCountry.code}${dummy}`,
      );

      if (phone?.isValid()) {
        max = len;
        break;
      }
    }

    setMobileMaxLength(max);
  }, [selectedCountry]);

  const goBackToEditMobile = () => {
    setOtp(["", "", "", ""]);
    setTimer(59);
    setStep(1);
  };

  const handleResendOtp = async () => {
    if (!lastOtpType) return;

    try {
      setLoading(true);

      const res = await sendOtp(
        userData.mobile,
        lastOtpType,
        selectedCountry?.code || "",
        true,
        "0",
      );

      if (res.data) {
        toast({
          title: "OTP Resent",
          description: "OTP has been resent successfully.",
        });

        setOtp(["", "", "", ""]);
        setTimer(59);
      } else {
        toast({
          // title: t.signup.failed,
          description: res.message,
          variant: "destructive",
        });
      }
    } catch (err: any) {
      toast({
        // title: t.signup.error,
        description: err.message,
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const india =
      countryList.find((c) => c.iso === "IN") ||
      countryList.find((c) => c.code === "+91");

    setSelectedCountry(india || countryList[0] || null);
  }, []);
  const filteredCountries = useMemo(() => {
    const q = search.toLowerCase().trim();

    if (!q) return countryList;

    return countryList
      .filter((c) => {
        return (
          c.name.toLowerCase().includes(q) ||
          c.iso.toLowerCase().includes(q) ||
          c.code.toLowerCase().includes(q)
        );
      })
      .sort((a, b) => {
        const aStarts = a.name.toLowerCase().startsWith(q) ? 0 : 1;
        const bStarts = b.name.toLowerCase().startsWith(q) ? 0 : 1;
        return aStarts - bStarts;
      });
  }, [search]);

  const lang = getStoredLanguage();
  const t = getTranslation(lang);

  useEffect(() => {
    if (timer > 0) {
      const countdown = setTimeout(() => setTimer(timer - 1), 1000);
      return () => clearTimeout(countdown);
    }
  }, [timer]);

  const handleOtpChange = (index: number, value: string) => {
    if (value.length <= 1 && /^\d*$/.test(value)) {
      const newOtp = [...otp];
      newOtp[index] = value;
      setOtp(newOtp);

      // Auto-focus next input
      if (value && index < 3) {
        inputRefs.current[index + 1]?.focus();
      }
    }
  };

  const handleKeyDown = (
    index: number,
    e: React.KeyboardEvent<HTMLInputElement>,
  ) => {
    if (e.key === "Backspace" && !otp[index] && index > 0) {
      // Move to previous input on backspace
      inputRefs.current[index - 1]?.focus();
    }
  };

  // 🧭 Step 1 → Send OTP
  const handleSendOTP = async (type: "0" | "1") => {
    if (!acceptedTerms) {
      toast({
        description: "Please accept the Terms & Conditions to continue.",
        variant: "destructive",
      });
      return;
    }

    if (!userData.mobile) {
      toast({
        // title: t.signup.missingInfo,
        description: t.signup.enterMobile,
        variant: "destructive",
      });
      return;
    }
    const mobileOnlyDigits = userData.mobile.replace(/\D/g, "");

    // ✅ build full international number: +91 + 9876543210
    const fullNumber = `${selectedCountry?.code}${mobileOnlyDigits}`;

    const phone = parsePhoneNumberFromString(fullNumber);

    if (!phone || !phone.isValid()) {
      toast({
        // title: "Invalid Mobile Number",
        description: `Please enter a valid mobile number for ${selectedCountry?.name}.`,
        variant: "destructive",
      });
      return;
    }

    // Indian numbers must start with 6-9
    if (selectedCountry?.code === "+91" && !/^[6-9]/.test(mobileOnlyDigits)) {
      toast({
        description: "Indian mobile numbers must start with 6, 7, 8, or 9.",
        variant: "destructive",
      });
      return;
    }

    try {
      setLoadingType(type);
      setLastOtpType(type);
      const res = await sendOtp(
        userData.mobile,
        type,
        selectedCountry?.code || "",
        true,
        "0",
      );
      const normalizeStatus = (status: any): boolean => {
        return status === true || status === "true" || status === "success";
      };
      const isValidData =
        normalizeStatus(res?.status) &&
        res?.data &&
        ((Array.isArray(res.data) && res.data.length > 0) ||
          !Array.isArray(res.data));

      if (isValidData) {
        // toast({ title: t.signup.otpSent, description: res.message });
        setStep(2);
      } else {
        toast({
          // title: t.signup.failed,
          description: res.message,
          variant: "destructive",
        });
      }
    } catch (err: any) {
      toast({
        // title: t.signup.error,
        description: err.message,
        variant: "destructive",
      });
    } finally {
      setLoadingType(null);
    }
  };

  // 🧭 Step 2 → Verify OTP
  const handleVerifyOTP = async () => {
    if (otp.length !== 4 && otp.length !== 6) {
      toast({
        // title: t.signup.invalidOtp,
        description: t.signup.invalidOtpDesc,
        variant: "destructive",
      });
      return;
    }

    try {
      setLoading(true);
      const res = await verifyOtp(
        userData.mobile,
        otp.join(""),
        selectedCountry?.code || "",
      );
      if (res.status) {
        toast({
          title: t.signup.otpVerified,
          description: t.signup.otpVerifiedDesc,
        });
        setStep(3);
        // loadCountries();
      } else {
        toast({
          // title: t.signup.verificationFailed,
          description: res.message,
          variant: "destructive",
        });
      }
    } catch (err: any) {
      toast({
        // title: t.signup.error,
        description: err.message,
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  // Auto-verify once all 4 OTP digits are entered
  useEffect(() => {
    if (
      step === 2 &&
      !loading &&
      otp.every((d) => d !== "") &&
      otp.join("").length === 4
    ) {
      handleVerifyOTP();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [otp, step]);

  const validatePassword = (password?: string) => {
    if (!password || password.trim() === "") {
      return "Password is required.";
    }

    const minLength = 8;
    const maxLength = 32;

    const isValidLength =
      password.length >= minLength && password.length <= maxLength;

    const hasUpper = /[A-Z]/.test(password);
    const hasLower = /[a-z]/.test(password);
    const hasNumber = /[0-9]/.test(password);
    const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password);

    if (!isValidLength || !hasUpper || !hasLower || !hasNumber || !hasSpecial) {
      return "Password must be at least 8 characters and include uppercase (A–Z), lowercase (a–z), number (0–9), and special symbol.";
    }

    return null;
  };
  // 🧭 Step 3 → Registration
  const handleRegister = async () => {
    if (!userData.name) {
      toast({
        // title: t.signup.missingFields,
        description: t.signup.nameRequired,
        variant: "destructive",
      });
      return;
    }
    if (!userData.gender) {
      toast({
        // title: t.signup.missingFields,
        description: t.signup.selectGender,
        variant: "destructive",
      });
      return;
    }
    // if (!userData.password) {
    //   toast({
    //     title: t.signup.missingFields,
    //     description: t.signup.passwordRequired,
    //     variant: "destructive",
    //   });
    //   return;
    // }
    if (!isPasswordValid) {
      toast({
        // title: "Invalid Password",
        description:
          "Password must contain at least 8 characters, one uppercase letter, one lowercase letter, one number and one special character.",
        variant: "destructive",
      });
      return;
    }

    if (confimPass !== userData.password) {
      toast({
        // title: "Password Mismatch",
        description: "Passwords do not match.",
        variant: "destructive",
      });
      return;
    }

    try {
      setLoading(true);

      const formData = new FormData();
      Object.entries(userData).forEach(([key, value]) =>
        formData.append(key, value),
      );
      formData.append("c_code", selectedCountry?.code || "");
      const res = await registerUser(formData);

      if (res?.status && res?.data) {
        const { jwt, name } = res.data;

        if (jwt) {
          localStorage.setItem("token", jwt);
        }
        localStorage.setItem("user_data", JSON.stringify(res.data));
        localStorage.setItem("user_name", name || "User");

        // Let the header (and other listeners) update immediately
        notifyAuthChange();

        // toast({
        //   title: t.signup.signupSuccess,
        //   description: res.message || t.signup.signupWelcome,
        // });

        // Show "How did you hear about us?" step before redirecting
        setStep(4);
      } else {
        toast({
          // title: t.signup.signupFailed,
          description: res?.message || "Something went wrong.",
          variant: "destructive",
        });
      }
    } catch (err: any) {
      console.error("❌ Register Error:", err);
      toast({
        // title: t.signup.error,
        description: err.message || "Something went wrong.",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  // Redirect after signup (used after step 4)
  const handleFinalRedirect = () => {
    const redirectTo = localStorage.getItem("redirectAfterAuth");
    if (redirectTo) {
      localStorage.removeItem("redirectAfterAuth");
      router.push(redirectTo);
    } else {
      window.location.replace("/");
    }
  };

  // Step 4 → Submit "How did you hear about us?"
  const handleHearAboutSubmit = async () => {
    const source = hearAboutSource;
    const message = hearAboutOther.trim();

    if (!source && !message) {
      toast({
        description: "Please select a source or type where you heard about us.",
        variant: "destructive",
      });
      return;
    }

    try {
      setLoading(true);
      const storedUser = localStorage.getItem("user_data");
      const userId = storedUser ? JSON.parse(storedUser)?.id : "";

      const formData = new FormData();
      formData.append("user_id", userId);
      formData.append("source", source || "other");
      formData.append("message", message);

      await submitHearAboutUs(formData);
    } catch (error) {
      console.error("Error submitting survey:", error);
    } finally {
      setLoading(false);
      handleFinalRedirect();
    }
  };

  // 🌍 Load Countries / States / Cities
  const loadCountries = async () => {
    const res = await getCountry();
    if (res.data) setCountry(res.data || []);
  };

  const loadStates = async (countryId: string) => {
    const res = await getStates(countryId);
    if (res.data) setStates(res.data || []);
  };

  const loadCities = async (stateId: string) => {
    const res = await getCities(stateId);
    if (res.data) setCities(res.data || []);
  };

  // Add these functions to handle gender selection
  const handleGenderSelect = (gender: string) => {
    setUserData({ ...userData, gender });
  };

  const ValidationRow = ({ valid, text }: { valid: boolean; text: string }) => (
    <div
      className={`flex items-center gap-2 text-sm ${
        valid ? "text-green-600" : "text-gray-400"
      }`}
    >
      <Check
        className={`w-4 h-4 ${valid ? "text-green-600" : "text-gray-300"}`}
      />
      <span>{text}</span>
    </div>
  );
  const passwordValidation = useMemo(() => {
    const password = userData.password;

    if (!password) {
      // Only show the general requirement after user has started typing and cleared
      if (passwordTouched) {
        return {
          valid: false,
          text: "Password must be at least 8 characters and include uppercase (A-Z), lowercase (a-z), number (0-9) and special symbol.",
        };
      }
      return null;
    }

    // Stage 1
    if (password.length < 8) {
      return {
        valid: false,
        text: "Password must be at least 8 characters long",
      };
    }

    const hasLower = /[a-z]/.test(password);
    const hasUpper = /[A-Z]/.test(password);
    const hasNumber = /[0-9]/.test(password);
    const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password);

    // Stage 2 — specific missing requirement messages
    if (!hasLower) {
      return {
        valid: false,
        text: "Password must contain at least one lowercase letter (a-z).",
      };
    }
    if (!hasUpper) {
      return {
        valid: false,
        text: "Password must contain at least one uppercase letter (A-Z).",
      };
    }
    if (!hasNumber) {
      return {
        valid: false,
        text: "Password must contain at least one number (0-9).",
      };
    }
    if (!hasSpecial) {
      return {
        valid: false,
        text: "Password must contain at least one special character (!@#$%^&*).",
      };
    }

    // Stage 3
    return {
      valid: true,
      text: "Password is valid.",
    };
  }, [userData.password, passwordTouched]);

  if (checkingAuth) return null;

  return (
    <div
      onClick={() => setShowDropdown(false)}
      className="min-h-screen flex items-start justify-center p-4 pt-24 lg:h-screen lg:overflow-hidden lg:items-start"
    >
      <div className="w-full max-w-8xl bg-white rounded-l-3xl overflow-hidden lg:h-[80vh]">
        <div className="grid lg:grid-cols-2 lg:h-[80vh]">
          {/* LEFT SIDE - SIGNUP FORM */}
          <div className="lg:overflow-y-auto lg:h-[80vh] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
            <div className="p-6 md:p-10 min-h-full flex items-center justify-center">
              <AnimatedSection className="w-full max-w-md">
                {step === 1 && (
                  <Card className=" border-0 border-[#fff] bg-white/80 backdrop-blur-sm">
                    <CardHeader className="text-center space-y-6 pb-8">
                      <CardTitle className="text-2xl font-bold text-gray-900">
                        {t.signup.createAccount}
                      </CardTitle>
                    </CardHeader>

                    <CardContent className="space-y-8">
                      {/* Mobile Number Field */}
                      <div className="space-y-4">
                        <Label
                          htmlFor="mobile"
                          className="text-base font-semibold text-gray-700"
                        >
                          {t.signup.mobileLabel}
                          <span className="text-red-500"> *</span>
                        </Label>

                        <div className="flex flex-row gap-2 sm:gap-3">
                          {/* Country Code Selector (relative only here) */}
                          <div className="relative w-[90px] sm:w-[140px] shrink-0">
                            <button
                              type="button"
                              disabled={!selectedCountry}
                              className="flex items-center justify-between gap-1 sm:gap-3 px-2 sm:px-3 border-2 border-gray-300 rounded-md bg-gray-50 w-full h-12 disabled:opacity-50"
                              onClick={(e) => {
                                e.stopPropagation();
                                setShowDropdown((prev) => !prev);
                                setSearch("");
                              }}
                            >
                              <div className="flex items-center gap-1 sm:gap-2">
                                <span className="hidden sm:inline text-2xl leading-none">
                                  {selectedCountry?.flag || "🌍"}
                                </span>
                                <span className="text-sm sm:text-base font-semibold text-gray-800">
                                  {selectedCountry?.code || "--"}
                                </span>
                              </div>

                              <span className="text-gray-500 text-xl sm:text-2xl">▾</span>
                            </button>

                            {/* Dropdown */}
                            {showDropdown && (
                              <div className="absolute left-0 top-full mt-2 z-50 w-[calc(100vw-3rem)] sm:w-[320px] bg-white shadow-lg rounded-md border border-gray-200 overflow-hidden">
                                {/* Search */}
                                <div className="p-2 border-b border-gray-200 bg-white sticky top-0">
                                  <input
                                    value={search}
                                    onChange={(e) => setSearch(e.target.value)}
                                    placeholder="Search country..."
                                    className="w-full h-10 px-3 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-[#FAA631] focus:border-[#FAA631]"
                                    autoFocus
                                  />
                                </div>

                                {/* List */}
                                <div className="max-h-56 overflow-y-auto">
                                  {filteredCountries.length > 0 ? (
                                    filteredCountries.map((item) => (
                                      <button
                                        key={`${item.iso}-${item.code}`}
                                        type="button"
                                        className="w-full flex items-center justify-between px-3 py-2 hover:bg-gray-100 transition text-left"
                                        onClick={() => {
                                          setSelectedCountry(item);
                                          setShowDropdown(false);
                                          setSearch("");
                                        }}
                                      >
                                        <span className="text-gray-800 text-sm font-medium truncate">
                                          {item.flag} {item.name}
                                        </span>

                                        <span className="text-gray-600 text-sm font-semibold whitespace-nowrap ml-3">
                                          {item.code}
                                        </span>
                                      </button>
                                    ))
                                  ) : (
                                    <div className="px-3 py-3 text-sm text-gray-500">
                                      No country found
                                    </div>
                                  )}
                                </div>
                              </div>
                            )}
                          </div>

                          {/* Mobile Number Input */}
                          <Input
                            id="mobile"
                            name="mobile"
                            type="tel"
                            inputMode="numeric"
                            pattern="[0-9]*"
                            // maxLength={15}
                            value={userData.mobile}
                            onChange={(e) => {
                              const digits = e.target.value
                                .replace(/\D/g, "")
                                .slice(0, mobileMaxLength);

                              setUserData({
                                ...userData,
                                mobile: digits,
                              });
                            }}
                            placeholder={t.signup.mobilePlaceholder}
                            className="h-12 text-base border-2 border-gray-300 focus:border-[#FAA631] transition-colors flex-1 min-w-0"
                          />
                        </div>
                      </div>

                      {/* Login Link */}
                      <div className="text-center pt-2">
                        <p className="text-sm text-gray-600">
                          {t.signup.haveAccount}{" "}
                          <Link
                            href="/login"
                            className="font-bold text-[#FAA631] transition-colors"
                          >
                            {t.signup.login}
                          </Link>
                        </p>
                      </div>

                      {/* Terms and Conditions */}
                      <label className="flex items-start gap-3 bg-orange-50 rounded-lg p-4 border border-orange-200 cursor-pointer select-none">
                        <input
                          type="checkbox"
                          checked={acceptedTerms}
                          onChange={(e) => setAcceptedTerms(e.target.checked)}
                          className="mt-0.5 w-4 h-4 accent-[#FAA631] cursor-pointer flex-shrink-0"
                        />
                        <p className="text-sm text-gray-700">
                          {t.signup.termsText}{" "}
                          <Link
                            href="/legal"
                            onClick={() =>
                              localStorage.setItem("legal_select_last", "1")
                            }
                            className="text-[#FAA631] font-semibold hover:underline"
                          >
                            {t.signup.termsLink}
                          </Link>
                           {" of the website."}
                        </p>
                      </label>

                      {/* OTP Buttons */}
                      <div className="space-y-4">
                        <Button
                          onClick={() => handleSendOTP("0")}
                          disabled={loadingType !== null || !acceptedTerms}
                          className="w-full h-12 bg-[#FAA631]  hover:orange-500  text-white text-base font-semibold shadow-lg hover:shadow-xl transition-all duration-300 disabled:opacity-60 disabled:cursor-not-allowed"
                        >
                          <Image
                            src="/images/icon_sms.svg"
                            alt="msg"
                            width={30}
                            height={30}
                            color="#fff"
                            className="mr-2"
                          />
                          {loadingType === "0"
                            ? t.signup.sending
                            : t.signup.sendOtpSms}
                        </Button>

                        <Button
                          variant="outline"
                          onClick={() => handleSendOTP("1")}
                          disabled={loadingType !== null || !acceptedTerms}
                          className="w-full h-12 border-2 border-[#FAA631] text-[#FAA631] hover:bg-[#FAA631] hover:text-white text-base font-semibold transition-all duration-300 disabled:opacity-60 disabled:cursor-not-allowed"
                        >
                          {loadingType === "1" ? (
                            t.signup.sending
                          ) : (
                            <>
                              <Image
                                src="/images/whatsApp.svg"
                                alt="WhatsApp"
                                width={30}
                                height={30}
                                className="mr-2"
                              />{" "}
                              {t.signup.sendOtpWhatsapp}
                            </>
                          )}
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                )}

                {step === 2 && (
                  <Card className=" border-0 bg-white/80 backdrop-blur-sm">
                    <CardHeader className="text-center space-y-6 pb-8">
                      <CardTitle className="text-2xl font-bold text-gray-900">
                        {t.signup.enterOtpTitle}
                      </CardTitle>
                    </CardHeader>

                    <CardContent className="space-y-8">
                      {/* OTP Sent Message */}
                      <div className="text-center space-y-2">
                        <p className="text-[#626262]">{t.signup.otpSentMsg}</p>

                        <div className="flex items-center justify-center gap-2 text-[#626262]">
                          <span>
                            {selectedCountry?.code} {userData.mobile}
                          </span>

                          <Edit
                            onClick={goBackToEditMobile}
                            className="text-[#FAA631] hover:text-orange-500 transition cursor-pointer"
                          />
                        </div>
                      </div>

                      {/* OTP Input Fields */}
                      <div className="space-y-6">
                        <div className="flex justify-center gap-3">
                          {otp.map((digit, index) => (
                            <Input
                              key={index}
                              ref={(el) => {
                                inputRefs.current[index] = el;
                              }}
                              value={digit}
                              onChange={(e) =>
                                handleOtpChange(index, e.target.value)
                              }
                              onKeyDown={(e) => handleKeyDown(index, e)}
                              type="text"
                              inputMode="numeric"
                              maxLength={1}
                              className="w-12 h-14 text-2xl text-center font-bold border-2 border-gray-300 transition-colors"
                            />
                          ))}
                        </div>

                        {/* Timer */}
                        <div className="text-center">
                          {!isTimerFinished ? (
                            <p className="text-gray-600 text-sm flex items-center justify-center gap-2">
                              <Clock className="w-4 h-4 text-gray-900" />
                              <span>{t.signup.waitingOtp}</span>
                              <span className="font-semibold text-gray-900">
                                {timer.toString().padStart(2, "0")}
                              </span>
                            </p>
                          ) : (
                            <div className="flex items-center justify-center gap-1 text-sm">
                              <span className="text-gray-600">
                                Didn’t receive the code?
                              </span>
                              <button
                                onClick={handleResendOtp}
                                className="font-semibold text-[#FAA631] hover:underline transition"
                              >
                                Resend OTP
                              </button>
                            </div>
                          )}
                        </div>
                      </div>

                      {/* Verify Button */}
                      <Button
                        onClick={handleVerifyOTP}
                        disabled={loading || otp.join("").length !== 4}
                        className="w-full h-12 bg-[#FAA631]  hover:orange-500 text-white text-base font-semibold shadow-lg hover:shadow-xl transition-all duration-300"
                      >
                        {loading ? t.signup.verifying : t.signup.verifyOtp}
                      </Button>
                    </CardContent>
                  </Card>
                )}

                {step === 3 && (
                  <Card className="border-0">
                    <CardHeader>
                      <CardTitle>{t.signup.registrationTitle}</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div>
                        <Label className="text-base font-semibold text-gray-700 ">
                          {t.signup.name}
                          <span className="text-red-500"> *</span>
                        </Label>
                        <Input
                          className="mt-3"
                          value={userData.name}
                          maxLength={30}
                          onChange={(e) =>
                            setUserData({
                              ...userData,
                              name: e.target.value.slice(0, 30),
                            })
                          }
                          placeholder={t.signup.namePlaceholder}
                        />
                      </div>
                      <div>
                        <Label className="text-base font-semibold text-gray-700">
                          {t.signup.selectGender}
                          <span className="text-red-500"> *</span>
                        </Label>
                        <div className="flex gap-6 mt-3">
                          <label
                            className="flex items-center space-x-3 cursor-pointer p-1.5 w-full border-1.5 border-gray-200 transition-colors border rounded-md"
                            onClick={() => handleGenderSelect("1")}
                          >
                            <div className="w-5 h-5 rounded-full border-2 border-gray-400 flex items-center justify-center">
                              <div
                                className={`w-3 h-3 rounded-full ${
                                  userData.gender === "1"
                                    ? "bg-[#FAA631]"
                                    : "bg-transparent"
                                }`}
                              />
                            </div>
                            <span
                              className={`text-base ${
                                userData.gender === "1"
                                  ? "font-semibold text-gray-900"
                                  : "text-gray-700"
                              }`}
                            >
                              {t.signup.male}
                            </span>
                          </label>

                          <label
                            className="flex items-center space-x-3 cursor-pointer p-1.5 w-full border-1.5 border-gray-200 transition-colors border rounded-md"
                            onClick={() => handleGenderSelect("2")}
                          >
                            <div className="w-5 h-5 rounded-full border-2 border-gray-400 flex items-center justify-center">
                              <div
                                className={`w-3 h-3 rounded-full ${
                                  userData.gender === "2"
                                    ? "bg-[#FAA631]"
                                    : "bg-transparent"
                                }`}
                              />
                            </div>
                            <span
                              className={`text-base ${
                                userData.gender === "2"
                                  ? "font-semibold text-gray-900"
                                  : "text-gray-700"
                              }`}
                            >
                              {t.signup.female}
                            </span>
                          </label>
                        </div>
                      </div>
                      <div>
                        <Label className="text-base font-semibold text-gray-700">
                          {t.signup.createPassword}
                          <span className="text-red-500"> *</span>
                        </Label>
                        <div className="relative">
                          <Input
                            style={{ marginTop: 15 }}
                            type={showPassword ? "text" : "password"}
                            value={userData.password}
                            onChange={(e) => {
                              if (!passwordTouched) setPasswordTouched(true);
                              setUserData({
                                ...userData,
                                password: e.target.value,
                              });
                            }}
                          />
                          <button
                            type="button"
                            onClick={() => setShowPassword(!showPassword)}
                            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                          >
                            {showPassword ? (
                              <EyeOff className="w-5 h-5" />
                            ) : (
                              <Eye className="w-5 h-5" />
                            )}
                          </button>
                        </div>

                        {passwordValidation && (
                          <>
                            {/* Mobile */}
                            <div className="block md:hidden mt-3">
                              <p
                                className={`text-sm leading-5 ${
                                  passwordValidation?.valid
                                    ? "text-green-600"
                                    : "text-red-500"
                                }`}
                              >
                                {passwordValidation?.valid ? "✓ " : "✗ "}{" "}
                                {passwordValidation?.text}
                              </p>
                            </div>

                            {/* Desktop */}
                            <div className="hidden md:block mt-3 space-y-2 rounded-lg border bg-gray-50 p-3">
                              <ValidationRow
                                valid={passwordRules.minLength}
                                text="At least 8 characters"
                              />

                              <ValidationRow
                                valid={passwordRules.upperCase}
                                text="One uppercase letter (A-Z)"
                              />

                              <ValidationRow
                                valid={passwordRules.lowerCase}
                                text="One lowercase letter (a-z)"
                              />

                              <ValidationRow
                                valid={passwordRules.number}
                                text="One number (0-9)"
                              />

                              <ValidationRow
                                valid={passwordRules.special}
                                text="One special character"
                              />
                            </div>
                          </>
                        )}
                      </div>
                      <div className="mt-3 hidden md:block">
                        <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                          <div
                            className={`h-full transition-all duration-300 ${
                              passwordStrength <= 2
                                ? "bg-red-500"
                                : passwordStrength <= 4
                                  ? "bg-yellow-500"
                                  : "bg-green-500"
                            }`}
                            style={{
                              width: `${(passwordStrength / 5) * 100}%`,
                            }}
                          />
                        </div>

                        <p className="text-xs mt-1 text-gray-500">
                          {passwordStrength <= 2
                            ? "Weak"
                            : passwordStrength <= 4
                              ? "Medium"
                              : "Strong"}
                        </p>
                      </div>
                      <div>
                        <Label className="text-base font-semibold text-gray-700">
                          {t.signup.confirmPassword}
                          <span className="text-red-500"> *</span>
                        </Label>
                        <div className="relative">
                          <Input
                            style={{ marginTop: 15 }}
                            type={showConfirmPassword ? "text" : "password"}
                            value={confimPass}
                            onChange={(e) => setConfirmPass(e.target.value)}
                            placeholder=""
                          />
                          <button
                            type="button"
                            onClick={() =>
                              setShowConfirmPassword(!showConfirmPassword)
                            }
                            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-700"
                          >
                            {showConfirmPassword ? (
                              <EyeOff className="w-5 h-5" />
                            ) : (
                              <Eye className="w-5 h-5" />
                            )}
                          </button>
                        </div>
                        {confimPass && (
                          <div
                            className={`mt-2 text-sm flex items-center gap-2 ${
                              confimPass === userData.password
                                ? "text-green-600"
                                : "text-red-500"
                            }`}
                          >
                            {confimPass === userData.password
                              ? "✓ Passwords match"
                              : "✗ Passwords do not match"}
                          </div>
                        )}
                      </div>

                      {/* <div>
                  <Label>Email</Label>
                  <Input
                    type="email"
                    value={userData.email}
                    onChange={(e) =>
                      setUserData({ ...userData, email: e.target.value })
                    }
                    placeholder="you@example.com"
                  />
                </div>
                

                <div>
                  <Label>Country</Label>
                  <select
                    className="w-full border rounded-md p-2"
                    onChange={(e) => {
                      setUserData({ ...userData, country: e.target.value });
                      loadStates(e.target.value);
                    }}
                  >
                    <option value="">Select Country</option>
                    {countries.map((c: any) => (
                      <option key={c.id} value={c.id}>
                        {c.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <Label>State</Label>
                  <select
                    className="w-full border rounded-md p-2"
                    onChange={(e) => {
                      setUserData({ ...userData, state: e.target.value });
                      loadCities(e.target.value);
                    }}
                  >
                    <option value="">Select State</option>
                    {states.map((s: any) => (
                      <option key={s.id} value={s.id}>
                        {s.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <Label>City</Label>
                  <select
                    className="w-full border rounded-md p-2"
                    onChange={(e) =>
                      setUserData({ ...userData, city: e.target.value })
                    }
                  >
                    <option value="">Select City</option>
                    {cities.map((c: any) => (
                      <option key={c.id} value={c.id}>
                        {c.name}
                      </option>
                    ))}
                  </select>
                </div> */}

                      <Button
                        onClick={handleRegister}
                        disabled={loading}
                        className="w-full bg-[#FAA631] hover:bg-orange-400 text-lg py-6"
                      >
                        {loading ? "Submitting..." : "Continue"}
                      </Button>
                    </CardContent>
                  </Card>
                )}

                {/* ======================================================
                STEP 4 — HOW DID YOU HEAR ABOUT US?
              ====================================================== */}
                {step === 4 && (
                  <Card className="border-0 border-[#fff] bg-white/80 backdrop-blur-sm">
                    <CardHeader className="text-center space-y-4 pb-6">
                      <CardTitle className="text-2xl font-bold text-gray-900">
                        How did you hear about us?
                      </CardTitle>
                      <p className="text-sm text-gray-500">
                        Help us understand our reach by selecting the platform
                        or source that introduced you to our service.
                      </p>
                    </CardHeader>

                    <CardContent className="space-y-6">
                      {/* Social Media Platforms */}
                      <div>
                        <p className="text-xs font-semibold text-gray-400 tracking-widest text-center mb-3">
                          SOCIAL MEDIA PLATFORMS
                        </p>
                        <div className="flex flex-wrap justify-center gap-2">
                          {[
                            "Facebook",
                            "Instagram",
                            "Twitter/X",
                            "LinkedIn",
                            "YouTube",
                          ].map((source) => (
                            <button
                              key={source}
                              type="button"
                              onClick={() => {
                                setHearAboutSource(source);
                                setHearAboutOther("");
                              }}
                              className={`px-4 py-2 rounded-full text-sm font-medium border transition-all ${
                                hearAboutSource === source
                                  ? "border-[#FAA631] bg-[#FFF4E4] text-[#FAA631]"
                                  : "border-gray-200 text-gray-700 hover:border-[#FAA631]"
                              }`}
                            >
                              {source}
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* Other Sources */}
                      <div>
                        <p className="text-xs font-semibold text-gray-400 tracking-widest text-center mb-3">
                          OTHER SOURCES
                        </p>
                        <div className="flex flex-wrap justify-center gap-2">
                          {["Friend", "Relative", "Random Person"].map(
                            (source) => (
                              <button
                                key={source}
                                type="button"
                                onClick={() => {
                                  setHearAboutSource(source);
                                  setHearAboutOther("");
                                }}
                                className={`px-4 py-2 rounded-full text-sm font-medium border transition-all ${
                                  hearAboutSource === source
                                    ? "border-[#FAA631] bg-[#FFF4E4] text-[#FAA631]"
                                    : "border-gray-200 text-gray-700 hover:border-[#FAA631]"
                                }`}
                              >
                                {source}
                              </button>
                            ),
                          )}
                        </div>
                      </div>

                      {/* Somewhere Else */}
                      <div>
                        <p className="text-xs font-semibold text-gray-400 tracking-widest text-center mb-3">
                          SOMEWHERE ELSE
                        </p>
                        <textarea
                          value={hearAboutOther}
                          onChange={(e) => {
                            setHearAboutOther(e.target.value);
                            if (e.target.value.trim()) {
                              setHearAboutSource("");
                            }
                          }}
                          placeholder="Type here..."
                          className="w-full h-24 border border-gray-200 rounded-xl px-4 py-3 text-sm text-gray-700 resize-none focus:outline-none focus:ring-2 focus:ring-[#FAA631] focus:border-[#FAA631]"
                        />
                      </div>

                      {/* Submit Button */}
                      <Button
                        onClick={handleHearAboutSubmit}
                        disabled={loading}
                        className="w-full h-12 bg-[#FAA631] hover:bg-orange-500 text-white text-base font-semibold shadow-lg hover:shadow-xl transition-all duration-300"
                      >
                        {loading ? t.signup.registering : t.signup.submit}
                      </Button>
                    </CardContent>
                  </Card>
                )}
              </AnimatedSection>
            </div>
          </div>

          {/* RIGHT SIDE - IMAGE (DESKTOP ONLY) */}
          <div className="hidden lg:flex items-center justify-center relative h-[80vh]">
            <img
              src="/images/courseQuiz.jpg"
              alt="Signup"
              className="w-full h-full object-cover rounded-2xl"
            />
          </div>
        </div>
      </div>
    </div>
  );
}
