"use client";

import * as React from "react";
import {
  User,
  Shield,
  KeyRound,
  Laptop,
  CheckCircle2,
  AlertTriangle,
  QrCode,
  Copy,
  Download,
  Check,
  ShieldAlert,
  Fingerprint,
  Lock,
  Plus,
  Trash2,
  Smartphone,
  Tablet,
  Monitor,
  MapPin,
  Clock,
  LogOut,
  RefreshCw,
  ShieldCheck,
} from "lucide-react";
import { FloatingInput } from "@/components/ui/floating-input";
import { Button } from "@/components/ui/button";
import { useAdminAuth } from "@/components/admin/admin-auth-provider";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { toast } from "sonner";

export interface ActiveSessionItem {
  id: string;
  browser: string;
  browserVersion: string | null;
  operatingSystem: string;
  deviceType: "Desktop" | "Mobile" | "Tablet" | "Unknown";
  deviceSummary: string;
  ipAddress: string | null;
  createdAt: string;
  lastSeenAt: string;
  locationDisplay: string;
  rawLocation?: any;
  networkSecurity?: {
    isVpn: boolean;
    isProxy: boolean;
    isTor: boolean;
    isRelay: boolean;
    isBlocked?: boolean;
    provider?: string | null;
  } | null;
  status: string;
  isCurrent: boolean;
}

function formatRelativeTime(isoString?: string | null): string {
  if (!isoString) return "just now";
  try {
    const timeMs = new Date(isoString).getTime();
    if (isNaN(timeMs)) return "recently";
    const diffSec = Math.floor((Date.now() - timeMs) / 1000);
    if (diffSec < 45) return "just now";
    if (diffSec < 90) return "1 min ago";
    const diffMin = Math.floor(diffSec / 60);
    if (diffMin < 60) return `${diffMin} min ago`;
    const diffHours = Math.floor(diffMin / 60);
    if (diffHours < 24) return `${diffHours} hr${diffHours > 1 ? "s" : ""} ago`;
    const diffDays = Math.floor(diffHours / 24);
    return `${diffDays} day${diffDays > 1 ? "s" : ""} ago`;
  } catch {
    return "recently";
  }
}

interface ProfileData {
  user: {
    id: string;
    name: string;
    email: string;
    level: "MAIN_ADMIN" | "SUB_ADMIN";
    role: string;
    twoFactorEnabled: boolean;
    lastLoginAt: string | null;
    createdAt: string;
  };
  session: {
    id: string;
    device: string;
    browser: string;
    createdAt: string;
    lastActiveAt: string;
  };
  permissions: string[];
}

export function SecurityPanel() {
  const {
    user,
    session,
    hasPasskey,
    passkeyCount,
    hasPin,
    refreshAuth,
    isLoading,
  } = useAdminAuth();

  // Password update form
  const [currentPassword, setCurrentPassword] = React.useState("");
  const [newPassword, setNewPassword] = React.useState("");
  const [confirmPassword, setConfirmPassword] = React.useState("");
  const [updatingPass, setUpdatingPass] = React.useState(false);
  const [passError, setPassError] = React.useState<string | null>(null);
  const [passSuccess, setPassSuccess] = React.useState<string | null>(null);

  // 2FA Enrollment State
  const [enrollModalOpen, setEnrollModalOpen] = React.useState(false);
  const [enrollStep, setEnrollStep] = React.useState<"PASSWORD" | "SCAN_QR" | "BACKUP_CODES">("PASSWORD");
  const [enrollPassword, setEnrollPassword] = React.useState("");
  const [enrollSecret, setEnrollSecret] = React.useState("");
  const [enrollQrUrl, setEnrollQrUrl] = React.useState("");
  const [enrollOtp, setEnrollOtp] = React.useState("");
  const [backupCodes, setBackupCodes] = React.useState<string[]>([]);
  const [enrollingLoading, setEnrollingLoading] = React.useState(false);
  const [enrollError, setEnrollError] = React.useState<string | null>(null);
  const [copiedKey, setCopiedKey] = React.useState(false);
  const [copiedBackupCodes, setCopiedBackupCodes] = React.useState(false);

  // 2FA Disable State
  const [disableModalOpen, setDisableModalOpen] = React.useState(false);
  const [disablePassword, setDisablePassword] = React.useState("");
  const [disableOtp, setDisableOtp] = React.useState("");
  const [disablingLoading, setDisablingLoading] = React.useState(false);
  const [disableError, setDisableError] = React.useState<string | null>(null);

  // Screen Lock PIN & Passkey State
  const [pinModalOpen, setPinModalOpen] = React.useState(false);
  const [pinPassword, setPinPassword] = React.useState("");
  const [pinNew, setPinNew] = React.useState("");
  const [pinConfirm, setPinConfirm] = React.useState("");
  const [pinLoading, setPinLoading] = React.useState(false);
  const [pinError, setPinError] = React.useState<string | null>(null);

  const [passkeyLoading, setPasskeyLoading] = React.useState(false);
  const [passkeySupported, setPasskeySupported] = React.useState(true);

  React.useEffect(() => {
    if (typeof window !== "undefined") {
      setPasskeySupported(Boolean(window.PublicKeyCredential));
    }
  }, []);

  // Active Sessions registry state
  const [activeSessions, setActiveSessions] = React.useState<ActiveSessionItem[]>([]);
  const [sessionsLoading, setSessionsLoading] = React.useState(true);
  const [revokingSessionId, setRevokingSessionId] = React.useState<string | null>(null);
  const [revokingOthers, setRevokingOthers] = React.useState(false);
  const [confirmRevokeModal, setConfirmRevokeModal] = React.useState<{
    open: boolean;
    session: ActiveSessionItem | null;
  }>({ open: false, session: null });
  const [confirmRevokeOthersModal, setConfirmRevokeOthersModal] = React.useState(false);
  const [showAllOtherSessions, setShowAllOtherSessions] = React.useState(false);

  const fetchSessions = React.useCallback(async () => {
    try {
      setSessionsLoading(true);
      const res = await fetch("/api/admin/sessions", { cache: "no-store" });
      if (res.ok) {
        const data = await res.json();
        setActiveSessions(data.sessions || []);
      }
    } catch (err) {
      console.error("Failed to load active sessions", err);
    } finally {
      setSessionsLoading(false);
    }
  }, []);

  React.useEffect(() => {
    fetchSessions();
  }, [fetchSessions]);

  const handleRevokeSingle = async () => {
    if (!confirmRevokeModal.session) return;
    const target = confirmRevokeModal.session;
    try {
      setRevokingSessionId(target.id);
      const res = await fetch(`/api/admin/sessions?id=${encodeURIComponent(target.id)}`, {
        method: "DELETE",
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to revoke session");
      toast.success("Session signed out successfully.");
      setConfirmRevokeModal({ open: false, session: null });
      await fetchSessions();
    } catch (err: any) {
      toast.error(err.message || "Failed to revoke session");
    } finally {
      setRevokingSessionId(null);
    }
  };

  const handleRevokeOthers = async () => {
    try {
      setRevokingOthers(true);
      const res = await fetch("/api/admin/sessions/revoke-others", {
        method: "POST",
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to sign out other devices");
      toast.success(data.message || "Signed out all other devices.");
      setConfirmRevokeOthersModal(false);
      await fetchSessions();
    } catch (err: any) {
      toast.error(err.message || "Failed to sign out other devices");
    } finally {
      setRevokingOthers(false);
    }
  };

  const handleUpdatePin = async (e: React.FormEvent) => {
    e.preventDefault();
    setPinError(null);
    if (!/^\d{4}$/.test(pinNew)) {
      setPinError("PIN must be exactly 4 numeric digits.");
      return;
    }
    if (pinNew !== pinConfirm) {
      setPinError("PINs do not match.");
      return;
    }
    try {
      setPinLoading(true);
      const res = await fetch("/api/admin/auth/pin/setup", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          pin: pinNew,
          confirmPin: pinConfirm,
          currentPassword: pinPassword,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to update PIN");
      toast.success("4-digit screen lock PIN updated successfully!");
      setPinModalOpen(false);
      setPinPassword("");
      setPinNew("");
      setPinConfirm("");
      await refreshAuth();
    } catch (err: any) {
      setPinError(err.message || "Failed to update PIN");
    } finally {
      setPinLoading(false);
    }
  };

  const handleRegisterPasskey = async () => {
    if (typeof window === "undefined" || !window.PublicKeyCredential) {
      toast.error("WebAuthn / Passkeys not supported on this browser.");
      return;
    }
    try {
      setPasskeyLoading(true);
      const challenge = new Uint8Array(32);
      crypto.getRandomValues(challenge);
      const userIdBytes = new TextEncoder().encode(user?.id || "admin");

      const credential = (await navigator.credentials.create({
        publicKey: {
          challenge,
          rp: { name: "Quto AI Admin", id: window.location.hostname },
          user: {
            id: userIdBytes,
            name: user?.email || "admin@quto.ai",
            displayName: user?.name || "Administrator",
          },
          pubKeyCredParams: [
            { alg: -7, type: "public-key" }, // ES256
            { alg: -257, type: "public-key" }, // RS256
          ],
          authenticatorSelection: {
            authenticatorAttachment: "platform",
            userVerification: "preferred",
          },
          timeout: 60000,
        },
      })) as PublicKeyCredential | null;

      if (!credential) throw new Error("Passkey creation was cancelled.");

      const res = await fetch("/api/admin/auth/webauthn/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id: credential.id,
          publicKey: btoa(String.fromCharCode(...new Uint8Array((credential.response as any).getPublicKey?.() || []))),
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Passkey registration failed");
      toast.success("Device passkey registered successfully!");
      await refreshAuth();
    } catch (err: any) {
      toast.error(err.message || "Biometric / passkey registration failed.");
    } finally {
      setPasskeyLoading(false);
    }
  };

  const handleRemovePasskeys = async () => {
    if (!confirm("Remove all enrolled device passkeys from your administrator account?")) return;
    try {
      setPasskeyLoading(true);
      const res = await fetch("/api/admin/auth/webauthn/register", {
        method: "DELETE",
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to remove passkeys");
      toast.success("All enrolled passkeys removed.");
      await refreshAuth();
    } catch (err: any) {
      toast.error(err.message || "Failed to remove passkeys.");
    } finally {
      setPasskeyLoading(false);
    }
  };

  const handlePasswordChange = async (e: React.FormEvent) => {
    e.preventDefault();
    setPassError(null);
    setPassSuccess(null);

    if (newPassword.length < 8) {
      setPassError("New password must be at least 8 characters long.");
      return;
    }

    if (newPassword !== confirmPassword) {
      setPassError("New password and confirmation do not match.");
      return;
    }

    setUpdatingPass(true);

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

      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to update password");

      setPassSuccess("Password updated successfully.");
      setCurrentPassword("");
      setNewPassword("");
      setConfirmPassword("");
    } catch (e) {
      setPassError((e as Error).message);
    } finally {
      setUpdatingPass(false);
    }
  };

  // 2FA Flow Handlers
  const startEnrollment = () => {
    setEnrollStep("PASSWORD");
    setEnrollPassword("");
    setEnrollOtp("");
    setEnrollError(null);
    setEnrollModalOpen(true);
  };

  const handleEnrollPasswordSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setEnrollError(null);
    setEnrollingLoading(true);

    try {
      const res = await fetch("/api/admin/auth/2fa/enroll", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password: enrollPassword }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Password verification failed.");

      setEnrollSecret(data.secret);
      setEnrollQrUrl(data.qrCodeDataUrl);
      setEnrollStep("SCAN_QR");
    } catch (err: any) {
      setEnrollError(err.message);
    } finally {
      setEnrollingLoading(false);
    }
  };

  const handleVerifyEnrollment = async (e: React.FormEvent) => {
    e.preventDefault();
    setEnrollError(null);
    setEnrollingLoading(true);

    try {
      const res = await fetch("/api/admin/auth/2fa/verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ secret: enrollSecret, code: enrollOtp }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Verification failed.");

      setBackupCodes(data.backupCodes || []);
      setEnrollStep("BACKUP_CODES");
      toast.success("2FA enabled successfully!");
      await refreshAuth();
    } catch (err: any) {
      setEnrollError(err.message);
    } finally {
      setEnrollingLoading(false);
    }
  };

  const handleDisable2FA = async (e: React.FormEvent) => {
    e.preventDefault();
    setDisableError(null);
    setDisablingLoading(true);

    try {
      const res = await fetch("/api/admin/auth/2fa/disable", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password: disablePassword, code: disableOtp }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Failed to disable 2FA.");

      toast.success("2FA has been disabled.");
      setDisableModalOpen(false);
      await refreshAuth();
    } catch (err: any) {
      setDisableError(err.message);
    } finally {
      setDisablingLoading(false);
    }
  };

  const copyManualKey = () => {
    navigator.clipboard.writeText(enrollSecret);
    setCopiedKey(true);
    setTimeout(() => setCopiedKey(false), 2000);
  };

  const copyAllBackupCodes = () => {
    navigator.clipboard.writeText(backupCodes.join("\n"));
    setCopiedBackupCodes(true);
    toast.success("Backup codes copied to clipboard!");
    setTimeout(() => setCopiedBackupCodes(false), 2000);
  };

  const downloadBackupCodes = () => {
    const text = `Quto AI Admin - Backup Recovery Codes\nGenerated: ${new Date().toISOString()}\nAccount: ${user?.email}\n\nEach code can be used once:\n${backupCodes.join("\n")}\n`;
    const blob = new Blob([text], { type: "text/plain" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `quto-admin-backup-codes-${user?.email}.txt`;
    a.click();
    URL.revokeObjectURL(url);
    toast.success("Backup codes file downloaded!");
  };

  if (isLoading) {
    return (
      <div className="py-12 text-center text-xs text-neutral-400">
        Loading profile credentials...
      </div>
    );
  }

  if (!user) {
    return (
      <div className="rounded-xl border border-red-200 bg-red-50 p-4 text-xs text-red-700">
        Failed to load administrator profile.
      </div>
    );
  }

  const isMainAdmin = user.level === "MAIN_ADMIN";

  const getDeviceIcon = (deviceType?: string) => {
    switch (deviceType?.toLowerCase()) {
      case "mobile":
        return <Smartphone className="h-4 w-4" />;
      case "tablet":
        return <Tablet className="h-4 w-4" />;
      default:
        return <Monitor className="h-4 w-4" />;
    }
  };

  const currentSessionObj =
    activeSessions.find((s) => s.isCurrent) ||
    (session
      ? {
          id: session.id,
          browser: session.browser,
          browserVersion: null,
          operatingSystem: "This Device",
          deviceType: "Desktop" as const,
          deviceSummary: `${session.browser} on ${session.device}`,
          ipAddress: null,
          createdAt: session.createdAt,
          lastSeenAt: session.lastActiveAt,
          locationDisplay: "Current session",
          rawLocation: null,
          networkSecurity: null,
          status: "ACTIVE",
          isCurrent: true,
        }
      : null);

  const otherSessions = activeSessions.filter((s) => !s.isCurrent);

  return (
    <div className="max-w-4xl space-y-8">
      <div className="grid grid-cols-1 gap-6 md:grid-cols-3">
        {/* Account Details */}
        <div className="md:col-span-1 rounded-2xl border border-neutral-200 bg-white p-6 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
          <div className="flex flex-col items-center text-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-full bg-neutral-900 text-white dark:bg-white dark:text-neutral-900">
              <User className="h-8 w-8" />
            </div>
            <h2 className="mt-3 font-bold text-base text-neutral-900 dark:text-white">
              {user.name}
            </h2>
            <span className="text-xs text-neutral-500">{user.email}</span>

            <div className="mt-3">
              <span
                className={`rounded-full px-2.5 py-0.5 text-[10px] font-bold uppercase tracking-wider ${
                  isMainAdmin
                    ? "bg-neutral-900 text-white dark:bg-white dark:text-neutral-900"
                    : "bg-neutral-100 text-neutral-800 dark:bg-neutral-800 dark:text-neutral-200"
                }`}
              >
                {isMainAdmin ? "MAIN ADMIN" : (user.role || "SUB_ADMIN").replace(/_/g, " ")}
              </span>
            </div>
          </div>

          <hr className="my-5 border-neutral-100 dark:border-neutral-800" />

          <div className="space-y-3 text-xs">
            <div>
              <span className="text-neutral-400">Account Created:</span>
              <div suppressHydrationWarning className="font-medium text-neutral-900 dark:text-white">
                {user.createdAt
                  ? new Date(user.createdAt).toLocaleDateString("en-US", {
                      year: "numeric",
                      month: "short",
                      day: "numeric",
                    })
                  : "Recently"}
              </div>
            </div>

            <div>
              <span className="text-neutral-400">Role Authority:</span>
              <div className="font-medium text-neutral-900 dark:text-white">
                {isMainAdmin ? "Unrestricted Global Admin" : (user.role || "").replace(/_/g, " ")}
              </div>
            </div>

            {!isMainAdmin && (
              <div className="rounded-lg bg-neutral-50 p-2.5 text-[11px] text-neutral-500 dark:bg-neutral-950">
                Sub-admin roles are managed by the Main Administrator.
              </div>
            )}
          </div>
        </div>

        {/* Security, 2FA & Password Forms */}
        <div className="md:col-span-2 space-y-6">
          {/* Real TOTP 2FA Management Card */}
          <div className="rounded-2xl border border-neutral-200 bg-white p-6 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-4">
            <div className="flex items-center justify-between border-b border-neutral-100 pb-3 dark:border-neutral-800">
              <div className="flex items-center gap-2">
                <Shield className="h-4 w-4 text-neutral-700 dark:text-neutral-300" />
                <h3 className="font-bold text-sm text-neutral-900 dark:text-white">
                  Two-Factor Authentication (2FA)
                </h3>
              </div>

              {user.twoFactorEnabled ? (
                <span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-bold text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300">
                  <CheckCircle2 className="h-3.5 w-3.5" />
                  <span>Enforced / Active</span>
                </span>
              ) : (
                <span className="inline-flex items-center gap-1.5 rounded-full bg-amber-100 px-2.5 py-0.5 text-[11px] font-bold text-amber-800 dark:bg-amber-950 dark:text-amber-300">
                  <AlertTriangle className="h-3.5 w-3.5" />
                  <span>Not Configured</span>
                </span>
              )}
            </div>

            <p className="text-xs text-neutral-500 leading-relaxed">
              Protect your administrative session with real TOTP two-factor authentication. Scannable with Google Authenticator, Microsoft Authenticator, 1Password, or Authy.
            </p>

            <div className="flex items-center justify-between pt-2">
              {user.twoFactorEnabled ? (
                <div className="flex items-center gap-3">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      setDisablePassword("");
                      setDisableOtp("");
                      setDisableError(null);
                      setDisableModalOpen(true);
                    }}
                    className="text-xs text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950/30"
                  >
                    Disable 2FA
                  </Button>
                </div>
              ) : (
                <Button
                  onClick={startEnrollment}
                  size="sm"
                  className="gap-2 rounded-xl text-xs font-semibold"
                >
                  <QrCode className="h-3.5 w-3.5" />
                  <span>Enable Authenticator App</span>
                </Button>
              )}
            </div>
          </div>

          {/* Dedicated 4-Digit Screen Lock PIN Card */}
          <div className="rounded-2xl border border-neutral-200 bg-white p-6 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-4">
            <div className="flex items-center justify-between border-b border-neutral-100 pb-3 dark:border-neutral-800">
              <div className="flex items-center gap-2">
                <Lock className="h-4 w-4 text-neutral-700 dark:text-neutral-300" />
                <h3 className="font-bold text-sm text-neutral-900 dark:text-white">
                  Console Screen Lock PIN
                </h3>
              </div>

              {hasPin ? (
                <span className="inline-flex items-center gap-1.5 rounded-full bg-cyan-100 px-2.5 py-0.5 text-[11px] font-bold text-cyan-800 dark:bg-cyan-950 dark:text-cyan-300">
                  <CheckCircle2 className="h-3.5 w-3.5" />
                  <span>4-Digit Secure PIN Active</span>
                </span>
              ) : (
                <span className="inline-flex items-center gap-1.5 rounded-full bg-amber-100 px-2.5 py-0.5 text-[11px] font-bold text-amber-800 dark:bg-amber-950 dark:text-amber-300">
                  <AlertTriangle className="h-3.5 w-3.5" />
                  <span>Not Configured</span>
                </span>
              )}
            </div>

            <p className="text-xs text-neutral-500 leading-relaxed">
              Quickly unlock your console session after inactivity using a dedicated 4-digit PIN, protected by salted scrypt hash verification and brute-force lockout protection.
            </p>

            <div className="flex items-center gap-3 pt-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  setPinPassword("");
                  setPinNew("");
                  setPinConfirm("");
                  setPinError(null);
                  setPinModalOpen(true);
                }}
                className="gap-2 text-xs font-semibold"
              >
                <KeyRound className="h-3.5 w-3.5" />
                <span>{hasPin ? "Change 4-Digit PIN" : "Set Up 4-Digit PIN"}</span>
              </Button>
            </div>
          </div>

          {/* Device Biometric / Passkey Card (WebAuthn) */}
          <div className="rounded-2xl border border-neutral-200 bg-white p-6 shadow-xs dark:border-neutral-800 dark:bg-neutral-900 space-y-4">
            <div className="flex items-center justify-between border-b border-neutral-100 pb-3 dark:border-neutral-800">
              <div className="flex items-center gap-2">
                <Fingerprint className="h-4 w-4 text-neutral-700 dark:text-neutral-300" />
                <h3 className="font-bold text-sm text-neutral-900 dark:text-white">
                  Device Passkey & Biometrics
                </h3>
              </div>

              {hasPasskey ? (
                <span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-bold text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300">
                  <CheckCircle2 className="h-3.5 w-3.5" />
                  <span>
                    Enabled ({passkeyCount === 1 ? "1 device enrolled" : `${passkeyCount} devices enrolled`})
                  </span>
                </span>
              ) : (
                <span className="inline-flex items-center gap-1.5 rounded-full bg-amber-100 px-2.5 py-0.5 text-[11px] font-bold text-amber-800 dark:bg-amber-950 dark:text-amber-300">
                  <AlertTriangle className="h-3.5 w-3.5" />
                  <span>Not Configured</span>
                </span>
              )}
            </div>

            <p className="text-xs text-neutral-500 leading-relaxed">
              Unlock your console session without passwords using platform biometrics such as Windows Hello, Touch ID, Face ID, or hardware security keys. Credential public keys are verified by WebAuthn challenges.
            </p>

            <div className="flex flex-wrap items-center gap-3 pt-2">
              {hasPasskey ? (
                <>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleRegisterPasskey}
                    disabled={passkeyLoading || !passkeySupported}
                    className="gap-2 text-xs font-semibold"
                  >
                    <Plus className="h-3.5 w-3.5 text-neutral-700 dark:text-neutral-300" />
                    <span>{passkeyLoading ? "Enrolling..." : "Add Another Device"}</span>
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleRemovePasskeys}
                    disabled={passkeyLoading}
                    className="gap-2 text-xs text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950/30"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                    <span>Remove All Passkeys</span>
                  </Button>
                </>
              ) : (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleRegisterPasskey}
                  disabled={passkeyLoading || !passkeySupported}
                  className="gap-2 text-xs font-semibold"
                >
                  <Fingerprint className="h-3.5 w-3.5 text-neutral-700 dark:text-neutral-300" />
                  <span>{passkeyLoading ? "Enrolling Passkey..." : "Enroll Device Passkey"}</span>
                </Button>
              )}

              {!passkeySupported && (
                <span className="text-[11px] text-neutral-400">
                  WebAuthn / Passkeys not supported on this browser.
                </span>
              )}
            </div>
          </div>

          {/* Password Form with Floating Inputs */}
          <div className="rounded-2xl border border-neutral-200 bg-white p-6 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
            <div className="flex items-center gap-2 border-b border-neutral-100 pb-3 dark:border-neutral-800">
              <KeyRound className="h-4 w-4 text-neutral-700 dark:text-neutral-300" />
              <h3 className="font-bold text-sm text-neutral-900 dark:text-white">
                Update Password
              </h3>
            </div>

            {passError && (
              <div className="mt-4 rounded-lg 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">
                {passError}
              </div>
            )}

            {passSuccess && (
              <div className="mt-4 rounded-lg border border-emerald-200 bg-emerald-50 p-3 text-xs text-emerald-800 dark:border-emerald-900/50 dark:bg-emerald-950/50 dark:text-emerald-200">
                {passSuccess}
              </div>
            )}

            <form onSubmit={handlePasswordChange} className="mt-4 space-y-4">
              <FloatingInput
                id="current-password"
                type="password"
                required
                label="Current Password"
                value={currentPassword}
                onChange={(e) => setCurrentPassword(e.target.value)}
              />

              <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <FloatingInput
                  id="new-password"
                  type="password"
                  required
                  minLength={8}
                  label="New Password (min 8 chars)"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                />

                <FloatingInput
                  id="confirm-password"
                  type="password"
                  required
                  minLength={8}
                  label="Confirm New Password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                />
              </div>

              <div className="flex justify-end pt-2">
                <Button
                  type="submit"
                  disabled={updatingPass}
                  className="rounded-xl text-xs font-semibold"
                >
                  {updatingPass ? "Updating..." : "Save Password"}
                </Button>
              </div>
            </form>
          </div>

          {/* Active Sessions Registry */}
          <div className="rounded-2xl border border-neutral-200 bg-white p-6 shadow-xs dark:border-neutral-800 dark:bg-neutral-900">
            {/* Header: Title, Count, Refresh, and Sign Out Other Devices */}
            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between border-b border-neutral-100 pb-4 dark:border-neutral-800">
              <div className="flex items-center gap-2.5">
                <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-neutral-100 text-neutral-800 dark:bg-neutral-800 dark:text-neutral-200">
                  <Laptop className="h-4 w-4" />
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <h3 className="font-bold text-sm text-neutral-900 dark:text-white">
                      Active Sessions
                    </h3>
                    <span className="rounded-full bg-emerald-50 px-2 py-0.5 text-[11px] font-semibold text-emerald-700 dark:bg-emerald-950/60 dark:text-emerald-300 border border-emerald-200/50 dark:border-emerald-800/50">
                      {activeSessions.length || 1} active
                    </span>
                  </div>
                  <p className="text-[11px] text-neutral-500 dark:text-neutral-400">
                    Devices currently signed into your administrative account
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-2 self-end sm:self-auto">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={fetchSessions}
                  disabled={sessionsLoading}
                  className="h-8 gap-1.5 rounded-lg text-xs"
                >
                  <RefreshCw className={`h-3.5 w-3.5 ${sessionsLoading ? "animate-spin" : ""}`} />
                  Refresh
                </Button>

                {otherSessions.length > 0 && (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => setConfirmRevokeOthersModal(true)}
                    disabled={revokingOthers}
                    className="h-8 gap-1.5 rounded-lg border-red-200 text-red-600 hover:bg-red-50 hover:text-red-700 dark:border-red-900/50 dark:text-red-400 dark:hover:bg-red-950/50 text-xs font-medium"
                  >
                    <LogOut className="h-3.5 w-3.5" />
                    Sign out other devices
                  </Button>
                )}
              </div>
            </div>

            {/* Content: Current Session Card + Other Sessions */}
            <div className="mt-5 space-y-4">
              {/* THIS DEVICE CARD */}
              {currentSessionObj && (
                <div className="relative rounded-xl border-2 border-emerald-500/20 bg-emerald-50/20 p-4 dark:border-emerald-500/30 dark:bg-emerald-950/10">
                  <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                    <div className="flex items-start gap-3">
                      <div className="mt-0.5 flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-300">
                        {getDeviceIcon(currentSessionObj.deviceType)}
                      </div>
                      <div className="space-y-1">
                        <div className="flex flex-wrap items-center gap-2">
                          <span className="font-semibold text-sm text-neutral-900 dark:text-white">
                            {currentSessionObj.browser} {currentSessionObj.browserVersion ? currentSessionObj.browserVersion : ""} on {currentSessionObj.operatingSystem}
                          </span>
                          <span className="rounded-full bg-emerald-600 px-2 py-0.5 text-[10px] font-bold text-white uppercase tracking-wider">
                            This Device
                          </span>
                          <span className="flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-medium text-emerald-800 dark:bg-emerald-950 dark:text-emerald-300">
                            <span className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse" />
                            Active now
                          </span>
                        </div>

                        <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-neutral-500 dark:text-neutral-400">
                          <span className="flex items-center gap-1">
                            <Clock className="h-3.5 w-3.5 text-neutral-400" />
                            Signed in: {new Date(currentSessionObj.createdAt).toLocaleString("en-US", {
                              dateStyle: "medium",
                              timeStyle: "short",
                            })}
                          </span>
                          <span className="flex items-center gap-1">
                            <MapPin className="h-3.5 w-3.5 text-neutral-400" />
                            {currentSessionObj.locationDisplay || "Location unavailable"}
                          </span>
                        </div>

                        {currentSessionObj.networkSecurity && (
                          <div className="pt-0.5 flex items-center gap-1.5 text-[11px] text-neutral-600 dark:text-neutral-300">
                            <ShieldCheck className="h-3.5 w-3.5 text-emerald-600" />
                            <span>Network: Direct / Clean IP</span>
                          </div>
                        )}
                      </div>
                    </div>

                    <div className="text-right text-[11px] font-mono text-neutral-400 self-end sm:self-auto">
                      Last active: {formatRelativeTime(currentSessionObj.lastSeenAt)}
                    </div>
                  </div>
                </div>
              )}

              {/* OTHER SESSIONS LIST */}
              {otherSessions.length === 0 ? (
                <div className="rounded-xl border border-neutral-100 bg-neutral-50/50 p-4 text-center text-xs text-neutral-500 dark:border-neutral-800 dark:bg-neutral-800/30 dark:text-neutral-400">
                  No other devices currently active. Your account is only signed in on this device.
                </div>
              ) : (
                <div className="space-y-3 pt-2">
                  <div className="flex items-center justify-between">
                    <h4 className="font-semibold text-xs text-neutral-600 uppercase tracking-wider dark:text-neutral-400">
                      Other Active Devices ({otherSessions.length})
                    </h4>
                  </div>

                  <div className="space-y-2.5">
                    {(showAllOtherSessions ? otherSessions : otherSessions.slice(0, 3)).map((sess) => (
                      <div
                        key={sess.id}
                        className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between rounded-xl border border-neutral-200 bg-white p-3.5 shadow-2xs hover:border-neutral-300 dark:border-neutral-800 dark:bg-neutral-900/60 dark:hover:border-neutral-700 transition-colors"
                      >
                        <div className="flex items-start gap-3">
                          <div className="mt-0.5 flex h-8 w-8 items-center justify-center rounded-lg bg-neutral-100 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-300">
                            {getDeviceIcon(sess.deviceType)}
                          </div>
                          <div className="space-y-0.5">
                            <div className="flex items-center gap-2">
                              <span className="font-medium text-xs text-neutral-900 dark:text-white">
                                {sess.browser} {sess.browserVersion ? sess.browserVersion : ""} on {sess.operatingSystem}
                              </span>
                              <span className="rounded bg-neutral-100 px-1.5 py-0.5 text-[10px] font-medium text-neutral-600 dark:bg-neutral-800 dark:text-neutral-300">
                                {sess.deviceType}
                              </span>
                            </div>
                            <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-neutral-400">
                              <span className="flex items-center gap-1">
                                <Clock className="h-3 w-3" />
                                Active {formatRelativeTime(sess.lastSeenAt)}
                              </span>
                              <span>•</span>
                              <span className="flex items-center gap-1">
                                <MapPin className="h-3 w-3" />
                                {sess.locationDisplay || "Location unavailable"}
                              </span>
                            </div>
                          </div>
                        </div>

                        <div className="flex items-center gap-2 self-end sm:self-auto">
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => setConfirmRevokeModal({ open: true, session: sess })}
                            disabled={revokingSessionId === sess.id}
                            className="h-7 text-xs px-2.5 rounded-lg border-neutral-200 hover:border-red-200 hover:bg-red-50 hover:text-red-600 dark:border-neutral-700 dark:hover:border-red-900 dark:hover:bg-red-950/30 dark:hover:text-red-400"
                          >
                            {revokingSessionId === sess.id ? "Revoking..." : "Sign Out"}
                          </Button>
                        </div>
                      </div>
                    ))}
                  </div>

                  {otherSessions.length > 3 && (
                    <div className="text-center pt-1">
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => setShowAllOtherSessions(!showAllOtherSessions)}
                        className="text-xs text-neutral-500 hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-white"
                      >
                        {showAllOtherSessions ? "Show less" : `View all ${otherSessions.length} other devices`}
                      </Button>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 2FA ENROLLMENT MODAL */}
      <Dialog open={enrollModalOpen} onOpenChange={setEnrollModalOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>
              {enrollStep === "PASSWORD" && "Confirm Your Password"}
              {enrollStep === "SCAN_QR" && "Scan Authenticator QR Code"}
              {enrollStep === "BACKUP_CODES" && "Save Your Backup Recovery Codes"}
            </DialogTitle>
            <DialogDescription>
              {enrollStep === "PASSWORD" && "Re-authenticate to generate your TOTP cryptographic secret."}
              {enrollStep === "SCAN_QR" && "Open Google Authenticator, Microsoft Authenticator, or 1Password and scan this QR code."}
              {enrollStep === "BACKUP_CODES" && "Keep these single-use recovery codes in a safe place. If you ever lose your authenticator app, each code can be used once to log in."}
            </DialogDescription>
          </DialogHeader>

          {enrollError && (
            <div className="rounded-lg 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">
              {enrollError}
            </div>
          )}

          {/* STEP 1: Password Re-Authentication */}
          {enrollStep === "PASSWORD" && (
            <form onSubmit={handleEnrollPasswordSubmit} className="space-y-4 pt-2">
              <FloatingInput
                id="enroll-reauth-password"
                type="password"
                required
                autoFocus
                label="Current Account Password"
                value={enrollPassword}
                onChange={(e) => setEnrollPassword(e.target.value)}
              />

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setEnrollModalOpen(false)}
                >
                  Cancel
                </Button>
                <Button
                  type="submit"
                  disabled={enrollingLoading || !enrollPassword}
                >
                  {enrollingLoading ? "Verifying..." : "Next: View QR Code"}
                </Button>
              </DialogFooter>
            </form>
          )}

          {/* STEP 2: Scan QR & Enter 6-digit OTP */}
          {enrollStep === "SCAN_QR" && (
            <form onSubmit={handleVerifyEnrollment} className="space-y-4 pt-2">
              <div className="flex flex-col items-center justify-center p-3 rounded-2xl border border-neutral-200 bg-neutral-50 dark:border-neutral-800 dark:bg-neutral-900">
                {/* Genuine Scannable QR Code */}
                {enrollQrUrl && (
                  <img
                    src={enrollQrUrl}
                    alt="Authenticator TOTP QR Code"
                    className="h-48 w-48 rounded-xl shadow-xs border border-neutral-200 bg-white p-2"
                  />
                )}

                {/* Manual Setup Key Fallback */}
                <div className="mt-3 w-full text-center">
                  <span className="text-[10px] font-semibold text-neutral-400 uppercase tracking-wider">
                    Manual Setup Key
                  </span>
                  <div className="mt-1 flex items-center justify-center gap-2">
                    <code className="rounded bg-neutral-200/70 px-2 py-1 font-mono text-xs font-bold text-neutral-800 dark:bg-neutral-800 dark:text-neutral-200">
                      {enrollSecret}
                    </code>
                    <button
                      type="button"
                      onClick={copyManualKey}
                      className="rounded p-1 text-neutral-500 hover:text-neutral-900 dark:hover:text-white"
                      title="Copy Secret"
                    >
                      {copiedKey ? <Check className="h-3.5 w-3.5 text-emerald-600" /> : <Copy className="h-3.5 w-3.5" />}
                    </button>
                  </div>
                </div>
              </div>

              <FloatingInput
                id="enroll-otp-code"
                required
                autoFocus
                label="Enter 6-Digit Code from App"
                value={enrollOtp}
                onChange={(e) => setEnrollOtp(e.target.value)}
                className="font-mono text-center tracking-widest text-base"
                maxLength={6}
              />

              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setEnrollModalOpen(false)}
                >
                  Cancel
                </Button>
                <Button
                  type="submit"
                  disabled={enrollingLoading || enrollOtp.length < 6}
                >
                  {enrollingLoading ? "Verifying..." : "Verify & Activate 2FA"}
                </Button>
              </DialogFooter>
            </form>
          )}

          {/* STEP 3: Single-Use Backup Codes */}
          {enrollStep === "BACKUP_CODES" && (
            <div className="space-y-4 pt-2">
              <div className="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-start gap-2">
                <ShieldAlert className="h-4 w-4 shrink-0 mt-0.5" />
                <span>Save these backup codes now! Each code can be used once if you lose access to your authenticator app.</span>
              </div>

              <div className="grid grid-cols-2 gap-2 rounded-xl border border-neutral-200 bg-neutral-50 p-4 dark:border-neutral-800 dark:bg-neutral-900">
                {backupCodes.map((code, idx) => (
                  <div key={idx} className="font-mono text-xs font-semibold text-neutral-800 dark:text-neutral-200 text-center py-1 bg-white dark:bg-neutral-800 rounded border border-neutral-200 dark:border-neutral-700">
                    {code}
                  </div>
                ))}
              </div>

              <div className="flex items-center gap-2">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={copyAllBackupCodes}
                  className="w-1/2 gap-1.5 text-xs"
                >
                  {copiedBackupCodes ? <Check className="h-3.5 w-3.5 text-emerald-600" /> : <Copy className="h-3.5 w-3.5" />}
                  <span>Copy Codes</span>
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={downloadBackupCodes}
                  className="w-1/2 gap-1.5 text-xs"
                >
                  <Download className="h-3.5 w-3.5" />
                  <span>Download .txt</span>
                </Button>
              </div>

              <DialogFooter className="pt-2">
                <Button
                  onClick={() => setEnrollModalOpen(false)}
                  className="w-full"
                >
                  I Have Saved My Codes
                </Button>
              </DialogFooter>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 2FA DISABLE MODAL */}
      <Dialog open={disableModalOpen} onOpenChange={setDisableModalOpen}>
        <DialogContent className="max-w-sm">
          <DialogHeader>
            <DialogTitle>Disable Two-Factor Authentication</DialogTitle>
            <DialogDescription>
              For security, enter your current password and either a live 6-digit OTP or a single-use backup code.
            </DialogDescription>
          </DialogHeader>

          {disableError && (
            <div className="rounded-lg 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">
              {disableError}
            </div>
          )}

          <form onSubmit={handleDisable2FA} className="space-y-4 pt-2">
            <FloatingInput
              id="disable-password"
              type="password"
              required
              label="Account Password"
              value={disablePassword}
              onChange={(e) => setDisablePassword(e.target.value)}
            />

            <FloatingInput
              id="disable-otp"
              required
              label="6-Digit OTP or Backup Code"
              value={disableOtp}
              onChange={(e) => setDisableOtp(e.target.value)}
              className="font-mono"
            />

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setDisableModalOpen(false)}
              >
                Cancel
              </Button>
              <Button
                type="submit"
                variant="destructive"
                disabled={disablingLoading || !disablePassword || !disableOtp}
              >
                {disablingLoading ? "Disabling..." : "Confirm & Disable"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* SCREEN LOCK PIN UPDATE MODAL */}
      <Dialog open={pinModalOpen} onOpenChange={setPinModalOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Update Screen Lock PIN</DialogTitle>
            <DialogDescription>
              Enter your master account password to authenticate and set your new 4-digit screen lock PIN.
            </DialogDescription>
          </DialogHeader>

          {pinError && (
            <div className="rounded-lg 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">
              {pinError}
            </div>
          )}

          <form onSubmit={handleUpdatePin} className="space-y-4 pt-2">
            <FloatingInput
              id="pin-master-password"
              type="password"
              showPasswordToggle
              required
              autoComplete="current-password"
              name="current-password"
              label="Account Master Password"
              value={pinPassword}
              onChange={(e) => setPinPassword(e.target.value)}
            />

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

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

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={() => setPinModalOpen(false)}
                disabled={pinLoading}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={pinLoading || pinNew.length !== 4 || pinConfirm.length !== 4}>
                {pinLoading ? "Saving..." : "Save PIN"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* CONFIRM REVOKE SINGLE SESSION MODAL */}
      <Dialog
        open={confirmRevokeModal.open}
        onOpenChange={(open) =>
          setConfirmRevokeModal({ open, session: open ? confirmRevokeModal.session : null })
        }
      >
        <DialogContent className="max-w-sm">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-red-600 dark:text-red-400">
              <LogOut className="h-5 w-5" />
              Sign Out Device
            </DialogTitle>
            <DialogDescription>
              Are you sure you want to sign out this session? The device will immediately lose access and must log in again.
            </DialogDescription>
          </DialogHeader>

          {confirmRevokeModal.session && (
            <div className="rounded-xl border border-neutral-200 bg-neutral-50 p-3 text-xs space-y-1 dark:border-neutral-800 dark:bg-neutral-900">
              <div className="font-semibold text-neutral-900 dark:text-white">
                {confirmRevokeModal.session.browser} on {confirmRevokeModal.session.operatingSystem} ({confirmRevokeModal.session.deviceType})
              </div>
              <div className="text-neutral-500">
                Location: {confirmRevokeModal.session.locationDisplay}
              </div>
              <div className="text-neutral-400">
                Last active: {formatRelativeTime(confirmRevokeModal.session.lastSeenAt)}
              </div>
            </div>
          )}

          <DialogFooter className="gap-2 sm:gap-0">
            <Button
              type="button"
              variant="outline"
              onClick={() => setConfirmRevokeModal({ open: false, session: null })}
              disabled={Boolean(revokingSessionId)}
            >
              Cancel
            </Button>
            <Button
              type="button"
              variant="destructive"
              onClick={handleRevokeSingle}
              disabled={Boolean(revokingSessionId)}
            >
              {revokingSessionId ? "Signing Out..." : "Sign Out Device"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* CONFIRM REVOKE ALL OTHER SESSIONS MODAL */}
      <Dialog open={confirmRevokeOthersModal} onOpenChange={setConfirmRevokeOthersModal}>
        <DialogContent className="max-w-sm">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2 text-red-600 dark:text-red-400">
              <ShieldAlert className="h-5 w-5" />
              Sign Out Other Devices
            </DialogTitle>
            <DialogDescription>
              This will immediately revoke all {otherSessions.length} other active session{otherSessions.length === 1 ? "" : "s"}. Your current device will remain logged in.
            </DialogDescription>
          </DialogHeader>

          <DialogFooter className="gap-2 sm:gap-0">
            <Button
              type="button"
              variant="outline"
              onClick={() => setConfirmRevokeOthersModal(false)}
              disabled={revokingOthers}
            >
              Cancel
            </Button>
            <Button
              type="button"
              variant="destructive"
              onClick={handleRevokeOthers}
              disabled={revokingOthers}
            >
              {revokingOthers ? "Signing Out Devices..." : "Sign Out All Other Devices"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

export default SecurityPanel;
