{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "timezone-mismatch",
  "title": "Timezone Mismatch",
  "description": "Banner shown when the device zone differs from the account zone: both clocks side by side, a one-time choice to use the device zone, a confirmation that keeps focus, remembered per pair of zones, comparing real clock changes so briefly drifting zones still count.",
  "dependencies": [
    "lucide-react",
    "@date-fns/tz",
    "@number-flow/react",
    "motion"
  ],
  "files": [
    {
      "path": "registry/default/timezone-mismatch/timezone-mismatch.tsx",
      "content": "\"use client\"\r\n\r\n// Bollard UI — timezone-mismatch · MIT licence · https://bollard-ui.vercel.app/components/timezone-mismatch\r\n\r\nimport * as React from \"react\"\r\nimport { tzOffset, tzScan } from \"@date-fns/tz\"\r\nimport NumberFlow from \"@number-flow/react\"\r\nimport { Check, Plane } from \"lucide-react\"\r\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\"\r\n\r\nimport { cn } from \"@/lib/utils\"\r\n\r\n/** Banner layout shared by every Bollard UI banner: one height, padding, icon size and action style. */\r\nconst bar = \"flex min-h-11 flex-wrap items-center gap-x-3 gap-y-1.5 px-3 py-1.5 text-sm\"\r\nconst action =\r\n  \"inline-flex h-8 shrink-0 items-center justify-center gap-1.5 rounded-md px-3 text-sm font-medium whitespace-nowrap outline-none transition-colors focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-60\"\r\n/** Banner tones, identical across Bollard UI banners. */\r\nconst tones = {\r\n  info: {\r\n    surface: \"border-sky-500/30 bg-background bg-linear-to-r from-sky-500/10 to-sky-500/10 text-sky-950 dark:text-sky-50\",\r\n    icon: \"text-sky-600 dark:text-sky-400\",\r\n    muted: \"text-sky-900/75 dark:text-sky-100/75\",\r\n    solid: \"bg-sky-700 text-white hover:bg-sky-800 dark:bg-sky-400 dark:text-sky-950 dark:hover:bg-sky-300\",\r\n    outline: \"border border-sky-700/25 hover:bg-sky-500/15 dark:border-sky-300/25\",\r\n  },\r\n} as const\r\n\r\nconst DAY = 86_400_000\r\n\r\n/** Offset from UTC in minutes for `timeZone` at `at` (Asia/Kolkata → 330). 0 for a zone the runtime doesn't know. */\r\nexport function zoneOffset(timeZone: string, at: number) {\r\n  try {\r\n    const offset = tzOffset(timeZone, new Date(at))\r\n    return Number.isFinite(offset) ? offset : 0\r\n  } catch {\r\n    return 0\r\n  }\r\n}\r\n\r\n/** Whether the runtime's tz database knows `timeZone`. */\r\nexport const isKnownZone = (timeZone: string) => {\r\n  try { return Number.isFinite(tzOffset(timeZone, new Date(0))) } catch { return false }\r\n}\r\n\r\n/**\r\n * Whether two zones show the same wall clock now and through the coming\r\n * year. Every real clock change is compared (from the tz database via\r\n * `tzScan`), not a monthly sample, so Jerusalem and Athens, which only part\r\n * ways for a couple of days each spring, count as different. Changes on the\r\n * same day to the same offset (Havana and New York) count as the same, so\r\n * nobody gets asked to \"switch\" over a few hours in the middle of the night.\r\n */\r\nexport function sameClock(a: string, b: string, at: number) {\r\n  if (a === b) return true\r\n  if (!isKnownZone(a) || !isKnownZone(b)) return false\r\n  if (zoneOffset(a, at) !== zoneOffset(b, at)) return false\r\n  const range = { start: new Date(at), end: new Date(at + 400 * DAY) }\r\n  const changesA = tzScan(a, range)\r\n  const changesB = tzScan(b, range)\r\n  return (\r\n    changesA.length === changesB.length &&\r\n    changesA.every(\r\n      (change, i) => change.offset === changesB[i].offset && Math.abs(change.date.getTime() - changesB[i].date.getTime()) < DAY,\r\n    )\r\n  )\r\n}\r\n\r\n/** \"5 h 30 min ahead\", \"3 h behind\". */\r\nexport function formatOffsetGap(minutes: number) {\r\n  const abs = Math.abs(minutes)\r\n  const parts = [Math.floor(abs / 60) && `${Math.floor(abs / 60)} h`, abs % 60 && `${abs % 60} min`].filter(Boolean)\r\n  return `${parts.join(\" \")} ${minutes > 0 ? \"ahead\" : \"behind\"}`\r\n}\r\n\r\n/** \"Europe/London\" → \"London\", \"America/Argentina/Buenos_Aires\" → \"Buenos Aires\". */\r\nexport const zoneCity = (timeZone: string) => timeZone.split(\"/\").pop()!.replace(/_/g, \" \")\r\n\r\nexport interface TimezoneMismatchProps extends Omit<React.ComponentProps<\"div\">, \"children\"> {\r\n  /** The time zone saved on the account; times are shown in it today. */\r\n  accountTimeZone: string\r\n  /** Override the detected device zone (tests, demos, or a zone from your own location service). */\r\n  deviceTimeZone?: string\r\n  /** Switch the account (or this session) to the device zone. */\r\n  onUseDeviceZone: (timeZone: string) => void\r\n  /** Called when the user keeps the account zone. */\r\n  onKeepAccountZone?: () => void\r\n  /** localStorage key that remembers the answer per account → device zone pair. `null` disables it. */\r\n  storageKey?: string | null\r\n  /** Templates: `{device}`, `{account}` (city names) and `{gap}` (\"5 h 30 min ahead\") are filled in. */\r\n  message?: string\r\n  /** Label of the device clock. */\r\n  deviceLabel?: string\r\n  /** Label of the account clock. */\r\n  accountLabel?: string\r\n  /** Label of the use-device-zone button. */\r\n  useDeviceLabel?: string\r\n  /** Label of the keep-account-zone button. */\r\n  keepAccountLabel?: string\r\n  /** Shown for a moment after the answer. `{zone}` is the city now used. */\r\n  doneText?: string\r\n  /** Accessible name of the banner. */\r\n  regionLabel?: string\r\n}\r\n\r\nconst fill = (template: string, values: Record<string, string>) =>\r\n  template.replace(/\\{(\\w+)\\}/g, (match, key: string) => values[key] ?? match)\r\n\r\nfunction readChoices(key: string): Record<string, string> {\r\n  try {\r\n    const value: unknown = JSON.parse(localStorage.getItem(key) ?? \"{}\")\r\n    if (!value || typeof value !== \"object\" || Array.isArray(value)) return {}\r\n    return Object.fromEntries(Object.entries(value).filter((entry): entry is [string, \"device\" | \"account\"] => entry[1] === \"device\" || entry[1] === \"account\"))\r\n  } catch {\r\n    return {}\r\n  }\r\n}\r\n\r\n/** Hour, minute and day period of `now` in `timeZone`, in the reader's own 12/24-hour habit. */\r\nfunction clockParts(now: number, timeZone: string) {\r\n  const parts = new Intl.DateTimeFormat(undefined, { timeZone, hour: \"numeric\", minute: \"2-digit\" }).formatToParts(now)\r\n  const get = (type: string) => parts.find((part) => part.type === type)?.value\r\n  return { hour: Number(get(\"hour\")), minute: Number(get(\"minute\")), period: get(\"dayPeriod\") }\r\n}\r\n\r\n/**\r\n * Stops travellers misreading every time in the app by hours. When the device\r\n * is in a different zone from the account, it shows both clocks side by side\r\n * (ticking digits, so they read as live clocks rather than labels) and asks\r\n * once which to use. The answer morphs the banner into a one-line confirmation\r\n * that keeps focus, then gets out of the way and is remembered for this pair of\r\n * zones, so it stays quiet for the rest of the trip and asks again on the next\r\n * one. Zones that tell the same time all year never trigger it.\r\n */\r\nexport function TimezoneMismatch({\r\n  accountTimeZone,\r\n  deviceTimeZone,\r\n  onUseDeviceZone,\r\n  onKeepAccountZone,\r\n  storageKey = \"bollard-ui:timezone-choice\",\r\n  message = \"You're in {device} time, {gap} of your account's {account} time.\",\r\n  deviceLabel = \"Device\",\r\n  accountLabel = \"Account\",\r\n  useDeviceLabel = \"Use device zone\",\r\n  keepAccountLabel = \"Keep account zone\",\r\n  doneText = \"Times now show in {zone} time.\",\r\n  regionLabel = \"Time zone mismatch\",\r\n  className,\r\n  ...props\r\n}: TimezoneMismatchProps) {\r\n  const [device, setDevice] = React.useState(deviceTimeZone)\r\n  const [now, setNow] = React.useState<number>()\r\n  const [answered, setAnswered] = React.useState(true)\r\n  const [done, setDone] = React.useState<string | null>(null)\r\n  const doneRef = React.useRef<HTMLParagraphElement>(null)\r\n  const reduceMotion = useReducedMotion()\r\n  const pair = `${accountTimeZone}→${device}`\r\n\r\n  React.useEffect(() => {\r\n    setDevice(deviceTimeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone)\r\n    setNow(Date.now())\r\n    const id = setInterval(() => setNow(Date.now()), 15_000)\r\n    return () => clearInterval(id)\r\n  }, [deviceTimeZone])\r\n\r\n  React.useEffect(() => {\r\n    setAnswered(device === undefined || (storageKey !== null && pair in readChoices(storageKey)))\r\n  }, [device, pair, storageKey])\r\n\r\n  // The confirmation takes focus (the buttons that had it are gone) and steps aside once focus moves on.\r\n  const focusOnMount = React.useCallback((node: HTMLParagraphElement | null) => {\r\n    doneRef.current = node\r\n    node?.focus()\r\n  }, [])\r\n  React.useEffect(() => {\r\n    if (!done) return\r\n    const id = setTimeout(() => document.activeElement !== doneRef.current && setDone(null), 4000)\r\n    return () => clearTimeout(id)\r\n  }, [done])\r\n\r\n  const choose = (choice: \"device\" | \"account\") => {\r\n    if (storageKey !== null) {\r\n      try { localStorage.setItem(storageKey, JSON.stringify({ ...readChoices(storageKey), [pair]: choice })) } catch {\r\n        // The choice still applies for this visit when storage is unavailable.\r\n      }\r\n    }\r\n    setAnswered(true)\r\n    setDone(zoneCity(choice === \"device\" ? device! : accountTimeZone))\r\n    if (choice === \"device\") onUseDeviceZone(device!)\r\n    else onKeepAccountZone?.()\r\n  }\r\n\r\n  const mismatch =\r\n    !answered &&\r\n    device !== undefined &&\r\n    now !== undefined &&\r\n    isKnownZone(device) &&\r\n    isKnownZone(accountTimeZone) &&\r\n    !sameClock(device, accountTimeZone, now)\r\n  const tone = tones.info\r\n  const spring = reduceMotion ? { duration: 0.12 } : { type: \"spring\" as const, stiffness: 380, damping: 36 }\r\n\r\n  const clock = (label: string, timeZone: string) => {\r\n    const day = new Intl.DateTimeFormat(\"en-CA\", { timeZone, dateStyle: \"short\" }).format(now)\r\n    const deviceDay = new Intl.DateTimeFormat(\"en-CA\", { timeZone: device, dateStyle: \"short\" }).format(now)\r\n    const { hour, minute, period } = clockParts(now!, timeZone)\r\n    return (\r\n      <div className=\"min-w-0 flex-1 rounded-md border border-sky-700/15 bg-background/70 px-3 py-2 dark:border-sky-300/15\">\r\n        <p className={cn(\"text-xs break-words\", tone.muted)}>\r\n          {label} · {zoneCity(timeZone)}\r\n        </p>\r\n        <p\r\n          className=\"text-lg font-semibold tabular-nums\"\r\n        >\r\n          <span className=\"sr-only\">{new Intl.DateTimeFormat(undefined, { timeZone, hour: \"numeric\", minute: \"2-digit\" }).format(now)}</span>\r\n          <span aria-hidden className=\"inline-flex items-baseline\">\r\n            <NumberFlow value={hour} animated={!reduceMotion} trend={0} />\r\n            <span>:</span>\r\n            <NumberFlow value={minute} format={{ minimumIntegerDigits: 2 }} animated={!reduceMotion} trend={0} digits={{ 1: { max: 5 } }} />\r\n            {period && <span className=\"ml-1 text-sm font-medium\">{period}</span>}\r\n          </span>\r\n          {day !== deviceDay && (\r\n            <span className={cn(\"ml-1.5 text-xs font-normal\", tone.muted)}>\r\n              {new Intl.DateTimeFormat(undefined, { timeZone, weekday: \"short\" }).format(now)}\r\n            </span>\r\n          )}\r\n        </p>\r\n      </div>\r\n    )\r\n  }\r\n\r\n  return (\r\n    <AnimatePresence initial={false}>\r\n      {(mismatch || done) && (\r\n        <motion.div\r\n          key=\"timezone-mismatch\"\r\n          initial={reduceMotion ? { opacity: 0 } : { opacity: 0, height: 0 }}\r\n          animate={{ opacity: 1, height: \"auto\" }}\r\n          exit={reduceMotion ? { opacity: 0 } : { opacity: 0, height: 0 }}\r\n          transition={spring}\r\n          className=\"overflow-hidden\"\r\n        >\r\n          <div\r\n            data-slot=\"timezone-mismatch\"\r\n            data-state={done ? \"done\" : \"asking\"}\r\n            role=\"region\"\r\n            aria-label={regionLabel}\r\n            className={cn(\"overflow-hidden rounded-lg border\", tone.surface, className)}\r\n            {...props}\r\n          >\r\n            <AnimatePresence mode=\"wait\" initial={false}>\r\n              {done ? (\r\n                <motion.p\r\n                  key=\"done\"\r\n                  ref={focusOnMount}\r\n                  tabIndex={-1}\r\n                  role=\"status\"\r\n                  onBlur={() => setDone(null)}\r\n                  initial={{ opacity: 0, y: reduceMotion ? 0 : 6 }}\r\n                  animate={{ opacity: 1, y: 0 }}\r\n                  transition={spring}\r\n                  className={cn(bar, \"font-medium outline-none\")}\r\n                >\r\n                  <Check aria-hidden className={cn(\"size-4 shrink-0\", tone.icon)} />\r\n                  {fill(doneText, { zone: done })}\r\n                </motion.p>\r\n              ) : (\r\n                mismatch && (\r\n                  <motion.div key=\"asking\" exit={{ opacity: 0, transition: { duration: 0.12 } }}>\r\n                    <div className={cn(bar, \"items-start py-2\")}>\r\n                      <Plane aria-hidden className={cn(\"mt-0.5 size-4 shrink-0\", tone.icon)} />\r\n                      <p className=\"min-w-0 flex-1 font-medium\" aria-live=\"polite\">\r\n                        {fill(message, {\r\n                          device: zoneCity(device!),\r\n                          account: zoneCity(accountTimeZone),\r\n                          gap: formatOffsetGap(zoneOffset(device!, now!) - zoneOffset(accountTimeZone, now!)),\r\n                        })}\r\n                      </p>\r\n                    </div>\r\n                    <div className=\"flex gap-2 px-3\">\r\n                      {clock(deviceLabel, device!)}\r\n                      {clock(accountLabel, accountTimeZone)}\r\n                    </div>\r\n                    <div className=\"flex flex-wrap justify-end gap-2 px-3 py-2\">\r\n                      <button type=\"button\" onClick={() => choose(\"account\")} className={cn(action, tone.outline)}>\r\n                        {keepAccountLabel}\r\n                      </button>\r\n                      <button type=\"button\" onClick={() => choose(\"device\")} className={cn(action, tone.solid)}>\r\n                        {useDeviceLabel}\r\n                      </button>\r\n                    </div>\r\n                  </motion.div>\r\n                )\r\n              )}\r\n            </AnimatePresence>\r\n          </div>\r\n        </motion.div>\r\n      )}\r\n    </AnimatePresence>\r\n  )\r\n}\r\n",
      "type": "registry:ui",
      "target": "@ui/timezone-mismatch.tsx"
    }
  ],
  "meta": {
    "stops": "Misread every time by hours while travelling",
    "mistakes": [
      "wrong time zone while travelling",
      "device timezone differs from account",
      "times off by hours",
      "ist vs local time confusion",
      "booking time wrong zone"
    ],
    "aliases": [
      "time zone",
      "timezone",
      "device time",
      "account time zone",
      "travel",
      "ist",
      "tz database",
      "clock",
      "settings"
    ],
    "flows": [
      "scheduling",
      "account-settings"
    ],
    "fields": [
      "datetime"
    ],
    "summary": "When the device's time zone differs from the account's, shows both clocks and asks once which to use, so times aren't misread while travelling.",
    "catches": [
      "Device and account zones that differ now or at any clock change in the coming year",
      "Zones that drift apart only for a few days (e.g. Jerusalem and Athens)",
      "Unknown zones the runtime can't resolve",
      "The user's choice, remembered per pair of zones"
    ],
    "limits": [
      "Choice is stored in localStorage on this device",
      "Device zone comes from the browser and can be wrong behind some VPNs or settings"
    ],
    "a11y": [
      "Banner is a region with an aria-label; result is role=status and receives focus",
      "Message in a polite live region",
      "Animations respect reduced motion"
    ],
    "usage": "import { TimezoneMismatch } from \"@/components/ui/timezone-mismatch\"",
    "runtimeDependencies": [
      "lucide-react",
      "@date-fns/tz",
      "@number-flow/react",
      "motion"
    ],
    "zeroRuntimeDependencies": false
  },
  "docs": "https://bollard-ui.vercel.app/components/timezone-mismatch",
  "categories": [
    "Context and awareness"
  ],
  "type": "registry:ui"
}
