/**
 * Forgot Password Page
 *
 * AUTH STRATEGY: Clerk-first with legacy OTP fallback.
 * When Clerk is configured (NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY is set),
 * this page immediately redirects to Clerk's sign-in page which has
 * a built-in "Forgot password?" link and reset flow.
 * When Clerk is NOT configured, the existing custom OTP-based form is shown.
 */
"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { UI, type Lang } from "@/lib/config";
import {
  EyeIcon,
  EyeSlashIcon,
  ShieldCheckIcon,
  LockClosedIcon,
  KeyIcon,
  CheckCircleIcon,
} from "@heroicons/react/24/outline";
import { logger } from "@/lib/logger";
import BrandLogo from "@/components/BrandLogo";

type ResetMethod = "email" | "phone";
type ResetStep = "input" | "otp" | "newPassword" | "success";

/**
 * Check if Clerk is the primary auth system.
 * NEXT_PUBLIC_ env vars are inlined at build time, so this works client-side.
 */
const isClerkConfigured = () =>
  Boolean(process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY);

export default function ForgotPasswordPage({
  params,
}: {
  params: { lang: Lang };
}) {
  const { lang } = params;
  const router = useRouter();
  const t = UI[lang].t;
  const dir = UI[lang].dir;

  // All hooks must be called unconditionally (React rules of hooks)
  const [resetMethod, setResetMethod] = useState<ResetMethod>("email");
  const [step, setStep] = useState<ResetStep>("input");
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [otpCode, setOtpCode] = useState("");
  const [resetToken, setResetToken] = useState("");

  const [formData, setFormData] = useState({
    identifier: "",
    newPassword: "",
    confirmPassword: "",
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  // ── Clerk-first path ──
  // When Clerk is active, redirect to Clerk's sign-in page.
  useEffect(() => {
    if (isClerkConfigured()) {
      router.replace(`/${lang}/clerk-login#/forgot-password`);
    }
  }, [lang, router]);

  // Fetch CSRF token on component mount (for legacy OTP flow)
  useEffect(() => {
    if (!isClerkConfigured()) {
      const fetchCSRFToken = async () => {
        try {
          await fetch("/api/csrf");
        } catch (err) {
          console.error("Failed to fetch CSRF token:", err);
        }
      };
      fetchCSRFToken();
    }
  }, []);

  // Show a brief loading state while redirecting to Clerk
  if (isClerkConfigured()) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[#EEF2F6]" dir={dir}>
        <div className="text-center">
          <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-[#0F9972] border-t-transparent" />
          <p className="mt-4 text-sm text-slate-600">
            {lang === "ar"
              ? "جارٍ التحويل إلى صفحة إعادة تعيين كلمة المرور..."
              : "Redirecting to password reset..."}
          </p>
        </div>
      </div>
    );
  }

  // Get CSRF token from cookie
  const getCSRFToken = (): string | null => {
    if (typeof document === "undefined") return null;
    const match = document.cookie.match(/csrf-token=([^;]+)/);
    return match ? match[1] : null;
  };

  // Password strength indicator
  const getPasswordStrength = (
    password: string,
  ): { strength: number; label: string; color: string } => {
    let strength = 0;
    if (password.length >= 12) strength++;
    if (/[a-z]/.test(password)) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/\d/.test(password)) strength++;
    if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) strength++;

    if (strength <= 2)
      return {
        strength: 1,
        label: lang === "ar" ? "ضعيفة" : "Weak",
        color: "bg-red-500",
      };
    if (strength <= 3)
      return {
        strength: 2,
        label: lang === "ar" ? "متوسطة" : "Fair",
        color: "bg-yellow-500",
      };
    if (strength <= 4)
      return {
        strength: 3,
        label: lang === "ar" ? "جيدة" : "Good",
        color: "bg-blue-500",
      };
    return {
      strength: 4,
      label: lang === "ar" ? "قوية" : "Strong",
      color: "bg-green-500",
    };
  };

  const validateIdentifier = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.identifier.trim()) {
      newErrors.identifier = t.fieldRequired;
      setErrors(newErrors);
      return false;
    }

    // Check if it's email or phone
    const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.identifier);
    const isPhone =
      /^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,9}$/.test(
        formData.identifier,
      );

    if (!isEmail && !isPhone) {
      newErrors.identifier =
        lang === "ar"
          ? "البريد الإلكتروني أو رقم الهاتف غير صالح"
          : "Invalid email or phone number";
      setErrors(newErrors);
      return false;
    }

    // Auto-detect reset method
    if (isEmail) {
      setResetMethod("email");
    } else if (isPhone) {
      setResetMethod("phone");
    }

    setErrors({});
    return true;
  };

  const handleSendReset = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateIdentifier()) {
      return;
    }

    setLoading(true);
    setError("");

    try {
      // Get CSRF token
      const csrfToken = getCSRFToken();

      if (!csrfToken) {
        setError(
          lang === "ar"
            ? "رمز الأمان مفقود. يرجى تحديث الصفحة."
            : "Security token missing. Please refresh the page.",
        );
        setLoading(false);
        return;
      }

      const response = await fetch("/api/auth/forgot-password", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          identifier: formData.identifier,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to send reset");
      }

      // If the API indicates Clerk handles password reset, redirect
      if (data.useClerk) {
        router.replace(`/${lang}/clerk-login#/forgot-password`);
        return;
      }

      // Always go to OTP verification step (for both email and phone)
      setStep("otp");
      setLoading(false);
    } catch (err) {
      logger.error("Send reset error", err);
      setError(
        (err as Error).message ||
          (lang === "ar"
            ? "فشل إرسال طلب إعادة التعيين"
            : "Failed to send reset request"),
      );
      setLoading(false);
    }
  };

  const handleVerifyOTP = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!otpCode || otpCode.length !== 6) {
      setError(
        lang === "ar"
          ? "أدخل رمز OTP المكون من 6 أرقام"
          : "Enter 6-digit OTP code",
      );
      return;
    }

    setLoading(true);
    setError("");

    try {
      // Get CSRF token
      const csrfToken = getCSRFToken();

      if (!csrfToken) {
        setError(
          lang === "ar"
            ? "رمز الأمان مفقود. يرجى تحديث الصفحة."
            : "Security token missing. Please refresh the page.",
        );
        setLoading(false);
        return;
      }

      const response = await fetch("/api/auth/verify-reset-otp", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          identifier: formData.identifier, // Works for both email and phone
          code: otpCode,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "OTP verification failed");
      }

      // Store reset token for password reset
      setResetToken(data.resetToken);
      setStep("newPassword");
      setLoading(false);
    } catch (err) {
      logger.error("OTP verification error", err);
      setError(
        (err as Error).message ||
          (lang === "ar" ? "رمز OTP غير صحيح" : "Invalid OTP code"),
      );
      setLoading(false);
    }
  };

  const handleResetPassword = async (e: React.FormEvent) => {
    e.preventDefault();

    const newErrors: Record<string, string> = {};

    if (!formData.newPassword) {
      newErrors.newPassword = t.fieldRequired;
    } else if (formData.newPassword.length < 12) {
      newErrors.newPassword =
        lang === "ar"
          ? "يجب أن تحتوي كلمة المرور على 12 حرفًا على الأقل"
          : "Password must be at least 12 characters";
    } else if (!/[a-z]/.test(formData.newPassword)) {
      newErrors.newPassword =
        lang === "ar"
          ? "يجب أن تحتوي كلمة المرور على أحرف صغيرة"
          : "Password must contain lowercase letters";
    } else if (!/[A-Z]/.test(formData.newPassword)) {
      newErrors.newPassword =
        lang === "ar"
          ? "يجب أن تحتوي كلمة المرور على أحرف كبيرة"
          : "Password must contain uppercase letters";
    } else if (!/\d/.test(formData.newPassword)) {
      newErrors.newPassword =
        lang === "ar"
          ? "يجب أن تحتوي كلمة المرور على أرقام"
          : "Password must contain numbers";
    } else if (
      !/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(formData.newPassword)
    ) {
      newErrors.newPassword =
        lang === "ar"
          ? "يجب أن تحتوي كلمة المرور على رموز خاصة"
          : "Password must contain special characters";
    }

    if (!formData.confirmPassword) {
      newErrors.confirmPassword = t.fieldRequired;
    } else if (formData.newPassword !== formData.confirmPassword) {
      newErrors.confirmPassword = t.passwordsDoNotMatch;
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    setLoading(true);
    setError("");

    try {
      // Get CSRF token
      const csrfToken = getCSRFToken();

      if (!csrfToken) {
        setError(
          lang === "ar"
            ? "رمز الأمان مفقود. يرجى تحديث الصفحة."
            : "Security token missing. Please refresh the page.",
        );
        setLoading(false);
        return;
      }

      const response = await fetch("/api/auth/reset-password", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          identifier: formData.identifier,
          newPassword: formData.newPassword,
          resetToken: resetToken,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Password reset failed");
      }

      // Success!
      setStep("success");
      setLoading(false);
    } catch (err) {
      logger.error("Reset password error", err);
      setError(
        (err as Error).message ||
          (lang === "ar"
            ? "فشل إعادة تعيين كلمة المرور"
            : "Failed to reset password"),
      );
      setLoading(false);
    }
  };

  const passwordStrength = formData.newPassword
    ? getPasswordStrength(formData.newPassword)
    : null;

  return (
    <main className="relative flex min-h-screen overflow-hidden bg-gradient-to-br from-neutral-50 via-white to-brand-green/5">
      {/* Background Pattern */}
      <div className="absolute inset-0 opacity-40">
        <div
          className="absolute inset-0"
          style={{
            backgroundImage: `radial-gradient(circle at 1px 1px, rgb(209 213 219 / 0.3) 1px, transparent 0)`,
            backgroundSize: "40px 40px",
          }}
        />
      </div>

      {/* Left Side - Brand Visual (Hidden on mobile) */}
      <div className="relative hidden lg:flex lg:w-1/2 xl:w-3/5 items-center justify-center bg-gradient-to-br from-brand-green via-brand-green/90 to-brand-green/80 p-12">
        {/* Decorative Elements */}
        <div className="absolute inset-0 overflow-hidden">
          <div className="absolute -top-40 -left-40 h-80 w-80 rounded-full bg-white/10 blur-3xl" />
          <div className="absolute -bottom-40 -right-40 h-96 w-96 rounded-full bg-white/10 blur-3xl" />
        </div>

        {/* Content */}
        <div className="relative z-10 max-w-lg space-y-8 text-white">
          {/* Logo */}
          <div className="inline-flex items-center rounded-2xl border border-white/20 bg-white/10 px-6 py-3 backdrop-blur-sm">
            <BrandLogo size="sm" tone="light" />
          </div>

          {/* Headline */}
          <div className="space-y-4">
            <h2 className="text-4xl font-extrabold leading-tight xl:text-5xl">
              {lang === "ar" ? "استعادة الوصول لحسابك" : "Recover Your Account"}
            </h2>
            <p className="text-lg text-white/90 leading-relaxed">
              {lang === "ar"
                ? "نساعدك على استعادة الوصول إلى حسابك بأمان وسهولة"
                : "Securely restore access to your account in just a few steps"}
            </p>
          </div>

          {/* Security Features */}
          <div className="space-y-4 pt-6">
            <div className="flex items-start gap-3">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-white/20 flex-shrink-0">
                <ShieldCheckIcon className="h-5 w-5" />
              </div>
              <div>
                <h3 className="font-semibold text-white mb-1">
                  {lang === "ar" ? "مصادقة آمنة" : "Secure Authentication"}
                </h3>
                <p className="text-sm text-white/80">
                  {lang === "ar"
                    ? "نستخدم OTP للتحقق من هويتك"
                    : "OTP verification to confirm your identity"}
                </p>
              </div>
            </div>
            <div className="flex items-start gap-3">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-white/20 flex-shrink-0">
                <LockClosedIcon className="h-5 w-5" />
              </div>
              <div>
                <h3 className="font-semibold text-white mb-1">
                  {lang === "ar" ? "تشفير شامل" : "End-to-End Encryption"}
                </h3>
                <p className="text-sm text-white/80">
                  {lang === "ar"
                    ? "جميع البيانات محمية بتشفير 256-bit"
                    : "All data protected with 256-bit encryption"}
                </p>
              </div>
            </div>
          </div>

          {/* Progress Indicator */}
          {step !== "success" && (
            <div className="pt-8 border-t border-white/20">
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm text-white/70">
                  {lang === "ar" ? "التقدم" : "Progress"}
                </span>
                <span className="text-sm font-semibold text-white">
                  {step === "input" ? "1/3" : step === "otp" ? "2/3" : "3/3"}
                </span>
              </div>
              <div className="h-2 bg-white/20 rounded-full overflow-hidden">
                <div
                  className="h-full bg-white rounded-full transition-all duration-500"
                  style={{
                    width:
                      step === "input"
                        ? "33%"
                        : step === "otp"
                          ? "66%"
                          : "100%",
                  }}
                />
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Right Side - Reset Form */}
      <div className="relative flex w-full items-center justify-center px-6 py-12 lg:w-1/2 xl:w-2/5">
        <div className="w-full max-w-md space-y-8">
          {/* Logo (Mobile Only) */}
          <div className="text-center lg:hidden">
            <BrandLogo href={`/${lang}`} size="md" />
          </div>

          {/* Card Container */}
          <div className="relative">
            {/* Glassmorphism Card */}
            <div className="rounded-2xl bg-white/80 backdrop-blur-xl shadow-2xl shadow-brand-green/5 border border-neutral-100 p-8 space-y-6">
              {/* Header */}
              <div className="space-y-2 text-center">
                <div className="flex justify-center mb-4">
                  <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-brand-green/10">
                    {step === "success" ? (
                      <CheckCircleIcon className="h-8 w-8 text-brand-green" />
                    ) : (
                      <KeyIcon className="h-8 w-8 text-brand-green" />
                    )}
                  </div>
                </div>
                <h2 className="text-3xl font-bold text-brand-ink tracking-tight">
                  {step === "input" && t.forgotPasswordTitle}
                  {step === "otp" && t.enterOTP}
                  {step === "newPassword" &&
                    (lang === "ar"
                      ? "إنشاء كلمة مرور جديدة"
                      : "Create New Password")}
                  {step === "success" && t.passwordResetSuccess}
                </h2>
                <p className="text-neutral-600 text-sm">
                  {step === "input" && t.forgotPasswordSubtitle}
                  {step === "otp" &&
                    (lang === "ar"
                      ? "أدخل الرمز المرسل إليك"
                      : "Enter the code sent to you")}
                  {step === "newPassword" &&
                    (lang === "ar"
                      ? "اختر كلمة مرور قوية وآمنة"
                      : "Choose a strong and secure password")}
                  {step === "success" &&
                    (lang === "ar"
                      ? "يمكنك الآن تسجيل الدخول بكلمة المرور الجديدة"
                      : "You can now log in with your new password")}
                </p>
              </div>

              {/* Error Message */}
              {error && (
                <div className="rounded-xl bg-red-50 border border-red-200 p-4 animate-shake">
                  <div className="flex items-start gap-3">
                    <svg
                      className="h-5 w-5 text-red-500 mt-0.5 flex-shrink-0"
                      fill="currentColor"
                      viewBox="0 0 20 20"
                    >
                      <path
                        fillRule="evenodd"
                        d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                        clipRule="evenodd"
                      />
                    </svg>
                    <p className="text-sm text-red-800 flex-1">{error}</p>
                  </div>
                </div>
              )}

              {/* Step 1: Enter Email/Phone */}
              {step === "input" && (
                <form
                  onSubmit={handleSendReset}
                  className="space-y-5"
                  dir={dir}
                >
                  {/* Email or Phone */}
                  <div className="group">
                    <label
                      htmlFor="identifier"
                      className="block text-sm font-semibold text-neutral-700 mb-2"
                    >
                      {t.emailOrPhone}
                    </label>
                    <input
                      id="identifier"
                      type="text"
                      value={formData.identifier}
                      onChange={(e) =>
                        setFormData({ ...formData, identifier: e.target.value })
                      }
                      className={`w-full rounded-xl border-2 ${
                        errors.identifier
                          ? "border-red-300 focus:border-red-400 focus:ring-red-100"
                          : "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20"
                      } px-4 py-3.5 text-sm bg-white/50 backdrop-blur-sm transition-all focus:outline-none focus:ring-4 hover:border-neutral-300`}
                      placeholder={
                        lang === "ar"
                          ? "example@domain.com أو +966xxxxxxxxx"
                          : "example@domain.com or +966xxxxxxxxx"
                      }
                      autoComplete="username"
                      autoFocus
                    />
                    {errors.identifier && (
                      <p className="mt-2 text-xs text-red-600 flex items-center gap-1.5">
                        <svg
                          className="h-4 w-4"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fillRule="evenodd"
                            d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
                            clipRule="evenodd"
                          />
                        </svg>
                        {errors.identifier}
                      </p>
                    )}
                  </div>

                  {/* Submit Button */}
                  <button
                    type="submit"
                    disabled={loading}
                    className="group relative w-full rounded-xl bg-gradient-to-r from-brand-green to-brand-green/90 px-6 py-4 text-sm font-bold text-white shadow-lg shadow-brand-green/25 transition-all hover:shadow-xl hover:shadow-brand-green/30 hover:-translate-y-0.5 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:translate-y-0 disabled:hover:shadow-lg overflow-hidden"
                  >
                    {/* Button shine effect */}
                    <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-200%] group-hover:translate-x-[200%] transition-transform duration-1000" />

                    <span className="relative flex items-center justify-center gap-2">
                      {loading && (
                        <svg
                          className="animate-spin h-5 w-5"
                          xmlns="http://www.w3.org/2000/svg"
                          fill="none"
                          viewBox="0 0 24 24"
                        >
                          <circle
                            className="opacity-25"
                            cx="12"
                            cy="12"
                            r="10"
                            stroke="currentColor"
                            strokeWidth="4"
                          ></circle>
                          <path
                            className="opacity-75"
                            fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                          ></path>
                        </svg>
                      )}
                      {loading
                        ? lang === "ar"
                          ? "جاري الإرسال..."
                          : "Sending..."
                        : resetMethod === "email"
                          ? t.sendResetLink
                          : t.sendResetOTP}
                    </span>
                  </button>

                  {/* Back to Login */}
                  <Link
                    href={`/${lang}/login`}
                    className="block text-center text-sm font-medium text-brand-green hover:text-brand-greenHover transition-colors"
                  >
                    {t.backToLogin}
                  </Link>
                </form>
              )}

              {/* Step 2: Verify OTP */}
              {step === "otp" && (
                <form
                  onSubmit={handleVerifyOTP}
                  className="space-y-5"
                  dir={dir}
                >
                  <div className="rounded-xl bg-gradient-to-br from-brand-green/10 to-brand-green/5 border border-brand-green/20 p-6 text-center space-y-3">
                    <div className="flex justify-center">
                      <div className="flex h-12 w-12 items-center justify-center rounded-full bg-brand-green/20">
                        <svg
                          className="h-6 w-6 text-brand-green"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
                          />
                        </svg>
                      </div>
                    </div>
                    <p className="text-sm text-neutral-700 font-medium">
                      {lang === "ar"
                        ? `تم إرسال رمز التحقق إلى ${formData.identifier}`
                        : `Verification code sent to ${formData.identifier}`}
                    </p>
                  </div>

                  {/* OTP Input */}
                  <div>
                    <label
                      htmlFor="otp"
                      className="block text-sm font-semibold text-neutral-700 mb-2"
                    >
                      {t.enterOTP}
                    </label>
                    <input
                      id="otp"
                      type="text"
                      inputMode="numeric"
                      maxLength={6}
                      value={otpCode}
                      onChange={(e) =>
                        setOtpCode(e.target.value.replace(/\D/g, ""))
                      }
                      className="w-full rounded-xl border-2 border-neutral-200 bg-white/50 backdrop-blur-sm px-6 py-4 text-center text-3xl font-bold tracking-[0.5em] focus:border-brand-green focus:outline-none focus:ring-4 focus:ring-brand-green/20 transition-all hover:border-neutral-300"
                      placeholder="• • • • • •"
                      autoComplete="one-time-code"
                      autoFocus
                    />
                    <p className="mt-2 text-xs text-neutral-500 text-center">
                      {lang === "ar"
                        ? "الرجاء إدخال الرمز المكون من 6 أرقام"
                        : "Please enter the 6-digit code"}
                    </p>
                  </div>

                  {/* Verify Button */}
                  <button
                    type="submit"
                    disabled={loading || otpCode.length !== 6}
                    className="group relative w-full rounded-xl bg-gradient-to-r from-brand-green to-brand-green/90 px-6 py-4 text-sm font-bold text-white shadow-lg shadow-brand-green/25 transition-all hover:shadow-xl hover:shadow-brand-green/30 hover:-translate-y-0.5 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:translate-y-0 disabled:hover:shadow-lg overflow-hidden"
                  >
                    <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-200%] group-hover:translate-x-[200%] transition-transform duration-1000" />
                    <span className="relative flex items-center justify-center gap-2">
                      {loading && (
                        <svg
                          className="animate-spin h-5 w-5"
                          xmlns="http://www.w3.org/2000/svg"
                          fill="none"
                          viewBox="0 0 24 24"
                        >
                          <circle
                            className="opacity-25"
                            cx="12"
                            cy="12"
                            r="10"
                            stroke="currentColor"
                            strokeWidth="4"
                          ></circle>
                          <path
                            className="opacity-75"
                            fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                          ></path>
                        </svg>
                      )}
                      {loading
                        ? lang === "ar"
                          ? "جاري التحقق..."
                          : "Verifying..."
                        : t.verifyButton}
                    </span>
                  </button>

                  {/* Resend Code */}
                  <button
                    type="button"
                    onClick={() => handleSendReset(new Event("submit") as any)}
                    disabled={loading}
                    className="w-full text-sm font-medium text-brand-green hover:text-brand-greenHover transition-colors disabled:opacity-50"
                  >
                    {lang === "ar" ? "إعادة إرسال الرمز" : "Resend code"}
                  </button>

                  {/* Back Button */}
                  <button
                    type="button"
                    onClick={() => {
                      setStep("input");
                      setOtpCode("");
                      setError("");
                    }}
                    className="w-full rounded-xl border-2 border-neutral-200 bg-white/50 backdrop-blur-sm px-6 py-3.5 text-sm font-semibold text-neutral-700 shadow-sm transition-all hover:border-neutral-300 hover:bg-white hover:shadow-md hover:-translate-y-0.5"
                  >
                    {t.backButton}
                  </button>
                </form>
              )}

              {/* Step 3: New Password */}
              {step === "newPassword" && (
                <form
                  onSubmit={handleResetPassword}
                  className="space-y-5"
                  dir={dir}
                >
                  {/* New Password */}
                  <div className="group">
                    <label
                      htmlFor="newPassword"
                      className="block text-sm font-semibold text-neutral-700 mb-2"
                    >
                      {t.newPassword}
                    </label>
                    <div className="relative">
                      <input
                        id="newPassword"
                        type={showPassword ? "text" : "password"}
                        value={formData.newPassword}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            newPassword: e.target.value,
                          })
                        }
                        className={`w-full rounded-xl border-2 ${
                          errors.newPassword
                            ? "border-red-300 focus:border-red-400 focus:ring-red-100"
                            : "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20"
                        } px-4 py-3.5 text-sm bg-white/50 backdrop-blur-sm transition-all focus:outline-none focus:ring-4 hover:border-neutral-300 ${
                          dir === "rtl" ? "pl-12 pr-4" : "pr-12 pl-4"
                        }`}
                        placeholder={
                          lang === "ar"
                            ? "أدخل كلمة المرور الجديدة"
                            : "Enter new password"
                        }
                        autoComplete="new-password"
                        autoFocus
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className={`absolute top-1/2 -translate-y-1/2 ${
                          dir === "rtl" ? "left-4" : "right-4"
                        } text-neutral-400 hover:text-neutral-600 transition-colors p-1 rounded-lg hover:bg-neutral-100`}
                      >
                        {showPassword ? (
                          <EyeSlashIcon className="h-5 w-5" />
                        ) : (
                          <EyeIcon className="h-5 w-5" />
                        )}
                      </button>
                    </div>

                    {/* Password Strength Indicator */}
                    {formData.newPassword && passwordStrength && (
                      <div className="mt-3">
                        <div className="flex items-center justify-between mb-1.5">
                          <span className="text-xs font-medium text-neutral-600">
                            {lang === "ar"
                              ? "قوة كلمة المرور"
                              : "Password strength"}
                          </span>
                          <span
                            className={`text-xs font-semibold ${
                              passwordStrength.strength === 1
                                ? "text-red-600"
                                : passwordStrength.strength === 2
                                  ? "text-yellow-600"
                                  : passwordStrength.strength === 3
                                    ? "text-blue-600"
                                    : "text-green-600"
                            }`}
                          >
                            {passwordStrength.label}
                          </span>
                        </div>
                        <div className="flex gap-1.5">
                          {[1, 2, 3, 4].map((level) => (
                            <div
                              key={level}
                              className={`h-1.5 flex-1 rounded-full transition-all duration-300 ${
                                level <= passwordStrength.strength
                                  ? passwordStrength.color
                                  : "bg-neutral-200"
                              }`}
                            />
                          ))}
                        </div>
                      </div>
                    )}

                    {errors.newPassword && (
                      <p className="mt-2 text-xs text-red-600 flex items-center gap-1.5">
                        <svg
                          className="h-4 w-4"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fillRule="evenodd"
                            d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
                            clipRule="evenodd"
                          />
                        </svg>
                        {errors.newPassword}
                      </p>
                    )}
                  </div>

                  {/* Confirm New Password */}
                  <div className="group">
                    <label
                      htmlFor="confirmPassword"
                      className="block text-sm font-semibold text-neutral-700 mb-2"
                    >
                      {t.confirmNewPassword}
                    </label>
                    <div className="relative">
                      <input
                        id="confirmPassword"
                        type={showConfirmPassword ? "text" : "password"}
                        value={formData.confirmPassword}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            confirmPassword: e.target.value,
                          })
                        }
                        className={`w-full rounded-xl border-2 ${
                          errors.confirmPassword
                            ? "border-red-300 focus:border-red-400 focus:ring-red-100"
                            : "border-neutral-200 focus:border-brand-green focus:ring-brand-green/20"
                        } px-4 py-3.5 text-sm bg-white/50 backdrop-blur-sm transition-all focus:outline-none focus:ring-4 hover:border-neutral-300 ${
                          dir === "rtl" ? "pl-12 pr-4" : "pr-12 pl-4"
                        }`}
                        placeholder={
                          lang === "ar"
                            ? "أعد إدخال كلمة المرور"
                            : "Re-enter password"
                        }
                        autoComplete="new-password"
                      />
                      <button
                        type="button"
                        onClick={() =>
                          setShowConfirmPassword(!showConfirmPassword)
                        }
                        className={`absolute top-1/2 -translate-y-1/2 ${
                          dir === "rtl" ? "left-4" : "right-4"
                        } text-neutral-400 hover:text-neutral-600 transition-colors p-1 rounded-lg hover:bg-neutral-100`}
                      >
                        {showConfirmPassword ? (
                          <EyeSlashIcon className="h-5 w-5" />
                        ) : (
                          <EyeIcon className="h-5 w-5" />
                        )}
                      </button>
                    </div>
                    {errors.confirmPassword && (
                      <p className="mt-2 text-xs text-red-600 flex items-center gap-1.5">
                        <svg
                          className="h-4 w-4"
                          fill="currentColor"
                          viewBox="0 0 20 20"
                        >
                          <path
                            fillRule="evenodd"
                            d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
                            clipRule="evenodd"
                          />
                        </svg>
                        {errors.confirmPassword}
                      </p>
                    )}
                  </div>

                  {/* Password Requirements */}
                  <div className="rounded-xl bg-neutral-50 border border-neutral-200 p-4">
                    <p className="text-xs font-semibold text-neutral-700 mb-2">
                      {lang === "ar"
                        ? "متطلبات كلمة المرور:"
                        : "Password requirements:"}
                    </p>
                    <ul className="space-y-1.5 text-xs text-neutral-600">
                      <li
                        className={`flex items-center gap-2 ${formData.newPassword.length >= 12 ? "text-green-600" : ""}`}
                      >
                        <span
                          className={`flex h-4 w-4 items-center justify-center rounded-full ${formData.newPassword.length >= 12 ? "bg-green-100" : "bg-neutral-200"}`}
                        >
                          {formData.newPassword.length >= 12 && (
                            <CheckCircleIcon className="h-3 w-3" />
                          )}
                        </span>
                        {lang === "ar"
                          ? "12 حرفًا على الأقل"
                          : "At least 12 characters"}
                      </li>
                      <li
                        className={`flex items-center gap-2 ${/[A-Z]/.test(formData.newPassword) ? "text-green-600" : ""}`}
                      >
                        <span
                          className={`flex h-4 w-4 items-center justify-center rounded-full ${/[A-Z]/.test(formData.newPassword) ? "bg-green-100" : "bg-neutral-200"}`}
                        >
                          {/[A-Z]/.test(formData.newPassword) && (
                            <CheckCircleIcon className="h-3 w-3" />
                          )}
                        </span>
                        {lang === "ar"
                          ? "حرف كبير واحد على الأقل"
                          : "One uppercase letter"}
                      </li>
                      <li
                        className={`flex items-center gap-2 ${/[a-z]/.test(formData.newPassword) ? "text-green-600" : ""}`}
                      >
                        <span
                          className={`flex h-4 w-4 items-center justify-center rounded-full ${/[a-z]/.test(formData.newPassword) ? "bg-green-100" : "bg-neutral-200"}`}
                        >
                          {/[a-z]/.test(formData.newPassword) && (
                            <CheckCircleIcon className="h-3 w-3" />
                          )}
                        </span>
                        {lang === "ar"
                          ? "حرف صغير واحد على الأقل"
                          : "One lowercase letter"}
                      </li>
                      <li
                        className={`flex items-center gap-2 ${/\d/.test(formData.newPassword) ? "text-green-600" : ""}`}
                      >
                        <span
                          className={`flex h-4 w-4 items-center justify-center rounded-full ${/\d/.test(formData.newPassword) ? "bg-green-100" : "bg-neutral-200"}`}
                        >
                          {/\d/.test(formData.newPassword) && (
                            <CheckCircleIcon className="h-3 w-3" />
                          )}
                        </span>
                        {lang === "ar" ? "رقم واحد على الأقل" : "One number"}
                      </li>
                      <li
                        className={`flex items-center gap-2 ${/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(formData.newPassword) ? "text-green-600" : ""}`}
                      >
                        <span
                          className={`flex h-4 w-4 items-center justify-center rounded-full ${/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(formData.newPassword) ? "bg-green-100" : "bg-neutral-200"}`}
                        >
                          {/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(
                            formData.newPassword,
                          ) && <CheckCircleIcon className="h-3 w-3" />}
                        </span>
                        {lang === "ar"
                          ? "رمز خاص واحد على الأقل"
                          : "One special character"}
                      </li>
                    </ul>
                  </div>

                  {/* Reset Button */}
                  <button
                    type="submit"
                    disabled={loading}
                    className="group relative w-full rounded-xl bg-gradient-to-r from-brand-green to-brand-green/90 px-6 py-4 text-sm font-bold text-white shadow-lg shadow-brand-green/25 transition-all hover:shadow-xl hover:shadow-brand-green/30 hover:-translate-y-0.5 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:translate-y-0 disabled:hover:shadow-lg overflow-hidden"
                  >
                    <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-200%] group-hover:translate-x-[200%] transition-transform duration-1000" />
                    <span className="relative flex items-center justify-center gap-2">
                      {loading && (
                        <svg
                          className="animate-spin h-5 w-5"
                          xmlns="http://www.w3.org/2000/svg"
                          fill="none"
                          viewBox="0 0 24 24"
                        >
                          <circle
                            className="opacity-25"
                            cx="12"
                            cy="12"
                            r="10"
                            stroke="currentColor"
                            strokeWidth="4"
                          ></circle>
                          <path
                            className="opacity-75"
                            fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                          ></path>
                        </svg>
                      )}
                      {loading
                        ? lang === "ar"
                          ? "جاري الحفظ..."
                          : "Saving..."
                        : t.resetPasswordButton}
                    </span>
                  </button>
                </form>
              )}

              {/* Step 4: Success */}
              {step === "success" && (
                <div className="space-y-6 text-center py-4">
                  {/* Success Animation */}
                  <div className="flex justify-center">
                    <div className="relative">
                      <div className="absolute inset-0 animate-ping opacity-20">
                        <div className="h-20 w-20 rounded-full bg-brand-green" />
                      </div>
                      <div className="relative flex h-20 w-20 items-center justify-center rounded-full bg-gradient-to-br from-brand-green to-brand-green/80 shadow-lg shadow-brand-green/30">
                        <CheckCircleIcon className="h-10 w-10 text-white" />
                      </div>
                    </div>
                  </div>

                  {/* Success Message */}
                  <div className="space-y-2">
                    <p className="text-neutral-600">
                      {lang === "ar"
                        ? "تم تغيير كلمة المرور بنجاح. يمكنك الآن تسجيل الدخول."
                        : "Password changed successfully. You can now log in."}
                    </p>
                  </div>

                  {/* Login Button */}
                  <button
                    onClick={() => router.push(`/${lang}/login`)}
                    className="group relative w-full rounded-xl bg-gradient-to-r from-brand-green to-brand-green/90 px-6 py-4 text-sm font-bold text-white shadow-lg shadow-brand-green/25 transition-all hover:shadow-xl hover:shadow-brand-green/30 hover:-translate-y-0.5 overflow-hidden"
                  >
                    <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-200%] group-hover:translate-x-[200%] transition-transform duration-1000" />
                    <span className="relative">{t.backToLogin}</span>
                  </button>
                </div>
              )}
            </div>

            {/* Security Badge */}
            <div className="mt-6 flex items-center justify-center gap-2 text-xs text-neutral-500">
              <ShieldCheckIcon className="h-4 w-4" />
              <span>
                {lang === "ar"
                  ? "محمي بتشفير 256-bit SSL"
                  : "Secured with 256-bit SSL encryption"}
              </span>
            </div>
          </div>

          {/* Back to Login Link (always visible) */}
          {step !== "success" && (
            <div className="text-center">
              <Link
                href={`/${lang}/login`}
                className="text-sm font-medium text-neutral-600 hover:text-brand-green transition-colors"
              >
                {lang === "ar" ? "← العودة لتسجيل الدخول" : "← Back to Login"}
              </Link>
            </div>
          )}

          {/* Footer Links */}
          <div className="flex items-center justify-center gap-6 text-xs text-neutral-500">
            <Link
              href={`/${lang}/privacy`}
              className="hover:text-brand-green transition-colors"
            >
              {lang === "ar" ? "سياسة الخصوصية" : "Privacy Policy"}
            </Link>
            <span>•</span>
            <Link
              href={`/${lang}/terms`}
              className="hover:text-brand-green transition-colors"
            >
              {lang === "ar" ? "الشروط والأحكام" : "Terms of Service"}
            </Link>
          </div>
        </div>
      </div>

      {/* Add custom animations */}
      <style jsx global>{`
        @keyframes shake {
          0%,
          100% {
            transform: translateX(0);
          }
          25% {
            transform: translateX(-10px);
          }
          75% {
            transform: translateX(10px);
          }
        }
        .animate-shake {
          animation: shake 0.5s ease-in-out;
        }
      `}</style>
    </main>
  );
}
