{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "two-step-setup",
  "type": "registry:block",
  "title": "Two-step Setup",
  "description": "Turn on authenticator-app 2FA in three calm steps: scan a coded QR or copy the setup key, type the six digits, then copy or download backup codes before you can finish.",
  "categories": [
    "block",
    "Auth"
  ],
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "utils",
    "https://coss.com/ui/r/button.json",
    "https://coss.com/ui/r/checkbox.json",
    "https://coss.com/ui/r/otp-field.json"
  ],
  "files": [
    {
      "path": "registry/devl/two-step-setup.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport { ArrowLeftIcon, CheckIcon, CopyIcon, DownloadIcon, ShieldCheckIcon, SmartphoneIcon, KeyRoundIcon } from \"lucide-react\";\nimport { AnimatePresence, motion, useAnimationControls, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { OTPField, OTPFieldInput, OTPFieldSeparator } from \"@/components/ui/otp-field\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface TwoStepSetupProps {\n  account?: string;\n  issuer?: string;\n  secret?: string;\n  backupCodes?: string[];\n  verify?: (code: string) => Promise<boolean>;\n  onCancel?: () => void;\n  onDone?: () => void;\n  className?: string;\n}\n\ntype Step = 0 | 1 | 2 | 3;\n\nconst ease = [0.23, 1, 0.32, 1] as const;\nconst press = \"transition-[box-shadow,scale,background-color] duration-150 active:scale-[0.97]\";\nconst STEPS = [\"Scan\", \"Verify\", \"Save codes\"];\n\nfunction useMeasuredHeight<T extends HTMLElement>() {\n  const ref = useRef<T>(null);\n  const [height, setHeight] = useState<number | \"auto\">(\"auto\");\n  useLayoutEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(() => setHeight(el.offsetHeight));\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n  return [ref, height] as const;\n}\n\nfunction useCopy() {\n  const [copied, setCopied] = useState<string | null>(null);\n  useEffect(() => {\n    if (!copied) return;\n    const t = setTimeout(() => setCopied(null), 1600);\n    return () => clearTimeout(t);\n  }, [copied]);\n  const copy = async (key: string, text: string) => {\n    try {\n      await navigator.clipboard.writeText(text);\n    } catch {}\n    setCopied(key);\n  };\n  return { copied, copy };\n}\n\nfunction SwapIcon({ on, children, done }: { on: boolean; children: ReactNode; done: ReactNode }) {\n  return (\n    <AnimatePresence initial={false} mode=\"popLayout\">\n      <motion.span\n        animate={{ opacity: 1, scale: 1 }}\n        className=\"flex\"\n        exit={{ opacity: 0, scale: 0.6 }}\n        initial={{ opacity: 0, scale: 0.6 }}\n        key={on ? \"on\" : \"off\"}\n        transition={{ duration: 0.14, ease }}\n      >\n        {on ? done : children}\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n\nfunction QrMock({ seed, size = 25 }: { seed: string; size?: number }) {\n  const cells = useMemo(() => {\n    let h = 2166136261;\n    for (const ch of seed) h = Math.imul(h ^ ch.charCodeAt(0), 16777619);\n    const rand = () => {\n      h ^= h << 13;\n      h ^= h >>> 17;\n      h ^= h << 5;\n      return ((h >>> 0) % 1000) / 1000;\n    };\n    const out: [number, number][] = [];\n    const inFinder = (x: number, y: number) =>\n      (x < 8 && y < 8) || (x >= size - 8 && y < 8) || (x < 8 && y >= size - 8);\n    const mid = Math.floor(size / 2);\n    const inLogo = (x: number, y: number) => Math.abs(x - mid) <= 3 && Math.abs(y - mid) <= 3;\n    for (let y = 0; y < size; y++) {\n      for (let x = 0; x < size; x++) {\n        if (inFinder(x, y) || inLogo(x, y)) continue;\n        if (y === 6 || x === 6) {\n          if ((x + y) % 2 === 0) out.push([x, y]);\n          continue;\n        }\n        if (rand() > 0.52) out.push([x, y]);\n      }\n    }\n    return out;\n  }, [seed, size]);\n  const finder = (x: number, y: number) => (\n    <g key={`${x}-${y}`}>\n      <rect height=\"6\" rx=\"1.6\" width=\"6\" x={x + 0.5} y={y + 0.5} fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1\" />\n      <rect height=\"3\" rx=\"0.8\" width=\"3\" x={x + 2} y={y + 2} fill=\"currentColor\" />\n    </g>\n  );\n  const mid = Math.floor(size / 2);\n  return (\n    <svg aria-hidden className=\"size-full\" shapeRendering=\"geometricPrecision\" viewBox={`-1 -1 ${size + 2} ${size + 2}`}>\n      {cells.map(([x, y]) => (\n        <rect fill=\"currentColor\" height=\"0.86\" key={`${x}.${y}`} rx=\"0.28\" width=\"0.86\" x={x + 0.07} y={y + 0.07} />\n      ))}\n      {finder(0, 0)}\n      {finder(size - 7, 0)}\n      {finder(0, size - 7)}\n      <rect className=\"fill-primary\" height=\"5\" rx=\"1.4\" width=\"5\" x={mid - 2.5} y={mid - 2.5} />\n      <path\n        className=\"stroke-primary-foreground\"\n        d={`M${mid - 1.1} ${mid + 0.1}l0.8 0.8 1.6-1.8`}\n        fill=\"none\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        strokeWidth=\"0.6\"\n      />\n    </svg>\n  );\n}\n\nfunction Rail({ step }: { step: Step }) {\n  const reduce = useReducedMotion();\n  return (\n    <ol className=\"grid grid-cols-3 gap-2\">\n      {STEPS.map((label, i) => {\n        const state = step > i ? \"done\" : step === i ? \"active\" : \"todo\";\n        return (\n          <li aria-current={state === \"active\" ? \"step\" : undefined} className=\"min-w-0\" key={label}>\n            <span className=\"block h-1 overflow-hidden rounded-full bg-muted\">\n              <motion.span\n                animate={{ scaleX: state === \"todo\" ? 0 : 1 }}\n                className=\"block h-full origin-left rounded-full bg-primary\"\n                initial={false}\n                transition={reduce ? { duration: 0 } : { duration: 0.35, ease }}\n              />\n            </span>\n            <span\n              className={cn(\n                \"mt-2 flex items-center gap-1 truncate text-xs transition-colors duration-200\",\n                state === \"todo\" ? \"text-muted-foreground\" : \"font-medium text-foreground\",\n              )}\n            >\n              {state === \"done\" && <CheckIcon className=\"size-3 shrink-0\" strokeWidth={3} />}\n              {label}\n            </span>\n          </li>\n        );\n      })}\n    </ol>\n  );\n}\n\nexport function TwoStepSetup({\n  account = \"jo@quillstack.io\",\n  issuer = \"Quillstack\",\n  secret = \"JBSWY3DPEHPK3PXP\",\n  backupCodes = [\"k7q2-9xmd\", \"p4tn-v8wc\", \"3hzr-m2ke\", \"w9fb-q6ys\", \"a5lc-t7np\", \"m8dj-4rvx\", \"z2ke-h9gq\", \"c6yw-n3fb\", \"r4mx-8tlz\", \"e7pv-2jdc\"],\n  verify = async () => true,\n  onCancel,\n  onDone,\n  className,\n}: TwoStepSetupProps) {\n  const reduce = useReducedMotion();\n  const uid = useId();\n  const [contentRef, height] = useMeasuredHeight<HTMLDivElement>();\n  const [step, setStep] = useState<Step>(0);\n  const [dir, setDir] = useState(1);\n  const [code, setCode] = useState(\"\");\n  const [status, setStatus] = useState<\"idle\" | \"checking\" | \"error\" | \"ok\">(\"idle\");\n  const [saved, setSaved] = useState(false);\n  const [downloaded, setDownloaded] = useState(false);\n  const { copied, copy } = useCopy();\n  const shake = useAnimationControls();\n  const otpRef = useRef<HTMLDivElement>(null);\n\n  const go = (next: Step) => {\n    setDir(next > step ? 1 : -1);\n    if (next === 1) {\n      setCode(\"\");\n      setStatus(\"idle\");\n    }\n    setStep(next);\n  };\n\n  useEffect(() => {\n    if (step !== 1) return;\n    const t = setTimeout(() => otpRef.current?.querySelector(\"input\")?.focus(), 260);\n    return () => clearTimeout(t);\n  }, [step]);\n\n  useEffect(() => {\n    if (status !== \"ok\") return;\n    const t = setTimeout(() => go(2), 650);\n    return () => clearTimeout(t);\n  }, [status]);\n\n  const check = async (value: string) => {\n    setStatus(\"checking\");\n    const ok = await verify(value);\n    if (ok) {\n      setStatus(\"ok\");\n      return;\n    }\n    setStatus(\"error\");\n    setCode(\"\");\n    if (!reduce) shake.start({ x: [0, -7, 7, -4, 4, 0], transition: { duration: 0.34, ease: \"easeOut\" } });\n  };\n\n  // Inputs are disabled while checking, so focus can only return once they're enabled again.\n  useEffect(() => {\n    if (status !== \"error\") return;\n    const t = setTimeout(() => otpRef.current?.querySelector(\"input\")?.focus(), 0);\n    return () => clearTimeout(t);\n  }, [status]);\n\n  const chunks = secret.match(/.{1,4}/g) ?? [secret];\n\n  const download = () => {\n    const text = `${issuer} backup codes for ${account}\\nEach code works once.\\n\\n${backupCodes.join(\"\\n\")}\\n`;\n    const url = URL.createObjectURL(new Blob([text], { type: \"text/plain\" }));\n    const a = document.createElement(\"a\");\n    a.href = url;\n    a.download = `${issuer.toLowerCase()}-backup-codes.txt`;\n    a.click();\n    setTimeout(() => URL.revokeObjectURL(url), 1000);\n    setDownloaded(true);\n  };\n\n  const variants = {\n    enter: (d: number) => (reduce ? { opacity: 0 } : { opacity: 0, x: d * 28 }),\n    center: { opacity: 1, x: 0 },\n    exit: (d: number) => (reduce ? { opacity: 0 } : { opacity: 0, x: d * -28 }),\n  };\n\n  return (\n    <section className={cn(\"mx-auto w-full max-w-[520px] overflow-hidden rounded-2xl border bg-card text-card-foreground shadow-xs/5\", className)}>\n      <motion.div\n        animate={{ height }}\n        initial={false}\n        transition={reduce ? { duration: 0 } : { type: \"spring\", stiffness: 380, damping: 38 }}\n      >\n        <div ref={contentRef}>\n          {step < 3 && (\n            <header className=\"px-5 pt-6 sm:px-7\">\n              <div className=\"flex items-start gap-3\">\n                <span className=\"flex size-9 shrink-0 items-center justify-center rounded-xl border bg-muted\">\n                  <ShieldCheckIcon className=\"size-4.5\" />\n                </span>\n                <div className=\"min-w-0\">\n                  <h2 className=\"text-balance font-semibold text-base tracking-tight\">Turn on two-step verification</h2>\n                  <p className=\"mt-0.5 text-pretty text-muted-foreground text-sm\">\n                    Add a code from your phone to every new sign-in on <span className=\"text-foreground\">{account}</span>.\n                  </p>\n                </div>\n              </div>\n              <div className=\"mt-5\">\n                <Rail step={step} />\n              </div>\n            </header>\n          )}\n\n          <div className=\"relative overflow-hidden\">\n            <AnimatePresence custom={dir} initial={false} mode=\"popLayout\">\n              {step === 0 && (\n                <motion.div\n                  animate=\"center\"\n                  className=\"px-5 pt-6 pb-6 sm:px-7\"\n                  custom={dir}\n                  exit=\"exit\"\n                  initial=\"enter\"\n                  key=\"scan\"\n                  transition={{ duration: 0.24, ease }}\n                  variants={variants}\n                >\n                  <div className=\"flex flex-col items-center gap-5 sm:flex-row sm:items-start sm:gap-6\">\n                    <div className=\"size-40 shrink-0 rounded-xl border bg-background p-2.5 text-foreground shadow-xs/5\">\n                      <QrMock seed={secret} />\n                    </div>\n                    <div className=\"w-full min-w-0\">\n                      <ol className=\"space-y-2.5 text-sm\">\n                        {[\"Open your authenticator app.\", `Scan the code to add ${issuer}.`].map((text, i) => (\n                          <li className=\"flex items-start gap-2.5\" key={text}>\n                            <span className=\"flex size-5 shrink-0 items-center justify-center rounded-full bg-muted font-medium text-[0.6875rem] tabular-nums\">\n                              {i + 1}\n                            </span>\n                            <span className=\"text-pretty pt-px\">{text}</span>\n                          </li>\n                        ))}\n                      </ol>\n                      <div className=\"mt-5 rounded-xl border bg-muted/40 p-3\">\n                        <p className=\"text-muted-foreground text-xs\">Can't scan? Enter this setup key instead.</p>\n                        <div className=\"mt-2 flex items-center gap-2\">\n                          <code className=\"min-w-0 flex-1 font-mono text-[0.8125rem] tracking-wide\">\n                            {chunks.map((c, i) => (\n                              <span className={cn(\"inline-block\", i > 0 && \"ms-1.5\")} key={i}>\n                                {c}\n                              </span>\n                            ))}\n                          </code>\n                          <Button\n                            aria-label={copied === \"secret\" ? \"Setup key copied\" : \"Copy setup key\"}\n                            className={press}\n                            onClick={() => copy(\"secret\", secret)}\n                            size=\"icon-sm\"\n                            variant=\"outline\"\n                          >\n                            <SwapIcon done={<CheckIcon className=\"text-success-foreground\" />} on={copied === \"secret\"}>\n                              <CopyIcon />\n                            </SwapIcon>\n                          </Button>\n                        </div>\n                      </div>\n                    </div>\n                  </div>\n                </motion.div>\n              )}\n\n              {step === 1 && (\n                <motion.div\n                  animate=\"center\"\n                  className=\"px-5 pt-6 pb-6 sm:px-7\"\n                  custom={dir}\n                  exit=\"exit\"\n                  initial=\"enter\"\n                  key=\"verify\"\n                  transition={{ duration: 0.24, ease }}\n                  variants={variants}\n                >\n                  <label className=\"block font-medium text-sm\" htmlFor={`${uid}-otp`}>\n                    Enter the 6-digit code from your app\n                  </label>\n                  <p className=\"mt-1 text-muted-foreground text-sm\">It changes every 30 seconds, so use the one on screen now.</p>\n                  <motion.div animate={shake} className=\"mt-5 flex justify-center sm:justify-start\" ref={otpRef}>\n                    <OTPField\n                      aria-describedby={`${uid}-otp-msg`}\n                      className={cn(status === \"ok\" && \"has-disabled:opacity-100\")}\n                      disabled={status === \"checking\" || status === \"ok\"}\n                      id={`${uid}-otp`}\n                      length={6}\n                      onValueChange={(v) => {\n                        setCode(v);\n                        if (status === \"error\") setStatus(\"idle\");\n                      }}\n                      onValueComplete={check}\n                      size=\"lg\"\n                      value={code}\n                    >\n                      {Array.from({ length: 6 }, (_, i) => (\n                        <span className=\"contents\" key={i}>\n                          {i === 3 && <OTPFieldSeparator />}\n                          <OTPFieldInput\n                            aria-invalid={status === \"error\" ? true : undefined}\n                            aria-label={`Digit ${i + 1}`}\n                            className={cn(\n                              \"size-11 text-lg sm:size-11 sm:text-lg transition-[border-color,box-shadow,background-color] duration-200\",\n                              status === \"ok\" && \"border-success/60 bg-success/6 selection:bg-transparent\",\n                            )}\n                          />\n                        </span>\n                      ))}\n                    </OTPField>\n                  </motion.div>\n                  <p\n                    aria-live=\"polite\"\n                    className={cn(\n                      \"mt-3 flex min-h-5 items-center justify-center gap-1.5 text-xs sm:justify-start\",\n                      status === \"error\" ? \"text-destructive-foreground\" : status === \"ok\" ? \"text-success-foreground\" : \"text-muted-foreground\",\n                    )}\n                    id={`${uid}-otp-msg`}\n                  >\n                    {status === \"checking\" && \"Checking…\"}\n                    {status === \"error\" && \"That code didn't match. Try the newest one from your app.\"}\n                    {status === \"ok\" && (\n                      <>\n                        <CheckIcon className=\"size-3.5\" strokeWidth={3} />\n                        Code accepted\n                      </>\n                    )}\n                  </p>\n                </motion.div>\n              )}\n\n              {step === 2 && (\n                <motion.div\n                  animate=\"center\"\n                  className=\"px-5 pt-6 pb-6 sm:px-7\"\n                  custom={dir}\n                  exit=\"exit\"\n                  initial=\"enter\"\n                  key=\"codes\"\n                  transition={{ duration: 0.24, ease }}\n                  variants={variants}\n                >\n                  <p className=\"font-medium text-sm\">Save your backup codes</p>\n                  <p className=\"mt-1 text-pretty text-muted-foreground text-sm\">\n                    If you lose your phone, each code gets you in once. We won't show them again.\n                  </p>\n                  <ol className=\"mt-4 grid grid-cols-2 gap-x-6 gap-y-2 rounded-xl border bg-muted/40 px-4 py-3.5 font-mono text-[0.8125rem]\">\n                    {backupCodes.map((c, i) => (\n                      <motion.li\n                        animate={{ opacity: 1 }}\n                        className=\"flex items-baseline gap-2.5\"\n                        initial={reduce ? false : { opacity: 0 }}\n                        key={c}\n                        transition={{ duration: 0.2, delay: 0.1 + i * 0.025 }}\n                      >\n                        <span className=\"w-4 text-end text-muted-foreground/70 text-xs tabular-nums\">{i + 1}</span>\n                        <span className=\"tracking-wide\">{c}</span>\n                      </motion.li>\n                    ))}\n                  </ol>\n                  <div className=\"mt-3 grid grid-cols-2 gap-2\">\n                    <Button className={press} onClick={() => copy(\"codes\", backupCodes.join(\"\\n\"))} variant=\"outline\">\n                      <SwapIcon done={<CheckIcon className=\"text-success-foreground\" />} on={copied === \"codes\"}>\n                        <CopyIcon />\n                      </SwapIcon>\n                      {copied === \"codes\" ? \"Copied\" : \"Copy all\"}\n                    </Button>\n                    <Button className={press} onClick={download} variant=\"outline\">\n                      <SwapIcon done={<CheckIcon className=\"text-success-foreground\" />} on={downloaded}>\n                        <DownloadIcon />\n                      </SwapIcon>\n                      Download .txt\n                    </Button>\n                  </div>\n                  <label className=\"mt-5 flex cursor-pointer items-center gap-2.5 text-sm\" htmlFor={`${uid}-saved`}>\n                    <Checkbox checked={saved} id={`${uid}-saved`} onCheckedChange={(v) => setSaved(Boolean(v))} />\n                    I've stored these somewhere safe\n                  </label>\n                </motion.div>\n              )}\n\n              {step === 3 && (\n                <motion.div\n                  animate={{ opacity: 1, y: 0 }}\n                  className=\"px-5 py-9 text-center sm:px-7\"\n                  exit={{ opacity: 0 }}\n                  initial={reduce ? { opacity: 0 } : { opacity: 0, y: 10 }}\n                  key=\"done\"\n                  transition={{ duration: 0.26, ease }}\n                >\n                  <motion.span\n                    animate={{ scale: 1, opacity: 1 }}\n                    className=\"mx-auto flex size-14 items-center justify-center rounded-2xl bg-success/12 text-success-foreground\"\n                    initial={reduce ? false : { scale: 0.8, opacity: 0 }}\n                    transition={{ type: \"spring\", stiffness: 420, damping: 22, delay: 0.08 }}\n                  >\n                    <ShieldCheckIcon className=\"size-7\" />\n                  </motion.span>\n                  <h2 className=\"mt-5 font-semibold text-lg tracking-tight\">Two-step verification is on</h2>\n                  <p className=\"mx-auto mt-1 max-w-[36ch] text-pretty text-muted-foreground text-sm\">\n                    Next time you sign in on a new device, we'll ask for a code from your app.\n                  </p>\n                  <dl className=\"mx-auto mt-6 max-w-[320px] divide-y rounded-xl border text-left text-sm\">\n                    <div className=\"flex items-center justify-between gap-3 px-3.5 py-2.5\">\n                      <dt className=\"flex items-center gap-2 text-muted-foreground\">\n                        <SmartphoneIcon className=\"size-4\" />\n                        Authenticator\n                      </dt>\n                      <dd>Added just now</dd>\n                    </div>\n                    <div className=\"flex items-center justify-between gap-3 px-3.5 py-2.5\">\n                      <dt className=\"flex items-center gap-2 text-muted-foreground\">\n                        <KeyRoundIcon className=\"size-4\" />\n                        Backup codes\n                      </dt>\n                      <dd className=\"tabular-nums\">{backupCodes.length} unused</dd>\n                    </div>\n                  </dl>\n                  <Button className={cn(\"mt-6\", press)} onClick={onDone}>\n                    Back to security settings\n                  </Button>\n                </motion.div>\n              )}\n            </AnimatePresence>\n          </div>\n\n          {step < 3 && (\n            <footer className=\"flex items-center justify-between gap-2 border-t bg-muted/40 px-5 py-3 sm:px-7\">\n              {step === 0 ? (\n                <Button className={press} onClick={onCancel} variant=\"ghost\">\n                  Cancel\n                </Button>\n              ) : (\n                <Button\n                  className={press}\n                  disabled={status === \"checking\" || (step === 1 && status === \"ok\")}\n                  onClick={() => go((step - 1) as Step)}\n                  variant=\"ghost\"\n                >\n                  <ArrowLeftIcon />\n                  Back\n                </Button>\n              )}\n              <span className=\"text-muted-foreground text-xs tabular-nums\">\n                Step {step + 1} of {STEPS.length}\n              </span>\n              {step === 0 && (\n                <Button className={press} onClick={() => go(1)}>\n                  I've scanned it\n                </Button>\n              )}\n              {step === 1 && (\n                <Button\n                  className={press}\n                  disabled={code.length < 6 || status === \"ok\"}\n                  loading={status === \"checking\"}\n                  onClick={() => check(code)}\n                >\n                  Verify\n                </Button>\n              )}\n              {step === 2 && (\n                <Button className={press} disabled={!saved} onClick={() => go(3)}>\n                  Finish setup\n                </Button>\n              )}\n            </footer>\n          )}\n        </div>\n      </motion.div>\n    </section>\n  );\n}\n"
    }
  ]
}