"use client";

/**
 * AdminIdleLock — In-Place Multi-Method Screen Lock
 *
 * ARCHITECTURE:
 *  1. One lock screen surface with in-place state transitions:
 *     - "pin": 4-digit numeric PIN entry with auto-focus, auto-advance, and instant auto-submit.
 *     - "password": In-place account password fallback using FloatingInput (NO popups).
 *     - "passkey": WebAuthn platform biometrics (Windows Hello, Touch ID, Face ID, security keys).
 *     - "forgot-pin": In-place PIN recovery form verified by account password.
 *  2. No nested popup-over-popup or dialog-over-dialog.
 *  3. Integrated with AdminAuthProvider to reflect real-time passkey enrollment status.
 */

import * as React from "react";
import Image from "next/image";
import {
  Lock,
  ArrowRight,
  LogOut,
  ShieldAlert,
  KeyRound,
  Fingerprint,
  RotateCcw,
  CheckCircle2,
  Mail,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { FloatingInput } from "@/components/ui/floating-input";
import { useRouter } from "next/navigation";
import { useAdminAuth } from "@/components/admin/admin-auth-provider";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

const IDLE_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes inactivity

export type LockMode =
  | "pin"
  | "password"
  | "passkey"
  | "forgot-pin"
  | "forgot-password";

export interface AdminIdleLockProps {
  userEmail?: string;
  userName?: string;
  initialLocked?: boolean;
}

export function AdminIdleLock({
  userEmail: propUserEmail,
  userName: propUserName,
  initialLocked = false,
}: AdminIdleLockProps) {
  const router = useRouter();
  const { user, isLocked: authLocked, setIsLocked: setAuthLocked, refreshAuth } = useAdminAuth();

  const [isLocked, setIsLockedLocal] = React.useState<boolean>(
    Boolean(initialLocked || authLocked)
  );

  const [mode, setMode] = React.useState<LockMode>("pin");
  const [pinDigits, setPinDigits] = React.useState<string[]>(["", "", "", ""]);
  const [password, setPassword] = React.useState("");

  // Forgot PIN State
  const [resetPassword, setResetPassword] = React.useState("");
  const [resetNewPin, setResetNewPin] = React.useState("");
  const [resetConfirmPin, setResetConfirmPin] = React.useState("");

  // Forgot Password State (Account Password Recovery)
  const [forgotPasswordEmail, setForgotPasswordEmail] = React.useState(
    propUserEmail || user?.email || ""
  );
  const [forgotPasswordSuccess, setForgotPasswordSuccess] = React.useState(false);
  const [forgotPasswordMessage, setForgotPasswordMessage] = React.useState<string | null>(null);
  const [forgotPasswordLoading, setForgotPasswordLoading] = React.useState(false);

  const [loading, setLoading] = React.useState(false);
  const [passkeyLoading, setPasskeyLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);
  const [lockoutSeconds, setLockoutSeconds] = React.useState(0);

  // Logout confirmation dialog
  const [logoutConfirmOpen, setLogoutConfirmOpen] = React.useState(false);
  const [loggingOut, setLoggingOut] = React.useState(false);

  const inputRefs = React.useRef<(HTMLInputElement | null)[]>([]);
  const passwordInputRef = React.useRef<HTMLInputElement | null>(null);
  const resetPasswordInputRef = React.useRef<HTMLInputElement | null>(null);
  const forgotEmailInputRef = React.useRef<HTMLInputElement | null>(null);
  const lastActivityRef = React.useRef<number>(Date.now());

  const userEmail = propUserEmail || user?.email || "admin@quto.ai";
  const userName = propUserName || user?.name || "Administrator";
  const hasPasskey = Boolean(user?.hasPasskey);

  // Keep forgotPasswordEmail in sync with user email
  React.useEffect(() => {
    if (userEmail && !forgotPasswordEmail) {
      setForgotPasswordEmail(userEmail);
    }
  }, [userEmail, forgotPasswordEmail]);

  const resetTimer = React.useCallback(() => {
    lastActivityRef.current = Date.now();
  }, []);

  // Synchronize lock state
  React.useEffect(() => {
    if (authLocked !== undefined && authLocked !== isLocked) {
      setIsLockedLocal(authLocked);
    }
  }, [authLocked, isLocked]);

  // Rate-limiting countdown
  React.useEffect(() => {
    if (lockoutSeconds <= 0) return;
    const t = setInterval(() => {
      setLockoutSeconds((prev) => (prev <= 1 ? 0 : prev - 1));
    }, 1000);
    return () => clearInterval(t);
  }, [lockoutSeconds]);

  // Focus management across active authentication modes
  React.useEffect(() => {
    if (!isLocked) return;
    const timer = setTimeout(() => {
      if (mode === "pin") {
        inputRefs.current[0]?.focus();
      } else if (mode === "password") {
        passwordInputRef.current?.focus();
      } else if (mode === "forgot-pin") {
        resetPasswordInputRef.current?.focus();
      } else if (mode === "forgot-password") {
        forgotEmailInputRef.current?.focus();
      }
    }, 120);
    return () => clearTimeout(timer);
  }, [isLocked, mode]);

  // Monitor user activity across events
  React.useEffect(() => {
    let lastThrottled = 0;
    const handleActivity = () => {
      const now = Date.now();
      if (now - lastThrottled > 1000) {
        lastThrottled = now;
        resetTimer();
      }
    };

    const events = ["mousemove", "mousedown", "keydown", "touchstart", "scroll"];
    events.forEach((ev) => window.addEventListener(ev, handleActivity, { passive: true }));

    const interval = setInterval(() => {
      const elapsed = Date.now() - lastActivityRef.current;
      if (elapsed >= IDLE_TIMEOUT_MS && !isLocked) {
        fetch("/api/admin/auth/lock", { method: "POST" }).catch(() => {});
        setIsLockedLocal(true);
        setAuthLocked(true);
      }
    }, 10000);

    return () => {
      events.forEach((ev) => window.removeEventListener(ev, handleActivity));
      clearInterval(interval);
    };
  }, [isLocked, resetTimer, setAuthLocked]);

  const switchMode = (newMode: LockMode) => {
    setMode(newMode);
    setError(null);
    setLoading(false);
    setPasskeyLoading(false);
    setForgotPasswordSuccess(false);
    setForgotPasswordMessage(null);

    if (newMode !== "pin") {
      setPinDigits(["", "", "", ""]);
    }
    if (newMode !== "password") {
      setPassword("");
    }
    if (newMode !== "forgot-pin") {
      setResetPassword("");
      setResetNewPin("");
      setResetConfirmPin("");
    }
    if (newMode === "forgot-password" && !forgotPasswordEmail) {
      setForgotPasswordEmail(userEmail);
    }

    if (newMode === "passkey") {
      setTimeout(() => {
        triggerPasskeyUnlock();
      }, 100);
    }
  };

  const handleUnlockSuccess = async () => {
    setIsLockedLocal(false);
    setAuthLocked(false);
    setMode("pin");
    setPinDigits(["", "", "", ""]);
    setPassword("");
    setResetPassword("");
    setResetNewPin("");
    setResetConfirmPin("");
    setForgotPasswordSuccess(false);
    setForgotPasswordMessage(null);
    setError(null);
    resetTimer();
    await refreshAuth();
    router.refresh();
  };

  // 1. PIN Unlock
  const verifyPinSubmission = async (fullPin: string) => {
    if (fullPin.length !== 4 || loading || lockoutSeconds > 0) return;

    setError(null);
    setLoading(true);

    try {
      const res = await fetch("/api/admin/auth/unlock", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ pin: fullPin }),
      });

      const data = await res.json();
      if (!res.ok) {
        if (res.status === 401 && (data.error?.includes("expired") || data.error?.includes("sign in"))) {
          router.push("/admin/login?reason=session_revoked");
          return;
        }
        if (res.status === 429) {
          setLockoutSeconds(60);
        }
        setError(data.error || "Incorrect PIN.");
        setPinDigits(["", "", "", ""]);
        inputRefs.current[0]?.focus();
        return;
      }

      await handleUnlockSuccess();
    } catch {
      setError("Failed to verify PIN. Please try again.");
      setPinDigits(["", "", "", ""]);
    } finally {
      setLoading(false);
    }
  };

  const handleDigitChange = (index: number, val: string) => {
    if (lockoutSeconds > 0) return;
    const clean = val.replace(/\D/g, "");
    if (!clean && val !== "") return;

    const nextDigits = [...pinDigits];
    nextDigits[index] = clean.slice(-1);
    setPinDigits(nextDigits);

    if (clean && index < 3) {
      inputRefs.current[index + 1]?.focus();
    }

    if (nextDigits.every((d) => d !== "")) {
      verifyPinSubmission(nextDigits.join(""));
    }
  };

  const handleKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Backspace" && !pinDigits[index] && index > 0) {
      inputRefs.current[index - 1]?.focus();
    }
  };

  const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
    e.preventDefault();
    const pasted = e.clipboardData.getData("text").replace(/\D/g, "").slice(0, 4);
    if (pasted.length === 4) {
      const arr = pasted.split("");
      setPinDigits(arr);
      verifyPinSubmission(pasted);
    }
  };

  // 2. Account Password Unlock
  const handlePasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!password || loading || lockoutSeconds > 0) return;

    setError(null);
    setLoading(true);

    try {
      const res = await fetch("/api/admin/auth/unlock", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password }),
      });

      const data = await res.json();
      if (!res.ok) {
        if (res.status === 429) {
          setLockoutSeconds(60);
        }
        setError(data.error || "Incorrect account password.");
        return;
      }

      await handleUnlockSuccess();
    } catch {
      setError("Failed to verify password. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  // 3. Device Passkey Unlock
  const triggerPasskeyUnlock = async () => {
    if (typeof window === "undefined" || !window.PublicKeyCredential) {
      setError("Device authentication is not available on this browser.");
      setPasskeyLoading(false);
      return;
    }

    try {
      setPasskeyLoading(true);
      setError(null);

      const challenge = new Uint8Array(32);
      crypto.getRandomValues(challenge);

      const assertion = (await navigator.credentials.get({
        publicKey: {
          challenge,
          rpId: window.location.hostname,
          userVerification: "preferred",
          timeout: 60000,
        },
      })) as PublicKeyCredential | null;

      if (!assertion) {
        throw new Error("Device authentication was cancelled.");
      }

      const res = await fetch("/api/admin/auth/unlock", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          credentialId: assertion.id,
          webauthn: {
            id: assertion.id,
            rawId: btoa(String.fromCharCode(...new Uint8Array(assertion.rawId))),
            type: assertion.type,
          },
        }),
      });

      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || "Passkey verification failed on server.");
      }

      await handleUnlockSuccess();
    } catch (err: any) {
      if (err.name === "NotAllowedError" || err.message?.includes("cancelled")) {
        setError("Device authentication was cancelled.");
      } else {
        setError(err.message || "Device authentication is not available on this device.");
      }
    } finally {
      setPasskeyLoading(false);
    }
  };

  // 4. In-Place PIN Reset Form
  const handleForgotPinSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (!/^\d{4}$/.test(resetNewPin)) {
      setError("New PIN must be exactly 4 numeric digits.");
      return;
    }
    if (resetNewPin !== resetConfirmPin) {
      setError("New PIN and confirmation PIN do not match.");
      return;
    }

    try {
      setLoading(true);
      const res = await fetch("/api/admin/auth/pin/setup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          pin: resetNewPin,
          confirmPin: resetConfirmPin,
          currentPassword: resetPassword,
        }),
      });

      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Failed to reset PIN.");
        return;
      }

      // Unlock immediately with the newly established PIN
      await verifyPinSubmission(resetNewPin);
    } catch {
      setError("Network error resetting PIN.");
    } finally {
      setLoading(false);
    }
  };

  // 5. Account Password Recovery Request
  const handleForgotPasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setForgotPasswordMessage(null);
    setForgotPasswordLoading(true);

    try {
      const res = await fetch("/api/admin/auth/forgot-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: forgotPasswordEmail }),
      });

      const data = await res.json();
      if (res.ok) {
        setForgotPasswordSuccess(true);
        setForgotPasswordMessage(
          data.message ||
            "If your account exists in our administrator directory, a secure password reset link has been dispatched to your email address."
        );
      } else {
        setError(data.error || "Failed to dispatch password reset request.");
      }
    } catch {
      setError("Network error requesting password reset link.");
    } finally {
      setForgotPasswordLoading(false);
    }
  };

  const handleConfirmSignOut = async () => {
    try {
      setLoggingOut(true);
      await fetch("/api/admin/auth/logout", { method: "POST" });
    } catch {}
    router.push("/admin/login");
    router.refresh();
  };

  if (!isLocked) return null;

  return (
    <>
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="idle-lock-title"
        className="pointer-events-auto fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 backdrop-blur-xs p-4 duration-200 animate-in fade-in-0 select-none"
      >
        <div className="w-full max-w-md rounded-2xl border border-neutral-200 bg-white p-8 shadow-xl dark:border-neutral-800 dark:bg-neutral-900 text-center transition-all">
          {/* Brand Header */}
          <div className="flex flex-col items-center">
            <div className="relative mb-3 flex h-12 w-12 items-center justify-center overflow-hidden rounded-xl bg-neutral-100 dark:bg-neutral-800 border border-neutral-200/60 dark:border-neutral-700/60 shadow-xs">
              <Image
                src="/images/quto-logo.webp"
                alt="Quto AI"
                width={40}
                height={40}
                className="object-contain"
                priority
              />
            </div>

            <div className="flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400 font-semibold text-xs mb-1">
              {mode === "passkey" ? (
                <Fingerprint className="h-3.5 w-3.5 text-neutral-700 dark:text-neutral-300" />
              ) : mode === "password" || mode === "forgot-pin" ? (
                <KeyRound className="h-3.5 w-3.5 text-neutral-700 dark:text-neutral-300" />
              ) : mode === "forgot-password" ? (
                <Mail className="h-3.5 w-3.5 text-neutral-700 dark:text-neutral-300" />
              ) : (
                <Lock className="h-3.5 w-3.5" />
              )}
              <span id="idle-lock-title" className="uppercase tracking-wider">
                {mode === "pin"
                  ? "Admin Session Locked"
                  : mode === "password"
                  ? "Password Unlock"
                  : mode === "passkey"
                  ? "Device Passkey"
                  : mode === "forgot-pin"
                  ? "Reset Screen Lock PIN"
                  : "Account Password Recovery"}
              </span>
            </div>

            <h2 className="text-xl font-bold text-neutral-900 dark:text-white tracking-tight">
              {userName}
            </h2>
            <p className="text-xs text-neutral-500 dark:text-neutral-400 mt-0.5 font-sans truncate max-w-xs">
              {userEmail}
            </p>

            <p className="text-xs text-neutral-600 dark:text-neutral-400 mt-2.5 leading-relaxed">
              {mode === "pin" && "Enter your 4-digit screen lock PIN to unlock your workspace."}
              {mode === "password" && "Enter your administrator account password to unlock."}
              {mode === "passkey" && "Use your device biometric sensor or security key."}
              {mode === "forgot-pin" && "Verify your administrator password to create a new PIN."}
              {mode === "forgot-password" && "Enter your registered email address to receive a reset link."}
            </p>
          </div>

          {/* Inline Error Display */}
          {error && (
            <div className="mt-4 rounded-xl border border-red-200 bg-red-50 p-3 text-xs text-red-700 dark:border-red-900/50 dark:bg-red-950/50 dark:text-red-300 flex items-center gap-2 text-left">
              <ShieldAlert className="h-4 w-4 shrink-0 text-red-600 dark:text-red-400" />
              <span>{error}</span>
            </div>
          )}

          {/* Lockout Countdown */}
          {lockoutSeconds > 0 && (
            <div className="mt-4 rounded-xl border border-amber-200 bg-amber-50 p-3 text-xs text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/50 dark:text-amber-300 flex items-center justify-center gap-2">
              <RotateCcw className="h-4 w-4 animate-spin shrink-0 text-amber-600" />
              <span>Locked out. Retry in {lockoutSeconds}s</span>
            </div>
          )}

          {/* MODE 1: PIN MODE */}
          {mode === "pin" && (
            <div className="mt-6">
              {/* 4-Digit PIN Input Slots (Non-Password Semantics to Eliminate Chrome Password Autofill) */}
              <div className="flex justify-center gap-3">
                {[0, 1, 2, 3].map((idx) => (
                  <input
                    key={idx}
                    ref={(el) => {
                      inputRefs.current[idx] = el;
                    }}
                    name={`admin-pin-slot-${idx}`}
                    type="text"
                    inputMode="numeric"
                    pattern="[0-9]*"
                    maxLength={1}
                    autoComplete="off"
                    style={{ WebkitTextSecurity: "disc" } as React.CSSProperties}
                    data-1p-ignore="true"
                    data-lpignore="true"
                    data-bwignore="true"
                    data-form-type="other"
                    disabled={loading || lockoutSeconds > 0}
                    value={pinDigits[idx]}
                    onChange={(e) => handleDigitChange(idx, e.target.value)}
                    onKeyDown={(e) => handleKeyDown(idx, e)}
                    onPaste={idx === 0 ? handlePaste : undefined}
                    className="h-14 w-12 rounded-xl border border-neutral-200 bg-neutral-50/50 text-center text-xl font-semibold text-neutral-900 shadow-2xs transition-[border-color,box-shadow,background-color] duration-200 focus:bg-white focus:border-neutral-900 focus:outline-none focus:ring-1 focus:ring-neutral-900 disabled:opacity-50 dark:border-neutral-800 dark:bg-neutral-950 dark:text-white dark:focus:bg-neutral-900 dark:focus:border-white dark:focus:ring-white"
                    aria-label={`PIN Digit ${idx + 1}`}
                  />
                ))}
              </div>

              <div className="mt-4 flex items-center justify-between text-xs text-neutral-500 px-1">
                <button
                  type="button"
                  onClick={() => switchMode("forgot-pin")}
                  className="text-xs text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white underline underline-offset-2 transition-colors cursor-pointer"
                >
                  Forgot PIN?
                </button>
                <span className="text-[11px] text-neutral-400">
                  {loading ? "Verifying..." : "Auto-submits at 4 digits"}
                </span>
              </div>

              {/* Action Buttons */}
              <div className="mt-5 space-y-2">
                {hasPasskey && (
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => switchMode("passkey")}
                    className="w-full h-10 gap-2 text-xs font-semibold rounded-xl text-neutral-700 hover:text-neutral-900 dark:text-neutral-300 dark:hover:text-white"
                  >
                    <Fingerprint className="h-4 w-4 text-neutral-600 dark:text-neutral-400" />
                    <span>Unlock with device passkey</span>
                  </Button>
                )}

                <Button
                  type="button"
                  variant="outline"
                  onClick={() => switchMode("password")}
                  className="w-full h-10 gap-2 text-xs font-semibold rounded-xl text-neutral-700 hover:text-neutral-900 dark:text-neutral-300 dark:hover:text-white"
                >
                  <KeyRound className="h-3.5 w-3.5 text-neutral-500 dark:text-neutral-400" />
                  <span>Unlock with account password</span>
                </Button>
              </div>
            </div>
          )}

          {/* MODE 2: PASSWORD MODE (IN-PLACE, NO POPUP) */}
          {mode === "password" && (
            <div className="mt-5">
              <form onSubmit={handlePasswordSubmit} className="space-y-4 text-left">
                <FloatingInput
                  ref={passwordInputRef}
                  id="screen-lock-password"
                  type="password"
                  showPasswordToggle
                  required
                  autoComplete="current-password"
                  name="current-password"
                  label="Account Password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  disabled={loading || lockoutSeconds > 0}
                />

                <div className="flex flex-col gap-2 pt-1">
                  <Button
                    type="submit"
                    className="w-full h-10 gap-2 text-xs font-semibold rounded-xl"
                    disabled={loading || !password || lockoutSeconds > 0}
                    loading={loading}
                  >
                    <span>{loading ? "Verifying password..." : "Unlock Workspace"}</span>
                    <ArrowRight className="h-3.5 w-3.5" />
                  </Button>

                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => switchMode("pin")}
                    className="w-full h-9 gap-2 text-xs rounded-xl text-neutral-600 dark:text-neutral-300"
                  >
                    <KeyRound className="h-3.5 w-3.5" />
                    <span>Back to PIN</span>
                  </Button>
                </div>

                {/* Password-specific recovery: Forgot password? */}
                <div className="pt-2 text-center">
                  <button
                    type="button"
                    onClick={() => switchMode("forgot-password")}
                    className="text-xs text-neutral-600 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white underline underline-offset-2 transition-colors cursor-pointer"
                  >
                    Forgot password?
                  </button>
                </div>

                {hasPasskey && (
                  <div className="pt-1 border-t border-neutral-100 dark:border-neutral-800">
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => switchMode("passkey")}
                      className="w-full h-8 gap-1.5 text-xs text-neutral-500 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"
                    >
                      <Fingerprint className="h-3.5 w-3.5" />
                      <span>Use device passkey</span>
                    </Button>
                  </div>
                )}
              </form>
            </div>
          )}

          {/* MODE 3: PASSKEY MODE (IN-PLACE, NO POPUP) */}
          {mode === "passkey" && (
            <div className="mt-6">
              <div className="flex flex-col items-center justify-center space-y-3 py-4 rounded-xl border border-neutral-100 bg-neutral-50/50 dark:border-neutral-800 dark:bg-neutral-950/40">
                <div className="relative flex h-14 w-14 items-center justify-center rounded-2xl bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 shadow-xs">
                  <Fingerprint
                    className={`h-7 w-7 text-neutral-800 dark:text-neutral-200 ${
                      passkeyLoading ? "animate-pulse" : ""
                    }`}
                  />
                </div>

                <div className="space-y-1">
                  <p className="text-xs font-semibold text-neutral-900 dark:text-white">
                    {passkeyLoading
                      ? "Starting device authentication..."
                      : "Device Authentication"}
                  </p>
                  <p className="text-[11px] text-neutral-500 max-w-xs leading-relaxed px-4">
                    {passkeyLoading
                      ? "Touch your sensor or follow your system prompt."
                      : "Biometric sensor, Windows Hello, Touch ID, or security key."}
                  </p>
                </div>

                {!passkeyLoading && (
                  <Button
                    type="button"
                    size="sm"
                    onClick={triggerPasskeyUnlock}
                    className="gap-2 text-xs font-semibold rounded-xl mt-1"
                  >
                    <Fingerprint className="h-3.5 w-3.5" />
                    <span>Start Device Authentication</span>
                  </Button>
                )}
              </div>

              <div className="mt-5 space-y-2">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => switchMode("pin")}
                  className="w-full h-9 gap-2 text-xs rounded-xl text-neutral-600 dark:text-neutral-300"
                >
                  <KeyRound className="h-3.5 w-3.5" />
                  <span>Back to PIN</span>
                </Button>

                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => switchMode("password")}
                  className="w-full h-9 gap-2 text-xs rounded-xl text-neutral-600 dark:text-neutral-300"
                >
                  <Lock className="h-3.5 w-3.5" />
                  <span>Unlock with account password</span>
                </Button>
              </div>
            </div>
          )}

          {/* MODE 4: FORGOT PIN MODE (IN-PLACE, NO POPUP) */}
          {mode === "forgot-pin" && (
            <div className="mt-5">
              <form onSubmit={handleForgotPinSubmit} className="space-y-4 text-left">
                <FloatingInput
                  ref={resetPasswordInputRef}
                  id="reset-account-password"
                  type="password"
                  showPasswordToggle
                  required
                  autoComplete="current-password"
                  name="current-password"
                  label="Account Password"
                  value={resetPassword}
                  onChange={(e) => setResetPassword(e.target.value)}
                  disabled={loading}
                />

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <FloatingInput
                    id="reset-new-pin"
                    type="text"
                    inputMode="numeric"
                    pattern="[0-9]*"
                    maxLength={4}
                    required
                    autoComplete="off"
                    name="new-screen-lock-pin"
                    style={{ WebkitTextSecurity: "disc" } as React.CSSProperties}
                    data-1p-ignore="true"
                    data-lpignore="true"
                    data-bwignore="true"
                    data-form-type="other"
                    label="New 4-Digit PIN"
                    value={resetNewPin}
                    onChange={(e) =>
                      setResetNewPin(e.target.value.replace(/\D/g, "").slice(0, 4))
                    }
                    className="font-mono tracking-widest text-center"
                    disabled={loading}
                  />

                  <FloatingInput
                    id="reset-confirm-pin"
                    type="text"
                    inputMode="numeric"
                    pattern="[0-9]*"
                    maxLength={4}
                    required
                    autoComplete="off"
                    name="confirm-screen-lock-pin"
                    style={{ WebkitTextSecurity: "disc" } as React.CSSProperties}
                    data-1p-ignore="true"
                    data-lpignore="true"
                    data-bwignore="true"
                    data-form-type="other"
                    label="Confirm New PIN"
                    value={resetConfirmPin}
                    onChange={(e) =>
                      setResetConfirmPin(e.target.value.replace(/\D/g, "").slice(0, 4))
                    }
                    className="font-mono tracking-widest text-center"
                    disabled={loading}
                  />
                </div>

                <div className="flex flex-col gap-2 pt-1">
                  <Button
                    type="submit"
                    className="w-full h-10 gap-2 text-xs font-semibold rounded-xl"
                    disabled={
                      loading ||
                      resetNewPin.length !== 4 ||
                      resetConfirmPin.length !== 4 ||
                      !resetPassword
                    }
                    loading={loading}
                  >
                    <span>{loading ? "Updating PIN..." : "Update PIN & Unlock"}</span>
                    <ArrowRight className="h-3.5 w-3.5" />
                  </Button>

                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => switchMode("pin")}
                    disabled={loading}
                    className="w-full h-9 gap-2 text-xs rounded-xl text-neutral-600 dark:text-neutral-300"
                  >
                    <KeyRound className="h-3.5 w-3.5" />
                    <span>Back to PIN</span>
                  </Button>
                </div>
              </form>
            </div>
          )}

          {/* MODE 5: FORGOT PASSWORD MODE (IN-PLACE ACCOUNT PASSWORD RECOVERY) */}
          {mode === "forgot-password" && (
            <div className="mt-5 space-y-4 text-left">
              {forgotPasswordSuccess ? (
                <div className="space-y-4 text-center">
                  <div className="rounded-xl border border-emerald-200 bg-emerald-50/70 p-4 dark:border-emerald-900/50 dark:bg-emerald-950/40 text-emerald-800 dark:text-emerald-200 text-xs flex flex-col items-center gap-2">
                    <CheckCircle2 className="h-6 w-6 text-emerald-600 dark:text-emerald-400 shrink-0" />
                    <p className="font-semibold text-sm">Reset Link Dispatched</p>
                    <p className="text-[11px] leading-relaxed text-emerald-700 dark:text-emerald-300">
                      {forgotPasswordMessage ||
                        "A secure password reset link has been dispatched to your email address."}
                    </p>
                  </div>

                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => switchMode("password")}
                    className="w-full h-9 gap-2 text-xs rounded-xl"
                  >
                    <KeyRound className="h-3.5 w-3.5" />
                    <span>Return to Password Unlock</span>
                  </Button>
                </div>
              ) : (
                <form onSubmit={handleForgotPasswordSubmit} className="space-y-4">
                  <FloatingInput
                    ref={forgotEmailInputRef}
                    id="forgot-password-email"
                    type="email"
                    required
                    autoComplete="email"
                    name="email"
                    label="Administrator Email"
                    value={forgotPasswordEmail}
                    onChange={(e) => setForgotPasswordEmail(e.target.value)}
                    disabled={forgotPasswordLoading}
                  />

                  <div className="flex flex-col gap-2 pt-1">
                    <Button
                      type="submit"
                      className="w-full h-10 gap-2 text-xs font-semibold rounded-xl"
                      disabled={forgotPasswordLoading || !forgotPasswordEmail}
                      loading={forgotPasswordLoading}
                    >
                      <Mail className="h-3.5 w-3.5" />
                      <span>{forgotPasswordLoading ? "Sending Link..." : "Send Reset Link"}</span>
                    </Button>

                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => switchMode("password")}
                      disabled={forgotPasswordLoading}
                      className="w-full h-9 gap-2 text-xs rounded-xl text-neutral-600 dark:text-neutral-300"
                    >
                      <KeyRound className="h-3.5 w-3.5" />
                      <span>Back to Password Unlock</span>
                    </Button>
                  </div>
                </form>
              )}
            </div>
          )}

          {/* Sign out and switch user */}
          <div className="mt-6 pt-4 border-t border-neutral-100 dark:border-neutral-800">
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={() => setLogoutConfirmOpen(true)}
              className="gap-1.5 text-xs text-neutral-500 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"
            >
              <LogOut className="h-3.5 w-3.5" />
              <span>Sign out and switch user</span>
            </Button>
          </div>
        </div>
      </div>

      {/* Logout Confirmation Dialog */}
      <AlertDialog open={logoutConfirmOpen} onOpenChange={setLogoutConfirmOpen}>
        <AlertDialogContent
          overlayClassName="z-[10000]"
          className="z-[10001] max-w-md"
        >
          <AlertDialogHeader>
            <AlertDialogTitle>Confirm Sign Out</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to end your administrator session? Any unsaved edits will be discarded.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={loggingOut}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmSignOut}
              disabled={loggingOut}
            >
              {loggingOut ? "Signing out..." : "Sign Out"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
