{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "floating-contact-button",
  "title": "Floating Contact Button",
  "author": "AlgorizeTech",
  "description": "A floating support bubble that expands into a chat panel, with state persisted to localStorage. Use it for live chat and contact widgets on marketing sites.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "src/components/custom/blocks/FloatingContactButtonBlock.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  Bot,\n  CheckCheck,\n  MessageSquare,\n  Send,\n  Sparkles,\n  X,\n} from \"lucide-react\";\nimport React, { useEffect, useRef, useState } from \"react\";\nimport { springLinear } from \"./motion-curves\";\n\nexport interface ChatMessage {\n  id: string;\n  text: string;\n  sender: \"user\" | \"agent\";\n  timestamp: string;\n}\n\nexport interface FloatingContactButtonProps\n  extends React.HTMLAttributes<HTMLDivElement> {\n  position?: \"bottom-right\" | \"bottom-left\";\n  containerMode?: \"fixed\" | \"absolute\";\n  title?: string;\n  subtitle?: string;\n  avatarUrl?: string;\n  defaultOpen?: boolean;\n  localStorageKey?: string;\n  defaultAccentColor?: string;\n  initialMessages?: ChatMessage[];\n  onSendMessage?: (message: string) => void;\n}\n\n// ==========================================\n// MOTION\n// The panel rises in and sinks out (0.22s, cubic-bezier(.16,1,.3,1)); each\n// message and the typing bubble fade and settle in as they mount; the launcher\n// swells on hover and dips on press; its icon turns out, then the other turns\n// in (0.15s each). The springs are CSS `linear()` curves generated from the\n// same stiffness/damping.\n// ==========================================\nconst RISE_SPRING = springLinear({ stiffness: 500, damping: 25 });\nconst SCALE_SPRING = springLinear({ stiffness: 550, damping: 30 });\nconst PANEL_EASE = \"cubic-bezier(0.16, 1, 0.3, 1)\";\nconst FADE_EASE = \"cubic-bezier(0.25, 0.1, 0.35, 1)\";\n// Tailwind's `transition-colors duration-300`, which the panel and launcher\n// carry: repeated here because their own transitions replace the property.\nconst COLOR_TRANSITIONS = [\n  \"color\",\n  \"background-color\",\n  \"border-color\",\n  \"outline-color\",\n  \"text-decoration-color\",\n  \"fill\",\n  \"stroke\",\n  \"--tw-gradient-from\",\n  \"--tw-gradient-via\",\n  \"--tw-gradient-to\",\n]\n  .map((property) => `${property} 300ms cubic-bezier(0.4, 0, 0.2, 1)`)\n  .join(\", \");\n\nconst FCB_CSS = `\n.fcb-panel {\n  transition: ${COLOR_TRANSITIONS}, opacity 0.22s ${PANEL_EASE},\n    translate 0.22s ${PANEL_EASE}, scale 0.22s ${PANEL_EASE};\n}\n.fcb-panel[data-state=\"closed\"] { opacity: 0; translate: 0 16px; scale: 0.96; }\n@keyframes fcb-fade-in { from { opacity: 0; } }\n@keyframes fcb-rise { from { translate: 0 6px; } }\n@keyframes fcb-pop { from { scale: 0.9; } }\n.fcb-message {\n  animation: fcb-fade-in 0.3s ${FADE_EASE},\n    fcb-rise ${RISE_SPRING.duration}ms ${RISE_SPRING.easing};\n}\n.fcb-typing {\n  animation: fcb-fade-in 0.3s ${FADE_EASE},\n    fcb-pop ${SCALE_SPRING.duration}ms ${SCALE_SPRING.easing};\n}\n.fcb-launcher {\n  transition: ${COLOR_TRANSITIONS},\n    scale ${SCALE_SPRING.duration}ms ${SCALE_SPRING.easing};\n}\n@media (hover: hover) {\n  .fcb-launcher:hover { scale: 1.05; }\n}\n.fcb-launcher:active { scale: 0.95; }\n.fcb-icon {\n  transition: rotate 0.15s cubic-bezier(0, 0, 0.58, 1),\n    opacity 0.15s cubic-bezier(0, 0, 0.58, 1);\n}\n.fcb-icon[data-icon=\"close\"][data-leaving] { rotate: 90deg; opacity: 0; }\n.fcb-icon[data-icon=\"open\"][data-leaving] { rotate: -90deg; opacity: 0; }\n@starting-style {\n  .fcb-panel[data-state=\"open\"] { opacity: 0; translate: 0 16px; scale: 0.96; }\n  .fcb-icon[data-icon=\"close\"] { rotate: -90deg; opacity: 0; }\n  .fcb-icon[data-icon=\"open\"] { rotate: 90deg; opacity: 0; }\n}\n`;\n\nfunction resolveColor(c: string): string {\n  if (!c || c === \"primary\" || c === \"default\") return \"var(--primary)\";\n  if (\n    c.startsWith(\"#\") ||\n    c.startsWith(\"rgb\") ||\n    c.startsWith(\"hsl\") ||\n    c.startsWith(\"var(\")\n  )\n    return c;\n  const colorMap: Record<string, string> = {\n    indigo: \"#6366f1\",\n    rose: \"#f43f5e\",\n    emerald: \"#10b981\",\n    zinc: \"#18181b\",\n    amber: \"#f59e0b\",\n    violet: \"#8b5cf6\",\n    cyan: \"#06b6d4\",\n    blue: \"#3b82f6\",\n  };\n  return colorMap[c] || \"var(--primary)\";\n}\n\nfunction hexToRgba(hex: string, alpha: number): string {\n  if (!hex) return `rgba(99, 102, 241, ${alpha})`;\n  const resolved = resolveColor(hex);\n  if (resolved.startsWith(\"var(\"))\n    return `color-mix(in srgb, ${resolved} ${alpha * 100}%, transparent)`;\n  if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(resolved)) {\n    let digits = resolved.substring(1);\n    if (digits.length === 3)\n      digits = digits\n        .split(\"\")\n        .map((d) => d + d)\n        .join(\"\");\n    const packed = parseInt(digits, 16);\n    return `rgba(${(packed >> 16) & 255},${(packed >> 8) & 255},${packed & 255},${alpha})`;\n  }\n  return resolved;\n}\n\nexport const FloatingContactButtonBlock = React.forwardRef<\n  HTMLDivElement,\n  FloatingContactButtonProps\n>(\n  (\n    {\n      position = \"bottom-right\",\n      containerMode = \"fixed\",\n      title = \"Chat with us\",\n      subtitle = \"We typically reply in a few minutes\",\n      avatarUrl = \"https://res.cloudinary.com/dodndg7ai/image/upload/f_webp,q_auto,w_250,c_limit/v1790150483/photo-1534528741775-53994a69daeb-1790150482280.jpg\",\n      defaultOpen = false,\n      localStorageKey = \"primaryColor\",\n      defaultAccentColor = \"var(--primary)\",\n      initialMessages = [\n        {\n          id: \"1\",\n          text: \"Hi there! 👋 How can we help you build something amazing today?\",\n          sender: \"agent\",\n          timestamp: \"Just now\",\n        },\n      ],\n      onSendMessage,\n      className,\n      ...props\n    },\n    ref,\n  ) => {\n    const [isOpen, setIsOpen] = useState(defaultOpen);\n    const [messages, setMessages] = useState<ChatMessage[]>(initialMessages);\n    const [inputValue, setInputValue] = useState(\"\");\n    const [isTyping, setIsTyping] = useState(false);\n    const [accentColor, setAccentColor] = useState<string>(defaultAccentColor);\n\n    // The panel stays mounted after closing until its exit has played.\n    const [panelMounted, setPanelMounted] = useState(isOpen);\n    if (isOpen && !panelMounted) setPanelMounted(true);\n\n    // The launcher shows one icon at a time: the current one turns out, and\n    // only then does the next one turn in.\n    const wantedIcon = isOpen ? \"close\" : \"open\";\n    const [shownIcon, setShownIcon] = useState(wantedIcon);\n    const iconLeaving = shownIcon !== wantedIcon;\n\n    // Backstops for when no transitionend arrives (e.g. a hidden tab).\n    useEffect(() => {\n      if (isOpen || !panelMounted) return;\n      const timer = setTimeout(() => setPanelMounted(false), 320);\n      return () => clearTimeout(timer);\n    }, [isOpen, panelMounted]);\n\n    useEffect(() => {\n      if (!iconLeaving) return;\n      const timer = setTimeout(() => setShownIcon(wantedIcon), 250);\n      return () => clearTimeout(timer);\n    }, [iconLeaving, wantedIcon]);\n\n    // Sandboxed scroll ref: Replaces scrollIntoView to prevent page jumps\n    const scrollContainerRef = useRef<HTMLDivElement>(null);\n\n    useEffect(() => {\n      if (typeof window === \"undefined\") return;\n\n      const loadColor = () => {\n        let foundColor: string | null = null;\n        const knownKeys = [\n          localStorageKey,\n          \"primaryColor\",\n          \"docs-theme-color\",\n          \"theme-color\",\n          \"accentColor\",\n          \"color\",\n        ];\n\n        for (const k of knownKeys) {\n          if (!k) continue;\n          try {\n            const val = localStorage.getItem(k);\n            if (val) {\n              const cleaned = val.replace(/['\"]/g, \"\").trim();\n              const hexMatch = cleaned.match(\n                /#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})\\b/,\n              );\n              if (hexMatch) {\n                foundColor = hexMatch[0];\n                break;\n              }\n            }\n          } catch {\n            // Unreadable stylesheet (cross-origin): fall through to the default.\n          }\n        }\n\n        const targetColor = foundColor || defaultAccentColor;\n        setAccentColor((prev) => (prev !== targetColor ? targetColor : prev));\n      };\n\n      loadColor();\n\n      const origProtoSetItem = Storage.prototype.setItem;\n      Storage.prototype.setItem = function (key: string, value: string) {\n        origProtoSetItem.apply(this, [key, value]);\n        loadColor();\n      };\n      const origInstanceSetItem = window.localStorage.setItem;\n      window.localStorage.setItem = function (key: string, value: string) {\n        origInstanceSetItem.apply(window.localStorage, [key, value]);\n        loadColor();\n      };\n\n      window.addEventListener(\"storage\", loadColor);\n      const intervalId = setInterval(loadColor, 100);\n\n      return () => {\n        Storage.prototype.setItem = origProtoSetItem;\n        window.localStorage.setItem = origInstanceSetItem;\n        window.removeEventListener(\"storage\", loadColor);\n        clearInterval(intervalId);\n      };\n    }, [localStorageKey, defaultAccentColor]);\n\n    // Sandboxed scrolling: Only scrolls inside the chat modal container\n    useEffect(() => {\n      if (isOpen && scrollContainerRef.current) {\n        const el = scrollContainerRef.current;\n        el.scrollTo({\n          top: el.scrollHeight,\n          behavior: \"smooth\",\n        });\n      }\n    }, [messages, isOpen, isTyping]);\n\n    const handleSend = (e?: React.FormEvent) => {\n      if (e) e.preventDefault();\n      if (!inputValue.trim()) return;\n\n      const userMsg: ChatMessage = {\n        id: Date.now().toString(),\n        text: inputValue.trim(),\n        sender: \"user\",\n        timestamp: new Date().toLocaleTimeString([], {\n          hour: \"2-digit\",\n          minute: \"2-digit\",\n        }),\n      };\n\n      setMessages((prev) => [...prev, userMsg]);\n      setInputValue(\"\");\n      if (onSendMessage) onSendMessage(userMsg.text);\n\n      setIsTyping(true);\n      setTimeout(() => {\n        setIsTyping(false);\n        setMessages((prev) => [\n          ...prev,\n          {\n            id: (Date.now() + 1).toString(),\n            text: \"Thanks for reaching out! A member of our engineering team will review your message and reply shortly.\",\n            sender: \"agent\",\n            timestamp: new Date().toLocaleTimeString([], {\n              hour: \"2-digit\",\n              minute: \"2-digit\",\n            }),\n          },\n        ]);\n      }, 1200);\n    };\n\n    const positionClasses =\n      position === \"bottom-right\"\n        ? \"bottom-4 right-4 sm:bottom-6 sm:right-6\"\n        : \"bottom-4 left-4 sm:bottom-6 sm:left-6\";\n\n    const modalAlignmentClasses =\n      position === \"bottom-right\"\n        ? \"right-0 origin-bottom-right\"\n        : \"left-0 origin-bottom-left\";\n\n    const modalWidthClass =\n      containerMode === \"fixed\"\n        ? \"w-[calc(100vw-2rem)] sm:w-[380px] max-w-[380px]\"\n        : \"w-[380px]\";\n\n    const modalHeightClass =\n      containerMode === \"fixed\"\n        ? \"h-[400px] sm:h-[480px] max-h-[calc(100vh-6rem)]\"\n        : \"h-[480px]\";\n\n    const activeBgGlow = hexToRgba(accentColor, 0.25);\n\n    // Auto-scale: shrink the entire widget when its parent container is narrow\n    const wrapperRef = useRef<HTMLDivElement>(null);\n    const [autoScale, setAutoScale] = useState(1);\n\n    useEffect(() => {\n      if (containerMode !== \"absolute\") return;\n      const el = wrapperRef.current;\n      if (!el) return;\n      const parent = el.offsetParent as HTMLElement | null;\n      if (!parent) return;\n\n      const observer = new ResizeObserver((entries) => {\n        for (const entry of entries) {\n          const w = entry.contentRect.width;\n          // Start scaling when container is narrower than 460px\n          setAutoScale(Math.min(1, Math.max(0.5, w / 460)));\n        }\n      });\n      observer.observe(parent);\n      return () => observer.disconnect();\n    }, [containerMode]);\n\n    const mergedRef = (node: HTMLDivElement | null) => {\n      (wrapperRef as React.MutableRefObject<HTMLDivElement | null>).current = node;\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) (ref as React.MutableRefObject<HTMLDivElement | null>).current = node;\n    };\n\n    return (\n      <div\n        ref={mergedRef}\n        className={cn(\n          \"pointer-events-none select-none\",\n          containerMode === \"fixed\" ? \"fixed z-50\" : \"absolute z-[5]\",\n          positionClasses,\n          \"w-14 h-14 sm:w-16 sm:h-16\",\n          className,\n        )}\n        style={\n          containerMode === \"absolute\" && autoScale < 1\n            ? {\n                transform: `scale(${autoScale})`,\n                transformOrigin:\n                  position === \"bottom-right\" ? \"bottom right\" : \"bottom left\",\n              }\n            : undefined\n        }\n        {...props}\n      >\n        <style>{FCB_CSS}</style>\n        {panelMounted && (\n          <div\n            data-state={isOpen ? \"open\" : \"closed\"}\n            onTransitionEnd={(e) => {\n              if (\n                e.target === e.currentTarget &&\n                e.propertyName === \"opacity\" &&\n                !isOpen\n              ) {\n                setPanelMounted(false);\n              }\n            }}\n            className={cn(\n              \"fcb-panel pointer-events-auto absolute bottom-full mb-3 sm:mb-4 rounded-2xl sm:rounded-3xl overflow-hidden border border-border/80 bg-background shadow-2xl flex flex-col transition-colors duration-300\",\n              modalAlignmentClasses,\n              modalWidthClass,\n              modalHeightClass,\n            )}\n          >\n            <div\n              style={{ backgroundColor: resolveColor(accentColor) }}\n              className=\"p-4 sm:p-5 text-primary-foreground flex items-center justify-between relative overflow-hidden shrink-0 transition-colors duration-300\"\n            >\n              <div className=\"absolute -right-10 -top-10 w-32 h-32 rounded-full bg-white/10 blur-xl pointer-events-none\" />\n              <div className=\"flex items-center gap-3 z-10 min-w-0\">\n                <div className=\"relative shrink-0\">\n                  <img\n                    src={avatarUrl}\n                    alt=\"Support Avatar\"\n                    className=\"w-9 h-9 sm:w-10 sm:h-10 rounded-full object-cover border-2 border-white/20 shadow-md\"\n                  />\n                  <span className=\"absolute bottom-0 right-0 w-2.5 h-2.5 sm:w-3 sm:h-3 rounded-full bg-emerald-400 border-2 border-primary-foreground\" />\n                </div>\n                <div className=\"flex flex-col min-w-0\">\n                  <div className=\"flex items-center gap-1.5\">\n                    <h3 className=\"font-semibold text-xs sm:text-sm tracking-tight truncate text-primary-foreground\">\n                      {title}\n                    </h3>\n                    <Sparkles className=\"w-3.5 h-3.5 opacity-80 shrink-0 animate-pulse text-primary-foreground\" />\n                  </div>\n                  <p className=\"text-[10px] sm:text-[11px] opacity-90 truncate font-medium text-primary-foreground\">\n                    {subtitle}\n                  </p>\n                </div>\n              </div>\n              <button\n                type=\"button\"\n                onClick={() => setIsOpen(false)}\n                className=\"w-7 h-7 sm:w-8 sm:h-8 rounded-full bg-black/10 hover:bg-black/20 flex items-center justify-center text-primary-foreground transition-colors cursor-pointer shrink-0 z-10\"\n              >\n                <X className=\"w-4 h-4 stroke-[2.5]\" />\n              </button>\n            </div>\n\n            {/* Sandboxed scroll container ref attached directly here */}\n            <div\n              ref={scrollContainerRef}\n              className=\"flex-1 p-3 sm:p-4 overflow-y-auto flex flex-col gap-3 sm:gap-3.5 bg-muted/50\"\n            >\n              <div className=\"text-center my-1\">\n                <span className=\"text-[10px] font-mono font-semibold uppercase tracking-widest px-2.5 py-1 rounded-full bg-muted/60 text-muted-foreground\">\n                  Today\n                </span>\n              </div>\n\n              {messages.map((msg) => {\n                const isUser = msg.sender === \"user\";\n                return (\n                  <div\n                    key={msg.id}\n                    className={cn(\n                      \"fcb-message flex flex-col max-w-[85%]\",\n                      isUser\n                        ? \"self-end items-end\"\n                        : \"self-start items-start\",\n                    )}\n                  >\n                    <div\n                      style={{\n                        backgroundColor: isUser\n                          ? resolveColor(accentColor)\n                          : undefined,\n                      }}\n                      className={cn(\n                        \"px-3.5 py-2 sm:px-4 sm:py-2.5 rounded-2xl text-xs sm:text-sm leading-relaxed shadow-sm transition-colors duration-300 break-words whitespace-pre-wrap max-w-full\",\n                        isUser\n                          ? \"rounded-br-xs font-medium text-primary-foreground\"\n                          : \"bg-card border border-border/80 text-foreground rounded-bl-xs\",\n                      )}\n                    >\n                      {msg.text}\n                    </div>\n                    <div className=\"flex items-center gap-1 mt-1 px-1\">\n                      <span className=\"text-[10px] text-muted-foreground font-mono\">\n                        {msg.timestamp}\n                      </span>\n                      {isUser && (\n                        <CheckCheck className=\"w-3 h-3 text-emerald-500 shrink-0\" />\n                      )}\n                    </div>\n                  </div>\n                );\n              })}\n\n              {isTyping && (\n                <div\n                  className=\"fcb-typing self-start flex items-center gap-2 px-4 py-3 rounded-2xl rounded-bl-xs bg-card border border-border/80 shadow-sm\"\n                >\n                  <Bot className=\"w-4 h-4 text-muted-foreground animate-bounce shrink-0\" />\n                  <div className=\"flex items-center gap-1\">\n                    <span className=\"w-1.5 h-1.5 rounded-full bg-muted-foreground animate-pulse\" />\n                    <span className=\"w-1.5 h-1.5 rounded-full bg-muted-foreground animate-pulse delay-75\" />\n                    <span className=\"w-1.5 h-1.5 rounded-full bg-muted-foreground animate-pulse delay-150\" />\n                  </div>\n                </div>\n              )}\n            </div>\n\n            <form\n              onSubmit={handleSend}\n              className=\"p-2.5 sm:p-3 bg-background border-t border-border/80 flex items-center gap-2 shrink-0\"\n            >\n              <input\n                type=\"text\"\n                value={inputValue}\n                onChange={(e) => setInputValue(e.target.value)}\n                placeholder=\"Write a message...\"\n                className=\"flex-1 h-9 sm:h-10 px-3 sm:px-3.5 text-xs sm:text-sm bg-muted border border-transparent focus:border-border rounded-xl outline-none text-foreground placeholder:text-muted-foreground transition-all\"\n              />\n              <button\n                type=\"submit\"\n                disabled={!inputValue.trim()}\n                style={{\n                  backgroundColor: inputValue.trim()\n                    ? resolveColor(accentColor)\n                    : undefined,\n                }}\n                className={cn(\n                  \"w-9 h-9 sm:w-10 sm:h-10 rounded-xl flex items-center justify-center transition-all duration-200 cursor-pointer shrink-0\",\n                  inputValue.trim()\n                    ? \"text-primary-foreground shadow-md hover:opacity-90 scale-105\"\n                    : \"bg-muted text-muted-foreground/60 cursor-not-allowed\",\n                )}\n              >\n                <Send className=\"w-3.5 h-3.5 sm:w-4 sm:h-4 stroke-[2.5]\" />\n              </button>\n            </form>\n          </div>\n        )}\n\n        <button\n          type=\"button\"\n          onClick={() => setIsOpen(!isOpen)}\n          style={{ backgroundColor: resolveColor(accentColor) }}\n          className={cn(\n            \"fcb-launcher pointer-events-auto absolute inset-0 flex items-center justify-center rounded-full text-primary-foreground shadow-2xl transition-colors duration-300 cursor-pointer outline-none\",\n          )}\n        >\n          <div\n            style={{ backgroundColor: activeBgGlow }}\n            className=\"absolute inset-0 rounded-full blur-xl -z-10 group-hover:blur-2xl transition-all duration-300\"\n          />\n\n          <div\n            key={shownIcon}\n            data-icon={shownIcon}\n            data-leaving={iconLeaving || undefined}\n            onTransitionEnd={(e) => {\n              if (\n                e.target === e.currentTarget &&\n                e.propertyName === \"opacity\" &&\n                iconLeaving\n              ) {\n                setShownIcon(wantedIcon);\n              }\n            }}\n            className={cn(\"fcb-icon\", shownIcon === \"open\" && \"relative\")}\n          >\n            {shownIcon === \"close\" ? (\n              <X className=\"w-6 h-6 sm:w-7 sm:h-7 stroke-[2.5]\" />\n            ) : (\n              <>\n                <MessageSquare className=\"w-6 h-6 sm:w-7 sm:h-7 stroke-[2.2]\" />\n                <span className=\"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-rose-500 ring-2 ring-primary-foreground animate-pulse\" />\n              </>\n            )}\n          </div>\n        </button>\n      </div>\n    );\n  },\n);\n\nFloatingContactButtonBlock.displayName = \"FloatingContactButtonBlock\";\n",
      "type": "registry:component",
      "target": "components/custom/blocks/FloatingContactButtonBlock.tsx"
    },
    {
      "path": "src/components/custom/blocks/motion-curves.ts",
      "content": "/**\n * Motion curves with no animation library behind them.\n *\n * The components here ship as CSS, GSAP or Motion builds that must move\n * identically, so the curves are computed once, from the same numbers, and\n * handed to whichever engine runs them:\n *\n *   - `cubicBezier(x1, y1, x2, y2)` → an easing function (GSAP accepts any\n *     `(progress) => value` as `ease`), exact for Motion's `ease: [..]` arrays\n *     and for CSS `cubic-bezier()`.\n *   - `spring({ stiffness, damping, mass })` → the analytic solution Motion\n *     Motion uses, as an easing function plus the time it takes to settle, or\n *     as a CSS `linear()` string for a fixed start and end.\n *   - `createSpringFollower` → a value that chases a moving target through the\n *     same spring every frame, like Motion's `useSpring`, for pointer-driven\n *     motion that no fixed curve can describe.\n */\n\n// ---------------------------------------------------------------------------\n// Cubic bezier\n// ---------------------------------------------------------------------------\n\n/**\n * The CSS / Motion cubic-bezier as a function of progress. Newton-Raphson\n * with a bisection fallback, the same solver browsers use.\n */\nexport function cubicBezier(x1: number, y1: number, x2: number, y2: number) {\n  if (x1 === y1 && x2 === y2) return (t: number) => t;\n\n  const a = (p1: number, p2: number) => 1 - 3 * p2 + 3 * p1;\n  const b = (p1: number, p2: number) => 3 * p2 - 6 * p1;\n  const c = (p1: number) => 3 * p1;\n  const at = (t: number, p1: number, p2: number) =>\n    ((a(p1, p2) * t + b(p1, p2)) * t + c(p1)) * t;\n  const slope = (t: number, p1: number, p2: number) =>\n    3 * a(p1, p2) * t * t + 2 * b(p1, p2) * t + c(p1);\n\n  const solveX = (x: number) => {\n    let t = x;\n    for (let i = 0; i < 8; i++) {\n      const s = slope(t, x1, x2);\n      if (Math.abs(s) < 1e-6) break;\n      const err = at(t, x1, x2) - x;\n      if (Math.abs(err) < 1e-7) return t;\n      t -= err / s;\n    }\n    let lo = 0;\n    let hi = 1;\n    t = x;\n    for (let i = 0; i < 30 && hi - lo > 1e-7; i++) {\n      const value = at(t, x1, x2);\n      if (value < x) lo = t;\n      else hi = t;\n      t = (lo + hi) / 2;\n    }\n    return t;\n  };\n\n  return (x: number) => (x <= 0 ? 0 : x >= 1 ? 1 : at(solveX(x), y1, y2));\n}\n\n/** Motion's named eases, as the cubic-beziers they are. */\nexport const MOTION_EASE = {\n  linear: [0, 0, 1, 1],\n  easeIn: [0.42, 0, 1, 1],\n  easeOut: [0, 0, 0.58, 1],\n  easeInOut: [0.42, 0, 0.58, 1],\n  circIn: [0.55, 0, 1, 0.45],\n  circOut: [0.55, 0, 0.45, 1],\n  circInOut: [0.85, 0, 0.15, 1],\n  backIn: [0.31, 0.01, 0.66, -0.59],\n  backOut: [0.33, 1.53, 0.69, 0.99],\n  anticipate: [0.66, -0.56, 0.34, 1.35],\n} as const;\n\n/**\n * Motion's default layout transition (`layout` / `layoutId`):\n * `{ duration: 0.45, ease: [0.4, 0, 0.1, 1] }`.\n */\nexport const LAYOUT_TRANSITION = { duration: 0.45, ease: [0.4, 0, 0.1, 1] as const };\n\n// ---------------------------------------------------------------------------\n// Spring\n// ---------------------------------------------------------------------------\n\nexport interface SpringOptions {\n  /** Motion default 100. */\n  stiffness?: number;\n  /** Motion default 10. */\n  damping?: number;\n  /** Motion default 1. */\n  mass?: number;\n  /** Starting velocity, in units of the whole distance per second. */\n  velocity?: number;\n  /** How close to the end counts as settled, as a fraction of the distance. */\n  restDelta?: number;\n}\n\n/**\n * Normalised position (0 → 1) of a spring released from 0 towards 1, at time\n * `t` seconds. The closed-form solution Motion's `spring()` generator\n * uses for the under-, critically and over-damped cases.\n */\nexport function springAt(options: SpringOptions = {}) {\n  const { stiffness = 100, damping = 10, mass = 1, velocity = 0 } = options;\n  const zeta = damping / (2 * Math.sqrt(stiffness * mass));\n  const omega0 = Math.sqrt(stiffness / mass);\n  // Motion's convention: distance still to cover, velocity toward it negated.\n  const delta = 1;\n  const v0 = -velocity;\n\n  if (zeta < 1) {\n    const omegaD = omega0 * Math.sqrt(1 - zeta * zeta);\n    return (t: number) => {\n      const envelope = Math.exp(-zeta * omega0 * t);\n      return (\n        1 -\n        envelope *\n          (((v0 + zeta * omega0 * delta) / omegaD) * Math.sin(omegaD * t) +\n            delta * Math.cos(omegaD * t))\n      );\n    };\n  }\n  if (zeta === 1) {\n    return (t: number) => 1 - Math.exp(-omega0 * t) * (delta + (v0 + omega0 * delta) * t);\n  }\n  const omegaD = omega0 * Math.sqrt(zeta * zeta - 1);\n  return (t: number) => {\n    const envelope = Math.exp(-zeta * omega0 * t);\n    const freq = Math.min(omegaD * t, 300);\n    return (\n      1 -\n      (envelope *\n        ((v0 + zeta * omega0 * delta) * Math.sinh(freq) + omegaD * delta * Math.cosh(freq))) /\n        omegaD\n    );\n  };\n}\n\n/** Seconds until the spring stays within `restDelta` of its end. */\nexport function springDuration(options: SpringOptions = {}) {\n  const at = springAt(options);\n  const restDelta = options.restDelta ?? 0.001;\n  const step = 1 / 240;\n  let lastOutside = 0;\n  for (let t = 0; t <= 10; t += step) {\n    if (Math.abs(1 - at(t)) > restDelta) lastOutside = t;\n    else if (t - lastOutside > 0.1) break;\n  }\n  return Math.max(lastOutside + step, step);\n}\n\n/**\n * A spring as a duration and an easing function over it — what GSAP takes:\n *\n *   const { duration, ease } = springEase({ stiffness: 300, damping: 20 });\n *   gsap.to(el, { y: 0, duration, ease });\n *\n * Exact for a fixed start and end; a spring that has to react mid-flight to a\n * new target needs `createSpringFollower` instead.\n */\nexport function springEase(options: SpringOptions = {}) {\n  const duration = springDuration(options);\n  const at = springAt(options);\n  return {\n    duration,\n    ease: (progress: number) => (progress >= 1 ? 1 : at(progress * duration)),\n  };\n}\n\n/**\n * A spring as a CSS `linear()` easing and its duration in ms, for\n * `transition` / `animation` with a fixed start and end.\n *\n *   const { easing, duration } = springLinear({ stiffness: 400, damping: 30 });\n *   el.style.transition = `transform ${duration}ms ${easing}`;\n */\nexport function springLinear(options: SpringOptions = {}, pointsPerSecond = 60) {\n  const duration = springDuration(options);\n  const at = springAt(options);\n  const count = Math.max(Math.ceil(duration * pointsPerSecond), 8);\n  const points: string[] = [];\n  for (let i = 0; i <= count; i++) {\n    const t = (i / count) * duration;\n    points.push(String(Math.round((i === count ? 1 : at(t)) * 10000) / 10000));\n  }\n  return { easing: `linear(${points.join(\", \")})`, duration: Math.round(duration * 1000) };\n}\n\n// ---------------------------------------------------------------------------\n// Spring follower (useSpring equivalent)\n// ---------------------------------------------------------------------------\n\n/** Something that calls back once per frame with the time since the last, in ms. */\nexport interface FrameTicker {\n  add: (callback: (deltaMs: number) => void) => () => void;\n}\n\n/** requestAnimationFrame as a ticker — the library-free default. */\nexport const rafTicker: FrameTicker = {\n  add(callback) {\n    let last = performance.now();\n    let frame = requestAnimationFrame(function tick(now) {\n      callback(now - last);\n      last = now;\n      frame = requestAnimationFrame(tick);\n    });\n    return () => cancelAnimationFrame(frame);\n  },\n};\n\nexport interface SpringFollower {\n  /** Chase a new target from wherever the value is now, keeping its velocity. */\n  set: (target: number) => void;\n  /** Move to a value instantly, with no motion. */\n  jump: (value: number) => void;\n  get: () => number;\n  destroy: () => void;\n}\n\n/**\n * A value that follows its target through a spring, integrating the same\n * equation of motion Motion's `useSpring` solves — so a pointer-driven spring\n * reads the same in every build. Runs only while moving; `onUpdate` receives\n * each new value.\n */\nexport function createSpringFollower(\n  initial: number,\n  onUpdate: (value: number) => void,\n  options: SpringOptions & { restSpeed?: number; ticker?: FrameTicker } = {},\n): SpringFollower {\n  const { stiffness = 100, damping = 10, mass = 1, ticker = rafTicker } = options;\n  const restDelta = options.restDelta ?? 0.01;\n  const restSpeed = options.restSpeed ?? 0.01;\n  let value = initial;\n  let target = initial;\n  let velocity = 0;\n  let stop: (() => void) | null = null;\n\n  const step = (deltaMs: number) => {\n    // Fixed 1ms sub-steps keep the integration stable for stiff springs and\n    // independent of the frame rate.\n    const steps = Math.min(Math.max(Math.round(deltaMs), 1), 250);\n    for (let i = 0; i < steps; i++) {\n      const force = -stiffness * (value - target) - damping * velocity;\n      velocity += (force / mass) * 0.001;\n      value += velocity * 0.001;\n    }\n    if (Math.abs(target - value) < restDelta && Math.abs(velocity) < restSpeed) {\n      value = target;\n      velocity = 0;\n      stop?.();\n      stop = null;\n    }\n    onUpdate(value);\n  };\n\n  return {\n    set(next) {\n      target = next;\n      if (!stop && value !== target) stop = ticker.add(step);\n    },\n    jump(next) {\n      stop?.();\n      stop = null;\n      value = target = next;\n      velocity = 0;\n      onUpdate(value);\n    },\n    get: () => value,\n    destroy() {\n      stop?.();\n      stop = null;\n    },\n  };\n}\n",
      "type": "registry:component",
      "target": "components/custom/blocks/motion-curves.ts"
    }
  ],
  "docs": "Named export: FloatingContactButtonBlock. `position` is bottom-right | bottom-left; `containerMode` fixed pins it to the viewport while absolute scopes it to a parent. Open state survives reloads via `localStorageKey`. Messages are local — connect your own backend.",
  "categories": [
    "communication",
    "marketing"
  ],
  "type": "registry:component"
}
