"use client";

import { useEffect, useLayoutEffect, 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 MaleIcon from "@/public/images/male.svg";
import FemaleIcon from "@/public/images/female.svg";
import {
  Award,
  Mail,
  Phone,
  User,
  School,
  MapPin,
  Calendar,
  CheckCircle,
  Camera,
  Upload,
  FileText,
} from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import {
  getCities,
  getCountry,
  getGocodStatus,
  getStates,
} from "@/lib/api/auth";
import { useRouter } from "next/navigation";
import { getHomeApi, registerOlympiad } from "@/lib/api/apis";
import Image from "next/image";
import { DEFAULT_LANGUAGE, getStoredLanguage, Language } from "@/lib/language";
import { getTranslation } from "@/src/hooks/useTranslation";
import {
  persistCourseMap,
  buildCourseMap,
  getCourseIdForLanguage,
  setActiveCourseLanguage,
} from "@/lib/courseSelection";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { uploadImageToBackend } from "@/lib/uploadImage";
import { notifyAuthChange } from "@/lib/authEvents";
import ImageUploadGuidelinesModal from "@/components/ImageUploadGuidelinesModal";
// import SuccessIcon from "@/public/images/success.svg";

interface UserData {
  name: string;
  email: string;
  mobile: string;
  country?: string;
  state?: string;
  city?: string;
}

export default function OlympiadRegister() {
  const { toast } = useToast();
  const [step, setStep] = useState(1);
  const [otp, setOtp] = useState("");
  const [registrationData, setRegistrationData] = useState({
    fullName: "",
    email: "",
    phone: "",
    dateOfBirth: "",
    schoolCollege: "",
    city: "",
    state: "",
    country: "India",
  });

  const [userData, setUserData] = useState({
    id: "",
    name: "",
    email: "",
    mobile: "",
    password: "",
    gender: "",
    country: "",
    state: "",
    city: "",
    dob: "",
    gocod: "",
    countryId: "",
    stateId: "",
    cityId: "",
  });
  const [countries, setCountries] = useState<any[]>([]);
  const [states, setStates] = useState<any[]>([]);
  const [cities, setCities] = useState<any[]>([]);
  const [gocodStatus, setGocodStatus] = useState<Record<string, any>>({});
  const [confimPass, setConfirmPass] = useState("");
  const [credentials, setCredentials] = useState({
    registrationNumber: "",
    password: "",
  });

  const [user, setUser] = useState<UserData | null>(null);
  const router = useRouter();
  const [profileFile, setProfileFile] = useState<File | null>(null);
  const [profilePreview, setProfilePreview] = useState<string>("");
  const [profileImageUrl, setProfileImageUrl] = useState<string>(""); // final CDN url
  const [uploading, setUploading] = useState(false);
  const [acceptedTerms, setAcceptedTerms] = useState(false);

  // Aadhar upload states
  const [frontAadharFile, setFrontAadharFile] = useState<File | null>(null);
  const [frontAadharPreview, setFrontAadharPreview] = useState<string>("");
  const [frontAadharUrl, setFrontAadharUrl] = useState<string>("");

  const [backAadharFile, setBackAadharFile] = useState<File | null>(null);
  const [backAadharPreview, setBackAadharPreview] = useState<string>("");
  const [backAadharUrl, setBackAadharUrl] = useState<string>("");

  const frontAadharRef = useRef<HTMLInputElement | null>(null);
  const backAadharRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    const stored = localStorage.getItem("user_data");

    if (!stored) {
      router.push("/login");
      return;
    }

    // Guard: if the user has already completed olympiad registration,
    // don't let them return to the registration form.
    const registerDetails = localStorage.getItem("register_details");
    if (registerDetails) {
      try {
        const rd = JSON.parse(registerDetails);
        if (rd?.regist_status == 1) {
          setRedirecting(true);
          router.replace("/");
          return;
        }
      } catch {
        // ignore malformed data and continue
      }
    }

    const data = JSON.parse(stored);
    // Required values check
    if (!data?.name || !data?.gender) {
      router.push("/login");
      return;
    }

    // Restore all saved values into userData
    setUserData((prev) => ({
      ...prev,
      id: data?.id ?? "",
      name: data?.name ?? "",
      email: data?.email ?? "",
      mobile: data?.mobile ?? "",
      password: data?.password ?? "",
      gender: data?.gender ?? "1",

      country: data?.country ?? "",
      state: data?.state ?? "",
      city: data?.city ?? "",
      dob: data?.dob ?? "",
      gocod: data?.gocod ?? "",
      countryId: data?.countryId ?? "",
      stateId: data?.stateId ?? "",
      cityId: data?.cityId ?? "",
    }));
  }, []);

  // ✅ added
  const [mounted, setMounted] = useState(false);
  const [redirecting, setRedirecting] = useState(false);
  const [lang, setLang] = useState<Language>(DEFAULT_LANGUAGE);
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  // Modal states
  const [showProfilePhotoModal, setShowProfilePhotoModal] = useState(false);
  const [showCourseModal, setShowCourseModal] = useState(false);
  useEffect(() => {
    const scrollToTop = (smooth: boolean = true) => {
      if (typeof window === "undefined") return;

      const scrollTopValue = step === 3 ? 280 : 0; // 👈 step 3 scroll little down

      window.scrollTo({
        top: scrollTopValue,
        behavior: "smooth",
      });
    };
    scrollToTop();
  }, [step]);

  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const allowedTypes = ["image/jpeg", "image/png"]; // jpg/jpeg both come as image/jpeg

    if (!allowedTypes.includes(file.type)) {
      toast({
        // title: "Invalid file type",
        description: t.olympiadRegister.onlyJpgPng,
        variant: "destructive",
      });

      // reset input so user can re-upload same file again
      e.target.value = "";
      return;
    }

    // optional validation
    if (file.size > 5 * 1024 * 1024) {
      toast({
        // title: "Image too large",
        description: t.olympiadRegister.uploadUnder5mb,
        variant: "destructive",
      });
      e.target.value = "";
      return;
    }

    setProfileFile(file);
    setProfilePreview(URL.createObjectURL(file));
    setProfileImageUrl(""); // reset old url if any
  };

  const handleAadharFileChange = (
    e: React.ChangeEvent<HTMLInputElement>,
    type: "front" | "back",
  ) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const allowedTypes = ["image/jpeg", "image/png", "application/pdf"];

    if (!allowedTypes.includes(file.type)) {
      toast({
        description: t.olympiadRegister.onlyJpgPngPdf,
        variant: "destructive",
      });
      e.target.value = "";
      return;
    }

    if (file.size > 5 * 1024 * 1024) {
      toast({
        description: t.olympiadRegister.uploadFileUnder5mb,
        variant: "destructive",
      });
      e.target.value = "";
      return;
    }

    if (type === "front") {
      setFrontAadharFile(file);
      setFrontAadharPreview(URL.createObjectURL(file));
      setFrontAadharUrl("");
    } else {
      setBackAadharFile(file);
      setBackAadharPreview(URL.createObjectURL(file));
      setBackAadharUrl("");
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setRegistrationData({
      ...registrationData,
      [e.target.name]: e.target.value,
    });
  };

  const handleSendOTP = async () => {
    if (
      !registrationData.fullName ||
      !registrationData.email ||
      !registrationData.phone
    ) {
      toast({
        // title: t.olympiadRegister.invalidDetails,
        description: t.olympiadRegister.fillAllDetails,
        variant: "destructive",
      });
      return;
    }

    const otpCode = Math.floor(100000 + Math.random() * 900000).toString();

    toast({
      // title: t.olympiadRegister.otpSent,
      description: `${t.olympiadRegister.otpSentTo} ${registrationData.email} ${t.olympiadRegister.andPhone} ${registrationData.phone}. ${t.olympiadRegister.enterOtp}: ${otpCode}`,
    });

    setStep(2);
  };

  const handleGenderSelect = (gender: string) => {
    setUserData({ ...userData, gender });
  };

  const handleVerifyOTP = () => {
    if (otp.length !== 6) {
      toast({
        // title: t.olympiadRegister.invalidOtp,
        description: t.olympiadRegister.invalidOtpDesc,
        variant: "destructive",
      });
      return;
    }

    const regNumber = `BG${new Date().getFullYear()}${Math.floor(
      100000 + Math.random() * 900000,
    )}`;
    const password = `GIT${Math.floor(1000 + Math.random() * 9000)}`;

    setCredentials({ registrationNumber: regNumber, password });
    setStep(3);

    toast({
      // title: t.olympiadRegister.registrationSuccess,
      description: t.olympiadRegister.credentialsGenerated,
    });
  };

  const handleGocod = async () => {
    try {
      const res = await getGocodStatus();
      console.log("gcvjnknekcnjkefv", res);
      setGocodStatus(res?.data[0] || {});
    } catch (error) {
      toast({
        // title: "GOCOD Check Failed",
        description: t.olympiadRegister.gocodCheckFailed,
        variant: "destructive",
      });
    }
  };

  useEffect(() => {
    loadCountries();
    handleGocod();
  }, []);

  const loadCountries = async () => {
    const res = await getCountry();
    if (res.data) setCountries(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 || []);
  };

  const [homeData, setHomeData] = useState<Record<string, any>>({});

  const handleHomeApi = async (id: string) => {
    const res = await getHomeApi(id);
    if (res?.data) {
      setHomeData(res.data || {});
      persistCourseMap(res?.data?.courses || []);
    }
  };

  const showErrorToast = (message: string) => {
    toast({
      // title: "Validation Error",
      description: message,
      variant: "destructive", // if your toast supports variants
    });
  };

  const handleDobChange = (value: string) => {
    const selectedDate = new Date(value);
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    if (selectedDate > today) {
      toast({
        // title: "Invalid Date",
        description: t.olympiadRegister.dobFuture,
        variant: "destructive",
      });
      return;
    }

    setUserData({ ...userData, dob: value });
  };

  const handleSubmit = async () => {
    setUploading(true);
    try {
      console.log("Starting handleSubmit...");

      if (!profilePreview) {
        showErrorToast(t.olympiadRegister.uploadProfileImage);
        setUploading(false);
        return;
      }
      if (!frontAadharPreview) {
        showErrorToast(t.olympiadRegister.uploadAadharFront);
        setUploading(false);
        return;
      }
      if (!backAadharPreview) {
        showErrorToast(t.olympiadRegister.uploadAadharBack);
        setUploading(false);
        return;
      }
      if (!userData.name.trim()) {
        showErrorToast(t.olympiadRegister.enterName);
        setUploading(false);
        return;
      }
      if (!userData.email) {
        showErrorToast(t.olympiadRegister.enterEmail);
        setUploading(false);
        return;
      }

      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(userData.email)) {
        showErrorToast(t.olympiadRegister.invalidEmail);
        setUploading(false);
        return;
      }

      if (!userData.dob) {
        showErrorToast(t.olympiadRegister.enterDob);
        setUploading(false);
        return;
      }
      if (gocodStatus?.is_mandatory === "1" && !userData.gocod) {
        showErrorToast(t.olympiadRegister.enterGocod);
        setUploading(false);
        return;
      }

      // Age validation - minimum 13 yrs
      const age = Math.floor(
        (new Date().getTime() - new Date(userData.dob).getTime()) /
          (365.25 * 24 * 60 * 60 * 1000),
      );

      if (!userData.country) {
        showErrorToast(t.olympiadRegister.selectCountry);
        setUploading(false);
        return;
      }
      if (!userData.state) {
        showErrorToast(t.olympiadRegister.selectState);
        setUploading(false);
        return;
      }
      if (!userData.city) {
        showErrorToast(t.olympiadRegister.selectCity);
        setUploading(false);
        return;
      }
      if (!acceptedTerms) {
        showErrorToast(
          t.olympiadRegister.acceptTerms,
        );
        setUploading(false);
        return;
      }

      let finalProfileUrl = profileImageUrl;
      let finalFrontAadharUrl = frontAadharUrl;
      let finalBackAadharUrl = backAadharUrl;

      // Upload profile image if not already uploaded
      if (profileFile && !finalProfileUrl) {
        console.log("Uploading profile image...");
        try {
          finalProfileUrl = await uploadImageToBackend(profileFile);
          setProfileImageUrl(finalProfileUrl);
          console.log("Profile image uploaded:", finalProfileUrl);
        } catch (uploadError) {
          console.error("Profile image upload error:", uploadError);
          showErrorToast(t.olympiadRegister.failedProfileUpload);
          setUploading(false);
          return;
        }
      }

      // Upload front Aadhar if not already uploaded
      if (frontAadharFile && !finalFrontAadharUrl) {
        console.log("Uploading front Aadhar...");
        try {
          finalFrontAadharUrl = await uploadImageToBackend(frontAadharFile, {
            maxSizeMB: 5,
            allowedTypes: ["image/jpeg", "image/png", "application/pdf"],
          });
          setFrontAadharUrl(finalFrontAadharUrl);
          console.log("Front Aadhar uploaded:", finalFrontAadharUrl);
        } catch (uploadError) {
          console.error("Front Aadhar upload error:", uploadError);
          showErrorToast(t.olympiadRegister.failedAadharFront);
          setUploading(false);
          return;
        }
      }

      // Upload back Aadhar if not already uploaded
      if (backAadharFile && !finalBackAadharUrl) {
        console.log("Uploading back Aadhar...");
        try {
          finalBackAadharUrl = await uploadImageToBackend(backAadharFile, {
            maxSizeMB: 5,
            allowedTypes: ["image/jpeg", "image/png", "application/pdf"],
          });
          setBackAadharUrl(finalBackAadharUrl);
          console.log("Back Aadhar uploaded:", finalBackAadharUrl);
        } catch (uploadError) {
          console.error("Back Aadhar upload error:", uploadError);
          showErrorToast(t.olympiadRegister.failedAadharBack);
          setUploading(false);
          return;
        }
      }

      console.log("All files uploaded, preparing FormData...");
      console.log("Final URLs:", {
        profile: finalProfileUrl,
        frontAadhar: finalFrontAadharUrl,
        backAadhar: finalBackAadharUrl,
      });

      const formData = new FormData();
      formData.append("id", userData.id);
      formData.append("name", userData.name);
      formData.append("email", userData.email);
      formData.append("gender", userData.gender);
      formData.append("country", userData.country);
      formData.append("state", userData.state);
      formData.append("city", userData.city);
      formData.append("dob", userData.dob);
      if (gocodStatus?.is_show === "1" && userData.gocod) {
        formData.append("gocod", userData.gocod);
      }

      formData.append("profile_image", finalProfileUrl || "");
      formData.append("front_aadhar", finalFrontAadharUrl || "");
      formData.append("back_aadhar", finalBackAadharUrl || "");

      console.log("Calling registerOlympiad API...");
      const res = await registerOlympiad(formData);

      console.log("API Response:", res);

      if (res?.status) {
        console.log("Registration successful!");
        localStorage.setItem("register_details", JSON.stringify(res.data));
        // Also refresh user_data so the header/profile pick up the new photo
        localStorage.setItem("user_data", JSON.stringify(res.data));
        // Let the header (and other listeners) update immediately
        notifyAuthChange();
        await handleHomeApi(userData.id);
        setStep(3);
      } else {
        console.error("Registration failed:", res?.message);
        showErrorToast(res?.message || "Registration failed");
      }
    } catch (error: any) {
      console.error("Submit error:", error);
      console.error("Error details:", {
        message: error?.message,
        stack: error?.stack,
        response: error?.response?.data,
      });
      showErrorToast(error?.message || "Something went wrong. Try again!");
    } finally {
      setUploading(false);
    }
  };
  useEffect(() => {
    setLang(getStoredLanguage());
    setMounted(true);
  }, []);

  if (!mounted || redirecting) return null;

  const t = getTranslation(lang);

  const openCourse = (courseLanguage: "hindi" | "english") => {
    const storedCourseId = getCourseIdForLanguage(courseLanguage);
    const fallbackCourseId =
      buildCourseMap(homeData?.courses || [])[courseLanguage] ?? null;
    const courseId = storedCourseId ?? fallbackCourseId;
    if (!courseId) return;
    setActiveCourseLanguage(courseLanguage);
    router.push("/quiz");
  };

  return (
    <div className="pt-20 min-h-screen bg-gradient-to-br from-orange-50 to-white">
      <div className="container mx-auto px-4 py-12">
        <AnimatedSection className="max-w-2xl mx-auto">
          <div className="text-center mb-8">
            <Award className="w-16 h-16 text-[#FAA631] mx-auto mb-4" />
            <h1 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
              {t.olympiadRegister.title}
            </h1>
            <p className="text-lg text-gray-600">
              {t.olympiadRegister.subtitle}
            </p>
          </div>

          {step === 1 && (
            <Card className="shadow-xl">
              <CardHeader>
                {/* <CardTitle>{t.olympiadRegister.formTitle}</CardTitle> */}
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex justify-center">
                  <div
                    className="relative cursor-pointer"
                    onClick={() => setShowProfilePhotoModal(true)}
                  >
                    <div className="w-32 h-32 rounded-full overflow-hidden bg-orange-50 flex items-center justify-center">
                      {profilePreview ? (
                        <Image
                          src={profilePreview}
                          alt="Profile"
                          fill
                          className="object-cover rounded-full"
                        />
                      ) : userData.gender === "1" ? (
                        <Image
                          src={MaleIcon}
                          alt="Male"
                          className="w-32 h-32"
                        />
                      ) : userData.gender === "2" ? (
                        <Image
                          src={FemaleIcon}
                          alt="Female"
                          className="w-32 h-32"
                        />
                      ) : (
                        <User className="w-16 h-16 text-gray-400" />
                      )}

                      <div className="absolute bottom-1 right-1 w-8 h-8 rounded-full bg-[#FAA631] flex items-center justify-center text-white">
                        <Camera className="w-4 h-4" />
                      </div>
                    </div>
                  </div>

                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/jpeg,image/png"
                    onChange={handleAvatarChange}
                    className="hidden"
                  />
                </div>
                <div className="text-center text-base font-semibold text-gray-700 mt-18">
                  {t.olympiadRegister.candidateImage}<span className="text-red-500"> *</span>
                </div>
                <div>
                  <Label>
                    {t.olympiadRegister.name}
                    <span className="text-red-500"> *</span>
                  </Label>
                  <Input
                    value={userData.name}
                    maxLength={30}
                    onChange={(e) =>
                      setUserData({ ...userData, name: e.target.value.slice(0, 30) })
                    }
                    placeholder={t.olympiadRegister.namePlaceholder}
                  />
                </div>
                <div>
                  <Label className="text-base font-semibold text-gray-700">
                    {t.olympiadRegister.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-[#FAA631] 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.olympiadRegister.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.olympiadRegister.female}
                      </span>
                    </label>
                  </div>
                </div>
                {/* <div>
                  <Label>Create Password</Label>
                  <Input
                    type="password"
                    value={userData.password}
                    onChange={(e) =>
                      setUserData({ ...userData, password: e.target.value })
                    }
                    placeholder="••••••••"
                  />
                </div>
                <div>
                  <Label>Confirm Password</Label>
                  <Input
                    type="password"
                    value={confimPass}
                    onChange={(e) => setConfirmPass(e.target.value)}
                    placeholder="••••••••"
                  />
                </div> */}
                <div>
                  <Label>
                    {t.olympiadRegister.email}
                    <span className="text-red-500"> *</span>
                  </Label>
                  <Input
                    type="email"
                    value={userData.email}
                    onChange={(e) =>
                      setUserData({ ...userData, email: e.target.value })
                    }
                    placeholder={t.olympiadRegister.emailPlaceholder}
                  />
                </div>
                <div>
                  <Label>
                    {t.olympiadRegister.dob}
                    <span className="text-red-500"> *</span>
                  </Label>
                  <div
                    className="relative mt-1 cursor-pointer"
                    onClick={() => {
                      const input = document.getElementById(
                        "dob-input",
                      ) as HTMLInputElement;
                      if (input) input.showPicker?.();
                    }}
                  >
                    <Input
                      id="dob-input"
                      type="date"
                      value={userData.dob}
                      max={new Date().toISOString().split("T")[0]}
                      onChange={(e) => handleDobChange(e.target.value)}
                      placeholder={t.olympiadRegister.dobPlaceholder}
                      className="cursor-pointer w-full"
                    />
                    {/* invisible full-cover layer so every pixel triggers the picker */}
                    <span className="absolute inset-0" aria-hidden="true" />
                  </div>
                </div>
                {gocodStatus?.is_show === "1" && (
                  <div>
                    <Label>
                      GOCOD
                      {gocodStatus?.is_mandatory === "1" && (
                        <span className="text-red-500"> *</span>
                      )}
                    </Label>
                    <Input
                      type="gocod"
                      value={userData.gocod}
                      onChange={(e) =>
                        setUserData({ ...userData, gocod: e.target.value })
                      }
                      placeholder={t.olympiadRegister.gocod}
                    />
                  </div>
                )}

                <div>
                  <Label>
                    {t.olympiadRegister.country}
                    <span className="text-red-500"> *</span>
                  </Label>
                  <select
                    value={userData?.countryId}
                    className="w-full border rounded-md p-2"
                    onChange={(e) => {
                      const id = e.target.value;
                      const option = e.target
                        .selectedOptions[0] as HTMLOptionElement;
                      const name = option.dataset.name ?? "";

                      setUserData({
                        ...userData,
                        country: name,
                        countryId: id,
                      }); // store NAME
                      loadStates(id); // send ID
                    }}
                  >
                    <option value="">{t.olympiadRegister.selectCountry}</option>
                    {countries.map((c: any) => (
                      <option key={c.id} value={c.id} data-name={c.name}>
                        {c.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <Label>
                    {t.olympiadRegister.state}
                    <span className="text-red-500"> *</span>
                  </Label>
                  <select
                    className="w-full border rounded-md p-2"
                    value={userData?.stateId}
                    onChange={(e) => {
                      const id = e.target.value;
                      const option = e.target
                        .selectedOptions[0] as HTMLOptionElement;
                      const name = option.dataset.name ?? "";

                      setUserData({ ...userData, state: name, stateId: id }); // store NAME
                      loadCities(id); // send ID
                    }}
                  >
                    <option value="">{t.olympiadRegister.selectState}</option>
                    {states.map((s: any) => (
                      <option key={s.id} value={s.id} data-name={s.name}>
                        {s.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <Label>
                    {t.olympiadRegister.city}
                    <span className="text-red-500"> *</span>
                  </Label>
                  <select
                    value={userData?.cityId}
                    className="w-full border rounded-md p-2"
                    onChange={(e) => {
                      const id = e.target.value;
                      const option = e.target
                        .selectedOptions[0] as HTMLOptionElement;
                      const name = option.dataset.name ?? "";
                      setUserData({ ...userData, city: name, cityId: id }); // store NAME only
                    }}
                  >
                    <option value="">{t.olympiadRegister.selectCity}</option>
                    {cities.map((c: any) => (
                      <option key={c.id} value={c.id} data-name={c.name}>
                        {c.name}
                      </option>
                    ))}
                  </select>
                </div>

                {/* AADHAR UPLOAD SECTION */}
                <div className="space-y-4 p-5 md:p-6 rounded-lg bg-gradient-to-br from-[#FFF9F1] to-[#FFF4E4] border-2 border-[#FAA631]/20">
                  <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                    <FileText className="w-5 h-5 text-[#FAA631]" />
                    Aadhar Upload
                    <span className="text-red-500"> *</span>
                  </h3>

                  <p className="text-sm text-gray-600">
                    {t.olympiadRegister.aadharDescription}
                  </p>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                    {/* Front Aadhar Upload */}
                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800">
                        Aadhar Front
                        <span className="text-red-500"> *</span>
                      </label>

                      <label className="relative flex flex-col items-center justify-center w-full h-40 border-2 border-dashed border-[#FAA631]/40 rounded-xl cursor-pointer bg-white hover:bg-[#FFF9F1] transition-colors">
                        {frontAadharPreview ? (
                          <div className="relative w-full h-full rounded-lg overflow-hidden">
                            {frontAadharFile?.type === "application/pdf" ? (
                              <div className="w-full h-full flex flex-col items-center justify-center bg-gray-100">
                                <FileText className="w-12 h-12 text-[#FAA631] mb-2" />
                                <p className="text-sm font-medium text-gray-700">
                                  PDF Uploaded
                                </p>
                              </div>
                            ) : (
                              <Image
                                src={frontAadharPreview}
                                alt="Aadhar Front"
                                fill
                                className="object-cover"
                              />
                            )}
                            <div className="absolute inset-0 bg-black/20 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity">
                              <Upload className="w-8 h-8 text-white" />
                            </div>
                          </div>
                        ) : (
                          <div className="flex flex-col items-center justify-center pt-5 pb-6">
                            <Upload className="w-8 h-8 text-[#FAA631] mb-2" />
                            <p className="text-sm font-medium text-gray-700">
                              Click to upload
                            </p>
                            <p className="text-xs text-gray-500">
                              JPG, PNG or PDF (Max 5MB)
                            </p>
                          </div>
                        )}
                        <input
                          ref={frontAadharRef}
                          type="file"
                          accept="image/jpeg,image/png,application/pdf"
                          onChange={(e) => handleAadharFileChange(e, "front")}
                          className="hidden"
                        />
                      </label>
                    </div>

                    {/* Back Aadhar Upload */}
                    <div className="space-y-3">
                      <label className="block text-sm font-semibold text-gray-800">
                        Aadhar Back
                        <span className="text-red-500"> *</span>
                      </label>

                      <label className="relative flex flex-col items-center justify-center w-full h-40 border-2 border-dashed border-[#FAA631]/40 rounded-xl cursor-pointer bg-white hover:bg-[#FFF9F1] transition-colors">
                        {backAadharPreview ? (
                          <div className="relative w-full h-full rounded-lg overflow-hidden">
                            {backAadharFile?.type === "application/pdf" ? (
                              <div className="w-full h-full flex flex-col items-center justify-center bg-gray-100">
                                <FileText className="w-12 h-12 text-[#FAA631] mb-2" />
                                <p className="text-sm font-medium text-gray-700">
                                  PDF Uploaded
                                </p>
                              </div>
                            ) : (
                              <Image
                                src={backAadharPreview}
                                alt="Aadhar Back"
                                fill
                                className="object-cover"
                              />
                            )}
                            <div className="absolute inset-0 bg-black/20 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity">
                              <Upload className="w-8 h-8 text-white" />
                            </div>
                          </div>
                        ) : (
                          <div className="flex flex-col items-center justify-center pt-5 pb-6">
                            <Upload className="w-8 h-8 text-[#FAA631] mb-2" />
                            <p className="text-sm font-medium text-gray-700">
                              Click to upload
                            </p>
                            <p className="text-xs text-gray-500">
                              JPG, PNG or PDF (Max 5MB)
                            </p>
                          </div>
                        )}
                        <input
                          ref={backAadharRef}
                          type="file"
                          accept="image/jpeg,image/png,application/pdf"
                          onChange={(e) => handleAadharFileChange(e, "back")}
                          className="hidden"
                        />
                      </label>
                    </div>
                  </div>

                  <p className="text-xs text-gray-600 bg-white p-2.5 rounded-lg border border-gray-200">
                    ℹ️ Your Aadhar information will be securely stored and used
                    for identity verification purposes only.
                  </p>
                </div>

                <div className="flex items-start gap-3 p-3 rounded-lg border border-gray-200 bg-gray-50">
                  <input
                    type="checkbox"
                    id="terms"
                    checked={acceptedTerms}
                    onChange={(e) => setAcceptedTerms(e.target.checked)}
                    className="mt-1 h-4 w-4 accent-[#FAA631] cursor-pointer"
                  />

                  <label
                    htmlFor="terms"
                    className="text-sm text-gray-700 leading-5 cursor-pointer"
                  >
                    I agree to the{" "}
                    <a
                      href="/legal"
                      target="_blank"
                      onClick={() =>
                        localStorage.setItem("legal_select_last", "1")
                      }
                      className="text-[#FAA631] font-medium underline"
                    >
                      Terms & Conditions
                    </a>{" "}
                    and{" "}
                    <a
                      href="/legal"
                      target="_blank"
                      className="text-[#FAA631] font-medium underline"
                    >
                      Privacy Policy
                    </a>
                    .
                  </label>
                </div>

                <Button
                  onClick={() => {
                    handleSubmit();
                    // setStep(3);
                  }}
                  // disabled={loading}
                  className="w-full bg-[#FAA631] hover:bg-orange-400 text-lg py-6"
                >
                  {uploading ? "Registering..." : t.olympiadRegister.submit}
                </Button>
              </CardContent>
            </Card>
          )}

          {step === 2 && (
            <Card className="shadow-xl">
              <CardHeader>
                <CardTitle>{t.olympiadRegister.verifyOtp}</CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <p className="text-gray-600">
                  {t.olympiadRegister.otpSentTo} ({registrationData.email}){" "}
                  {t.olympiadRegister.andPhone} ({registrationData.phone}).
                </p>

                <div>
                  <Label htmlFor="otp">{t.olympiadRegister.enterOtp}</Label>
                  <Input
                    id="otp"
                    value={otp}
                    onChange={(e) => setOtp(e.target.value)}
                    placeholder={t.olympiadRegister.enterOtpPlaceholder}
                    maxLength={6}
                    className="mt-2 text-center text-2xl tracking-widest"
                  />
                </div>

                <div className="flex gap-4">
                  <Button
                    onClick={() => setStep(1)}
                    variant="outline"
                    className="flex-1 hover:bg-[#FAA631]"
                  >
                    {t.olympiadRegister.back}
                  </Button>
                  <Button
                    onClick={handleVerifyOTP}
                    className="flex-1 bg-[#FAA631] hover:bg-orange-400"
                  >
                    {t.olympiadRegister.verifyOtp}
                  </Button>
                </div>

                <Button
                  onClick={handleSendOTP}
                  variant="link"
                  className="w-full text-[#FAA631]"
                >
                  {t.olympiadRegister.resendOtp}
                </Button>
              </CardContent>
            </Card>
          )}

          {step === 3 && (
            <div className="min-h-screen relative flex items-center justify-center px-2 py-8">
              {/* Background */}
              {/* <div className="absolute inset-0 overflow-hidden">
                <Image
                  src="/images/confetti-bg.png"
                  alt="confetti"
                  fill
                  className="object-cover opacity-60"
                  priority={false}
                />
                <div className="absolute inset-0 bg-gradient-to-b from-white/70 via-[#FFF9F1]/80 to-[#FFF9F1]" />
              </div> */}

              {/* Close Button */}
              {/* <button
                type="button"
                onClick={() => router.push("/")}
                className="absolute top-6 right-6 z-10 w-10 h-10 rounded-full bg-white/90 shadow flex items-center justify-center text-gray-700 hover:bg-white transition active:scale-95"
                aria-label="Close"
              >
                ✕
              </button> */}

              {/* Content Card */}
              <div className="relative z-10 w-full max-w-2xl">
                <div className="bg-white/90 backdrop-blur-md rounded-3xl shadow-xl border border-white/60 p-6 sm:p-10">
                  {/* Success Icon */}
                  <div className="flex justify-center">
                    <div className="w-24 h-24 sm:w-28 sm:h-28 rounded-full bg-[#FFF4E4] flex items-center justify-center shadow-sm">
                      <Image
                        src="/images/success.svg"
                        alt="Success"
                        width={70}
                        height={70}
                        className="w-14 h-14 sm:w-16 sm:h-16"
                      />
                    </div>
                  </div>

                  {/* Title */}
                  <h2 className="mt-6 text-center text-2xl sm:text-3xl font-bold text-gray-900">
                    {t.olympiadRegister.congratulations}!
                  </h2>

                  {/* Message */}
                  <p className="text-center text-gray-600 mt-3 text-sm sm:text-base leading-relaxed">
                    {t.olympiadRegister.successMessage}
                  </p>

                  {/* Next Steps */}
                  <div className="mt-8">
                    <h3 className="text-gray-900 font-semibold text-base sm:text-lg mb-3 text-center sm:text-left">
                      {t.olympiadRegister.whatsNext}
                    </h3>

                    <div className="grid gap-3 sm:gap-4">
                      {[
                        t.olympiadRegister.next1,
                        t.olympiadRegister.next2,
                        t.olympiadRegister.next3,
                      ].map((item, idx) => (
                        <div
                          key={idx}
                          className="flex items-start gap-3 bg-[#FFF9F1] border border-[#FFE6C7] rounded-2xl p-4"
                        >
                          <div className="w-8 h-8 rounded-full bg-[#FAA631] text-white flex items-center justify-center font-semibold text-sm shrink-0">
                            {idx + 1}
                          </div>
                          <p className="text-gray-700 text-sm sm:text-base leading-snug">
                            {item}
                          </p>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* CTA Button */}
                  <button
                    onClick={() => setShowCourseModal(true)}
                    className="w-full mt-8 py-3.5 rounded-full bg-[#FAA631] text-white font-semibold text-base shadow-md hover:bg-[#e18b20] transition active:scale-95"
                  >
                    {t.olympiadRegister.takeCourse}
                  </button>

                  {/* Secondary Link */}
                  <button
                    onClick={() => router.push("/")}
                    className="w-full mt-3 py-3 rounded-full text-gray-700 font-medium hover:bg-gray-100 transition"
                  >
                    Go to Home
                  </button>
                </div>
              </div>
            </div>
          )}
        </AnimatedSection>

        {/* Course Language Selection Modal */}
        <Dialog open={showCourseModal} onOpenChange={setShowCourseModal}>
          <DialogContent className="w-full max-w-sm mx-auto sm:rounded-2xl border-0 p-0 overflow-hidden">
            <div className="bg-[#FAA631] px-6 py-8 flex flex-col items-center gap-6">
              <DialogHeader>
                <DialogTitle className="text-white text-xl font-bold text-center">
                  Choose Your Course Language
                </DialogTitle>
              </DialogHeader>
              <button
                onClick={() => {
                  setShowCourseModal(false);
                  openCourse("hindi");
                }}
                className="w-full py-4 rounded-xl bg-white text-[#FAA631] font-semibold text-lg hover:bg-orange-50 transition active:scale-95"
              >
                Hindi Course
              </button>
              <button
                onClick={() => {
                  setShowCourseModal(false);
                  openCourse("english");
                }}
                className="w-full py-4 rounded-xl bg-white text-[#FAA631] font-semibold text-lg hover:bg-orange-50 transition active:scale-95"
              >
                English Course
              </button>
            </div>
          </DialogContent>
        </Dialog>

        {/* Image Upload Guidelines Modal */}
        <ImageUploadGuidelinesModal
          isOpen={showProfilePhotoModal}
          onConfirm={() => {
            setShowProfilePhotoModal(false);
            fileInputRef.current?.click();
          }}
          onCancel={() => setShowProfilePhotoModal(false)}
          title="Image Upload Guidelines"
        />
      </div>
    </div>
  );
}
