"use client";

import { useState, useEffect, useCallback, useRef, useLayoutEffect } from "react";
import { Capacitor } from "@capacitor/core";
import { Button, Card, CardContent } from "@/lib/morphy-ux/morphy";
import {
  Lock,
  Loader2,
  AlertCircle,
  Key,
  Check,
  Copy,
  Download,
  Shield,
  ArrowRight,
  Fingerprint,
} from "lucide-react";
import { VaultService } from "@/lib/services/vault-service";
import { downloadTextFile } from "@/lib/utils/native-download";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { morphyToast as toast } from "@/lib/morphy-ux/morphy";
import { User } from "firebase/auth";

import { useVault } from "@/lib/vault/vault-context";
import { HushhLoader } from "@/components/app-ui/hushh-loader";
import { Icon } from "@/lib/morphy-ux/ui";
import type { GeneratedVaultKeyMode } from "@/lib/services/vault-bootstrap-service";
import { VaultMethodService, type VaultMethod } from "@/lib/services/vault-method-service";
import { VaultMethodPromptLocalService } from "@/lib/services/vault-method-prompt-local-service";
import { resolvePasskeyRpId } from "@/lib/vault/passkey-rp";
import { copyToClipboard } from "@/lib/utils/clipboard";
import { reloadWindow } from "@/lib/utils/browser-navigation";
import {
  toInvestorLoading,
  toInvestorMessage,
  toInvestorVaultUnlockError,
} from "@/lib/copy/investor-language";
import {
  getNativeTestConfig,
  getNativeUiTestVaultPassphrase,
  isNativeUiTestSession,
  preferPassphraseUnlockForAutomation,
  shouldSkipGeneratedVaultUnlockForAutomation,
  useNativeTestConfig,
} from "@/lib/testing/native-test";

type VaultStep =
  | "checking"
  | "intro"
  | "create"
  | "unlock"
  | "recovery"
  | "method";
type VaultMode = "passphrase" | GeneratedVaultKeyMode;

interface VaultFlowProps {
  user: User;
  onSuccess: (meta?: { mode: VaultMode }) => void;
  // Callback to inform parent about current step (e.g. to hide headers)
  onStepChange?: (step: VaultStep) => void;
  enableGeneratedDefault?: boolean;
}

export function VaultFlow({
  user,
  onSuccess,
  onStepChange,
  enableGeneratedDefault = false,
}: VaultFlowProps) {
  const ACTION_BUTTON_SIZE = "lg" as const;
  const [step, setStep] = useState<VaultStep>("checking");
  const [error, setError] = useState<string | null>(null);
  const [passphrase, setPassphrase] = useState("");
  const [confirmPassphrase, setConfirmPassphrase] = useState("");
  const [recoveryKey, setRecoveryKey] = useState<string>("");
  const [recoveryKeyInput, setRecoveryKeyInput] = useState("");
  const [copied, setCopied] = useState(false);
  const [isUnlocking, setIsUnlocking] = useState(false);
  const [vaultMode, setVaultMode] = useState<VaultMode>("passphrase");
  const [unlockHint, setUnlockHint] = useState<string | null>(null);
  const [availableGeneratedMethod, setAvailableGeneratedMethod] =
    useState<GeneratedVaultKeyMode | null>(null);
  const [unlockWithPassphraseFallback, setUnlockWithPassphraseFallback] =
    useState(() => shouldSkipGeneratedVaultUnlockForAutomation());
  const [pendingUnlockKey, setPendingUnlockKey] = useState<string | null>(null);
  const [recommendedQuickMethod, setRecommendedQuickMethod] =
    useState<VaultMethod | null>(null);
  const autoGeneratedPromptedRef = useRef(false);
  const nativeTestConfig = useNativeTestConfig();
  const shouldPreferPassphraseUnlock =
    preferPassphraseUnlockForAutomation(nativeTestConfig);
  const skipGeneratedUnlockForAutomation =
    shouldSkipGeneratedVaultUnlockForAutomation();
  const currentRpId = resolvePasskeyRpId({
    isNative: Capacitor.isNativePlatform(),
    hostname: typeof window !== "undefined" ? window.location.hostname : null,
  });

  const { unlockVault } = useVault();

  // Notify parent of step changes
  useEffect(() => {
    onStepChange?.(step);
  }, [step, onStepChange]);

  const isGeneratedVaultMode =
    vaultMode === "generated_default_native_biometric" ||
    vaultMode === "generated_default_web_prf" ||
    vaultMode === "generated_default_native_passkey_prf";
  const hasActiveGeneratedWrapper =
    isGeneratedVaultMode && availableGeneratedMethod === vaultMode;
  const shouldShowPassphraseUnlock =
    !hasActiveGeneratedWrapper || unlockWithPassphraseFallback;
  const createPassphraseTooShort =
    step === "create" && passphrase.length > 0 && passphrase.length < 8;
  const createPassphraseMismatch =
    step === "create" &&
    confirmPassphrase.length > 0 &&
    passphrase !== confirmPassphrase;
  const createPassphraseHelperText = createPassphraseTooShort
    ? "Minimum 8 characters required."
    : createPassphraseMismatch
      ? "Passphrases do not match."
      : null;

  const generatedUnlockLabel =
    vaultMode === "generated_default_web_prf" ||
    vaultMode === "generated_default_native_passkey_prf"
      ? "Passkey"
      : vaultMode === "generated_default_native_biometric"
        ? "Device security"
        : "Secure unlock";
  const compactGeneratedUnlockLabel = "Passkey";
  const hasGeneratedUnlockAlternative = Boolean(availableGeneratedMethod);
  const showVaultKeyAlternative =
    hasActiveGeneratedWrapper && !unlockWithPassphraseFallback;
  const showPasskeyAlternative =
    !hasActiveGeneratedWrapper &&
    hasGeneratedUnlockAlternative &&
    !unlockWithPassphraseFallback;
  const showRecoveryAlternative = true;
  const showUnlockOtherMethods =
    showVaultKeyAlternative || showPasskeyAlternative || showRecoveryAlternative;

  const finalizeUnlock = useCallback(async (decryptedKey: string): Promise<boolean> => {
    try {
      const { token, expiresAt } = await VaultService.getOrIssueVaultOwnerToken(user.uid);
      VaultService.setVaultCheckCache(user.uid, true);
      unlockVault(decryptedKey, token, expiresAt);
      onSuccess({ mode: vaultMode });
      return true;
    } catch (tokenError) {
      console.error("Failed to issue VAULT_OWNER token:", tokenError);
      toast.error("Vault opened, but we could not complete access setup. Please try again.");
      return false;
    }
  }, [onSuccess, unlockVault, user.uid, vaultMode]);

  // Initial Vault Status Check
  useEffect(() => {
    const checkStatus = async () => {
      try {
        const hasVault = await VaultService.checkVault(user.uid);
        if (!hasVault) {
          setVaultMode("passphrase");
          setUnlockWithPassphraseFallback(false);
          setUnlockHint(null);
          setStep("intro");
          return;
        }

        try {
          setUnlockHint(null);
          const vaultData = await VaultService.getVaultState(user.uid);
          const preferPassphraseForAutomation =
            shouldSkipGeneratedVaultUnlockForAutomation();
          const primaryWrapper = VaultService.getPrimaryWrapper(vaultData);
          const quickMethodCandidates: VaultMethod[] = Capacitor.isNativePlatform()
            ? [
                "generated_default_native_passkey_prf",
                "generated_default_native_biometric",
              ]
            : ["generated_default_web_prf"];
          const quickMethod =
            quickMethodCandidates
              .map((method) => VaultService.getWrapperByMethod(vaultData, method))
              .find((wrapper) => !!wrapper) ?? null;
          const nextQuickMethod = (quickMethod?.method as GeneratedVaultKeyMode | undefined) ?? null;
          setAvailableGeneratedMethod(nextQuickMethod);
          const primaryPrefersQuickMethod =
            vaultData.primaryMethod === "generated_default_native_biometric" ||
            vaultData.primaryMethod === "generated_default_web_prf" ||
            vaultData.primaryMethod === "generated_default_native_passkey_prf";

          if (primaryPrefersQuickMethod && !nextQuickMethod) {
            setVaultMode("passphrase");
            setUnlockWithPassphraseFallback(true);
            setUnlockHint(
              toInvestorMessage("VAULT_PASSKEY_ENROLL_REQUIRED")
            );
          } else if (
            preferPassphraseForAutomation &&
            VaultService.getWrapperByMethod(vaultData, "passphrase")
          ) {
            setVaultMode("passphrase");
            setUnlockWithPassphraseFallback(true);
          } else if (primaryPrefersQuickMethod && nextQuickMethod) {
            setVaultMode(nextQuickMethod);
            setUnlockWithPassphraseFallback(preferPassphraseForAutomation);
          } else if (
            primaryWrapper.method === "generated_default_native_biometric" ||
            primaryWrapper.method === "generated_default_web_prf" ||
            primaryWrapper.method === "generated_default_native_passkey_prf"
          ) {
            setVaultMode(primaryWrapper.method);
            setUnlockWithPassphraseFallback(preferPassphraseForAutomation);
          } else {
            setVaultMode(vaultData.primaryMethod);
            setUnlockWithPassphraseFallback(false);
          }
        } catch (metadataError) {
          console.warn("Vault mode detection failed, defaulting to passphrase:", metadataError);
          setVaultMode("passphrase");
          setAvailableGeneratedMethod(null);
          setUnlockWithPassphraseFallback(false);
          setUnlockHint(null);
        }
        setStep("unlock");
      } catch (err) {
        console.error("Vault status check failed:", err);
        const errorCode =
          typeof (err as { code?: unknown } | null | undefined)?.code === "string"
            ? (err as { code: string }).code
            : null;
        const errorHint =
          typeof (err as { hint?: unknown } | null | undefined)?.hint === "string"
            ? (err as { hint: string }).hint
            : null;
        if (errorCode === "DATABASE_UNAVAILABLE") {
          setError(errorHint || toInvestorMessage("LOCAL_BACKEND_UNAVAILABLE"));
        } else {
          setError(toInvestorMessage("VAULT_STATUS_UNAVAILABLE"));
        }
      }
    };
    checkStatus();
  }, [nativeTestConfig.vaultPassphrase, shouldPreferPassphraseUnlock, user.uid]);

  useLayoutEffect(() => {
    if (step !== "unlock") {
      return;
    }
    const testPassphrase = getNativeUiTestVaultPassphrase();
    if (!testPassphrase || !shouldSkipGeneratedVaultUnlockForAutomation()) {
      return;
    }
    setUnlockWithPassphraseFallback(true);
    setPassphrase(testPassphrase);
  }, [step, nativeTestConfig.vaultPassphrase]);

  const handleCreatePassphrase = async () => {
    if (passphrase.length < 8) {
      toast.error("Use at least 8 characters.");
      return;
    }
    if (passphrase !== confirmPassphrase) {
      toast.error("Passphrases do not match.");
      return;
    }

    setIsUnlocking(true);
    try {
      setError(null);
      // 1. Generate encrypted vault data
      const vaultData = await VaultService.createVault(passphrase);
      const vaultKeyHash = await VaultService.hashVaultKey(vaultData.vaultKeyHex);

      // 2. Save multi-wrapper vault state (mandatory passphrase wrapper)
      await VaultService.setupVaultState(user.uid, {
        vaultKeyHash,
        primaryMethod: "passphrase",
        recoveryEncryptedVaultKey: vaultData.recoveryEncryptedVaultKey,
        recoverySalt: vaultData.recoverySalt,
        recoveryIv: vaultData.recoveryIv,
        wrappers: [
          {
            method: "passphrase",
            encryptedVaultKey: vaultData.encryptedVaultKey,
            salt: vaultData.salt,
            iv: vaultData.iv,
          },
        ],
      });

      // 3. Verify state persisted correctly before moving ahead.
      const persistedState = await VaultService.getVaultState(user.uid);
      await VaultService.assertVaultKeyMatchesState(
        persistedState,
        vaultData.vaultKeyHex
      );
      if (!VaultService.getWrapperByMethod(persistedState, "passphrase")) {
        throw new Error("Vault setup verification failed: passphrase wrapper missing.");
      }

      setVaultMode("passphrase");
      VaultService.setVaultCheckCache(user.uid, true);
      setRecoveryKey(vaultData.recoveryKey);
      setStep("recovery"); // Show recovery key dialog
    } catch (err: any) {
      console.error("Create vault error:", err);
      toast.error(err.message || "We could not create your Vault. Please try again.");
    } finally {
      setIsUnlocking(false);
    }
  };

  const handleUnlockPassphraseWith = useCallback(async (passphraseValue: string) => {
    setIsUnlocking(true);
    try {
      setError(null);
      const vaultData = await VaultService.getVaultState(user.uid);
      const decryptedKey = await VaultService.unlockWithMethod({
        state: vaultData,
        method: "passphrase",
        secretMaterial: passphraseValue,
      });

      if (decryptedKey) {
        if (enableGeneratedDefault) {
          const capability = await VaultMethodService.getCapabilityMatrix();
          if (capability.recommendedMethod !== "passphrase") {
            const hasRecommendedWrapper =
              VaultService.getWrapperByMethod(vaultData, capability.recommendedMethod) !== null;
            const promptState = await VaultMethodPromptLocalService.load(user.uid);
            const dismissedForRecommendedMethod =
              promptState?.dismissed_for_method === capability.recommendedMethod &&
              promptState?.dismissed_for_rp_id === currentRpId;

            if (!hasRecommendedWrapper && !dismissedForRecommendedMethod) {
              setPendingUnlockKey(decryptedKey);
              setRecommendedQuickMethod(capability.recommendedMethod);
              setStep("method");
              return;
            }
          }
        }
        await finalizeUnlock(decryptedKey);
      } else {
        const message = "That passphrase did not match. Please try again.";
        setError(message);
        toast.error(message);
      }
    } catch (err: any) {
      console.error("Unlock error:", err);
      const message = toInvestorVaultUnlockError(err);
      setError(message);
      toast.error(message);
    } finally {
      setIsUnlocking(false);
    }
  }, [currentRpId, enableGeneratedDefault, finalizeUnlock, user.uid]);

  const handleUnlockPassphrase = useCallback(async () => {
    const passphraseToUse = passphrase;
    return handleUnlockPassphraseWith(passphraseToUse);
  }, [handleUnlockPassphraseWith, passphrase]);

  useEffect(() => {
    if (typeof window === "undefined") {
      return;
    }

    const bridge = window.__HUSHH_NATIVE_TEST__;
    if (!bridge?.enabled) {
      return;
    }

    const liveConfig = getNativeTestConfig();
    const testPassphrase = liveConfig.vaultPassphrase?.trim();
    if (!testPassphrase || step !== "unlock" || !isNativeUiTestSession(liveConfig)) {
      return;
    }

    bridge.triggerVaultUnlock = () => {
      if (isUnlocking) {
        return;
      }
      setUnlockWithPassphraseFallback(true);
      setPassphrase(testPassphrase);
      void handleUnlockPassphraseWith(testPassphrase);
    };

    if (shouldPreferPassphraseUnlock) {
      setUnlockWithPassphraseFallback(true);
      setPassphrase(testPassphrase);
      void handleUnlockPassphraseWith(testPassphrase);
    }

    return () => {
      if (window.__HUSHH_NATIVE_TEST__) {
        window.__HUSHH_NATIVE_TEST__.triggerVaultUnlock = null;
      }
    };
  }, [handleUnlockPassphraseWith, isUnlocking, shouldPreferPassphraseUnlock, step]);

  useEffect(() => {
    if (step !== "method" || !isNativeUiTestSession() || !pendingUnlockKey) {
      return;
    }
    void (async () => {
      if (recommendedQuickMethod) {
        try {
          await VaultMethodPromptLocalService.dismiss(
            user.uid,
            recommendedQuickMethod,
            currentRpId
          );
        } catch (dismissError) {
          console.warn("[VaultFlow] UITest quick-unlock dismissal failed:", dismissError);
        }
      }
      await finalizeUnlock(pendingUnlockKey);
    })();
  }, [
    currentRpId,
    finalizeUnlock,
    pendingUnlockKey,
    recommendedQuickMethod,
    step,
    user.uid,
  ]);

  const handleUnlockGeneratedDefault = useCallback(async () => {
    setIsUnlocking(true);
    try {
      setError(null);
      if (
        Capacitor.isNativePlatform() &&
        vaultMode === "generated_default_web_prf"
      ) {
        throw new Error(
          toInvestorMessage("VAULT_PASSKEY_ENROLL_REQUIRED")
        );
      }
      const vaultData = await VaultService.getVaultState(user.uid);
      const generatedWrapper = VaultService.getWrapperByMethod(vaultData, vaultMode, {
        wrapperId:
          vaultData.primaryMethod === vaultMode
            ? vaultData.primaryWrapperId
            : undefined,
      });
      if (!generatedWrapper) {
        throw new Error("Quick unlock is not enabled on this device yet.");
      }
      const decryptedKey = await VaultService.unlockGeneratedDefaultVault({
        userId: user.uid,
        encryptedVaultKey: generatedWrapper.encryptedVaultKey,
        salt: generatedWrapper.salt,
        iv: generatedWrapper.iv,
        keyMode: generatedWrapper.method,
        authMethod: generatedWrapper.method,
        passkeyCredentialId: generatedWrapper.passkeyCredentialId,
        passkeyPrfSalt: generatedWrapper.passkeyPrfSalt,
      });

      if (!decryptedKey) {
        throw new Error("Quick unlock is not ready. Use your passphrase.");
      }

      await VaultService.assertVaultKeyMatchesState(vaultData, decryptedKey);
      await finalizeUnlock(decryptedKey);
    } catch (err: any) {
      console.error("Generated vault unlock failed:", err);
      const message = toInvestorVaultUnlockError(err);
      setError(message);
      toast.error(message);
    } finally {
      setIsUnlocking(false);
    }
  }, [finalizeUnlock, user.uid, vaultMode]);

  const handleRecoveryKeySubmit = async () => {
    setIsUnlocking(true);
    try {
      setError(null);
      const vaultData = await VaultService.getVaultState(user.uid);
      const decryptedKey = await VaultService.unlockVaultWithRecoveryKey(
        recoveryKeyInput,
        vaultData.recoveryEncryptedVaultKey,
        vaultData.recoverySalt,
        vaultData.recoveryIv
      );

      if (decryptedKey) {
        await VaultService.assertVaultKeyMatchesState(vaultData, decryptedKey);
        await finalizeUnlock(decryptedKey);
      } else {
        const message = "That recovery key did not match. Please try again.";
        setError(message);
        toast.error(message);
      }
    } catch (err: unknown) {
      console.error("Recovery key unlock failed:", err);
      const message = toInvestorVaultUnlockError(err);
      setError(message);
      toast.error(message);
    } finally {
      setIsUnlocking(false);
    }
  };

  const handleCopyRecoveryKey = async () => {
    const copiedToClipboard = await copyToClipboard(recoveryKey);
    if (!copiedToClipboard) {
      toast.error("Could not copy the recovery key on this device.");
      return;
    }

    setCopied(true);
    toast.success("Recovery key copied to clipboard");
    setTimeout(() => setCopied(false), 2000);
  };

  const handleRecoveryKeyContinue = async () => {
    try {
      // Auto-unlock now that unique key is saved
      const vaultData = await VaultService.getVaultState(user.uid);
      const passphraseWrapper = VaultService.getWrapperByMethod(
        vaultData,
        "passphrase"
      );
      let decryptedKey: string | null = null;

      if (passphraseWrapper && passphrase) {
        decryptedKey = await VaultService.unlockWithMethod({
          state: vaultData,
          method: "passphrase",
          secretMaterial: passphrase,
        });
      }

      if (!decryptedKey) {
        throw new Error("Auto-unlock returned empty vault key.");
      }

      // Post-create optional method upsell: keep a single active KEK, but allow
      // immediate switch to quick unlock before entering the app.
      if (vaultMode === "passphrase" && enableGeneratedDefault) {
        const capability = await VaultMethodService.getCapabilityMatrix();
        if (capability.recommendedMethod !== "passphrase") {
          const promptState = await VaultMethodPromptLocalService.load(user.uid);
          const dismissedForRecommendedMethod =
            promptState?.dismissed_for_method === capability.recommendedMethod &&
            promptState?.dismissed_for_rp_id === currentRpId;
          if (!dismissedForRecommendedMethod) {
            setPendingUnlockKey(decryptedKey);
            setRecommendedQuickMethod(capability.recommendedMethod);
            setStep("method");
            return;
          }
        }
      }

      const finalized = await finalizeUnlock(decryptedKey);
      if (!finalized) return;
    } catch (err) {
      console.error("Auto-unlock after creation failed", err);
      // If auto-unlock fails, send user to unlock screen to try manually.
      toast.error(
        vaultMode === "passphrase"
          ? "Quick unlock was not available. Enter your passphrase."
          : "Quick unlock was not available. Try passphrase or recovery key."
      );
      setStep("unlock");
      return;
    }
  };

  useEffect(() => {
    if (
      step !== "unlock" ||
      !hasActiveGeneratedWrapper ||
      skipGeneratedUnlockForAutomation ||
      unlockWithPassphraseFallback
    ) {
      autoGeneratedPromptedRef.current = false;
      return;
    }
    if (autoGeneratedPromptedRef.current) return;
    autoGeneratedPromptedRef.current = true;
    void handleUnlockGeneratedDefault();
  }, [
    handleUnlockGeneratedDefault,
    hasActiveGeneratedWrapper,
    skipGeneratedUnlockForAutomation,
    step,
    unlockWithPassphraseFallback,
  ]);

  if (step === "checking") {
    if (error) {
      return (
        <Card variant="none" effect="fill">
          <CardContent className="p-6 text-center py-8">
            <div className="space-y-4">
              <div className="text-destructive mb-2">
                <Icon icon={AlertCircle} size={32} className="mx-auto" />
              </div>
              <p className="text-muted-foreground">{error}</p>
              <Button
                onClick={reloadWindow}
                variant="none"
                className="border border-input bg-background hover:bg-accent hover:text-accent-foreground"
              >
                Try again
              </Button>
            </div>
          </CardContent>
        </Card>
      );
    }

    return <HushhLoader label={toInvestorLoading("VAULT")} />;
  }

  return (
    <>
      <Card
        variant="none"
        effect="fill"
        className="overflow-hidden"
      >
        <CardContent className="max-h-[calc(100svh-8rem)] space-y-3 overflow-y-auto p-4 pb-[calc(1rem+env(safe-area-inset-bottom,0px))] sm:max-h-[calc(100svh-10rem)] sm:space-y-4 sm:p-6">
          {/* Intro / Education Step */}
          {step === "intro" && (
            <div className="space-y-6 text-center animate-in fade-in slide-in-from-bottom-4 duration-500">
              <div className="flex justify-center mb-4">
                <div className="h-20 w-20 rounded-2xl bg-primary/10 flex items-center justify-center">
                  <Icon icon={Shield} size={40} className="text-primary" />
                </div>
              </div>
              
              <div className="space-y-2">
                <h3 className="text-2xl font-bold tracking-tight">Secure Your Digital Vault</h3>
                <p className="text-muted-foreground text-balance max-w-sm mx-auto">
                  Hussh uses end-to-end encryption to protect your personal data.
                  Create your passphrase first, then optionally enable faster sign-in.
                </p>
              </div>

              <div className="text-left bg-muted/50 rounded-xl p-4 space-y-3 text-sm border border-border/50">
                <div className="flex gap-3">
                  <div className="mt-0.5 min-w-[1.25rem] text-primary">
                     <Icon icon={Check} size="md" />
                  </div>
                  <p><span className="font-semibold block text-foreground">You hold the only key</span> We cannot see your data or reset your password.</p>
                </div>
                <div className="flex gap-3">
                   <div className="mt-0.5 min-w-[1.25rem] text-primary">
                     <Icon icon={Check} size="md" />
                  </div>
                  <p><span className="font-semibold block text-foreground">Protected by default</span> Your data stays private and secure.</p>
                </div>
              </div>

              <div className="space-y-2">
              <Button 
                  variant="gradient" 
                  size={ACTION_BUTTON_SIZE}
                  fullWidth
                  className="group whitespace-normal text-center leading-snug px-4"
                  onClick={() => {
                    setError(null);
                    setStep("create");
                  }}
                >
                  Continue to Vault Setup
                  <Icon
                    icon={ArrowRight}
                    size="md"
                    className="ml-2 transition-transform group-hover:translate-x-1"
                  />
                </Button>

              </div>
            </div>
          )}

          {/* Create Passphrase */}
          {step === "create" && (
            <div className="space-y-3">
              <div className="text-center">
                <Icon icon={Lock} size={36} className="mx-auto text-primary mb-3" />
                <h3 className="text-lg font-semibold sm:text-xl">Create Your Vault Passphrase</h3>
                <p className="mt-1.5 text-sm text-muted-foreground sm:text-base">
                  This passphrase protects your Vault. Keep it private.
                </p>
              </div>
              <div className="space-y-2">
                <Label htmlFor="passphrase" className="text-sm sm:text-base">Passphrase</Label>
                <Input
                  id="passphrase"
                  type="password"
                  placeholder="Enter your passphrase"
                  value={passphrase}
                  onChange={(e) => setPassphrase(e.target.value)}
                  autoFocus
                  className="h-11 px-3 text-base sm:h-12 sm:px-4 sm:text-lg"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="confirm" className="text-sm sm:text-base">Confirm Passphrase</Label>
                <Input
                  id="confirm"
                  type="password"
                  placeholder="Confirm your passphrase"
                  value={confirmPassphrase}
                  onChange={(e) => setConfirmPassphrase(e.target.value)}
                  className="h-11 px-3 text-base sm:h-12 sm:px-4 sm:text-lg"
                />
                {createPassphraseHelperText && (
                  <p className="text-xs font-medium text-destructive" role="status">
                    {createPassphraseHelperText}
                  </p>
                )}
              </div>
              <div className="rounded-xl border border-border/60 bg-muted/20 p-2.5 text-[11px] text-muted-foreground sm:p-3 sm:text-sm">
                <p className="font-semibold text-foreground">Passphrase requirements</p>
                <ul className="mt-1 list-disc space-y-0.5 pl-4">
                  <li>Minimum 8 characters</li>
                  <li>Use a memorable phrase unique to you</li>
                  <li>Avoid reused passwords from other apps</li>
                </ul>
                <p className="mt-1.5 text-[10px] text-muted-foreground sm:mt-2 sm:text-xs">
                  You can enable passkey or device unlock later from Profile.
                </p>
              </div>
              <Button
                variant="gradient"
                effect="glass"
                size="default"
                fullWidth
                className="mt-2 h-11 text-sm sm:mt-4 sm:h-12 sm:text-base"
                onClick={handleCreatePassphrase}
                disabled={isUnlocking || passphrase.length < 8 || passphrase !== confirmPassphrase}
              >
                {isUnlocking ? (
                  <>
                    <Icon icon={Loader2} size="md" className="mr-2 animate-spin" /> Creating Vault...
                  </>
                ) : (
                  "Create Vault"
                )}
              </Button>
            </div>
          )}

          {/* Unlock Passphrase */}
          {step === "unlock" && (
            <div className="space-y-2.5">
              <div className="text-center">
                <Icon
                  icon={isGeneratedVaultMode ? Fingerprint : Lock}
                  size={24}
                  className="mx-auto mb-2 text-primary"
                />
                <h3 className="text-base font-semibold sm:text-lg">Unlock Your Vault</h3>
                <p className="mt-1 line-clamp-1 text-xs text-muted-foreground sm:text-sm">
                  {isGeneratedVaultMode
                    ? "Confirm with your device to open Vault"
                    : "Enter your passphrase to open Vault"}
                </p>
                {unlockHint ? (
                  <p className="mt-1 text-xs font-medium text-amber-500">
                    {unlockHint}
                  </p>
                ) : null}
              </div>
              {shouldShowPassphraseUnlock && (
                <div className="space-y-1.5">
                  <Label htmlFor="unlock-passphrase" className="text-xs font-medium sm:text-sm">
                    Vault Key
                  </Label>
                  <Input
                    id="unlock-passphrase"
                    type="password"
                    placeholder="Enter vault key"
                    value={passphrase}
                    onChange={(e) => setPassphrase(e.target.value)}
                    onKeyDown={(e) =>
                      e.key === "Enter" && handleUnlockPassphrase()
                    }
                    autoFocus
                    className="h-10 px-3 text-base sm:h-11"
                  />
                </div>
              )}
              <div className="flex flex-col gap-2 pt-1">
                {shouldShowPassphraseUnlock && (
                  <Button
                    variant="gradient"
                    effect="glass"
                    size="default"
                    fullWidth
                    className="h-10 text-sm font-semibold sm:h-11"
                    onClick={() => void handleUnlockPassphrase()}
                    disabled={isUnlocking || !passphrase}
                  >
                    {isUnlocking ? (
                      <>
                        <Icon icon={Loader2} size="sm" className="mr-2 animate-spin" /> Unlocking...
                      </>
                    ) : (
                      "Unlock"
                    )}
                  </Button>
                )}

                {hasActiveGeneratedWrapper && !unlockWithPassphraseFallback && (
                  <div className="flex min-h-10 items-center justify-center rounded-xl border border-border/60 bg-muted/20 px-3 py-2 text-xs text-muted-foreground sm:text-sm">
                    {isUnlocking ? (
                      <span className="inline-flex items-center">
                        <Icon icon={Loader2} size="sm" className="mr-2 animate-spin" />
                        Prompting {generatedUnlockLabel.toLowerCase()}...
                      </span>
                    ) : (
                      `Prompting ${generatedUnlockLabel.toLowerCase()}...`
                    )}
                  </div>
                )}

                {hasActiveGeneratedWrapper && !unlockWithPassphraseFallback && error && (
                  <Button
                    variant="none"
                    effect="fade"
                    size="default"
                    fullWidth
                    className="h-10 text-sm sm:h-11"
                    onClick={() => void handleUnlockGeneratedDefault()}
                    disabled={isUnlocking}
                  >
                    Try again
                  </Button>
                )}

                {showUnlockOtherMethods ? (
                  <div className="space-y-1.5 pt-1">
                    <p className="text-xs font-medium text-muted-foreground">Other methods</p>
                    <div className="grid grid-cols-2 gap-2">
                      {showVaultKeyAlternative ? (
                        <Button
                          variant="none"
                          effect="fade"
                          size="default"
                          fullWidth
                          className="h-10 px-2 text-xs sm:h-11 sm:text-sm"
                          data-testid="vault-use-passphrase-instead"
                          onClick={() => {
                            setError(null);
                            setUnlockWithPassphraseFallback(true);
                          }}
                          disabled={isUnlocking}
                        >
                          Vault Key
                        </Button>
                      ) : null}
                      {(hasActiveGeneratedWrapper && unlockWithPassphraseFallback) ||
                      showPasskeyAlternative ? (
                        <Button
                          variant="none"
                          effect="fade"
                          size="default"
                          fullWidth
                          className="h-10 px-2 text-xs sm:h-11 sm:text-sm"
                          onClick={() => {
                            setError(null);
                            setPassphrase("");
                            setUnlockWithPassphraseFallback(false);
                            if (!hasActiveGeneratedWrapper && availableGeneratedMethod) {
                              setVaultMode(availableGeneratedMethod);
                            }
                          }}
                          disabled={isUnlocking}
                        >
                          {compactGeneratedUnlockLabel}
                        </Button>
                      ) : null}
                      {showRecoveryAlternative ? (
                        <Button
                          variant="none"
                          effect="glass"
                          size="default"
                          fullWidth
                          className="h-10 px-2 text-xs sm:h-11 sm:text-sm"
                          onClick={() => {
                            setError(null);
                            setStep("recovery");
                          }}
                          disabled={isUnlocking}
                        >
                          Recovery Key
                        </Button>
                      ) : null}
                    </div>
                  </div>
                ) : null}
              </div>
            </div>
          )}

          {/* Recovery Key Input */}
          {step === "recovery" && !recoveryKey && (
            <div className="space-y-2.5">
              <div className="text-center">
                <Icon icon={Key} size={24} className="mx-auto mb-2 text-primary" />
                <h3 className="text-base font-semibold sm:text-lg">Enter Recovery Key</h3>
                <p className="mt-1 line-clamp-1 text-xs text-muted-foreground sm:text-sm">
                  Enter your recovery key to open Vault
                </p>
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="recovery-key" className="text-xs font-medium sm:text-sm">Recovery Key</Label>
                <Input
                  id="recovery-key"
                  placeholder="HRK-XXXX-XXXX-XXXX-XXXX"
                  value={recoveryKeyInput}
                  onChange={(e) =>
                    setRecoveryKeyInput(e.target.value.toUpperCase())
                  }
                  className="h-10 px-3 font-mono text-base sm:h-11"
                />
              </div>
              <div className="flex flex-col gap-2 pt-2">
                <Button
                  variant="gradient"
                  effect="glass"
                  size="default"
                  fullWidth
                  className="h-10 text-sm font-semibold sm:h-11"
                  onClick={handleRecoveryKeySubmit}
                  disabled={isUnlocking || !recoveryKeyInput}
                >
                  {isUnlocking ? (
                    <>
                      <Icon icon={Loader2} size="sm" className="mr-2 animate-spin" /> Unlocking...
                    </>
                  ) : (
                    "Unlock"
                  )}
                </Button>
                <div className="space-y-1.5">
                  <p className="text-xs font-medium text-muted-foreground">Other methods</p>
                  <div className="grid grid-cols-2 gap-2">
                    <Button
                      variant="none"
                      effect="glass"
                      size="default"
                      fullWidth
                      className="h-10 px-2 text-xs sm:h-11 sm:text-sm"
                      onClick={() => {
                        setError(null);
                        setUnlockWithPassphraseFallback(true);
                        setStep("unlock");
                      }}
                      disabled={isUnlocking}
                    >
                      Vault Key
                    </Button>
                    {availableGeneratedMethod ? (
                      <Button
                        variant="none"
                        effect="glass"
                        size="default"
                        fullWidth
                        className="h-10 px-2 text-xs sm:h-11 sm:text-sm"
                        onClick={() => {
                          setError(null);
                          setPassphrase("");
                          setVaultMode(availableGeneratedMethod);
                          setUnlockWithPassphraseFallback(false);
                          setStep("unlock");
                        }}
                        disabled={isUnlocking}
                      >
                        {compactGeneratedUnlockLabel}
                      </Button>
                    ) : null}
                  </div>
                </div>
              </div>
            </div>
          )}

          {step === "method" && (
            <div className="space-y-3">
              <div className="text-center">
                <Icon
                  icon={
                    recommendedQuickMethod === "generated_default_web_prf" ||
                    recommendedQuickMethod === "generated_default_native_passkey_prf"
                      ? Key
                      : Fingerprint
                  }
                  size={36}
                  className="mx-auto mb-3 text-primary"
                />
                <h3 className="text-lg font-semibold sm:text-xl">Enable quicker unlock?</h3>
                <p className="mt-1.5 text-sm text-muted-foreground sm:text-base">
                  You can keep passphrase unlock, or enable{" "}
                  {recommendedQuickMethod === "generated_default_web_prf" ||
                  recommendedQuickMethod === "generated_default_native_passkey_prf"
                    ? "passkey"
                    : "device biometric"}{" "}
                  and still retain passphrase and recovery-key backup.
                </p>
              </div>

              <div className="flex flex-col gap-3 pt-2">
                <Button
                  variant="gradient"
                  effect="glass"
                  size="default"
                  fullWidth
                  className="h-11 text-sm sm:h-12 sm:text-base"
                  disabled={isUnlocking || !pendingUnlockKey || !recommendedQuickMethod}
                  onClick={async () => {
                    if (!pendingUnlockKey || !recommendedQuickMethod) return;
                    setIsUnlocking(true);
                    try {
                      const result = await VaultMethodService.switchMethod({
                        userId: user.uid,
                        currentVaultKey: pendingUnlockKey,
                        displayName: user.displayName || user.email || "Hussh User",
                        targetMethod: recommendedQuickMethod,
                      });
                      setVaultMode(result.method);
                      const finalized = await finalizeUnlock(pendingUnlockKey);
                      if (!finalized) return;
                      toast.success(
                        result.method === "generated_default_web_prf" ||
                        result.method === "generated_default_native_passkey_prf"
                          ? "Passkey unlock enabled."
                          : "Biometric unlock enabled."
                      );
                    } catch (err: any) {
                      console.error("Quick unlock enable failed:", err);
                      toast.error(
                        err?.message || "Couldn't enable quick unlock right now."
                      );
                    } finally {
                      setIsUnlocking(false);
                    }
                  }}
                >
                  {isUnlocking ? (
                    <>
                      <Icon icon={Loader2} size="md" className="mr-2 animate-spin" />
                      Enabling...
                    </>
                  ) : (
                    `Enable ${
                      recommendedQuickMethod === "generated_default_web_prf" ||
                      recommendedQuickMethod === "generated_default_native_passkey_prf"
                        ? "Passkey"
                        : "Biometric"
                    }`
                  )}
                </Button>

                <Button
                  variant="none"
                  effect="fade"
                  size="default"
                  fullWidth
                  className="h-11 whitespace-normal px-4 text-center text-sm leading-snug sm:h-12 sm:text-base"
                  disabled={isUnlocking || !pendingUnlockKey}
                  onClick={async () => {
                    if (!pendingUnlockKey) return;
                    if (recommendedQuickMethod) {
                      try {
                        await VaultMethodPromptLocalService.dismiss(
                          user.uid,
                          recommendedQuickMethod,
                          currentRpId
                        );
                      } catch (dismissError) {
                        console.warn(
                          "[VaultFlow] Failed to persist quick-unlock dismissal:",
                          dismissError
                        );
                      }
                    }
                    await finalizeUnlock(pendingUnlockKey);
                  }}
                >
                  Not now, continue with passphrase
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Recovery Key Dialog (New User) */}
      <Dialog
        open={step === "recovery" && !!recoveryKey}
        onOpenChange={() => {}}
      >
        <DialogContent
          className="z-[520] w-[calc(100%-1rem)] max-h-[calc(100svh-1rem)] overflow-y-auto sm:max-w-md"
          onPointerDownOutside={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <div className="flex items-center gap-2">
              <Icon icon={Key} size="lg" className="text-orange-500" />
              <DialogTitle>Save Your Recovery Key</DialogTitle>
            </div>
            <DialogDescription>
              This is the ONLY way to recover your vault if you forget your
              vault credentials. Store it somewhere safe!
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <Alert className="bg-orange-500/10 border-orange-500/50">
              <Icon icon={AlertCircle} size="sm" className="text-orange-500" />
              <AlertDescription className="text-orange-700 dark:text-orange-300">
                Write this down or save it securely. You cannot recover it
                later!
              </AlertDescription>
            </Alert>

            <div className="p-4 bg-muted rounded-lg border-2 border-dashed">
              <code className="text-lg font-mono font-bold tracking-wide">
                {recoveryKey}
              </code>
            </div>

            <div className="flex flex-col gap-2 sm:flex-row">
              <Button
                variant="none"
                className="flex-1 border border-gray-200 dark:border-gray-700 whitespace-normal"
                onClick={handleCopyRecoveryKey}
              >
                {copied ? (
                  <>
                    <Icon icon={Check} size="sm" className="mr-2 text-green-500" />
                    Copied!
                  </>
                ) : (
                  <>
                    <Icon icon={Copy} size="sm" className="mr-2" />
                    Copy
                  </>
                )}
              </Button>
              <Button
                variant="none"
                className="flex-1 border border-gray-200 dark:border-gray-700 whitespace-normal"
                onClick={async () => {
                  const content = `Hussh Recovery Key\n\n${recoveryKey}\n\nStore this file securely. This is the ONLY way to recover your vault if you lose your vault credentials.`;
                  await downloadTextFile(content, "hushh-recovery-key.txt");
                }}
              >
                <Icon icon={Download} size="sm" className="mr-2" />
                Download
              </Button>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="gradient"
              effect="glass"
              size={ACTION_BUTTON_SIZE}
              className="w-full whitespace-normal text-center leading-snug h-auto min-h-12 px-4"
              onClick={handleRecoveryKeyContinue}
            >
              I've Saved My Recovery Key
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
