{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"promo-bar","type":"registry:ui","title":"Promo bar","description":"Announcement bar on a warm drifting ember surface with a short phone text, a live countdown and a dismissal that never flashes back on reload.","dependencies":["lucide-react","motion"],"registryDependencies":["utils"],"files":[{"path":"registry/items/promo-bar/promo-bar.tsx","type":"registry:ui","target":"components/facade/promo-bar.tsx","content":"\"use client\";\n\nimport * as React from \"react\";\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { X } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\n/* ---------- Ember surface engine (same as ember-gradient, inlined so this file stays self-contained) ---------- */\n\nexport type EmberPreset = \"ember\" | \"moss\" | \"dusk\";\n\nexport interface EmberPalette {\n  /** Solid base under the fields. Keep it dark so white text stays readable. */\n  base: string;\n  /** Up to five field colors, placed top left, bottom left, center, bottom right, top right. */\n  fields: string[];\n}\n\n/** A preset name, a palette object, or an array whose first entry is the base. */\nexport type EmberPaletteInput = EmberPreset | EmberPalette | string[];\n\nexport const emberPalettes: Record<EmberPreset, EmberPalette> = {\n  ember: { base: \"#17130F\", fields: [\"#895735\", \"#193D25\", \"#444A29\", \"#943C27\", \"#895735\"] },\n  moss: { base: \"#10140F\", fields: [\"#5A6B32\", \"#1F4A2C\", \"#3E4A2A\", \"#7A5A2E\", \"#26402F\"] },\n  dusk: { base: \"#16121A\", fields: [\"#7A3F2F\", \"#2C2F4A\", \"#4A2E44\", \"#9A5A33\", \"#3A2A3E\"] },\n};\n\nfunction resolvePalette(input: EmberPaletteInput): EmberPalette {\n  if (typeof input === \"string\") return emberPalettes[input] ?? emberPalettes.ember;\n  if (Array.isArray(input)) return { base: input[0] ?? emberPalettes.ember.base, fields: input.slice(1) };\n  return input;\n}\n\n/* Field placement. Sizes use container units: wide surfaces get wide bands\n   (like a 52px bar), tall ones get round pools instead of vertical stripes.\n   `w` and `h` are percent of the surface, `cap` limits height to cap x width,\n   `push` moves a field past its anchored edge by that share of its own size. */\ntype Field = {\n  x: \"left\" | \"right\" | \"center\";\n  y: \"top\" | \"bottom\" | \"center\";\n  w: number;\n  h: number;\n  cap: number;\n  push: [number, number];\n  opacity: number;\n  drift: \"a\" | \"b\" | \"c\";\n  factor: number;\n  delay: number;\n};\n\nconst FIELDS: Field[] = [\n  { x: \"left\", y: \"top\", w: 70, h: 100, cap: 1.1, push: [0.25, 0.35], opacity: 0.85, drift: \"a\", factor: 1, delay: 0 },\n  { x: \"left\", y: \"bottom\", w: 62, h: 95, cap: 1.1, push: [0.25, 0.3], opacity: 0.9, drift: \"b\", factor: 1.27, delay: -0.3 },\n  { x: \"center\", y: \"center\", w: 52, h: 84, cap: 1, push: [0, 0], opacity: 0.4, drift: \"c\", factor: 0.86, delay: -0.55 },\n  { x: \"right\", y: \"bottom\", w: 72, h: 100, cap: 1.1, push: [0.22, 0.3], opacity: 0.9, drift: \"b\", factor: 1.13, delay: -0.7 },\n  { x: \"right\", y: \"top\", w: 50, h: 84, cap: 1, push: [0.2, 0.4], opacity: 0.5, drift: \"a\", factor: 0.94, delay: -0.2 },\n];\n\nfunction fieldBox(f: Field): React.CSSProperties {\n  const width = `max(${f.w}cqw, ${f.w * 0.55}cqh)`;\n  const height = `min(${f.h}cqh, max(${f.w * f.cap}cqw, ${f.w * 0.55 * f.cap}cqh))`;\n  const box: React.CSSProperties = { width, height };\n  if (f.x === \"center\") box.left = `calc(50% - ${width} / 2)`;\n  else box[f.x] = `calc(${width} * ${-f.push[0]})`;\n  if (f.y === \"center\") box.top = `calc(50% - ${height} / 2)`;\n  else box[f.y] = `calc(${height} * ${-f.push[1]})`;\n  return box;\n}\n\n/* Transform and opacity only, so the drift runs on the compositor. The fields\n   are soft radial gradients, no blur filter is repainted per frame. */\nconst EMBER_CSS = `\n@keyframes facade-ember-a{0%{transform:translate3d(0,0,0) scale(1);opacity:1}50%{transform:translate3d(10%,14%,0) scale(1.08);opacity:.78}100%{transform:translate3d(-6%,6%,0) scale(.95);opacity:1}}\n@keyframes facade-ember-b{0%{transform:translate3d(0,0,0) scale(1.04)}50%{transform:translate3d(-12%,-6%,0) scale(.94)}100%{transform:translate3d(6%,-12%,0) scale(1.1)}}\n@keyframes facade-ember-c{0%{transform:translate3d(0,0,0) scale(.95);opacity:.6}50%{transform:translate3d(14%,-10%,0) scale(1.12);opacity:1}100%{transform:translate3d(-10%,8%,0) scale(1);opacity:.7}}\n.facade-ember-field{position:absolute;border-radius:9999px;will-change:transform,opacity;animation-timing-function:ease-in-out;animation-iteration-count:infinite;animation-direction:alternate}\n.facade-ember[data-paused] .facade-ember-field{animation-play-state:paused}\n.facade-ember-stack{position:absolute;inset:0;transition-property:opacity;transition-timing-function:ease-in-out}\n@media (prefers-reduced-motion:reduce){.facade-ember-field{animation:none!important}.facade-ember-stack{transition:none!important}}\n`;\n\nconst GRAIN =\n  \"url(\\\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\\\")\";\n\ninterface EmberLayerProps {\n  palette: EmberPaletteInput;\n  cycle?: boolean;\n  cyclePalettes?: EmberPaletteInput[];\n  cycleDuration?: number;\n  speed?: number;\n  grain?: boolean | number;\n  intensity?: number;\n  /** Pauses drift and cycling, e.g. while the surface is off screen. */\n  paused?: boolean;\n}\n\nfunction EmberLayer({\n  palette,\n  cycle = false,\n  cyclePalettes,\n  cycleDuration = 30,\n  speed = 26,\n  grain = true,\n  intensity = 1,\n  paused = false,\n}: EmberLayerProps) {\n  const reduce = useReducedMotion();\n  const first = resolvePalette(palette);\n  const others = (cyclePalettes ?? (Object.keys(emberPalettes) as EmberPreset[]).filter((k) => k !== palette)).map(\n    resolvePalette,\n  );\n  const stacks = cycle ? [first, ...others] : [first];\n  const [active, setActive] = React.useState(0);\n  const running = cycle && !reduce && !paused && stacks.length > 1;\n\n  React.useEffect(() => {\n    if (!running) return;\n    const id = window.setInterval(() => setActive((i) => (i + 1) % stacks.length), cycleDuration * 1000);\n    return () => window.clearInterval(id);\n  }, [running, stacks.length, cycleDuration]);\n\n  const fade = Math.min(8, cycleDuration / 3);\n  const grainOpacity = grain === true ? 0.16 : typeof grain === \"number\" ? grain : 0;\n\n  return (\n    <div\n      aria-hidden\n      className=\"facade-ember pointer-events-none absolute inset-0 -z-10 overflow-hidden\"\n      data-paused={paused || undefined}\n      style={{ backgroundColor: `var(--ember-base, ${first.base})`, containerType: \"size\" }}\n    >\n      <style href=\"facade-ember-v1\" precedence=\"medium\">\n        {EMBER_CSS}\n      </style>\n      {stacks.map((p, s) => (\n        <div\n          key={s}\n          className=\"facade-ember-stack\"\n          style={{\n            opacity: s === active ? 1 : 0,\n            transitionDuration: `${fade}s`,\n            backgroundColor: s === 0 ? undefined : p.base,\n          }}\n        >\n          <div className=\"absolute inset-0\" style={{ opacity: intensity }}>\n            {FIELDS.map((f, i) => {\n              const raw = p.fields[i % Math.max(1, p.fields.length)];\n              if (!raw) return null;\n              // The first palette reads CSS variables, so a theme can override colors without props.\n              const color = s === 0 ? `var(--ember-${i + 1}, ${raw})` : raw;\n              const duration = speed * f.factor;\n              return (\n                <span\n                  key={i}\n                  className=\"facade-ember-field\"\n                  style={{\n                    ...fieldBox(f),\n                    opacity: f.opacity,\n                    // A short plateau before the falloff keeps small surfaces from showing hot spots.\n                    background: `radial-gradient(closest-side, ${color} 0%, ${color} 22%, color-mix(in srgb, ${color} 50%, transparent) 62%, transparent 100%)`,\n                    animationName: `facade-ember-${f.drift}`,\n                    animationDuration: `${duration}s`,\n                    animationDelay: `${f.delay * duration}s`,\n                  }}\n                />\n              );\n            })}\n          </div>\n        </div>\n      ))}\n      {grainOpacity > 0 && (\n        <div\n          className=\"absolute inset-0 mix-blend-overlay\"\n          style={{ opacity: grainOpacity, backgroundImage: GRAIN, backgroundSize: \"160px 160px\" }}\n        />\n      )}\n    </div>\n  );\n}\n\n/** Pauses the surface while it is scrolled out of view. */\nfunction useOffscreen<T extends Element>(ref: React.RefObject<T | null>) {\n  const [off, setOff] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el || typeof IntersectionObserver === \"undefined\") return;\n    const io = new IntersectionObserver(([e]) => setOff(!e.isIntersecting), { rootMargin: \"120px\" });\n    io.observe(el);\n    return () => io.disconnect();\n  }, [ref]);\n  return off;\n}\n\n/* ---------- end of engine ---------- */\n\nexport interface PromoBarProps {\n  /** Message on tablet and desktop. */\n  text: React.ReactNode;\n  /** Shorter message below 640px. Falls back to `text`. */\n  mobileText?: React.ReactNode;\n  /** Short bold lead, e.g. \"Fall special\". Hidden on phones to save space. */\n  badge?: string;\n  href?: string;\n  linkLabel?: string;\n  /** ISO date with offset (\"2026-11-30T23:59:00-05:00\"). Shows a live countdown next to the text. */\n  countdownTo?: string;\n  /** Words before the countdown. Defaults to \"Ends in\". */\n  countdownLabel?: string;\n  /** Show the countdown below 640px too. Off by default so the bar stays one line on phones. */\n  countdownOnMobile?: boolean;\n  /** Hide the bar once the countdown reaches zero. Defaults to true. */\n  hideWhenExpired?: boolean;\n  dismissible?: boolean;\n  /** localStorage key that remembers the dismissal. Change it for every new campaign. */\n  storageKey?: string;\n  /** Called after the bar has collapsed. */\n  onDismiss?: () => void;\n  /** Surface colors. Defaults to \"ember\". */\n  palette?: EmberPaletteInput;\n  /** Cross-fade slowly between the presets. */\n  cycle?: boolean;\n  /** Let the color fields drift. Defaults to true. Always static with reduced motion. */\n  drift?: boolean;\n  className?: string;\n}\n\nconst EASE = [0.16, 1, 0.3, 1] as const;\nconst ATTR = \"data-promo-bar-dismissed\";\n\nconst safeKey = (key: string) => key.replace(/[^a-zA-Z0-9_-]/g, \"\");\n\n/**\n * Pre-paint script that hides an already dismissed bar before first paint.\n * The bar renders this inline right above itself, so it works without setup.\n * If you render the bar lower in the tree, you can also put it in <head>:\n *   <script dangerouslySetInnerHTML={{ __html: promoBarScript(\"fall-tuneup-2026\") }} />\n * This module is a client module, so call it from a client component or copy the string.\n */\nexport function promoBarScript(storageKey = \"facade-promo-bar\") {\n  const key = safeKey(storageKey);\n  return `try{if(localStorage.getItem(${JSON.stringify(key)})===\"1\"){var d=document.documentElement,v=d.getAttribute(\"${ATTR}\")||\"\";if((\" \"+v+\" \").indexOf(\" ${key} \")<0)d.setAttribute(\"${ATTR}\",(v+\" ${key}\").trim())}}catch(e){}`;\n}\n\nfunction markDismissed(key: string) {\n  const d = document.documentElement;\n  const v = d.getAttribute(ATTR) ?? \"\";\n  if (!` ${v} `.includes(` ${key} `)) d.setAttribute(ATTR, `${v} ${key}`.trim());\n}\n\nconst useIsomorphicLayoutEffect = typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nfunction remaining(target: number) {\n  const total = Math.max(0, Math.floor((target - Date.now()) / 1000));\n  return {\n    total,\n    d: Math.floor(total / 86400),\n    h: Math.floor((total % 86400) / 3600),\n    m: Math.floor((total % 3600) / 60),\n    s: total % 60,\n  };\n}\n\nconst pad = (n: number) => String(n).padStart(2, \"0\");\n\nexport function PromoBar({\n  text,\n  mobileText,\n  badge,\n  href,\n  linkLabel = \"Learn more\",\n  countdownTo,\n  countdownLabel = \"Ends in\",\n  countdownOnMobile = false,\n  hideWhenExpired = true,\n  dismissible = true,\n  storageKey = \"facade-promo-bar\",\n  onDismiss,\n  palette = \"ember\",\n  cycle = false,\n  drift = true,\n  className,\n}: PromoBarProps) {\n  const reduce = useReducedMotion();\n  const key = safeKey(storageKey);\n  const target = countdownTo ? Date.parse(countdownTo) : NaN;\n  const hasCountdown = Number.isFinite(target);\n  // The countdown renders after mount only, server and client clocks never agree to the second.\n  const [left, setLeft] = React.useState<ReturnType<typeof remaining> | null>(null);\n  const [open, setOpen] = React.useState(true);\n  const ref = React.useRef<HTMLDivElement>(null);\n  const offscreen = useOffscreen(ref);\n\n  React.useEffect(() => {\n    if (!hasCountdown) return;\n    const tick = () => setLeft(remaining(target));\n    tick();\n    const id = window.setInterval(tick, 1000);\n    return () => window.clearInterval(id);\n  }, [hasCountdown, target]);\n\n  // Client-rendered bars (client navigation, dynamic imports) never run the inline script.\n  // A layout effect runs before paint, so a dismissed bar is hidden before it can flash.\n  useIsomorphicLayoutEffect(() => {\n    try {\n      if (localStorage.getItem(key) === \"1\") markDismissed(key);\n    } catch {}\n  }, [key]);\n\n  function dismiss() {\n    setOpen(false);\n    try {\n      localStorage.setItem(key, \"1\");\n    } catch {}\n  }\n\n  function collapsed() {\n    markDismissed(key);\n    onDismiss?.();\n  }\n\n  if (hasCountdown && hideWhenExpired && left?.total === 0) return null;\n\n  return (\n    <>\n      <script suppressHydrationWarning dangerouslySetInnerHTML={{ __html: promoBarScript(key) }} />\n      <style href={`facade-promo-bar-${key}`} precedence=\"medium\">\n        {`html[${ATTR}~=\"${key}\"] [data-promo-bar=\"${key}\"]{display:none}`}\n      </style>\n      <motion.div\n        ref={ref}\n        role=\"region\"\n        aria-label=\"Promotion\"\n        data-promo-bar={key}\n        initial={false}\n        animate={open ? { height: \"auto\" } : { height: 0 }}\n        transition={{ duration: reduce ? 0 : 0.4, ease: EASE }}\n        onAnimationComplete={() => {\n          if (!open) collapsed();\n        }}\n        className={cn(\"relative isolate w-full overflow-hidden text-white\", className)}\n      >\n        <EmberLayer palette={palette} cycle={cycle} paused={!drift || offscreen} grain />\n        <div className=\"mx-auto flex min-h-12 max-w-[1120px] items-center gap-3 px-4 py-2 sm:min-h-14 sm:px-6\">\n          {dismissible && <span className=\"w-7 shrink-0\" aria-hidden />}\n\n          <p className=\"flex min-w-0 flex-1 flex-wrap items-center justify-center gap-x-3 gap-y-0.5 text-center text-[13px] leading-snug sm:text-sm\">\n            <span className=\"min-w-0\">\n              {badge && <span className=\"mr-1.5 hidden font-semibold sm:inline\">{badge}</span>}\n              <span className=\"text-white/90 sm:hidden\">{mobileText ?? text}</span>\n              <span className=\"hidden text-white/90 sm:inline\">{text}</span>\n            </span>\n\n            {hasCountdown && (\n              <span\n                role=\"timer\"\n                aria-label={\n                  left ? `${countdownLabel} ${left.d} days, ${left.h} hours and ${left.m} minutes` : countdownLabel\n                }\n                className={cn(\n                  \"shrink-0 items-center gap-1.5 rounded-full bg-black/25 px-2.5 py-0.5 text-[12px] font-medium tabular-nums text-white ring-1 ring-white/15\",\n                  countdownOnMobile ? \"inline-flex\" : \"hidden sm:inline-flex\",\n                )}\n              >\n                <span className=\"text-white/70\" aria-hidden>\n                  {countdownLabel}\n                </span>\n                {/* Fixed width placeholder until mount, so nothing shifts when the time appears */}\n                <span aria-hidden className={cn(!left && \"invisible\")}>\n                  {left ? (left.d > 0 ? `${left.d}d ${pad(left.h)}h ${pad(left.m)}m` : `${pad(left.h)}:${pad(left.m)}:${pad(left.s)}`) : \"0d 00h 00m\"}\n                </span>\n              </span>\n            )}\n\n            {href && (\n              <a\n                href={href}\n                className=\"shrink-0 rounded font-medium underline decoration-white/50 underline-offset-4 transition-colors hover:decoration-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/80\"\n              >\n                {linkLabel}\n              </a>\n            )}\n          </p>\n\n          {dismissible && (\n            <button\n              type=\"button\"\n              onClick={dismiss}\n              aria-label=\"Dismiss promotion\"\n              className=\"grid size-7 shrink-0 place-items-center rounded-full text-white/75 transition hover:bg-white/10 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/80\"\n            >\n              <X className=\"size-4\" aria-hidden />\n            </button>\n          )}\n        </div>\n      </motion.div>\n    </>\n  );\n}\n\nexport default PromoBar;\n"}],"categories":["feedback"],"meta":{"tier":"free","demo":"\"use client\";\n\nimport * as React from \"react\";\nimport { Flame, Menu } from \"lucide-react\";\nimport { PromoBar } from \"./promo-bar\";\n\nconst KEY = \"facade-demo-promo-bar\";\n\n/** End of the current month at 11:59 pm, so the demo countdown is always running. */\nfunction endOfMonth() {\n  const now = new Date();\n  return new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 0);\n}\n\nexport default function Demo() {\n  const [run, setRun] = React.useState(0);\n  const [dismissed, setDismissed] = React.useState(false);\n  const end = React.useMemo(endOfMonth, []);\n  const day = end.toLocaleDateString(\"en-US\", { month: \"long\", day: \"numeric\" });\n\n  function showAgain() {\n    try {\n      localStorage.removeItem(KEY);\n    } catch {}\n    const d = document.documentElement;\n    const v = (d.getAttribute(\"data-promo-bar-dismissed\") ?? \"\").split(\" \").filter((k) => k && k !== KEY);\n    d.setAttribute(\"data-promo-bar-dismissed\", v.join(\" \"));\n    setDismissed(false);\n    setRun((r) => r + 1);\n  }\n\n  return (\n    <div className=\"mx-auto w-full max-w-4xl p-4\">\n      <div className=\"overflow-hidden rounded-[22px] bg-background shadow-float\">\n        <PromoBar\n          key={run}\n          storageKey={KEY}\n          badge=\"Tune-up special\"\n          text={`$89 furnace or AC tune-up, through ${day}.`}\n          mobileText=\"$89 furnace or AC tune-up.\"\n          href=\"#book\"\n          linkLabel=\"Book a visit\"\n          countdownTo={end.toISOString()}\n          onDismiss={() => setDismissed(true)}\n        />\n        <header className=\"flex h-14 items-center justify-between border-b border-border px-5\">\n          <div className=\"flex items-center gap-2.5 text-[15px] font-semibold tracking-[-0.01em]\">\n            <span className=\"grid size-7 place-items-center rounded-lg bg-foreground text-background\">\n              <Flame className=\"size-3.5\" aria-hidden />\n            </span>\n            Blue Ridge Comfort Co.\n          </div>\n          <nav className=\"hidden items-center gap-7 text-[14px] text-muted-foreground sm:flex\">\n            <span>Heating</span>\n            <span>Cooling</span>\n            <span>Service plans</span>\n            <span className=\"rounded-full bg-foreground px-4 py-1.5 text-[13px] font-medium text-background\">Book service</span>\n          </nav>\n          <Menu className=\"size-5 text-muted-foreground sm:hidden\" aria-hidden />\n        </header>\n        <div className=\"px-5 py-10\">\n          <div className=\"h-3 w-24 rounded-full bg-muted\" />\n          <div className=\"mt-4 h-7 w-3/4 max-w-md rounded-lg bg-muted\" />\n          <div className=\"mt-2 h-7 w-1/2 max-w-xs rounded-lg bg-muted\" />\n          {dismissed && (\n            <button\n              type=\"button\"\n              onClick={showAgain}\n              className=\"mt-6 rounded-full bg-muted px-3.5 py-1.5 text-[13px] font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n            >\n              Show the bar again\n            </button>\n          )}\n        </div>\n      </div>\n    </div>\n  );\n}\n"}}