"use client";

import React, { useState, useEffect } from "react";
import { useOnboarding } from "../context/OnboardingContext";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import {
  User,
  Mail,
  Phone,
  ChevronLeft,
  ChevronRight,
  Loader2,
  AlertCircle,
  CheckCircle2,
  Edit2,
  Eye,
  EyeOff,
  Lock,
} from "lucide-react";
import { toast } from "sonner";

const COUNTRY_DIAL_CODES: Record<string, string> = {
  IN: "+91",
  US: "+1",
  GB: "+44",
  CA: "+1",
  AU: "+61",
  AE: "+971",
  SG: "+65",
  DEFAULT: "+1",
};

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000";

const apiFetch = async (path: string, body: object) => {
  const res = await fetch(`${API_BASE}${path}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    body: JSON.stringify(body),
  });
  const data = await res.json();
  if (!res.ok)
    throw new Error(data?.message || `Request failed: ${res.status}`);
  return data;
};

// Password strength checker
const checkPasswordStrength = (
  password: string,
): {
  score: number;
  message: string;
  color: string;
} => {
  let score = 0;
  if (password.length >= 8) score++;
  if (password.length >= 12) score++;
  if (/[A-Z]/.test(password)) score++;
  if (/[a-z]/.test(password)) score++;
  if (/[0-9]/.test(password)) score++;
  if (/[^A-Za-z0-9]/.test(password)) score++;

  if (score <= 2) {
    return { score, message: "Weak", color: "text-red-500" };
  } else if (score <= 4) {
    return { score, message: "Medium", color: "text-yellow-500" };
  } else {
    return { score, message: "Strong", color: "text-green-500" };
  }
};

// OTP Modal with proper auto-focus
const OtpModal = ({
  email,
  isOpen,
  onClose,
  onVerified,
  stateKey,
  type,
}: {
  email: string;
  isOpen: boolean;
  onClose: () => void;
  onVerified: () => void;
  stateKey: string;
  type: string;
}) => {
  const { setOtpState } = useOnboarding();
  const inputs = React.useRef<(HTMLInputElement | null)[]>([]);
  const [otp, setOtp] = useState("");
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const timerRef = React.useRef<NodeJS.Timeout | null>(null);

  React.useEffect(() => {
    if (isOpen) {
      setOtp("");
      setTimeout(() => inputs.current[0]?.focus(), 100);
    }
  }, [isOpen]);

  React.useEffect(() => {
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, []);

  const startCountdown = () => {
    setCountdown(60);
    if (timerRef.current) clearInterval(timerRef.current);
    timerRef.current = setInterval(() => {
      setCountdown((p) => {
        if (p <= 1) {
          if (timerRef.current) clearInterval(timerRef.current);
          return 0;
        }
        return p - 1;
      });
    }, 1000);
  };

  const resendOtp = async () => {
    setLoading(true);
    try {
      const data = await apiFetch("/otp/send-otp", { email, type });
      if (data.success) {
        toast.success(`OTP resent to ${email}`);
        startCountdown();
      } else {
        toast.error(data.message || "Failed to resend");
      }
    } catch (e: any) {
      toast.error(e.message || "Failed");
    } finally {
      setLoading(false);
    }
  };

  const verifyOtp = async () => {
    if (otp.length < 6) {
      toast.error("Enter all 6 digits");
      return;
    }
    setLoading(true);
    try {
      const data = await apiFetch("/otp/verify-otp", { email, otp, type });
      if (data.success) {
        toast.success("Email verified! ✅");
        setOtpState(stateKey, {
          verified: true,
          loading: false,
          sent: true,
          otp,
        });
        onVerified();
        onClose();
      } else {
        toast.error(data.message || "Invalid OTP");
        setOtp("");
        inputs.current[0]?.focus();
      }
    } catch (e: any) {
      toast.error(e.message || "Verification failed");
    } finally {
      setLoading(false);
    }
  };

  const handleDigit = (i: number, v: string) => {
    const clean = v.replace(/\D/, "");

    if (clean === "") {
      const arr = otp.split("");
      arr[i] = "";
      const newOtp = arr.join("");
      setOtp(newOtp);
      if (i > 0) {
        inputs.current[i - 1]?.focus();
      }
      return;
    }

    const arr = otp.split("");
    arr[i] = clean;
    const newOtp = arr.join("").slice(0, 6);
    setOtp(newOtp);

    if (i < 5 && newOtp.length === i + 1) {
      inputs.current[i + 1]?.focus();
    }
  };

  const handleKey = (i: number, e: React.KeyboardEvent) => {
    if (e.key === "Backspace") {
      e.preventDefault();
      if (otp[i]) {
        const arr = otp.split("");
        arr[i] = "";
        setOtp(arr.join(""));
      } else if (i > 0) {
        inputs.current[i - 1]?.focus();
        const arr = otp.split("");
        arr[i - 1] = "";
        setOtp(arr.join(""));
      }
    }
    if (e.key === "Enter" && otp.length === 6) verifyOtp();
  };

  const handlePaste = (e: React.ClipboardEvent) => {
    e.preventDefault();
    const pasted = e.clipboardData
      .getData("text")
      .replace(/\D/g, "")
      .slice(0, 6);
    setOtp(pasted);
    if (pasted.length === 6) {
      inputs.current[5]?.focus();
      verifyOtp();
    } else if (pasted.length > 0) {
      inputs.current[pasted.length - 1]?.focus();
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div
        className="absolute inset-0 bg-black/40 backdrop-blur-sm"
        onClick={onClose}
      />
      <div className="relative bg-white rounded-2xl shadow-2xl w-full max-w-sm p-7 animate-in fade-in zoom-in-95 duration-200">
        <button
          onClick={onClose}
          className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition-colors"
          aria-label="Close"
        >
          ✕
        </button>

        <div className="flex justify-center mb-5">
          <div className="w-16 h-16 rounded-2xl bg-blue-50 flex items-center justify-center">
            <Mail className="w-8 h-8 text-blue-600" />
          </div>
        </div>

        <h3 className="text-xl font-bold text-gray-900 text-center mb-1">
          Check Your Email
        </h3>
        <p className="text-sm text-gray-500 text-center mb-1">
          We sent a 6-digit code to
        </p>
        <p className="text-sm font-semibold text-blue-600 text-center mb-6 truncate px-4">
          {email}
        </p>

        <div className="flex justify-center gap-2 mb-6">
          {Array.from({ length: 6 }).map((_, i) => (
            <input
              key={i}
              ref={(el) => {
                inputs.current[i] = el;
              }}
              type="text"
              inputMode="numeric"
              maxLength={1}
              value={otp[i] || ""}
              disabled={loading}
              onChange={(e) => handleDigit(i, e.target.value)}
              onKeyDown={(e) => handleKey(i, e)}
              onPaste={handlePaste}
              className={cn(
                "w-11 h-12 text-center text-lg font-bold rounded-xl border-2 outline-none transition-all",
                loading
                  ? "bg-gray-50 border-gray-200 text-gray-400 cursor-not-allowed"
                  : otp[i]
                    ? "border-blue-500 bg-blue-50 text-blue-700"
                    : "border-gray-200 bg-white text-gray-900 focus:border-blue-500 focus:bg-blue-50",
              )}
            />
          ))}
        </div>

        <Button
          onClick={verifyOtp}
          disabled={otp.length < 6 || loading}
          className="w-full bg-blue-600 hover:bg-blue-700 rounded-xl font-semibold mb-4 h-11"
        >
          {loading ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              Verifying…
            </>
          ) : (
            <>Verify Code</>
          )}
        </Button>

        <p className="text-center text-xs text-gray-500">
          Didn't receive it?{" "}
          {countdown > 0 ? (
            <span className="text-gray-400">Resend in {countdown}s</span>
          ) : (
            <button
              onClick={resendOtp}
              disabled={loading}
              className="text-blue-600 font-semibold hover:underline"
              type="button"
            >
              Resend OTP
            </button>
          )}
        </p>
      </div>
    </div>
  );
};

// Email Input with OTP, Smart Matching, and Edit Capability
const EmailInputWithOtp = ({
  label,
  email,
  onChange,
  error,
  stateKey,
  type,
  orgEmail,
}: {
  label: string;
  email: string;
  onChange: (v: string) => void;
  error?: string;
  stateKey: string;
  type: string;
  orgEmail: string;
}) => {
  const { otpState, setOtpState } = useOnboarding();
  const state = otpState[stateKey as keyof typeof otpState] as any;
  const orgState = otpState["orgEmail" as keyof typeof otpState] as any;
  const [modalOpen, setModalOpen] = useState(false);
  const [sending, setSending] = useState(false);
  const [emailExists, setEmailExists] = useState<boolean | null>(null);
  const [checkingEmail, setCheckingEmail] = useState(false);
  const [isEditing, setIsEditing] = useState(false);

  useEffect(() => {
    if (!email || !/\S+@\S+\.\S+/.test(email)) {
      setEmailExists(null);
      return;
    }

    const timer = setTimeout(async () => {
      setCheckingEmail(true);
      try {
        const res = await apiFetch("/client/check-email", {
          email,
          type: "User",
        });
        setEmailExists(res.exists);
      } catch {
        setEmailExists(null);
      } finally {
        setCheckingEmail(false);
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [email]);

  useEffect(() => {
    if (checkingEmail) return;

    if (
      email &&
      orgEmail &&
      email.toLowerCase() === orgEmail.toLowerCase() &&
      orgState?.verified &&
      !state?.verified &&
      emailExists === false
    ) {
      setOtpState(stateKey, { verified: true, sent: true, otp: "" });
      toast.success("✓ Email auto-verified — same as organization email");
    }
  }, [
    email,
    orgEmail,
    orgState?.verified,
    state?.verified,
    emailExists,
    checkingEmail,
    stateKey,
    setOtpState,
  ]);

  const handleSendOtp = async () => {
    if (!email || !/\S+@\S+\.\S+/.test(email)) {
      toast.error("Enter a valid email first");
      return;
    }

    if (emailExists === true) {
      toast.error(
        "This email is already registered. Please use a different email.",
      );
      return;
    }

    if (emailExists === null) {
      toast.error("Checking email availability... please wait");
      return;
    }

    if (email.toLowerCase() === orgEmail.toLowerCase() && orgState?.verified) {
      setOtpState(stateKey, { verified: true, sent: true, otp: "" });
      toast.success("✓ Auto-verified — same email already confirmed");
      return;
    }

    setSending(true);
    try {
      const data = await apiFetch("/otp/send-otp", { email, type });
      if (data.success) {
        toast.success(`OTP sent to ${email}`);
        setOtpState(stateKey, { sent: true, verified: false, otp: "" });
        setModalOpen(true);
      } else {
        toast.error(data.message || "Failed to send OTP");
      }
    } catch (e: any) {
      toast.error(e.message || "Failed to send OTP");
    } finally {
      setSending(false);
    }
  };

  const handleEditEmail = () => {
    setIsEditing(true);
    setOtpState(stateKey, { verified: false, sent: false, otp: "" });
    setEmailExists(null);
  };

  const handleEmailChange = (value: string) => {
    onChange(value);
    setEmailExists(null);
    if (state?.verified || isEditing) {
      setOtpState(stateKey, { verified: false, sent: false, otp: "" });
    }
  };

  const isSameAsOrg =
    email && orgEmail && email.toLowerCase() === orgEmail.toLowerCase();

  const isDisabled =
    state?.verified ||
    (isSameAsOrg &&
      orgState?.verified &&
      emailExists === false &&
      !checkingEmail);

  const isVerified =
    state?.verified ||
    (isSameAsOrg &&
      orgState?.verified &&
      emailExists === false &&
      !checkingEmail &&
      !isEditing);

  return (
    <>
      <div className="space-y-1.5">
        <Label className="text-sm font-semibold text-gray-700">
          {label} <span className="text-rose-500">*</span>
        </Label>

        <div className="flex gap-2">
          <div className="relative flex-1">
            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
            <Input
              type="email"
              className={cn(
                "pl-10",
                isVerified
                  ? "border-emerald-400 bg-emerald-50/60 text-emerald-800"
                  : "",
                error ? "border-rose-400" : "",
              )}
              placeholder="email@example.com"
              value={email}
              disabled={isDisabled}
              onChange={(e) => handleEmailChange(e.target.value)}
            />
          </div>

          {isVerified ? (
            <div className="flex items-center gap-1.5">
              <div className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-emerald-100 text-emerald-700 text-xs font-bold whitespace-nowrap border border-emerald-200">
                <CheckCircle2 className="w-3.5 h-3.5" /> Verified
              </div>
              <button
                type="button"
                onClick={handleEditEmail}
                className="p-2 rounded-xl hover:bg-gray-100 text-gray-500 transition-colors"
                title="Change email"
              >
                <Edit2 className="w-4 h-4" />
              </button>
            </div>
          ) : (
            <Button
              type="button"
              size="sm"
              onClick={handleSendOtp}
              disabled={
                sending || !email || checkingEmail || emailExists === true
              }
              className="whitespace-nowrap bg-blue-600 hover:bg-blue-700 rounded-xl px-4"
            >
              {sending || checkingEmail ? (
                <Loader2 className="w-3.5 h-3.5 animate-spin" />
              ) : state?.sent ? (
                "Resend OTP"
              ) : (
                "Send OTP"
              )}
            </Button>
          )}
        </div>

        {emailExists === true && !isVerified && (
          <div className="flex items-start gap-2 p-3 rounded-lg bg-rose-50 border border-rose-200">
            <AlertCircle className="w-4 h-4 text-rose-600 mt-0.5 flex-shrink-0" />
            <p className="text-xs text-rose-700">
              <strong>Email already registered</strong> — This email is already
              in use. Please use a different email address.
            </p>
          </div>
        )}

        {isSameAsOrg &&
          orgState?.verified &&
          emailExists === false &&
          !isVerified && (
            <div className="flex items-start gap-2 p-3 rounded-lg bg-emerald-50 border border-emerald-200">
              <CheckCircle2 className="w-4 h-4 text-emerald-600 mt-0.5 flex-shrink-0" />
              <p className="text-xs text-emerald-700">
                <strong>Same email as organization</strong> — already verified,
                no need to verify again!
              </p>
            </div>
          )}

        {error && <p className="text-xs text-rose-600 font-medium">{error}</p>}

        {state?.sent && !state?.verified && !isSameAsOrg && !isVerified && (
          <p className="text-xs text-gray-500">
            OTP sent —{" "}
            <button
              type="button"
              onClick={() => setModalOpen(true)}
              className="text-blue-600 font-semibold hover:underline"
            >
              click to enter code
            </button>
          </p>
        )}
      </div>

      <OtpModal
        email={email}
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        onVerified={() => setIsEditing(false)}
        stateKey={stateKey}
        type={type}
      />
    </>
  );
};

const SectionCard = ({
  icon,
  title,
  children,
}: {
  icon: React.ReactNode;
  title: string;
  children: React.ReactNode;
}) => (
  <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
    <div className="flex items-center gap-3 px-6 py-4 bg-gray-50 border-b border-gray-100">
      <div className="w-8 h-8 rounded-lg bg-blue-100 flex items-center justify-center">
        {icon}
      </div>
      <h2 className="text-base font-bold text-gray-800">{title}</h2>
    </div>
    <div className="p-6">{children}</div>
  </div>
);

const Field = ({
  label,
  required,
  error,
  children,
}: {
  label: string;
  required?: boolean;
  error?: string;
  children: React.ReactNode;
}) => (
  <div className="space-y-1.5">
    <Label className="text-sm font-semibold text-gray-700">
      {label} {required && <span className="text-rose-500">*</span>}
    </Label>
    {children}
    {error && <p className="text-xs text-rose-600 font-medium">{error}</p>}
  </div>
);

// Password Input Component with Eye Toggle and Strength Meter
const PasswordInput = ({
  label,
  value,
  onChange,
  error,
  placeholder,
  showStrengthMeter = false,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  error?: string;
  placeholder?: string;
  showStrengthMeter?: boolean;
}) => {
  const [showPassword, setShowPassword] = useState(false);
  const strength = showStrengthMeter ? checkPasswordStrength(value) : null;

  return (
    <div className="space-y-1.5">
      <Label className="text-sm font-semibold text-gray-700">
        {label} <span className="text-rose-500">*</span>
      </Label>
      <div className="relative">
        <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
        <Input
          type={showPassword ? "text" : "password"}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder || "••••••••"}
          className={cn("pl-10 pr-10", error ? "border-rose-400" : "")}
        />
        <button
          type="button"
          onClick={() => setShowPassword(!showPassword)}
          className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
          aria-label={showPassword ? "Hide password" : "Show password"}
        >
          {showPassword ? (
            <EyeOff className="w-4 h-4" />
          ) : (
            <Eye className="w-4 h-4" />
          )}
        </button>
      </div>

      {showStrengthMeter && value && (
        <div className="mt-2 space-y-1">
          <div className="flex gap-1 h-1.5">
            <div
              className={cn(
                "flex-1 rounded-full transition-all",
                strength && strength.score >= 1 ? "bg-red-500" : "bg-gray-200",
              )}
            />
            <div
              className={cn(
                "flex-1 rounded-full transition-all",
                strength && strength.score >= 2
                  ? "bg-orange-400"
                  : "bg-gray-200",
              )}
            />
            <div
              className={cn(
                "flex-1 rounded-full transition-all",
                strength && strength.score >= 3
                  ? "bg-yellow-500"
                  : "bg-gray-200",
              )}
            />
            <div
              className={cn(
                "flex-1 rounded-full transition-all",
                strength && strength.score >= 4
                  ? "bg-green-400"
                  : "bg-gray-200",
              )}
            />
            <div
              className={cn(
                "flex-1 rounded-full transition-all",
                strength && strength.score >= 5
                  ? "bg-green-600"
                  : "bg-gray-200",
              )}
            />
            <div
              className={cn(
                "flex-1 rounded-full transition-all",
                strength && strength.score >= 6
                  ? "bg-green-700"
                  : "bg-gray-200",
              )}
            />
          </div>
          <p className={cn("text-xs font-medium", strength?.color)}>
            Password strength: {strength?.message}
          </p>
          <ul className="text-xs text-gray-500 space-y-0.5 mt-1">
            <li className={cn(value.length >= 8 ? "text-green-600" : "")}>
              ✓ At least 8 characters
            </li>
            <li className={cn(/[A-Z]/.test(value) ? "text-green-600" : "")}>
              ✓ Uppercase letter (A-Z)
            </li>
            <li className={cn(/[a-z]/.test(value) ? "text-green-600" : "")}>
              ✓ Lowercase letter (a-z)
            </li>
            <li className={cn(/[0-9]/.test(value) ? "text-green-600" : "")}>
              ✓ Number (0-9)
            </li>
            <li
              className={cn(/[^A-Za-z0-9]/.test(value) ? "text-green-600" : "")}
            >
              ✓ Special character (!@#$%^&*)
            </li>
          </ul>
        </div>
      )}

      {error && <p className="text-xs text-rose-600 font-medium">{error}</p>}
    </div>
  );
};

export default function Step3UserDetails({
  onNext,
  onBack,
}: {
  onNext: () => void;
  onBack: () => void;
}) {
  const {
    userData,
    setUserData,
    organizationData,
    updateLead,
    validateStep3,
    locationData,
    formatPhoneNumber,
  } = useOnboarding();

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [submitting, setSubmitting] = useState(false);

  const countryCode = locationData?.country_code || "IN";

  const handleUser = (field: string, value: string) => {
    if (field === "phone") {
      value = formatPhoneNumber(value);
    }
    setUserData({ [field]: value });
    setErrors((prev) => ({ ...prev, [`user_${field}`]: "" }));
  };

  const validatePasswords = () => {
    const newErrors: Record<string, string> = {};
    const password = userData.password || "";
    const confirmPassword = userData.confirmPassword || "";

    if (!password) {
      newErrors.password = "Password is required";
    } else if (password.length < 8) {
      newErrors.password = "Password must be at least 8 characters";
    } else if (!/[A-Z]/.test(password)) {
      newErrors.password =
        "Password must contain at least one uppercase letter";
    } else if (!/[a-z]/.test(password)) {
      newErrors.password =
        "Password must contain at least one lowercase letter";
    } else if (!/[0-9]/.test(password)) {
      newErrors.password = "Password must contain at least one number";
    } else if (!/[^A-Za-z0-9]/.test(password)) {
      newErrors.password =
        "Password must contain at least one special character";
    }

    if (!confirmPassword) {
      newErrors.confirmPassword = "Please confirm your password";
    } else if (password !== confirmPassword) {
      newErrors.confirmPassword = "Passwords do not match";
    }

    setErrors((prev) => ({ ...prev, ...newErrors }));
    return Object.keys(newErrors).length === 0;
  };

  const localValidate = () => {
    const e: Record<string, string> = {};
    if (!userData.firstName?.trim()) e.user_firstName = "Required";
    if (!userData.lastName?.trim()) e.user_lastName = "Required";
    if (!userData.email?.trim()) e.user_email = "Required";
    else if (!/\S+@\S+\.\S+/.test(userData.email))
      e.user_email = "Invalid email";
    if (!userData.phone?.trim()) e.user_phone = "Required";

    setErrors(e);

    if (Object.keys(e).length > 0) return false;

    const passwordsValid = validatePasswords();
    if (!passwordsValid) return false;

    return validateStep3();
  };

  const handleContinue = async () => {
    if (!localValidate()) return;

    setSubmitting(true);
    try {
      const success = await updateLead({
        status: "user_details_completed",
        userData: {
          ...userData,
        },
      });
      if (success) {
        onNext();
      }
    } catch (error) {
      toast.error("Failed to save user details");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="max-w-3xl mx-auto">
      <div className="mb-8">
        <h1 className="text-3xl font-extrabold text-gray-900 mb-1">
          Your Details
        </h1>
        <p className="text-gray-500 text-sm">
          This will be your admin account for managing the organization.
        </p>
      </div>

      <div className="space-y-6">
        {/* User Information */}
        <SectionCard
          icon={<User className="w-4 h-4 text-blue-600" />}
          title="Account Information"
        >
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
            <Field label="First Name" required error={errors.user_firstName}>
              <Input
                placeholder="your name"
                value={userData.firstName || ""}
                onChange={(e) => handleUser("firstName", e.target.value)}
              />
            </Field>

            <Field label="Last Name" required error={errors.user_lastName}>
              <Input
                placeholder="last name"
                value={userData.lastName || ""}
                onChange={(e) => handleUser("lastName", e.target.value)}
              />
            </Field>

            {/* Email and Phone */}
            <div className="sm:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-5">
              <EmailInputWithOtp
                label="Email Address"
                email={userData.email || ""}
                onChange={(v) => handleUser("email", v)}
                error={errors.user_email}
                stateKey="userEmail"
                type="User"
                orgEmail={organizationData?.email || ""}
              />

              <Field label="Phone Number" required error={errors.user_phone}>
                <div className="flex rounded-xl border-2 border-gray-200 overflow-hidden focus-within:border-blue-500">
                  <div className="flex items-center gap-1.5 px-3 bg-gray-50 border-r border-gray-200 text-sm font-semibold text-gray-600 whitespace-nowrap">
                    <Phone className="w-3.5 h-3.5 text-gray-400" />
                    <span className="text-gray-700">
                      {COUNTRY_DIAL_CODES[
                        organizationData?.address?.country_code || countryCode
                      ] || COUNTRY_DIAL_CODES.DEFAULT}
                    </span>
                  </div>
                  <input
                    type="tel"
                    value={(userData.phone || "").replace(
                      new RegExp(
                        `^\\${COUNTRY_DIAL_CODES[organizationData?.address?.country_code || countryCode] || COUNTRY_DIAL_CODES.DEFAULT}\\s?`,
                      ),
                      "",
                    )}
                    onChange={(e) =>
                      handleUser(
                        "phone",
                        e.target.value.replace(/[^\d\s\-]/g, ""),
                      )
                    }
                    placeholder="XXXXX XXXXX"
                    className="flex-1 px-3 py-1 text-sm outline-none bg-white text-gray-900"
                  />
                </div>
              </Field>
            </div>

            {/* Password Fields */}
            <div className="sm:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-5">
              <PasswordInput
                label="Password"
                value={userData.password || ""}
                onChange={(v) => handleUser("password", v)}
                error={errors.password}
                placeholder="Create a strong password"
                showStrengthMeter={true}
              />

              <PasswordInput
                label="Confirm Password"
                value={userData.confirmPassword || ""}
                onChange={(v) => handleUser("confirmPassword", v)}
                error={errors.confirmPassword}
                placeholder="Confirm your password"
                showStrengthMeter={false}
              />
            </div>
          </div>

          {/* Info Box */}
          <div className="mt-5 p-4 rounded-lg bg-blue-50 border border-blue-100 flex gap-3">
            <AlertCircle className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
            <p className="text-xs text-blue-700">
              This email will be your <strong>admin login</strong> to access the
              dashboard. You'll receive login credentials and setup instructions
              here. Use a strong password to secure your account.
            </p>
          </div>
        </SectionCard>

        {/* Navigation */}
        <div className="flex justify-between pt-2 pb-6">
          <Button
            variant="outline"
            onClick={onBack}
            className="gap-2 rounded-xl"
            disabled={submitting}
          >
            <ChevronLeft className="w-4 h-4" /> Back
          </Button>
          <Button
            onClick={handleContinue}
            disabled={submitting}
            className="bg-blue-600 hover:bg-blue-700 gap-2 rounded-xl px-7 shadow-lg shadow-blue-200 disabled:opacity-50"
          >
            {submitting ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" /> Saving…
              </>
            ) : (
              <>
                <span>Continue to Payment</span>{" "}
                <ChevronRight className="w-4 h-4" />
              </>
            )}
          </Button>
        </div>
      </div>
    </div>
  );
}
