{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-chat",
  "title": "AI Chat",
  "author": "AlgorizeTech",
  "description": "Ask the user to pick one of 5 ai chat variants: https://avaraui.com/view/ai-chat. This item holds 5 of them as looks of one component (default, compact, minimal, glass, liquid-glass). Skip the question if the user already named one. An AI assistant interface with thread history sidebar, streaming-style responses and a prompt composer. Use it as the front end for an LLM feature.",
  "dependencies": [
    "gsap",
    "lucide-react"
  ],
  "registryDependencies": [
    "https://avaraui.com/r/ui-liquid-glass.json",
    "utils"
  ],
  "files": [
    {
      "path": "src/components/custom/blocks/Ai-chat.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport gsap from \"gsap\";\nimport {\n  Bot,\n  Calendar,\n  ChartLine,\n  Check,\n  ChevronDown,\n  CircleHelp,\n  Copy,\n  Cpu,\n  Crown,\n  Edit2,\n  FileText,\n  Gauge,\n  Globe,\n  ImageIcon,\n  Mail,\n  Menu,\n  MessageSquare,\n  Mic,\n  MoreVertical,\n  Paperclip,\n  Plus,\n  Rocket,\n  Send,\n  Settings,\n  Sparkles,\n  ThumbsDown,\n  ThumbsUp,\n  Trash2,\n  X,\n  Zap,\n} from \"lucide-react\";\nimport {\n  createRef,\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useInsertionEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { bezierEase } from \"./gsap-motion\";\nimport { SurfaceContext, useSurface } from \"./glass-panel-context\";\nimport { MOTION_EASE, springEase, springLinear } from \"./motion-curves\";\n\n// ==========================================\n// VARIANT & COLOR CONFIGURATION\n// ==========================================\nexport type AIChatVariant = \"default\" | \"minimal\" | \"glass\" | \"compact\" | \"liquid-glass\";\n\nimport {\n  LiquidGlassBackground,\n  LiquidGlassSvgFilter,\n  formatRadius,\n} from \"@/components/custom/ui/liquid-glass\";\nexport { LiquidGlassSvgFilter };\n\n// We use (string & {}) to preserve IDE autocomplete for the predefined types\n// while still allowing any arbitrary hex string like \"#000fff\".\nexport type AIChatColor =\n  | \"indigo\"\n  | \"rose\"\n  | \"emerald\"\n  | \"zinc\"\n  | (string & {});\n\nconst chatVariants: Record<AIChatVariant, Record<string, string>> = {\n  default: {\n    wrapper:\n      \"bg-background border border-border shadow-none\",\n    sidebar:\n      \"bg-card/95 backdrop-blur-xl border-r border-border shadow-2xl lg:shadow-none rounded-r-2xl rounded-l-none lg:rounded-none\",\n    main: \"bg-background\",\n    header:\n      \"bg-background/80 border-b border-border backdrop-blur-xl\",\n    input: \"bg-muted border border-border\",\n    msgUser: \"text-white rounded-2xl rounded-tr-sm shadow-sm\",\n    msgAi:\n      \"bg-card text-foreground border border-border rounded-2xl rounded-tl-sm shadow-sm\",\n  },\n  minimal: {\n    wrapper: \"bg-transparent border-none shadow-none rounded-none\",\n    sidebar:\n      \"bg-background/95 dark:bg-zinc-900/95 lg:bg-muted/50 backdrop-blur-2xl rounded-r-2xl rounded-l-none lg:rounded-2xl border border-border lg:mr-4 shadow-2xl lg:shadow-none\",\n    main: \"bg-transparent\",\n    header: \"bg-transparent border-b border-border mb-2\",\n    input: \"bg-muted border border-border\",\n    msgUser: \"text-white rounded-2xl rounded-br-sm shadow-sm\",\n    msgAi: \"bg-muted text-foreground rounded-2xl rounded-bl-sm\",\n  },\n  compact: {\n    wrapper:\n      \"bg-background border border-border shadow-none\",\n    sidebar: \"\",\n    main: \"bg-background\",\n    header:\n      \"bg-background/80 border-b border-border backdrop-blur-xl\",\n    input: \"bg-muted border border-border\",\n    msgUser: \"text-white rounded-2xl rounded-tr-sm shadow-sm\",\n    msgAi:\n      \"bg-card text-foreground border border-border rounded-2xl rounded-tl-sm shadow-sm\",\n  },\n  glass: {\n    wrapper:\n      \"bg-white/40 dark:bg-black/40 backdrop-blur-2xl border border-white/20 dark:border-white/10 shadow-2xl\",\n    sidebar:\n      \"bg-white/40 dark:bg-zinc-950/60 lg:bg-white/[0.08] lg:dark:bg-white/[0.03] backdrop-blur-3xl backdrop-saturate-150 border-r border-white/25 dark:border-white/10 shadow-2xl lg:shadow-none rounded-r-2xl rounded-l-none lg:rounded-none\",\n    main: \"bg-transparent\",\n    header:\n      \"bg-white/10 dark:bg-black/10 border-b border-white/20 dark:border-white/10 backdrop-blur-md\",\n    input:\n      \"bg-white/30 dark:bg-black/30 border border-white/30 dark:border-white/10 backdrop-blur-md\",\n    msgUser: \"text-white rounded-2xl rounded-tr-sm shadow-lg\",\n    msgAi:\n      \"bg-white/50 dark:bg-black/50 backdrop-blur-md text-foreground border border-white/30 dark:border-white/10 rounded-2xl rounded-tl-sm\",\n  },\n  \"liquid-glass\": {\n    wrapper:\n      \"bg-transparent border-0 shadow-[0_25px_60px_rgba(0,0,0,0.45)] text-white [--foreground:#ffffff] [--muted-foreground:rgba(255,255,255,0.75)] [--color-foreground:#ffffff] [--color-muted-foreground:rgba(255,255,255,0.75)]\",\n    sidebar:\n      \"bg-white/[0.07] dark:bg-black/25 border-r border-white/20 dark:border-white/10\",\n    main: \"bg-transparent\",\n    header:\n      \"bg-white/[0.07] dark:bg-black/25 border-b border-white/20 dark:border-white/10\",\n    input:\n      \"bg-white/15 dark:bg-black/30 border border-white/20 dark:border-white/10 backdrop-blur-md text-white placeholder:text-white/60\",\n    msgUser: \"text-white rounded-2xl rounded-tr-sm shadow-md border border-white/20\",\n    msgAi:\n      \"bg-white/15 dark:bg-white/10 backdrop-blur-md text-white border border-white/20 dark:border-white/15 rounded-2xl rounded-tl-sm shadow-sm\",\n  },\n};\n\nconst colorThemes: Record<string, Record<string, string>> = {\n  primary: {\n    primaryText: \"text-primary\",\n    primaryBg: \"bg-primary hover:bg-primary/90 text-primary-foreground\",\n    primaryHover: \"hover:text-primary hover:bg-primary/10\",\n    lightBg: \"bg-primary/10 text-foreground\",\n    gradient: \"from-primary to-primary/80\",\n    shadow: \"shadow-primary/20\",\n    ring: \"focus-within:border-primary/50 focus-within:ring-primary/10\",\n    focusRing: \"focus:ring-primary/20\",\n    inputBorder: \"border-primary/30\",\n  },\n  indigo: {\n    primaryText: \"text-indigo-500 dark:text-indigo-400\",\n    primaryBg: \"bg-indigo-500 hover:bg-indigo-600 text-white\",\n    primaryHover:\n      \"hover:text-indigo-500 hover:bg-indigo-50 dark:hover:bg-indigo-500/10\",\n    lightBg:\n      \"bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-300\",\n    gradient: \"from-indigo-500 to-purple-600\",\n    shadow: \"shadow-indigo-500/20\",\n    ring: \"focus-within:border-indigo-500/50 focus-within:ring-indigo-500/10\",\n    focusRing: \"focus:ring-indigo-500/20\",\n    inputBorder: \"border-indigo-300 dark:border-indigo-500/50\",\n  },\n  rose: {\n    primaryText: \"text-rose-500 dark:text-rose-400\",\n    primaryBg: \"bg-rose-500 hover:bg-rose-600 text-white\",\n    primaryHover:\n      \"hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10\",\n    lightBg: \"bg-rose-50 dark:bg-rose-500/10 text-rose-700 dark:text-rose-300\",\n    gradient: \"from-rose-500 to-orange-500\",\n    shadow: \"shadow-rose-500/20\",\n    ring: \"focus-within:border-rose-500/50 focus-within:ring-rose-500/10\",\n    focusRing: \"focus:ring-rose-500/20\",\n    inputBorder: \"border-rose-300 dark:border-rose-500/50\",\n  },\n  emerald: {\n    primaryText: \"text-emerald-500 dark:text-emerald-400\",\n    primaryBg: \"bg-emerald-500 hover:bg-emerald-600 text-white\",\n    primaryHover:\n      \"hover:text-emerald-500 hover:bg-emerald-50 dark:hover:bg-emerald-500/10\",\n    lightBg:\n      \"bg-emerald-50 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-300\",\n    gradient: \"from-emerald-500 to-teal-500\",\n    shadow: \"shadow-emerald-500/20\",\n    ring: \"focus-within:border-emerald-500/50 focus-within:ring-emerald-500/10\",\n    focusRing: \"focus:ring-emerald-500/20\",\n    inputBorder: \"border-emerald-300 dark:border-emerald-500/50\",\n  },\n  zinc: {\n    primaryText: \"text-zinc-900 dark:text-zinc-100\",\n    primaryBg:\n      \"bg-zinc-900 hover:bg-zinc-800 dark:bg-zinc-100 dark:hover:bg-zinc-200 text-white dark:text-zinc-900\",\n    primaryHover:\n      \"hover:text-zinc-900 dark:hover:text-white hover:bg-zinc-100 dark:hover:bg-zinc-800\",\n    lightBg: \"bg-zinc-100 dark:bg-zinc-800/50 text-zinc-900 dark:text-zinc-100\",\n    gradient: \"from-zinc-700 to-zinc-900 dark:from-zinc-300 dark:to-zinc-500\",\n    shadow: \"shadow-zinc-900/10 dark:shadow-white/10\",\n    ring: \"focus-within:border-zinc-500/50 focus-within:ring-zinc-500/10\",\n    focusRing: \"focus:ring-zinc-500/20\",\n    inputBorder: \"border-zinc-300 dark:border-zinc-500/50\",\n  },\n};\n\nexport type ChatThread = {\n  id: number | string;\n  title: string;\n  date: string;\n};\n\n/**\n * Roles the component understands.\n *\n * The `(string & {})` member keeps IDE autocomplete for \"ai\" and \"user\" while\n * still accepting a plain `string`. That lets consumers pass an inferred array\n * literal — `const messages = [{ id: 1, role: \"ai\", ... }]` — without needing\n * `as const` or an explicit `Message[]` annotation. Any role that is not\n * \"user\" is rendered as an AI message.\n */\nexport type MessageRole = \"ai\" | \"user\" | (string & {});\n\n/** A file that travelled with a message — what the bubble renders. */\nexport type MessageAttachment = {\n  id: string;\n  name: string;\n  size: number;\n  type: string;\n  /** Object URL or remote URL; images render as thumbnails when present. */\n  previewUrl?: string;\n};\n\nexport type Message = {\n  id: number | string;\n  role: MessageRole;\n  content: string;\n  time: string;\n  attachments?: MessageAttachment[];\n  /** Display name of the model that produced (or was asked for) this message. */\n  model?: string;\n  /** Display label of the effort level in force for this message. */\n  effort?: string;\n};\n\nexport type ChatModel = {\n  id: string;\n  name: string;\n  description?: string;\n  /** Small tag beside the name, e.g. \"New\" or \"Beta\". */\n  badge?: string;\n  /**\n   * Marks the top paid tier: a gold \"Premium\" badge follows the name, the\n   * picker pill turns gold while it is chosen, and choosing it plays a one-off\n   * flourish on the pill and the prompt bar.\n   */\n  premium?: boolean;\n  /**\n   * Marks the middle paid tier: an electric-blue \"Pro\" badge, a blue pill\n   * while chosen, and its own one-off flourish when picked. `premium` wins if\n   * both are set.\n   */\n  pro?: boolean;\n};\n\ntype ModelTier = \"premium\" | \"pro\";\n\nconst modelTier = (model: ChatModel): ModelTier | undefined =>\n  model.premium ? \"premium\" : model.pro ? \"pro\" : undefined;\n\nexport type EffortLevel = \"low\" | \"medium\" | \"high\" | \"max\" | (string & {});\n\nexport type EffortOption = {\n  id: EffortLevel;\n  label: string;\n  description?: string;\n  /** 1–4, how many bars the indicator lights. */\n  level: number;\n};\n\n/**\n * One row of the composer's \"+\" menu. `action: \"upload\"` opens the file\n * picker; everything else (the default) drops `@Label` into the prompt so the\n * request can name the source it wants.\n */\nexport type ComposerTool = {\n  id: string;\n  label: string;\n  description?: string;\n  icon?: React.ReactNode;\n  action?: \"upload\" | \"mention\";\n};\n\n/** What `onSend` receives — everything the composer knows when a prompt goes out. */\nexport type SendPayload = {\n  content: string;\n  attachments: MessageAttachment[];\n  model: ChatModel;\n  effort: EffortOption;\n  /** Tools named in the prompt as `@Label`, in the order they appear. */\n  tools: ComposerTool[];\n};\n\n/**\n * Bring-your-own upload. Report progress as 0–100; resolve when the file is\n * stored, reject to mark the chip as failed. `signal` aborts when the user\n * removes the chip mid-flight.\n */\nexport type UploadHandler = (\n  file: File,\n  onProgress: (percent: number) => void,\n  signal: AbortSignal,\n) => Promise<void>;\n\ntype UploadStatus = \"uploading\" | \"done\" | \"error\";\n\ntype PendingAttachment = MessageAttachment & {\n  file: File;\n  progress: number;\n  status: UploadStatus;\n};\n\nconst defaultModels: ChatModel[] = [\n  {\n    id: \"lumen-ultra\",\n    name: \"Lumen Ultra\",\n    description: \"Deepest reasoning for hard problems\",\n    premium: true,\n  },\n  {\n    id: \"lumen-plus\",\n    name: \"Lumen Plus\",\n    description: \"Best for everyday complex work\",\n    pro: true,\n  },\n  {\n    id: \"lumen-flash\",\n    name: \"Lumen Flash\",\n    description: \"Fast answers at a lower cost\",\n  },\n  {\n    id: \"lumen-mini\",\n    name: \"Lumen Mini\",\n    description: \"Lightweight, near-instant replies\",\n  },\n];\n\nconst defaultEfforts: EffortOption[] = [\n  { id: \"low\", label: \"Low\", description: \"Quickest reply\", level: 1 },\n  {\n    id: \"medium\",\n    label: \"Medium\",\n    description: \"Balanced speed and depth\",\n    level: 2,\n  },\n  {\n    id: \"high\",\n    label: \"High\",\n    description: \"Thinks longer before answering\",\n    level: 3,\n  },\n  { id: \"max\", label: \"Max\", description: \"Most thorough reasoning\", level: 4 },\n];\n\nconst defaultTools: ComposerTool[] = [\n  {\n    id: \"files\",\n    label: \"Photos & files\",\n    description: \"Upload from this device\",\n    icon: <Paperclip className=\"w-4 h-4\" />,\n    action: \"upload\",\n  },\n  {\n    id: \"web\",\n    label: \"Web search\",\n    description: \"Live results\",\n    icon: <Globe className=\"w-4 h-4\" />,\n  },\n  {\n    id: \"sales\",\n    label: \"Sales data\",\n    description: \"Revenue and churn\",\n    icon: <ChartLine className=\"w-4 h-4\" />,\n  },\n  {\n    id: \"documents\",\n    label: \"Documents\",\n    description: \"Specs, notes, briefs\",\n    icon: <FileText className=\"w-4 h-4\" />,\n  },\n  {\n    id: \"mail\",\n    label: \"Mail\",\n    description: \"Read and draft mail\",\n    icon: <Mail className=\"w-4 h-4\" />,\n  },\n  {\n    id: \"calendar\",\n    label: \"Calendar\",\n    description: \"Events and availability\",\n    icon: <Calendar className=\"w-4 h-4\" />,\n  },\n];\n\n/** `@Label` as it is written into the prompt. */\nconst mentionFor = (tool: ComposerTool) => `@${tool.label}`;\n\nconst formatBytes = (bytes: number) => {\n  if (bytes < 1024) return `${bytes} B`;\n  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;\n  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n};\n\n/**\n * Stand-in for a network upload: eases to 100% over one to three seconds\n * depending on size, with a short hitch near the end the way real transfers\n * have. Swap it out with the `uploadFile` prop.\n */\nconst simulateUpload: UploadHandler = (file, onProgress, signal) =>\n  new Promise<void>((resolve, reject) => {\n    const total = 1400 + Math.min(file.size / 15000, 2200);\n    const start = performance.now();\n    const tick = (now: number) => {\n      if (signal.aborted) {\n        reject(new DOMException(\"Upload cancelled\", \"AbortError\"));\n        return;\n      }\n      const t = Math.min(Math.max((now - start) / total, 0), 1);\n      const eased = 1 - Math.pow(1 - t, 2.4);\n      const hitch = t > 0.72 && t < 0.82 ? 0.72 : eased;\n      onProgress(Math.round(Math.min(hitch, eased) * 100));\n      if (t < 1) requestAnimationFrame(tick);\n      else resolve();\n    };\n    requestAnimationFrame(tick);\n  });\n\nexport default function AIChat({\n  chatHistory = [],\n  initialMessages = [],\n  variant = \"default\",\n  color = \"primary\",\n  showSidebar = variant !== \"compact\",\n  heroTitle = \"What can I help you with?\",\n  heroSubtitle,\n  models = defaultModels,\n  defaultModelId,\n  onModelChange,\n  efforts = defaultEfforts,\n  defaultEffort = \"medium\",\n  onEffortChange,\n  onSend,\n  uploadFile,\n  accept,\n  maxFiles = 6,\n  tools = defaultTools,\n  rounded,\n  className,\n}: {\n  chatHistory?: readonly ChatThread[];\n  initialMessages?: readonly Message[];\n  variant?: AIChatVariant;\n  color?: AIChatColor;\n  /**\n   * Renders the thread history beside the conversation. Off for `compact`,\n   * on for every other variant; pass `false` to drop it from any shell.\n   */\n  showSidebar?: boolean;\n  /**\n   * Shown above the prompt bar while a sidebar-less conversation is still\n   * empty — the hero state before anything has been said.\n   */\n  heroTitle?: string;\n  heroSubtitle?: string;\n  /** Models offered in the composer's picker. */\n  models?: readonly ChatModel[];\n  /** Which model is selected on mount; the first one when omitted. */\n  defaultModelId?: string;\n  onModelChange?: (model: ChatModel) => void;\n  /** Effort levels offered in the composer's picker. */\n  efforts?: readonly EffortOption[];\n  /** Which effort is selected on mount. */\n  defaultEffort?: EffortLevel;\n  onEffortChange?: (effort: EffortOption) => void;\n  /** Fires with the prompt, its finished attachments and the chosen model and effort. */\n  onSend?: (payload: SendPayload) => void;\n  /** Real upload for attachments. Uploads are simulated when omitted. */\n  uploadFile?: UploadHandler;\n  /** Passed to the file input, e.g. \"image/*,.pdf\". Anything when omitted. */\n  accept?: string;\n  /** Maximum attachments on one message. */\n  maxFiles?: number;\n  /** Rows of the \"+\" menu. One `action: \"upload\"` row opens the picker; the rest insert `@Label`. */\n  tools?: readonly ComposerTool[];\n  /** Optional dynamic corner rounding radius value (e.g. \"24px\", \"1.5rem\", or Tailwind class) */\n  rounded?: string | number;\n  className?: string;\n}) {\n  const isCustomHex = color.startsWith(\"#\");\n\n  // 1. If it's a custom hex, we generate opacity variants and inject them into the DOM\n  const customVars = isCustomHex\n    ? ({\n        \"--chat-custom\": color,\n        \"--chat-custom-10\": `${color}1a`, // 10% opacity\n        \"--chat-custom-20\": `${color}33`, // 20% opacity\n        \"--chat-custom-50\": `${color}80`, // 50% opacity\n      } as React.CSSProperties)\n    : {};\n\n  // 2. We dynamically assemble the Tailwind theme mapping to point to our CSS variables\n  const theme = isCustomHex\n    ? {\n        primaryText: \"text-[var(--chat-custom)]\",\n        primaryBg: \"bg-[var(--chat-custom)] hover:brightness-110 text-white\",\n        primaryHover:\n          \"hover:text-[var(--chat-custom)] hover:bg-[var(--chat-custom-10)]\",\n        lightBg: \"bg-[var(--chat-custom-10)] text-[var(--chat-custom)]\",\n        gradient: \"from-[var(--chat-custom)] to-[var(--chat-custom-50)]\",\n        shadow: \"shadow-[0_4px_14px_0_var(--chat-custom-20)]\",\n        ring: \"focus-within:border-[var(--chat-custom-50)] focus-within:ring-2 focus-within:ring-[var(--chat-custom-10)]\",\n        focusRing: \"focus:ring-2 focus:ring-[var(--chat-custom-20)]\",\n        inputBorder: \"border-[var(--chat-custom-50)]\",\n      }\n    : colorThemes[color] || colorThemes[\"primary\"];\n\n  const styles = chatVariants[variant];\n  const inheritedSurface = useSurface();\n  const isLiquid = variant === \"liquid-glass\" || inheritedSurface === \"liquid-glass\";\n  const surfaceValue = isLiquid ? \"liquid-glass\" : inheritedSurface;\n\n  // Ink for the accent-gradient tiles, read off `theme.primaryBg` so it matches\n  // the button text: `primary` pairs with primary-foreground, not white.\n  const onAccentText =\n    theme.primaryBg\n      .split(\" \")\n      .filter((c) => c.startsWith(\"text-\") || c.startsWith(\"dark:text-\"))\n      .join(\" \") || \"text-primary-foreground\";\n\n  // Without a sidebar there is nothing to pick a thread from, so an empty\n  // history starts one conversation seeded with `initialMessages`.\n  const [threads] = useState<readonly ChatThread[]>(() =>\n    chatHistory.length === 0 && !showSidebar\n      ? [{ id: \"conversation\", title: \"New Conversation\", date: \"Today\" }]\n      : chatHistory,\n  );\n\n  const [chats, setChats] = useState<ChatThread[]>(() => [...threads]);\n  const [activeChatId, setActiveChatId] = useState<number | string | null>(\n    threads.length > 0 ? threads[0].id : null,\n  );\n\n  const [messagesMap, setMessagesMap] = useState<\n    Record<string | number, Message[]>\n  >(() => {\n    const map: Record<string | number, Message[]> = {};\n    threads.forEach((chat, index) => {\n      map[chat.id] =\n        index === 0\n          ? [...initialMessages]\n          : [\n              {\n                id: `welcome-${chat.id}`,\n                role: \"ai\",\n                content: `Hello! You are viewing the chat: \"${chat.title}\". How can I help you further?`,\n                time: new Date().toLocaleTimeString([], {\n                  hour: \"2-digit\",\n                  minute: \"2-digit\",\n                }),\n              },\n            ];\n    });\n    return map;\n  });\n\n  const [inputValue, setInputValue] = useState(\"\");\n  const [isTyping, setIsTyping] = useState(false);\n  const [isSidebarOpen, setIsSidebarOpen] = useState(false);\n  const [editingChatId, setEditingChatId] = useState<number | string | null>(\n    null,\n  );\n  const [editTitleValue, setEditTitleValue] = useState(\"\");\n\n  const [selectedModelId, setSelectedModelId] = useState<string>(\n    () => defaultModelId ?? models[0]?.id ?? \"\",\n  );\n  const [selectedEffortId, setSelectedEffortId] =\n    useState<EffortLevel>(defaultEffort);\n  const [attachments, setAttachments] = useState<PendingAttachment[]>([]);\n  const [isDragging, setIsDragging] = useState(false);\n  const [openMenu, setOpenMenu] = useState<\"tools\" | \"model\" | \"effort\" | null>(\n    null,\n  );\n  // Counts tier picks while the flourish plays (0 = idle); each new value\n  // remounts the flourish so a quick re-pick replays it from the start.\n  const [tierFx, setTierFx] = useState(0);\n\n  const composerRef = useRef<HTMLFormElement>(null);\n  const fileInputRef = useRef<HTMLInputElement>(null);\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const abortControllers = useRef(new Map<string, AbortController>());\n\n  const selectedModel =\n    models.find((m) => m.id === selectedModelId) ??\n    models[0] ??\n    defaultModels[1];\n  const selectedEffort =\n    efforts.find((e) => e.id === selectedEffortId) ??\n    efforts[0] ??\n    defaultEfforts[1];\n\n  const isUploading = attachments.some((a) => a.status === \"uploading\");\n\n  const chatScrollRef = useRef<HTMLDivElement>(null);\n  const activeMessages = activeChatId ? messagesMap[activeChatId] || [] : [];\n\n  const voice = useVoiceInput(\n    useCallback((transcript: string) => setInputValue(transcript), []),\n    () => inputValue,\n  );\n\n  // Abort in-flight uploads when the component unmounts.\n  useEffect(() => {\n    const controllers = abortControllers.current;\n    return () => {\n      controllers.forEach((c) => c.abort());\n      controllers.clear();\n    };\n  }, []);\n\n  const updateAttachment = (id: string, patch: Partial<PendingAttachment>) =>\n    setAttachments((prev) =>\n      prev.map((a) => (a.id === id ? { ...a, ...patch } : a)),\n    );\n\n  const addFiles = (incoming: FileList | File[]) => {\n    const room = Math.max(0, maxFiles - attachments.length);\n    const next: PendingAttachment[] = Array.from(incoming)\n      .slice(0, room)\n      .map((file) => ({\n        id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n        name: file.name,\n        size: file.size,\n        type: file.type,\n        previewUrl: file.type.startsWith(\"image/\")\n          ? URL.createObjectURL(file)\n          : undefined,\n        file,\n        progress: 0,\n        status: \"uploading\",\n      }));\n    if (next.length === 0) return;\n\n    setAttachments((prev) => [...prev, ...next]);\n\n    const upload = uploadFile ?? simulateUpload;\n    next.forEach((att) => {\n      const controller = new AbortController();\n      abortControllers.current.set(att.id, controller);\n      upload(\n        att.file,\n        (pct) => updateAttachment(att.id, { progress: pct }),\n        controller.signal,\n      )\n        .then(() => updateAttachment(att.id, { progress: 100, status: \"done\" }))\n        .catch((err: unknown) => {\n          if ((err as { name?: string })?.name !== \"AbortError\")\n            updateAttachment(att.id, { status: \"error\" });\n        })\n        .finally(() => abortControllers.current.delete(att.id));\n    });\n  };\n\n  const removeAttachment = (id: string) => {\n    abortControllers.current.get(id)?.abort();\n    setAttachments((prev) => {\n      const target = prev.find((a) => a.id === id);\n      if (target?.previewUrl) URL.revokeObjectURL(target.previewUrl);\n      return prev.filter((a) => a.id !== id);\n    });\n  };\n\n  /** Runs a \"+\" menu row: open the picker, or write `@Label` at the caret. */\n  const runTool = (tool: ComposerTool) => {\n    setOpenMenu(null);\n    if (tool.action === \"upload\") {\n      fileInputRef.current?.click();\n      return;\n    }\n    const token = mentionFor(tool);\n    const el = textareaRef.current;\n    const value = inputValue;\n    const already = value.includes(token);\n    let caret = value.length;\n    if (!already) {\n      const start = el?.selectionStart ?? value.length;\n      const end = el?.selectionEnd ?? value.length;\n      const before = value.slice(0, start);\n      const after = value.slice(end);\n      const lead = before && !/\\s$/.test(before) ? \" \" : \"\";\n      const trail = after && !/^\\s/.test(after) ? \" \" : \" \";\n      const next = `${before}${lead}${token}${trail}${after}`;\n      caret = (before + lead + token + trail).length;\n      setInputValue(next);\n    }\n    requestAnimationFrame(() => {\n      el?.focus();\n      el?.setSelectionRange(caret, caret);\n    });\n  };\n\n  const selectModel = (model: ChatModel) => {\n    // A pick outside the tiers cuts a flourish that is still playing short.\n    if (model.id !== selectedModel.id) {\n      const animate =\n        !!modelTier(model) &&\n        !window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n      setTierFx((n) => (animate ? n + 1 : 0));\n    }\n    setSelectedModelId(model.id);\n    setOpenMenu(null);\n    onModelChange?.(model);\n  };\n\n  const selectEffort = (effort: EffortOption) => {\n    setSelectedEffortId(effort.id);\n    onEffortChange?.(effort);\n  };\n\n  const maxEffortLevel = Math.max(...efforts.map((e) => e.level));\n  const isMaxEffort = selectedEffort.level >= maxEffortLevel;\n  const selectedTier = modelTier(selectedModel);\n  const tierLook = selectedTier && TIERS[selectedTier];\n\n  useEffect(() => {\n    if (chatScrollRef.current) {\n      chatScrollRef.current.scrollTop = chatScrollRef.current.scrollHeight;\n    }\n  }, [activeMessages, isTyping]);\n\n  const handleNewChat = () => {\n    const newId = Date.now();\n    const newChat = { id: newId, title: \"New Conversation\", date: \"Today\" };\n\n    setChats([newChat, ...chats]);\n    setMessagesMap((prev) => ({\n      ...prev,\n      // Without a sidebar a new thread starts at the hero, not at a greeting.\n      [newId]: showSidebar\n        ? [\n            {\n              id: Date.now() + 1,\n              role: \"ai\",\n              content:\n                \"Hello! I am your AI assistant. How can I help you today?\",\n              time: new Date().toLocaleTimeString([], {\n                hour: \"2-digit\",\n                minute: \"2-digit\",\n              }),\n            },\n          ]\n        : [],\n    }));\n    setActiveChatId(newId);\n    if (typeof window !== \"undefined\" && window.innerWidth < 1024)\n      setIsSidebarOpen(false);\n  };\n\n  const handleSelectChat = (id: string | number) => {\n    if (editingChatId) return;\n    setActiveChatId(id);\n    if (typeof window !== \"undefined\" && window.innerWidth < 1024)\n      setIsSidebarOpen(false);\n  };\n\n  const startEditingChat = (chat: ChatThread, e: React.MouseEvent) => {\n    e.stopPropagation();\n    setEditingChatId(chat.id);\n    setEditTitleValue(chat.title);\n  };\n\n  const saveEditChat = (\n    id: string | number,\n    e?: React.MouseEvent | React.KeyboardEvent,\n  ) => {\n    e?.stopPropagation();\n    if (!editTitleValue.trim()) return;\n    setChats(\n      chats.map((c) => (c.id === id ? { ...c, title: editTitleValue } : c)),\n    );\n    setEditingChatId(null);\n    setEditTitleValue(\"\");\n  };\n\n  const cancelEditChat = (e?: React.MouseEvent | React.KeyboardEvent) => {\n    e?.stopPropagation();\n    setEditingChatId(null);\n    setEditTitleValue(\"\");\n  };\n\n  const handleDeleteChat = (id: string | number, e: React.MouseEvent) => {\n    e.stopPropagation();\n    const updatedChats = chats.filter((c) => c.id !== id);\n    setChats(updatedChats);\n\n    const updatedMessagesMap = { ...messagesMap };\n    delete updatedMessagesMap[id];\n    setMessagesMap(updatedMessagesMap);\n\n    if (activeChatId === id) {\n      setActiveChatId(updatedChats.length > 0 ? updatedChats[0].id : null);\n    }\n  };\n\n  const handleSendMessage = (e?: React.FormEvent) => {\n    e?.preventDefault();\n    const content = inputValue.trim();\n    if (!activeChatId || isUploading || voice.isListening) return;\n    if (!content && attachments.length === 0) return;\n\n    const sent: MessageAttachment[] = attachments\n      .filter((a) => a.status === \"done\")\n      .map(({ id, name, size, type, previewUrl }) => ({\n        id,\n        name,\n        size,\n        type,\n        previewUrl,\n      }));\n\n    const userMsg: Message = {\n      id: Date.now(),\n      role: \"user\",\n      content,\n      time: new Date().toLocaleTimeString([], {\n        hour: \"2-digit\",\n        minute: \"2-digit\",\n      }),\n      attachments: sent.length ? sent : undefined,\n    };\n\n    const mentioned = tools\n      .filter((t) => t.action !== \"upload\" && content.includes(mentionFor(t)))\n      .sort(\n        (a, b) =>\n          content.indexOf(mentionFor(a)) - content.indexOf(mentionFor(b)),\n      );\n\n    onSend?.({\n      content,\n      attachments: sent,\n      model: selectedModel,\n      effort: selectedEffort,\n      tools: mentioned,\n    });\n\n    setMessagesMap((prev) => ({\n      ...prev,\n      [activeChatId]: [...(prev[activeChatId] || []), userMsg],\n    }));\n\n    setChats((prev) =>\n      prev.map((c) =>\n        c.id === activeChatId && c.title === \"New Conversation\"\n          ? {\n              ...c,\n              title:\n                inputValue.slice(0, 25) + (inputValue.length > 25 ? \"...\" : \"\"),\n            }\n          : c,\n      ),\n    );\n\n    setInputValue(\"\");\n    setAttachments([]);\n    setIsTyping(true);\n\n    const fileNote =\n      sent.length > 0\n        ? `I've received ${sent.length === 1 ? sent[0].name : `${sent.length} files`} and read through ${sent.length === 1 ? \"it\" : \"them\"}. `\n        : \"\";\n    const toolNote =\n      mentioned.length > 0\n        ? `Checking ${mentioned.map((t) => t.label).join(\", \")} for you. `\n        : \"\";\n\n    setTimeout(\n      () => {\n        const aiMsg: Message = {\n          id: Date.now() + 1,\n          role: \"ai\",\n          content: `${fileNote}${toolNote}That's a great point! Based on your input, I can process this and generate the optimal solution. Let me know if you need any specific adjustments.`,\n          time: new Date().toLocaleTimeString([], {\n            hour: \"2-digit\",\n            minute: \"2-digit\",\n          }),\n          model: selectedModel.name,\n          effort: selectedEffort.label,\n        };\n\n        setMessagesMap((prev) => ({\n          ...prev,\n          [activeChatId]: [...(prev[activeChatId] || []), aiMsg],\n        }));\n        setIsTyping(false);\n      },\n      // Higher effort \"thinks\" a little longer, so the picker visibly does something.\n      900 + selectedEffort.level * 400,\n    );\n  };\n\n  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n    if (e.key === \"Enter\" && !e.shiftKey) {\n      e.preventDefault();\n      handleSendMessage();\n    }\n    if (e.key === \"Escape\") {\n      setOpenMenu(null);\n      if (voice.isListening) voice.stop();\n    }\n  };\n\n  const isHero = !showSidebar && activeMessages.length === 0 && !isTyping;\n\n  /** The prompt bar — rendered under the thread, or alone in the hero state. */\n  const composer = (\n    <div className=\"p-4 sm:p-6 bg-transparent shrink-0 z-10\">\n      <div className=\"max-w-3xl mx-auto\">\n        <form\n          ref={composerRef}\n          onSubmit={handleSendMessage}\n          onDragOver={(e) => {\n            e.preventDefault();\n            if (!isDragging) setIsDragging(true);\n          }}\n          onDragLeave={(e) => {\n            if (!e.currentTarget.contains(e.relatedTarget as Node))\n              setIsDragging(false);\n          }}\n          onDrop={(e) => {\n            e.preventDefault();\n            setIsDragging(false);\n            if (e.dataTransfer.files.length) addFiles(e.dataTransfer.files);\n          }}\n          className={cn(\n            \"relative flex flex-col gap-1 rounded-2xl p-2 transition-all shadow-sm\",\n            styles.input,\n            theme.ring,\n            isDragging && cn(\"ring-2\", theme.inputBorder),\n            isMaxEffort && cn(\"shadow-lg\", theme.shadow),\n          )}\n        >\n          <MaxEffortGlow active={isMaxEffort} className={theme.primaryText} />\n          {tierFx > 0 && tierLook && (\n            <tierLook.Sweep key={tierFx} onDone={() => setTierFx(0)} />\n          )}\n\n          <input\n            ref={fileInputRef}\n            type=\"file\"\n            multiple\n            accept={accept}\n            className=\"hidden\"\n            onChange={(e) => {\n              if (e.target.files?.length) addFiles(e.target.files);\n              e.target.value = \"\";\n            }}\n          />\n\n          {/* Drop hint */}\n          <Presence\n            show={isDragging}\n            hidden={{ opacity: 0 }}\n            shown={{ opacity: 1 }}\n            {...FADE}\n          >\n            {(ref, style) => (\n              <div\n                ref={ref}\n                style={style}\n                className={cn(\n                  \"absolute inset-0 z-20 rounded-2xl border-2 border-dashed flex items-center justify-center gap-2 text-sm font-semibold bg-background/80 backdrop-blur-sm pointer-events-none\",\n                  theme.inputBorder,\n                  theme.primaryText,\n                )}\n              >\n                <Paperclip className=\"w-4 h-4\" /> Drop files to attach\n              </div>\n            )}\n          </Presence>\n\n          {/* Attachments */}\n          <Presence\n            show={attachments.length > 0}\n            appear={false}\n            hidden={{ opacity: 0, height: 0 }}\n            shown={{ opacity: 1, height: \"auto\" }}\n            duration={0.25}\n            ease={EASE_OUT}\n          >\n            {(ref, style) => (\n              <div ref={ref} style={style} className=\"overflow-hidden\">\n                <AttachmentChips\n                  attachments={attachments}\n                  theme={theme}\n                  onRemove={removeAttachment}\n                />\n              </div>\n            )}\n          </Presence>\n\n          {/* Prompt / listening surface */}\n          <div className=\"relative\">\n            <textarea\n              ref={textareaRef}\n              value={inputValue}\n              onChange={(e) => setInputValue(e.target.value)}\n              onKeyDown={handleKeyDown}\n              placeholder={\n                voice.isListening ? \"\" : \"Message the AI Assistant...\"\n              }\n              className={cn(\n                \"w-full max-h-32 bg-transparent border-none focus:outline-none text-[15px] text-foreground placeholder:text-muted-foreground resize-none py-3 px-2 [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none] cursor-text transition-opacity\",\n                voice.isListening && \"opacity-0 pointer-events-none\",\n              )}\n              rows={1}\n              style={{ minHeight: \"48px\" }}\n            />\n            <Presence\n              show={voice.isListening}\n              hidden={{ opacity: 0, y: 4 }}\n              shown={{ opacity: 1, y: 0 }}\n              duration={0.2}\n              ease={EASE_OUT}\n            >\n              {(ref, style) => (\n                <div\n                  ref={ref}\n                  style={style}\n                  className=\"absolute inset-0 flex items-center gap-3 px-2\"\n                >\n                  <ListeningWave\n                    barsRef={voice.barsRef}\n                    live={voice.hasLiveAudio}\n                    className={theme.primaryText}\n                  />\n                  <div className=\"min-w-0 flex-1\">\n                    <p\n                      className={cn(\n                        \"text-sm font-semibold leading-tight\",\n                        theme.primaryText,\n                      )}\n                    >\n                      Listening…\n                    </p>\n                    <p className=\"text-xs text-muted-foreground truncate\">\n                      {inputValue\n                        ? inputValue\n                        : voice.supportsDictation\n                          ? \"Speak now — tap the mic to stop\"\n                          : \"Dictation isn't available in this browser\"}\n                    </p>\n                  </div>\n                </div>\n              )}\n            </Presence>\n          </div>\n\n          {/* Toolbar */}\n          <div className=\"flex items-center justify-between gap-2\">\n            <div className=\"flex items-center gap-0.5 sm:gap-1 min-w-0\">\n              <ComposerMenu\n                open={openMenu === \"tools\"}\n                onOpenChange={(open) => setOpenMenu(open ? \"tools\" : null)}\n                theme={theme}\n                icon={\n                  <Plus\n                    className={cn(\n                      \"w-[18px] h-[18px] transition-transform duration-200\",\n                      openMenu === \"tools\" && \"rotate-45\",\n                    )}\n                  />\n                }\n                label=\"Add files or tools\"\n                iconOnly\n                width=\"w-[280px] sm:w-[340px]\"\n                boundaryRef={composerRef}\n              >\n                <div className=\"p-1\">\n                  {tools.map((tool) => {\n                    const isUpload = tool.action === \"upload\";\n                    const full = isUpload && attachments.length >= maxFiles;\n                    return (\n                      <button\n                        key={tool.id}\n                        type=\"button\"\n                        role=\"menuitem\"\n                        disabled={full}\n                        onClick={() => runTool(tool)}\n                        className={cn(\n                          \"w-full flex items-center gap-3 px-2.5 sm:px-3 py-2 sm:py-2.5 rounded-lg text-left transition-colors disabled:opacity-40 cursor-pointer disabled:cursor-not-allowed\",\n                          isLiquid\n                            ? \"hover:bg-white/15 text-white\"\n                            : \"hover:bg-muted\",\n                        )}\n                      >\n                        <span\n                          className={cn(\n                            \"shrink-0\",\n                            isLiquid ? \"text-white/80\" : \"text-muted-foreground\",\n                          )}\n                        >\n                          {tool.icon ?? <Plus className=\"w-4 h-4\" />}\n                        </span>\n                        <span className=\"min-w-0 flex items-baseline gap-2 truncate\">\n                          <span\n                            className={cn(\n                              \"text-sm font-semibold\",\n                              isLiquid ? \"text-white\" : \"text-foreground\",\n                            )}\n                          >\n                            {tool.label}\n                          </span>\n                          {tool.description && (\n                            <span\n                              className={cn(\n                                \"text-xs truncate\",\n                                isLiquid ? \"text-white/70\" : \"text-muted-foreground\",\n                              )}\n                            >\n                              {tool.description}\n                            </span>\n                          )}\n                        </span>\n                      </button>\n                    );\n                  })}\n                </div>\n              </ComposerMenu>\n\n              <ComposerMenu\n                open={openMenu === \"model\"}\n                onOpenChange={(open) => setOpenMenu(open ? \"model\" : null)}\n                theme={theme}\n                icon={\n                  tierLook ? (\n                    <tierLook.Icon\n                      key={tierFx}\n                      className={cn(\n                        \"w-3.5 h-3.5 mb-0.25\",\n                        tierFx > 0 && tierLook.iconPop,\n                      )}\n                    />\n                  ) : (\n                    <Cpu className=\"w-3.5 h-3.5 mb-0.25\" />\n                  )\n                }\n                label={selectedModel.name}\n                heading=\"Model\"\n                highlighted={!!tierLook}\n                highlightClassName={tierLook ? tierLook.pill : undefined}\n                flourish={\n                  tierFx > 0 && tierLook && <tierLook.PillFlash key={tierFx} />\n                }\n                boundaryRef={composerRef}\n              >\n                {models.map((model) => {\n                  const active = model.id === selectedModel.id;\n                  const tier = modelTier(model);\n                  return (\n                    <MenuItem\n                      key={model.id}\n                      active={active}\n                      theme={theme}\n                      onClick={() => selectModel(model)}\n                    >\n                      <div className=\"min-w-0 flex-1\">\n                        <div className=\"flex items-center gap-1.5\">\n                          <span className=\"text-sm font-semibold truncate\">\n                            {model.name}\n                          </span>\n                          {model.badge && (\n                            <span\n                              className={cn(\n                                \"text-[9px] font-semibold uppercase tracking-wide px-1.5 py-px rounded-full\",\n                                isLiquid ? \"bg-white/20 text-white\" : theme.lightBg,\n                              )}\n                            >\n                              {model.badge}\n                            </span>\n                          )}\n                          {tier && <TierBadge tier={tier} />}\n                        </div>\n                        {model.description && (\n                          <p\n                            className={cn(\n                              \"text-xs truncate\",\n                              isLiquid ? \"text-white/70\" : \"text-muted-foreground\",\n                            )}\n                          >\n                            {model.description}\n                          </p>\n                        )}\n                      </div>\n                    </MenuItem>\n                  );\n                })}\n              </ComposerMenu>\n\n              <ComposerMenu\n                open={openMenu === \"effort\"}\n                onOpenChange={(open) => setOpenMenu(open ? \"effort\" : null)}\n                theme={theme}\n                icon={\n                  isMaxEffort ? (\n                    <Sparkles className=\"w-3.5 h-3.5 mb-0.25\" />\n                  ) : (\n                    <Gauge className=\"w-3.5 h-3.5 mb-0.25\" />\n                  )\n                }\n                label={selectedEffort.label}\n                highlighted={isMaxEffort}\n                width=\"w-60 sm:w-72\"\n                boundaryRef={composerRef}\n              >\n                <div className=\"p-2.5 sm:p-3\">\n                  <div className=\"flex items-center justify-between gap-3\">\n                    <p\n                      className={cn(\n                        \"text-xs sm:text-sm font-medium leading-none\",\n                        isLiquid ? \"text-white/80\" : \"text-muted-foreground\",\n                      )}\n                    >\n                      Effort\n                      <span\n                        className={cn(\n                          \"ml-2 font-semibold\",\n                          isLiquid ? \"text-white\" : \"text-foreground\",\n                        )}\n                      >\n                        {selectedEffort.label}\n                      </span>\n                    </p>\n                    <span\n                      title={\n                        selectedEffort.description ??\n                        \"How long the model thinks before answering\"\n                      }\n                      className={cn(\n                        \"p-0.5 -mr-0.5 rounded-full cursor-help transition-colors\",\n                        isLiquid\n                          ? \"text-white/70 hover:text-white\"\n                          : \"text-muted-foreground/70 hover:text-foreground\",\n                      )}\n                    >\n                      <CircleHelp className=\"w-3.5 h-3.5 sm:w-4 sm:h-4\" />\n                    </span>\n                  </div>\n                  <div\n                    className={cn(\n                      \"mt-3 sm:mt-4 mb-1.5 sm:mb-2 flex items-center justify-between text-[11px] sm:text-xs font-medium leading-none\",\n                      isLiquid ? \"text-white/70\" : \"text-muted-foreground\",\n                    )}\n                  >\n                    <span>Faster</span>\n                    <span>Smarter</span>\n                  </div>\n                  <EffortSlider\n                    efforts={efforts}\n                    value={efforts.findIndex((e) => e.id === selectedEffort.id)}\n                    onChange={(i) => selectEffort(efforts[i])}\n                    theme={theme}\n                  />\n                </div>\n              </ComposerMenu>\n            </div>\n\n            <div className=\"flex items-center gap-1 shrink-0\">\n              <button\n                type=\"button\"\n                onClick={() => {\n                  voice.toggle();\n                  if (voice.isListening) textareaRef.current?.focus();\n                }}\n                title={voice.isListening ? \"Stop listening\" : \"Dictate\"}\n                aria-pressed={voice.isListening}\n                className={cn(\n                  \"relative p-1.5 sm:p-2 rounded-xl transition-colors cursor-pointer\",\n                  voice.isListening\n                    ? cn(\"text-white shadow-md\", theme.primaryBg)\n                    : cn(\"text-muted-foreground\", theme.primaryHover),\n                )}\n              >\n                {voice.isListening && (\n                  <>\n                    <span\n                      className={cn(\n                        \"absolute inset-0 rounded-xl animate-ping opacity-40\",\n                        theme.primaryBg,\n                      )}\n                    />\n                    <span\n                      className={cn(\n                        \"absolute -inset-1 rounded-2xl opacity-30 blur-sm\",\n                        theme.primaryBg,\n                      )}\n                    />\n                  </>\n                )}\n                <Mic className=\"relative w-4 h-4 sm:w-5 sm:h-5\" />\n              </button>\n              <button\n                type=\"submit\"\n                disabled={\n                  (!inputValue.trim() && attachments.length === 0) ||\n                  isUploading ||\n                  voice.isListening\n                }\n                className={cn(\n                  \"p-2 sm:p-2.5 rounded-xl hover:scale-105 active:scale-95 disabled:opacity-50 disabled:hover:scale-100 transition-all shadow-sm cursor-pointer disabled:cursor-not-allowed\",\n                  theme.primaryBg,\n                )}\n                title={\n                  isUploading ? \"Waiting for uploads to finish\" : \"Send message\"\n                }\n              >\n                <Send className=\"w-4 h-4\" />\n              </button>\n            </div>\n          </div>\n        </form>\n        <p className=\"text-center text-[11px] font-medium text-muted-foreground mt-3 cursor-default\">\n          AI can make mistakes. Consider verifying important information.\n        </p>\n      </div>\n    </div>\n  );\n\n  const formattedRadius = formatRadius(rounded);\n  const dynamicRadiusStyle: React.CSSProperties =\n    formattedRadius !== undefined\n      ? { borderRadius: formattedRadius }\n      : typeof rounded === \"string\"\n        ? {}\n        : { borderRadius: \"var(--radius-3xl, 1.5rem)\" };\n\n  return (\n    <SurfaceContext.Provider value={surfaceValue}>\n      <div\n        style={{\n          ...customVars,\n          ...dynamicRadiusStyle,\n        }}\n      className={cn(\n        \"w-full max-w-full h-[650px] sm:h-[750px] flex overflow-hidden relative font-sans box-border transition-colors duration-300 isolate [contain:paint] [transform:translateZ(0)]\",\n        typeof rounded === \"string\" && !formatRadius(rounded) ? rounded : \"\",\n        styles.wrapper,\n        className,\n      )}\n    >\n      <style>{MOTION_CSS}</style>\n      <LiquidGlassSvgFilter />\n      {variant === \"liquid-glass\" && (\n        <LiquidGlassBackground radius={formattedRadius ?? \"var(--radius-3xl, 1.5rem)\"} />\n      )}\n\n      {/* === LEFT SIDEBAR === */}\n      {showSidebar && (\n        <aside\n          className={cn(\n            `absolute lg:relative z-30 w-[280px] max-w-[85vw] shrink-0 h-full flex flex-col transition-transform duration-300 ease-in-out ${isSidebarOpen ? \"translate-x-0\" : \"-translate-x-full lg:translate-x-0\"}`,\n            \"rounded-l-[inherit] max-lg:rounded-r-2xl lg:rounded-r-none overflow-hidden\",\n            styles.sidebar,\n            variant === \"liquid-glass\" && \"rounded-l-[inherit] max-lg:rounded-r-2xl max-lg:border-r max-lg:border-white/20\",\n          )}\n        >\n          {variant === \"liquid-glass\" && (\n            <LiquidGlassBackground\n              radius={formattedRadius ?? \"var(--radius-3xl, 1.5rem)\"}\n              bgPosition=\"left center\"\n              showOuterShadow={false}\n              contrastOverlayClassName=\"bg-black/35 dark:bg-black/50 backdrop-blur-[2px]\"\n            />\n          )}\n\n          <div\n            className={cn(\n              \"p-5 border-b shrink-0 relative z-10\",\n              variant === \"liquid-glass\" || variant === \"glass\"\n                ? \"border-white/20 dark:border-white/10\"\n                : \"border-border\",\n            )}\n          >\n            <div className=\"flex items-center justify-between mb-4 lg:hidden\">\n              <h2\n                className={cn(\n                  \"font-semibold\",\n                  variant === \"liquid-glass\"\n                    ? \"text-white\"\n                    : variant === \"glass\"\n                      ? \"text-zinc-900 dark:text-white\"\n                      : \"text-foreground\",\n                )}\n              >\n                History\n              </h2>\n              <button\n                onClick={() => setIsSidebarOpen(false)}\n                className={cn(\n                  \"p-1 rounded-lg transition-colors cursor-pointer\",\n                  variant === \"liquid-glass\"\n                    ? \"text-white/70 hover:text-white hover:bg-white/15\"\n                    : variant === \"glass\"\n                      ? \"text-zinc-700 hover:text-zinc-900 hover:bg-white/30 dark:text-zinc-300 dark:hover:text-white dark:hover:bg-white/10\"\n                      : \"text-muted-foreground hover:text-foreground hover:bg-muted/60\",\n                )}\n                aria-label=\"Close sidebar\"\n              >\n                <X className=\"w-5 h-5\" />\n              </button>\n            </div>\n            <button\n              onClick={handleNewChat}\n              className={cn(\n                \"w-full flex items-center justify-center gap-2 py-3 rounded-xl font-semibold transition-all shadow-md active:scale-95 cursor-pointer\",\n                variant === \"liquid-glass\"\n                  ? \"bg-white/20 hover:bg-white/30 text-white border border-white/25 shadow-lg backdrop-blur-md\"\n                  : cn(theme.primaryBg, theme.shadow),\n              )}\n            >\n              <Plus className=\"w-4 h-4\" /> New Chat\n            </button>\n          </div>\n\n          <div className=\"flex-1 overflow-y-auto [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none] p-3 relative z-10\">\n            {[\"Today\", \"Yesterday\", \"Previous 7 Days\"].map((dateGroup) => {\n              const groupChats = chats.filter((c) => c.date === dateGroup);\n              if (groupChats.length === 0) return null;\n\n              return (\n                <div key={dateGroup} className=\"mb-6\">\n                  <p\n                    className={cn(\n                      \"text-[11px] font-semibold uppercase tracking-wider mb-2 px-3\",\n                      variant === \"liquid-glass\"\n                        ? \"text-white/70\"\n                        : variant === \"glass\"\n                          ? \"text-zinc-800 dark:text-zinc-200\"\n                          : \"text-muted-foreground\",\n                    )}\n                  >\n                    {dateGroup}\n                  </p>\n                  <div className=\"space-y-0.5\">\n                    {groupChats.map((chat) => {\n                      const isActive = activeChatId === chat.id;\n                      const isEditing = editingChatId === chat.id;\n\n                      return (\n                        <div\n                          key={chat.id}\n                          onClick={() => handleSelectChat(chat.id)}\n                          className={cn(\n                            \"flex items-center justify-between px-3 py-2.5 rounded-lg cursor-pointer transition-all text-sm group\",\n                            isActive\n                              ? variant === \"liquid-glass\"\n                                ? \"bg-white/20 text-white font-semibold shadow-sm border border-white/20 backdrop-blur-md\"\n                                : variant === \"glass\"\n                                  ? \"bg-white/30 dark:bg-white/15 text-zinc-900 dark:text-white font-semibold shadow-sm border border-white/30 dark:border-white/15 backdrop-blur-md\"\n                                  : cn(\"font-semibold\", theme.lightBg)\n                              : variant === \"liquid-glass\"\n                                ? \"text-white/80 hover:text-white hover:bg-white/10 font-medium\"\n                                : variant === \"glass\"\n                                  ? \"text-zinc-800 dark:text-zinc-200 hover:text-zinc-950 dark:hover:text-white hover:bg-white/15 dark:hover:bg-white/10 font-medium\"\n                                  : \"text-muted-foreground hover:bg-muted font-medium hover:text-foreground\",\n                          )}\n                        >\n                          {isEditing ? (\n                            <div\n                              className=\"flex items-center gap-2 w-full cursor-default\"\n                              onClick={(e) => e.stopPropagation()}\n                            >\n                              <MessageSquare\n                                className={cn(\n                                  \"w-4 h-4 shrink-0\",\n                                  variant === \"liquid-glass\" ? \"text-white\" : theme.primaryText,\n                                )}\n                              />\n                              <input\n                                autoFocus\n                                value={editTitleValue}\n                                onChange={(e) =>\n                                  setEditTitleValue(e.target.value)\n                                }\n                                onKeyDown={(e) => {\n                                  if (e.key === \"Enter\")\n                                    saveEditChat(chat.id, e);\n                                  if (e.key === \"Escape\") cancelEditChat(e);\n                                }}\n                                className={cn(\n                                  \"flex-1 bg-background border rounded px-2 py-0.5 text-xs outline-none text-foreground cursor-text\",\n                                  variant === \"liquid-glass\" && \"bg-black/40 border-white/30 text-white\",\n                                  theme.inputBorder,\n                                  theme.focusRing,\n                                )}\n                              />\n                              <button\n                                onClick={(e) => saveEditChat(chat.id, e)}\n                                className=\"text-emerald-500 hover:text-emerald-400 cursor-pointer shrink-0\"\n                              >\n                                <Check className=\"w-4 h-4\" />\n                              </button>\n                              <button\n                                onClick={cancelEditChat}\n                                className=\"text-rose-500 hover:text-rose-400 cursor-pointer shrink-0\"\n                              >\n                                <X className=\"w-4 h-4\" />\n                              </button>\n                            </div>\n                          ) : (\n                            <>\n                              <div className=\"flex items-center gap-3 truncate pr-2 min-w-0\">\n                                <MessageSquare\n                                  className={cn(\n                                    \"w-4 h-4 shrink-0\",\n                                    isActive\n                                      ? variant === \"liquid-glass\"\n                                        ? \"text-white\"\n                                        : theme.primaryText\n                                      : variant === \"liquid-glass\"\n                                        ? \"text-white/70 group-hover:text-white\"\n                                        : variant === \"glass\"\n                                          ? \"text-zinc-700 dark:text-zinc-300 group-hover:text-zinc-950 dark:group-hover:text-white\"\n                                          : \"text-muted-foreground group-hover:text-foreground\",\n                                  )}\n                                />\n                                <span className=\"truncate\">{chat.title}</span>\n                              </div>\n                              <div className=\"flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0\">\n                                <button\n                                  onClick={(e) => startEditingChat(chat, e)}\n                                  className={cn(\n                                    \"p-1.5 rounded-md transition-colors cursor-pointer\",\n                                    variant === \"liquid-glass\"\n                                      ? \"text-white/70 hover:text-white hover:bg-white/20\"\n                                      : variant === \"glass\"\n                                        ? \"text-zinc-700 hover:text-zinc-950 hover:bg-white/20 dark:text-zinc-300 dark:hover:text-white dark:hover:bg-white/10\"\n                                        : cn(\n                                            \"text-muted-foreground\",\n                                            theme.primaryHover,\n                                          ),\n                                  )}\n                                >\n                                  <Edit2 className=\"w-3.5 h-3.5\" />\n                                </button>\n                                <button\n                                  onClick={(e) => handleDeleteChat(chat.id, e)}\n                                  className={cn(\n                                    \"p-1.5 rounded-md transition-colors cursor-pointer\",\n                                    variant === \"liquid-glass\"\n                                      ? \"text-white/70 hover:text-rose-400 hover:bg-rose-500/20\"\n                                      : variant === \"glass\"\n                                        ? \"text-zinc-700 hover:text-rose-600 hover:bg-rose-500/10 dark:text-zinc-300 dark:hover:text-rose-400\"\n                                        : \"text-muted-foreground hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/20\",\n                                  )}\n                                >\n                                  <Trash2 className=\"w-3.5 h-3.5\" />\n                                </button>\n                              </div>\n                            </>\n                          )}\n                        </div>\n                      );\n                    })}\n                  </div>\n                </div>\n              );\n            })}\n          </div>\n\n          <div\n            className={cn(\n              \"p-4 border-t shrink-0 flex items-center justify-between cursor-pointer transition-colors relative z-10\",\n              variant === \"liquid-glass\"\n                ? \"border-white/20 dark:border-white/10 hover:bg-white/10 text-white\"\n                : variant === \"glass\"\n                  ? \"border-white/20 dark:border-white/10 hover:bg-white/15 dark:hover:bg-white/10\"\n                  : \"border-border hover:bg-muted\",\n            )}\n          >\n            <div className=\"flex items-center gap-3\">\n              <div\n                className={cn(\n                  \"w-8 h-8 rounded-full bg-gradient-to-tr flex items-center justify-center font-semibold text-xs shadow-sm\",\n                  theme.gradient,\n                  theme.primaryBg.includes(\"text-\")\n                    ? theme.primaryBg\n                        .split(\" \")\n                        .filter(\n                          (c) =>\n                            c.startsWith(\"text-\") || c.startsWith(\"dark:text-\"),\n                        )\n                        .join(\" \")\n                    : \"text-primary-foreground\",\n                )}\n              >\n                JM\n              </div>\n              <span\n                className={cn(\n                  \"text-sm font-semibold\",\n                  variant === \"liquid-glass\"\n                    ? \"text-white\"\n                    : variant === \"glass\"\n                      ? \"text-zinc-900 dark:text-white\"\n                      : \"text-foreground\",\n                )}\n              >\n                Joel M.\n              </span>\n            </div>\n            <Settings\n              className={cn(\n                \"w-4 h-4 transition-colors\",\n                variant === \"liquid-glass\"\n                  ? \"text-white/70 hover:text-white\"\n                  : variant === \"glass\"\n                    ? \"text-zinc-700 hover:text-zinc-950 dark:text-zinc-300 dark:hover:text-white\"\n                    : \"text-muted-foreground hover:text-foreground\",\n              )}\n            />\n          </div>\n        </aside>\n      )}\n\n      {showSidebar && isSidebarOpen && (\n        <div\n          className=\"absolute inset-0 z-20 lg:hidden cursor-pointer transition-opacity duration-300 rounded-[inherit] overflow-hidden\"\n          onClick={() => setIsSidebarOpen(false)}\n        >\n          {variant === \"liquid-glass\" ? (\n            <LiquidGlassBackground\n              radius={formattedRadius ?? \"var(--radius-3xl, 1.5rem)\"}\n              showOuterShadow={false}\n              contrastOverlayClassName=\"bg-black/50 dark:bg-black/70 backdrop-blur-md\"\n            />\n          ) : (\n            <div\n              className={cn(\n                \"absolute inset-0 rounded-[inherit]\",\n                variant === \"glass\"\n                  ? \"bg-black/25 dark:bg-black/45 backdrop-blur-[2px]\"\n                  : \"bg-black/50 dark:bg-black/70 backdrop-blur-sm\",\n              )}\n            />\n          )}\n        </div>\n      )}\n\n      {/* === MAIN CHAT AREA === */}\n      <main\n        className={cn(\n          \"flex-1 flex flex-col min-w-0 relative z-10 transition-colors duration-300\",\n          styles.main,\n        )}\n      >\n        {!activeChatId ? (\n          <div className=\"flex-1 flex flex-col items-center justify-center p-6 text-center\">\n            <div\n              className={cn(\n                \"w-24 h-24 bg-gradient-to-tr rounded-3xl flex items-center justify-center mb-6 border border-border rotate-3 shrink-0 shadow-xl\",\n                variant === \"liquid-glass\" && \"border-white/20 shadow-2xl\",\n                theme.gradient,\n                theme.shadow,\n                onAccentText,\n              )}\n            >\n              <Bot className=\"w-10 h-10 -rotate-3\" />\n            </div>\n            <h2\n              className={cn(\n                \"text-2xl font-semibold mb-2\",\n                variant === \"liquid-glass\" ? \"text-white\" : \"text-foreground\",\n              )}\n            >\n              How can I help you today?\n            </h2>\n            <p\n              className={cn(\n                \"text-sm max-w-md mb-8\",\n                variant === \"liquid-glass\" ? \"text-white/70\" : \"text-muted-foreground\",\n              )}\n            >\n              {showSidebar\n                ? \"Select a conversation from the sidebar or start a new one to begin chatting.\"\n                : \"Start a new conversation to begin chatting.\"}\n            </p>\n            <div className=\"flex items-center gap-4\">\n              {showSidebar && (\n                <button\n                  className={cn(\n                    \"lg:hidden px-6 py-2.5 rounded-xl text-sm font-semibold shadow-sm transition-all active:scale-95\",\n                    variant === \"liquid-glass\"\n                      ? \"bg-white/20 hover:bg-white/30 text-white border border-white/25 backdrop-blur-md\"\n                      : \"bg-card border border-border text-foreground\",\n                  )}\n                  onClick={() => setIsSidebarOpen(true)}\n                >\n                  View History\n                </button>\n              )}\n              <button\n                onClick={handleNewChat}\n                className={cn(\n                  \"px-6 py-2.5 rounded-xl text-sm font-semibold transition-all active:scale-95 flex items-center gap-2 shadow-md\",\n                  variant === \"liquid-glass\"\n                    ? \"bg-white/20 hover:bg-white/30 text-white border border-white/25 shadow-lg backdrop-blur-md\"\n                    : cn(theme.primaryBg, theme.shadow),\n                )}\n              >\n                <Plus className=\"w-4 h-4\" /> New Chat\n              </button>\n            </div>\n          </div>\n        ) : isHero ? (\n          <div className=\"flex-1 flex flex-col items-center justify-center min-h-0\">\n            <div className=\"aichat-rise-10 w-full max-w-3xl px-4 sm:px-6 text-center\">\n              <h2\n                className={cn(\n                  \"text-2xl sm:text-4xl font-semibold tracking-tight\",\n                  variant === \"liquid-glass\" ? \"text-white\" : \"text-foreground\",\n                )}\n              >\n                {heroTitle}\n              </h2>\n              {heroSubtitle && (\n                <p\n                  className={cn(\n                    \"mt-2 text-sm sm:text-base\",\n                    variant === \"liquid-glass\" ? \"text-white/70\" : \"text-muted-foreground\",\n                  )}\n                >\n                  {heroSubtitle}\n                </p>\n              )}\n            </div>\n            <div className=\"aichat-rise-14 w-full\">{composer}</div>\n          </div>\n        ) : (\n          <>\n            <header\n              className={cn(\n                \"h-[72px] px-4 sm:px-6 flex justify-between items-center shrink-0 flex-none z-10 transition-colors duration-300\",\n                styles.header,\n              )}\n            >\n              <div className=\"flex items-center gap-3\">\n                {showSidebar && (\n                  <button\n                    className={cn(\n                      \"lg:hidden transition-colors shrink-0\",\n                      variant === \"liquid-glass\"\n                        ? \"text-white/70 hover:text-white\"\n                        : \"text-muted-foreground hover:text-foreground\",\n                    )}\n                    onClick={() => setIsSidebarOpen(true)}\n                  >\n                    <Menu className=\"w-5 h-5\" />\n                  </button>\n                )}\n                <div className=\"flex items-center gap-3\">\n                  <div\n                    className={cn(\n                      \"w-9 h-9 bg-gradient-to-br rounded-xl flex items-center justify-center shadow-sm\",\n                      theme.gradient,\n                      theme.shadow,\n                      theme.primaryBg.includes(\"text-\")\n                        ? theme.primaryBg\n                            .split(\" \")\n                            .filter(\n                              (c) =>\n                                c.startsWith(\"text-\") ||\n                                c.startsWith(\"dark:text-\"),\n                            )\n                            .join(\" \")\n                        : \"text-primary-foreground\",\n                    )}\n                  >\n                    <Sparkles className=\"w-4 h-4\" />\n                  </div>\n                  <div>\n                    <h2\n                      className={cn(\n                        \"text-sm font-semibold leading-tight\",\n                        variant === \"liquid-glass\" ? \"text-white\" : \"text-foreground\",\n                      )}\n                    >\n                      AI Assistant\n                    </h2>\n                    <p\n                      className={cn(\n                        \"text-xs font-medium mt-0.5\",\n                        variant === \"liquid-glass\" ? \"text-emerald-400\" : \"text-emerald-600 dark:text-emerald-400\",\n                      )}\n                    >\n                      Online & Ready\n                    </p>\n                  </div>\n                </div>\n              </div>\n              <div className=\"flex items-center gap-1\">\n                {!showSidebar && (\n                  <button\n                    type=\"button\"\n                    onClick={handleNewChat}\n                    title=\"New chat\"\n                    className={cn(\n                      \"flex items-center gap-1.5 h-9 px-3 rounded-lg text-xs font-semibold transition-colors cursor-pointer\",\n                      variant === \"liquid-glass\"\n                        ? \"bg-white/20 hover:bg-white/30 text-white border border-white/25 shadow-sm\"\n                        : cn(theme.lightBg, theme.primaryText),\n                    )}\n                  >\n                    <Plus className=\"w-4 h-4\" />\n                    <span className=\"hidden sm:inline\">New chat</span>\n                  </button>\n                )}\n                <button\n                  className={cn(\n                    \"p-2 rounded-lg transition-colors\",\n                    variant === \"liquid-glass\"\n                      ? \"text-white/70 hover:text-white hover:bg-white/10\"\n                      : \"text-muted-foreground hover:text-foreground hover:bg-muted\",\n                  )}\n                >\n                  <MoreVertical className=\"w-5 h-5\" />\n                </button>\n              </div>\n            </header>\n\n            <div\n              ref={chatScrollRef}\n              className=\"flex-1 overflow-y-auto p-4 sm:p-6 scroll-smooth\"\n            >\n              <div className=\"flex flex-col gap-6 max-w-3xl mx-auto pb-4\">\n                {activeMessages.map((msg) => (\n                  <div\n                    key={msg.id}\n                    className={`flex gap-4 ${msg.role === \"user\" ? \"flex-row-reverse\" : \"flex-row\"}`}\n                  >\n                    <div className=\"shrink-0\">\n                      {msg.role !== \"user\" ? (\n                        <div\n                          className={cn(\n                            \"w-8 h-8 bg-gradient-to-br rounded-lg flex items-center justify-center shadow-sm\",\n                            theme.gradient,\n                            theme.primaryBg.includes(\"text-\")\n                              ? theme.primaryBg\n                                  .split(\" \")\n                                  .filter(\n                                    (c) =>\n                                      c.startsWith(\"text-\") ||\n                                      c.startsWith(\"dark:text-\"),\n                                  )\n                                  .join(\" \")\n                              : \"text-primary-foreground\",\n                          )}\n                        >\n                          <Bot className=\"w-5 h-5\" />\n                        </div>\n                      ) : (\n                        <div\n                          className={cn(\n                            \"w-8 h-8 rounded-lg bg-gradient-to-tr flex items-center justify-center font-semibold text-xs shadow-sm\",\n                            theme.gradient,\n                            theme.primaryBg.includes(\"text-\")\n                              ? theme.primaryBg\n                                  .split(\" \")\n                                  .filter(\n                                    (c) =>\n                                      c.startsWith(\"text-\") ||\n                                      c.startsWith(\"dark:text-\"),\n                                  )\n                                  .join(\" \")\n                              : \"text-primary-foreground\",\n                          )}\n                        >\n                          JM\n                        </div>\n                      )}\n                    </div>\n\n                    <div\n                      className={`flex flex-col gap-1 max-w-[85%] sm:max-w-[80%] ${msg.role === \"user\" ? \"items-end\" : \"items-start\"}`}\n                    >\n                      <div\n                        className={cn(\n                          `px-5 py-3.5 text-[15px] whitespace-pre-wrap leading-relaxed`,\n                          msg.role === \"user\"\n                            ? cn(styles.msgUser, theme.primaryBg)\n                            : styles.msgAi,\n                        )}\n                      >\n                        {msg.attachments && msg.attachments.length > 0 && (\n                          <div\n                            className={cn(\n                              \"flex flex-wrap gap-2\",\n                              msg.content && \"mb-3\",\n                            )}\n                          >\n                            {msg.attachments.map((file) =>\n                              file.previewUrl &&\n                              file.type.startsWith(\"image/\") ? (\n                                <img\n                                  key={file.id}\n                                  src={file.previewUrl}\n                                  alt={file.name}\n                                  className=\"h-24 max-w-[180px] rounded-xl object-cover border border-white/20\"\n                                />\n                              ) : (\n                                <div\n                                  key={file.id}\n                                  className=\"flex items-center gap-2 rounded-xl bg-current/10 px-3 py-2 text-xs max-w-[220px]\"\n                                >\n                                  <FileText className=\"w-4 h-4 shrink-0 opacity-80\" />\n                                  <span className=\"truncate font-semibold\">\n                                    {file.name}\n                                  </span>\n                                  <span className=\"shrink-0 opacity-70\">\n                                    {formatBytes(file.size)}\n                                  </span>\n                                </div>\n                              ),\n                            )}\n                          </div>\n                        )}\n                        {msg.content}\n                      </div>\n\n                      <div\n                        className={`flex items-center gap-3 mt-1 px-1 ${msg.role === \"user\" ? \"justify-end\" : \"justify-start\"}`}\n                      >\n                        <span\n                          className={cn(\n                            \"text-[10px] font-medium\",\n                            variant === \"liquid-glass\" ? \"text-white/60\" : \"text-muted-foreground\",\n                          )}\n                        >\n                          {msg.time}\n                          {msg.model && (\n                            <span className=\"opacity-80\">\n                              {\" \"}\n                              · {msg.model}\n                              {msg.effort && ` · ${msg.effort} effort`}\n                            </span>\n                          )}\n                        </span>\n                        {msg.role !== \"user\" && (\n                          <div\n                            className={cn(\n                              \"flex items-center gap-1.5\",\n                              variant === \"liquid-glass\" ? \"text-white/70\" : \"text-muted-foreground\",\n                            )}\n                          >\n                            <button\n                              className={cn(\n                                \"p-1 rounded transition-colors\",\n                                variant === \"liquid-glass\"\n                                  ? \"hover:text-white hover:bg-white/10\"\n                                  : \"hover:text-foreground hover:bg-muted\",\n                              )}\n                            >\n                              <Copy className=\"w-3.5 h-3.5\" />\n                            </button>\n                            <button className=\"p-1 hover:text-emerald-500 hover:bg-emerald-50 dark:hover:bg-emerald-500/10 rounded transition-colors\">\n                              <ThumbsUp className=\"w-3.5 h-3.5\" />\n                            </button>\n                            <button className=\"p-1 hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 rounded transition-colors\">\n                              <ThumbsDown className=\"w-3.5 h-3.5\" />\n                            </button>\n                          </div>\n                        )}\n                      </div>\n                    </div>\n                  </div>\n                ))}\n\n                {isTyping && (\n                  <div className=\"flex gap-4 flex-row items-end animate-in fade-in slide-in-from-bottom-2 duration-300\">\n                    <div\n                      className={cn(\n                        \"shrink-0 w-8 h-8 bg-gradient-to-br rounded-lg flex items-center justify-center shadow-sm mb-5\",\n                        theme.gradient,\n                        onAccentText,\n                      )}\n                    >\n                      <Bot className=\"w-5 h-5\" />\n                    </div>\n                    <div\n                      className={cn(\n                        \"px-4 py-3.5 flex items-center gap-1.5 mb-5\",\n                        styles.msgAi,\n                      )}\n                    >\n                      <span\n                        className={cn(\n                          \"w-1.5 h-1.5 rounded-full animate-bounce [animation-delay:-0.3s]\",\n                          variant === \"liquid-glass\" ? \"bg-white/70\" : \"bg-muted-foreground\",\n                        )}\n                      />\n                      <span\n                        className={cn(\n                          \"w-1.5 h-1.5 rounded-full animate-bounce [animation-delay:-0.15s]\",\n                          variant === \"liquid-glass\" ? \"bg-white/70\" : \"bg-muted-foreground\",\n                        )}\n                      />\n                      <span\n                        className={cn(\n                          \"w-1.5 h-1.5 rounded-full animate-bounce\",\n                          variant === \"liquid-glass\" ? \"bg-white/70\" : \"bg-muted-foreground\",\n                        )}\n                      />\n                    </div>\n                  </div>\n                )}\n              </div>\n            </div>\n\n            {composer}\n          </>\n        )}\n      </main>\n    </div>\n  </SurfaceContext.Provider>\n);\n}\n\n// ==========================================\n// COMPOSER PIECES\n// ==========================================\ntype Theme = Record<string, string>;\n\n// ==========================================\n// MOTION\n// ==========================================\n/** Motion's named eases, for the tweens below. */\nconst EASE_OUT = bezierEase(MOTION_EASE.easeOut);\nconst EASE_IN = bezierEase(MOTION_EASE.easeIn);\n/** Motion's default fade: 0.3s on cubic-bezier(0.25, 0.1, 0.35, 1). */\nconst FADE = { duration: 0.3, ease: bezierEase([0.25, 0.1, 0.35, 1]) };\n/** The rocket's launch. */\nconst ROCKET_SPRING = springEase({ stiffness: 260, damping: 16 });\n/** Attachment chips: in, out, and the glide of the others into a gap. */\nconst CHIP_SPRING = springEase({ stiffness: 320, damping: 24 });\n/**\n * When a removed chip is taken out of the tray: the moment its fade-out\n * spring counts as settled (Motion rests an opacity spring once it is within\n * 0.005 and slower than 0.01/s), a little after the motion itself ends.\n */\nconst CHIP_EXIT_SETTLE = 0.65;\n/** The effort slider's thumb and fill. */\nconst SLIDER_SPRING = springEase({ stiffness: 400, damping: 30 });\n\nconst CHECK_SPRING = springLinear({ stiffness: 380, damping: 14 });\nconst FAIL_SPRING = springLinear({ stiffness: 550, damping: 30 });\nconst EASE_IN_OUT_CSS = \"cubic-bezier(0.42, 0, 0.58, 1)\";\nconst EASE_OUT_CSS = \"cubic-bezier(0, 0, 0.58, 1)\";\n/** The premium flourish on the prompt bar: one lap of the edge beam. */\nconst PREMIUM_SWEEP_S = 1.6;\nconst PREMIUM_ORBIT_CSS = \"cubic-bezier(0.45, 0, 0.2, 1)\";\n/** The Pro flourish on the prompt bar: trace, flicker and fade. */\nconst PRO_SURGE_S = 1.3;\n\n/**\n * The fixed, self-running animations — entrances that play once on mount and\n * the loops — as plain CSS. Rendered once by AIChat.\n */\nconst MOTION_CSS = `\n@keyframes aichat-rise-10 { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }\n@keyframes aichat-rise-14 { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: none; } }\n.aichat-rise-10 { animation: aichat-rise-10 0.4s ${EASE_OUT_CSS} backwards; }\n.aichat-rise-14 { animation: aichat-rise-14 0.4s ${EASE_OUT_CSS} 0.08s backwards; }\n\n@keyframes aichat-rocket-bob {\n  0%, 50%, 100% { transform: translateY(0); }\n  25% { transform: translateY(-1.5px); }\n  75% { transform: translateY(1.5px); }\n}\n.aichat-rocket-bob { animation: aichat-rocket-bob 1.4s ${EASE_IN_OUT_CSS} infinite; }\n@keyframes aichat-exhaust {\n  0%, 100% { transform: scaleX(0.6) rotate(-45deg); opacity: 0.7; }\n  25% { transform: scaleX(1.3) rotate(-45deg); opacity: 1; }\n  50% { transform: scaleX(0.8) rotate(-45deg); opacity: 0.8; }\n  75% { transform: scaleX(1.1) rotate(-45deg); opacity: 1; }\n}\n.aichat-exhaust { animation: aichat-exhaust 0.35s ${EASE_IN_OUT_CSS} infinite; }\n\n@keyframes aichat-ring { from { transform: scale(0.4); opacity: 0.9; } to { transform: scale(2.6); opacity: 0; } }\n.aichat-ring { animation: aichat-ring 0.6s ${EASE_OUT_CSS} both; }\n@keyframes aichat-check { from { transform: scale(0) rotate(-90deg); } to { transform: scale(1) rotate(0deg); } }\n.aichat-check { animation: aichat-check ${CHECK_SPRING.duration}ms ${CHECK_SPRING.easing} 0.15s both; }\n@keyframes aichat-pop { from { transform: scale(0); } to { transform: scale(1); } }\n.aichat-pop { animation: aichat-pop ${FAIL_SPRING.duration}ms ${FAIL_SPRING.easing} both; }\n\n@keyframes aichat-glow-pulse { 0%, 100% { opacity: 0.12; } 50% { opacity: 0.26; } }\n.aichat-glow-pulse { animation: aichat-glow-pulse 3.2s ${EASE_IN_OUT_CSS} infinite; }\n@keyframes aichat-speck {\n  0% { opacity: 0; transform: translateY(0) scale(0.4); }\n  50% { opacity: 0.9; transform: translateY(-6px) scale(1.3); }\n  100% { opacity: 0; transform: translateY(-12px) scale(0.4); }\n}\n.aichat-speck { animation: aichat-speck 1s ${EASE_IN_OUT_CSS} infinite backwards; }\n\n@keyframes aichat-premium-life { 0% { opacity: 0; } 10%, 70% { opacity: 1; } 100% { opacity: 0; } }\n.aichat-premium-life { animation: aichat-premium-life ${PREMIUM_SWEEP_S}s linear both; }\n@keyframes aichat-premium-orbit {\n  from { transform: translate(-50%, -50%) rotate(0deg); }\n  to { transform: translate(-50%, -50%) rotate(360deg); }\n}\n.aichat-premium-orbit { animation: aichat-premium-orbit ${PREMIUM_SWEEP_S}s ${PREMIUM_ORBIT_CSS} both; }\n@keyframes aichat-premium-sheen {\n  from { transform: translateX(-120%) skewX(-20deg); }\n  to { transform: translateX(420%) skewX(-20deg); }\n}\n.aichat-premium-sheen { animation: aichat-premium-sheen 1s ${EASE_IN_OUT_CSS} 0.15s both; }\n@keyframes aichat-premium-bloom {\n  0% { opacity: 0; transform: scale(0.98); }\n  35% { opacity: 0.6; }\n  100% { opacity: 0; transform: scale(1.03); }\n}\n.aichat-premium-bloom { animation: aichat-premium-bloom 1.1s ${EASE_OUT_CSS} 0.1s both; }\n@keyframes aichat-premium-ping { from { opacity: 0.8; transform: none; } to { opacity: 0; transform: scale(1.12, 1.45); } }\n.aichat-premium-ping { animation: aichat-premium-ping 0.6s ${EASE_OUT_CSS} both; }\n@keyframes aichat-premium-shine { from { transform: translateX(-100%) skewX(-20deg); } to { transform: translateX(320%) skewX(-20deg); } }\n.aichat-premium-shine { animation: aichat-premium-shine 0.7s ${EASE_IN_OUT_CSS} 0.1s both; }\n@keyframes aichat-crown-pop {\n  0% { transform: scale(0) rotate(-45deg); }\n  60% { transform: scale(1.3) rotate(12deg); }\n  100% { transform: none; }\n}\n.aichat-crown-pop { animation: aichat-crown-pop 0.55s ${EASE_OUT_CSS} both; }\n\n@keyframes aichat-pro-life { 0% { opacity: 0; } 6%, 72% { opacity: 1; } 100% { opacity: 0; } }\n.aichat-pro-life { animation: aichat-pro-life ${PRO_SURGE_S}s linear both; }\n@keyframes aichat-pro-trace { from { clip-path: inset(0 50%); } to { clip-path: inset(0); } }\n@keyframes aichat-pro-flicker {\n  0%, 40%, 80%, 100% { opacity: 1; }\n  20% { opacity: 0.25; }\n  60% { opacity: 0.45; }\n}\n.aichat-pro-trace {\n  animation: aichat-pro-trace 0.5s ${EASE_OUT_CSS} both,\n    aichat-pro-flicker 0.45s linear 0.5s both;\n}\n@keyframes aichat-pro-scan { from { transform: translateY(100%); } to { transform: translateY(-100%); } }\n.aichat-pro-scan { animation: aichat-pro-scan 0.9s ${EASE_IN_OUT_CSS} 0.2s both; }\n@keyframes aichat-pro-charge { 0% { opacity: 0; } 40% { opacity: 0.55; } 100% { opacity: 0; } }\n.aichat-pro-charge { animation: aichat-pro-charge 0.7s ${EASE_OUT_CSS} 0.45s both; }\n@keyframes aichat-pro-flash { 0% { opacity: 0; } 15% { opacity: 0.3; } 30% { opacity: 0.05; } 45% { opacity: 0.25; } 100% { opacity: 0; } }\n.aichat-pro-flash { animation: aichat-pro-flash 0.6s linear both; }\n@keyframes aichat-pro-spark {\n  0% { opacity: 0; transform: translate(-50%, -50%); }\n  10% { opacity: 1; }\n  100% { opacity: 0; transform: translate(calc(-50% + var(--aichat-spark-x)), calc(-50% + var(--aichat-spark-y))) scale(0.3); }\n}\n.aichat-pro-spark { animation: aichat-pro-spark 0.5s ${EASE_OUT_CSS} 0.15s both; }\n@keyframes aichat-zap-strike {\n  0% { opacity: 0; transform: translateY(-8px) scale(0.6); }\n  35% { opacity: 1; transform: translateY(0) scale(1.3); }\n  50% { opacity: 0.35; }\n  65% { opacity: 1; transform: scale(1); }\n  100% { opacity: 1; transform: none; }\n}\n.aichat-zap-strike { animation: aichat-zap-strike 0.5s ${EASE_OUT_CSS} both; }\n\n@keyframes aichat-wave {\n  0%, 100% { transform: scaleY(0.15); }\n  25% { transform: scaleY(var(--aichat-wave-peak)); }\n  50% { transform: scaleY(0.3); }\n  75% { transform: scaleY(var(--aichat-wave-echo)); }\n}\n.aichat-wave { animation: aichat-wave 1s ${EASE_IN_OUT_CSS} infinite backwards; }\n`;\n\ntype PresencePose = { opacity?: number; y?: number; scale?: number; height?: number | \"auto\" };\n\n/** A pose as inline style, for the first frame before any tween runs. */\nconst poseStyle = ({ opacity, y, scale, height }: PresencePose): React.CSSProperties => ({\n  opacity,\n  height,\n  transform: y !== undefined || scale !== undefined ? `translateY(${y ?? 0}px) scale(${scale ?? 1})` : undefined,\n});\n\n/**\n * Mounts its child while `show` is on, and keeps it mounted — frozen as it\n * last rendered — while it animates out: in from `hidden` to `shown`, back to\n * `hidden` on the way out. Turning `show` back on mid-exit reverses from\n * wherever the child is. With `appear={false}`, a child present on the first\n * render starts shown.\n */\nfunction Presence({\n  show,\n  appear = true,\n  hidden,\n  shown,\n  duration,\n  ease,\n  children,\n}: {\n  show: boolean;\n  appear?: boolean;\n  hidden: PresencePose;\n  shown: PresencePose;\n  duration: number;\n  ease: (progress: number) => number;\n  children: (\n    ref: React.RefObject<HTMLDivElement | null>,\n    style: React.CSSProperties | undefined,\n  ) => React.ReactNode;\n}) {\n  // A stable box for the child element, handed to the render function below\n  // (and read only in effects); a state-held RefObject so render can pass it on.\n  const [box] = useState(() => createRef<HTMLDivElement>());\n  const [mounted, setMounted] = useState(show);\n  if (show && !mounted) setMounted(true);\n  // Server render and first frame: the entry pose, when the child enters.\n  const [mountStyle] = useState(() => (show && appear ? poseStyle(hidden) : undefined));\n  const firstRun = useRef(true);\n  const seen = useRef<HTMLDivElement | null>(null);\n  useLayoutEffect(() => {\n    const first = firstRun.current;\n    firstRun.current = false;\n    const el = box.current;\n    if (!el) return;\n    const fresh = el !== seen.current;\n    seen.current = el;\n    gsap.killTweensOf(el);\n    if (show) {\n      if (!fresh) gsap.to(el, { ...shown, duration, ease });\n      else if (!first || appear) gsap.fromTo(el, { ...hidden }, { ...shown, duration, ease });\n      return;\n    }\n    gsap.to(el, { ...hidden, duration, ease, onComplete: () => setMounted(false) });\n    // The poses are fixed per call site.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [show, mounted]);\n  useEffect(\n    () => () => {\n      if (seen.current) gsap.killTweensOf(seen.current);\n    },\n    [],\n  );\n\n  // While leaving, it keeps rendering what it showed last: the render function\n  // from the last render where it was shown (its closure holds that render's\n  // values).\n  const [lastChildren, setLastChildren] = useState(() => children);\n  if (show && lastChildren !== children) setLastChildren(() => children);\n  const render = show ? children : lastChildren;\n  return mounted ? render(box, mountStyle) : null;\n}\n\n/** A chip's motion: its entry/exit pose and any glide towards its new slot. */\ninterface ChipMotion {\n  el: HTMLDivElement;\n  opacity: number;\n  scale: number;\n  y: number;\n  glideX: number;\n  glideY: number;\n}\n\nfunction paintChip(m: ChipMotion) {\n  const x = m.glideX;\n  const y = m.glideY + m.y;\n  m.el.style.transform = x || y || m.scale !== 1 ? `translate(${x}px, ${y}px) scale(${m.scale})` : \"none\";\n  m.el.style.opacity = String(m.opacity);\n}\n\n/**\n * The attachment chips. A new chip springs in; a removed one springs out in\n * place, and once it has gone the chips after it glide into the gap on the\n * same spring. Chips already there when the tray opens don't animate.\n */\nfunction AttachmentChips({\n  attachments,\n  theme,\n  onRemove,\n}: {\n  attachments: PendingAttachment[];\n  theme: Theme;\n  onRemove: (id: string) => void;\n}) {\n  const chips = useRef(new Map<string, ChipMotion>());\n  const [firstIds] = useState(() => new Set(attachments.map((a) => a.id)));\n  // Chips that have finished leaving, and what was on screen last render.\n  const [gone, setGone] = useState<ReadonlySet<string>>(() => new Set());\n  const [onScreen, setOnScreen] = useState<PendingAttachment[]>(attachments);\n\n  // Removed chips stay where they were, in their old slot, until they're out.\n  const present = new Set(attachments.map((a) => a.id));\n  const rendered = [...attachments];\n  onScreen.forEach((att, i) => {\n    if (!present.has(att.id) && !gone.has(att.id)) rendered.splice(i, 0, att);\n  });\n  if (rendered.length !== onScreen.length || rendered.some((att, i) => att !== onScreen[i])) {\n    setOnScreen(rendered);\n  }\n  // A finished chip only needs remembering while it is still in `onScreen`.\n  if ([...gone].some((id) => !rendered.some((att) => att.id === id))) {\n    setGone(new Set([...gone].filter((id) => rendered.some((att) => att.id === id))));\n  }\n\n  // Where each chip's layout box sat before this commit touched the DOM —\n  // measured by <ChipLayoutSnapshot> just ahead of the tray's DOM updates.\n  const beforeRef = useRef(new Map<string, { x: number; y: number }>());\n\n  const leaving = useRef(new Map<string, gsap.core.Tween>());\n  useLayoutEffect(() => {\n    const before = beforeRef.current;\n    chips.current.forEach((m, id) => {\n      // Out: fade and shrink in place, then drop it.\n      if (!present.has(id) && !leaving.current.has(id)) {\n        gsap.killTweensOf(m, \"opacity,scale,y\");\n        gsap.to(m, { opacity: 0, scale: 0.85, y: 6, ...CHIP_SPRING, onUpdate: () => paintChip(m) });\n        leaving.current.set(\n          id,\n          gsap.delayedCall(CHIP_EXIT_SETTLE, () => {\n            leaving.current.delete(id);\n            setGone((current) => new Set(current).add(id));\n          }),\n        );\n        return;\n      }\n      // Glide: the chips after a removed one move up from where they were.\n      const was = before.get(id);\n      if (!was) return;\n      const dx = was.x - m.el.offsetLeft;\n      const dy = was.y - m.el.offsetTop;\n      if (!dx && !dy) return;\n      gsap.killTweensOf(m, \"glideX,glideY\");\n      m.glideX += dx;\n      m.glideY += dy;\n      paintChip(m);\n      gsap.to(m, { glideX: 0, glideY: 0, ...CHIP_SPRING, onUpdate: () => paintChip(m) });\n    });\n  });\n\n  const register = useCallback((id: string, el: HTMLDivElement | null) => {\n    const old = chips.current.get(id);\n    if (old && old.el === el) return;\n    if (old) {\n      gsap.killTweensOf(old);\n      leaving.current.get(id)?.kill();\n      leaving.current.delete(id);\n      chips.current.delete(id);\n    }\n    if (!el) return;\n    const m: ChipMotion = { el, opacity: 1, scale: 1, y: 0, glideX: 0, glideY: 0 };\n    chips.current.set(id, m);\n    if (firstIds.has(id)) return;\n    // In: springs up from slightly below, small and transparent.\n    m.opacity = 0;\n    m.scale = 0.85;\n    m.y = 6;\n    paintChip(m);\n    gsap.to(m, { opacity: 1, scale: 1, y: 0, ...CHIP_SPRING, onUpdate: () => paintChip(m) });\n  }, [firstIds]);\n\n  return (\n    <>\n      <ChipLayoutSnapshot chipsRef={chips} beforeRef={beforeRef} />\n      <div className=\"flex flex-wrap gap-2 px-1 pt-1.5 pb-1\">\n        {rendered.map((att) => (\n          <AttachmentChip\n            key={att.id}\n            register={register}\n            attachment={att}\n            theme={theme}\n            onRemove={() => onRemove(att.id)}\n          />\n        ))}\n      </div>\n    </>\n  );\n}\n\n/**\n * Records where each chip's layout box sits just before a commit changes the\n * tray. Rendered ahead of the tray, so its insertion effect runs before the\n * tray's own DOM updates in the same commit; renders nothing.\n */\nfunction ChipLayoutSnapshot({\n  chipsRef,\n  beforeRef,\n}: {\n  chipsRef: React.RefObject<Map<string, ChipMotion>>;\n  beforeRef: React.RefObject<Map<string, { x: number; y: number }>>;\n}) {\n  useInsertionEffect(() => {\n    beforeRef.current = new Map(\n      Array.from(chipsRef.current, ([id, m]) => [id, { x: m.el.offsetLeft, y: m.el.offsetTop }] as const),\n    );\n  });\n  return null;\n}\n\n/**\n * The upload indicator: a rocket that launches from the left, rides the\n * progress along the track with a flickering exhaust, then blasts off the end\n * and hands over to a check when the file has landed.\n */\nfunction RocketProgress({\n  progress,\n  status,\n  theme,\n}: {\n  progress: number;\n  status: UploadStatus;\n  theme: Theme;\n}) {\n  const done = status === \"done\";\n  const failed = status === \"error\";\n  // Position and fill are CSS transitions: they keep gliding between progress\n  // events even when the page's JS frame budget is tight.\n  const glide = \"left 450ms cubic-bezier(0.22, 1, 0.36, 1)\";\n\n  // The rocket stays mounted after the upload ends, long enough to blast off.\n  const flying = !done && !failed;\n  const [rocketMounted, setRocketMounted] = useState(flying);\n  if (flying && !rocketMounted) setRocketMounted(true);\n  // While it leaves, it keeps the position it launched from.\n  const [launchedFrom, setLaunchedFrom] = useState(progress);\n  if (flying && launchedFrom !== progress) setLaunchedFrom(progress);\n  const rocketRef = useRef<HTMLDivElement>(null);\n  const craftRef = useRef<HTMLDivElement>(null);\n  useLayoutEffect(() => {\n    const rocket = rocketRef.current;\n    const craft = craftRef.current;\n    if (!rocket || !craft) return;\n    gsap.killTweensOf([rocket, craft]);\n    if (flying) {\n      // Launch: pops up from below, tilting from 60deg to its 45deg cruise.\n      // The -50%/-50% is the element's own Tailwind centring, which GSAP's\n      // transform would otherwise replace.\n      gsap.fromTo(\n        craft,\n        { xPercent: -50, yPercent: -50, x: 0, y: 8, scale: 0, rotation: 60, opacity: 0 },\n        { y: 0, scale: 1, rotation: 45, opacity: 1, ...ROCKET_SPRING },\n      );\n      return;\n    }\n    // Blast-off: the rocket shoots to the end of the track while the craft\n    // climbs away and fades; it unmounts once both are done.\n    gsap.to(rocket, { left: \"100%\", duration: 0.2, ease: EASE_OUT });\n    gsap.to(craft, {\n      x: 14,\n      y: -18,\n      scale: 0.4,\n      opacity: 0,\n      rotation: 20,\n      duration: 0.35,\n      ease: EASE_IN,\n      onComplete: () => setRocketMounted(false),\n    });\n  }, [flying, rocketMounted]);\n  useEffect(() => {\n    const rocket = rocketRef;\n    const craft = craftRef;\n    return () => {\n      const targets = [rocket.current, craft.current].filter(Boolean);\n      if (targets.length) gsap.killTweensOf(targets);\n    };\n  }, []);\n\n  return (\n    <div className=\"relative h-5 w-full\">\n      {/* Track */}\n      <div className=\"absolute left-0 right-0 top-1/2 -translate-y-1/2 h-[3px] rounded-full bg-foreground/10 overflow-hidden\">\n        <div\n          style={{\n            width: `${done ? 100 : progress}%`,\n            transition: \"width 450ms cubic-bezier(0.22, 1, 0.36, 1)\",\n          }}\n          className={cn(\n            \"h-full rounded-full\",\n            failed\n              ? \"bg-rose-500\"\n              : done\n                ? \"bg-emerald-500\"\n                : cn(\"bg-current opacity-70\", theme.primaryText),\n          )}\n        />\n      </div>\n\n      {/* Rocket */}\n      {rocketMounted && (\n        <div\n          ref={rocketRef}\n          className={cn(\"absolute top-1/2 z-10\", theme.primaryText)}\n          style={{ left: `${flying ? progress : launchedFrom}%`, transition: glide }}\n        >\n          <div ref={craftRef} className=\"relative -translate-x-1/2 -translate-y-1/2\">\n            {/* Bob while in flight */}\n            <div className=\"aichat-rocket-bob relative\">\n              {/* Exhaust: sits behind the tail (bottom-left of the rotated icon) */}\n              <span className=\"aichat-exhaust absolute left-[-9px] top-[9px] h-[3px] w-3 rounded-full bg-gradient-to-l from-orange-400 via-amber-300 to-transparent origin-right\" />\n              <Rocket className=\"w-3.5 h-3.5 drop-shadow-sm\" />\n            </div>\n          </div>\n        </div>\n      )}\n\n      {/* Landing */}\n      {done && (\n        <span className=\"absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 z-10 flex items-center justify-center\">\n          <span className=\"aichat-ring absolute size-4 rounded-full bg-emerald-500/40\" />\n          <span className=\"aichat-check relative size-4 rounded-full bg-emerald-500 text-white flex items-center justify-center shadow-sm\">\n            <Check className=\"w-2.5 h-2.5\" strokeWidth={3.5} />\n          </span>\n        </span>\n      )}\n      {failed && (\n        <span className=\"aichat-pop absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 z-10 size-4 rounded-full bg-rose-500 text-white flex items-center justify-center\">\n          <X className=\"w-2.5 h-2.5\" strokeWidth={3.5} />\n        </span>\n      )}\n    </div>\n  );\n}\n\nfunction AttachmentChip({\n  attachment,\n  theme,\n  onRemove,\n  register,\n}: {\n  attachment: PendingAttachment;\n  theme: Theme;\n  onRemove: () => void;\n  /** Hands the chip's root element to the tray, for it to animate. */\n  register?: (id: string, el: HTMLDivElement | null) => void;\n}) {\n  // One stable callback per chip, so React attaches it once, not every render.\n  const id = attachment.id;\n  const chipRef = useCallback(\n    (el: HTMLDivElement | null) => {\n      register?.(id, el);\n    },\n    [register, id],\n  );\n  const isImage = attachment.type.startsWith(\"image/\");\n  const statusText =\n    attachment.status === \"done\"\n      ? \"Uploaded\"\n      : attachment.status === \"error\"\n        ? \"Failed\"\n        : `${attachment.progress}%`;\n\n  return (\n    <div\n      ref={chipRef}\n      className=\"group relative flex items-center gap-2.5 rounded-xl border border-border bg-card/90 pl-2 pr-3 py-2 w-[232px] max-w-full shadow-sm\"\n    >\n      <div\n        className={cn(\n          \"size-9 shrink-0 rounded-lg overflow-hidden flex items-center justify-center\",\n          theme.lightBg,\n        )}\n      >\n        {isImage && attachment.previewUrl ? (\n          <img\n            src={attachment.previewUrl}\n            alt=\"\"\n            className=\"size-full object-cover\"\n          />\n        ) : isImage ? (\n          <ImageIcon className=\"w-4 h-4\" />\n        ) : (\n          <FileText className=\"w-4 h-4\" />\n        )}\n      </div>\n\n      <div className=\"min-w-0 flex-1\">\n        <div className=\"flex items-center justify-between gap-2 leading-tight\">\n          <span className=\"text-xs font-semibold text-foreground truncate\">\n            {attachment.name}\n          </span>\n          <span\n            className={cn(\n              \"text-[10px] font-semibold tabular-nums shrink-0\",\n              attachment.status === \"done\"\n                ? \"text-emerald-600 dark:text-emerald-400\"\n                : attachment.status === \"error\"\n                  ? \"text-rose-500\"\n                  : \"text-muted-foreground\",\n            )}\n          >\n            {statusText}\n          </span>\n        </div>\n        <RocketProgress\n          progress={attachment.progress}\n          status={attachment.status}\n          theme={theme}\n        />\n        <p className=\"text-[10px] text-muted-foreground leading-none -mt-0.5\">\n          {formatBytes(attachment.size)}\n        </p>\n      </div>\n\n      <button\n        type=\"button\"\n        onClick={onRemove}\n        aria-label={`Remove ${attachment.name}`}\n        className=\"absolute -top-1.5 -right-1.5 size-5 rounded-full bg-foreground text-background flex items-center justify-center shadow opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity cursor-pointer\"\n      >\n        <X className=\"w-3 h-3\" strokeWidth={3} />\n      </button>\n    </div>\n  );\n}\n\nconst THUMB_WIDTH = 14;\nconst TRACK_INSET = 3;\n\n/**\n * Faster ↔ Smarter slider with one stop per effort option. A transparent\n * native range input sits on top for pointer, touch and keyboard handling;\n * the visuals underneath follow its value.\n */\nfunction EffortSlider({\n  efforts,\n  value,\n  onChange,\n  theme,\n}: {\n  efforts: readonly EffortOption[];\n  value: number;\n  onChange: (index: number) => void;\n  theme: Theme;\n}) {\n  const surface = useSurface();\n  const isLiquid = surface === \"liquid-glass\";\n\n  const last = Math.max(efforts.length - 1, 1);\n  const index = Math.min(Math.max(0, value), last);\n  // Stop centres run from half a thumb in from each end, inside the track inset.\n  const stopLeft = (i: number) => {\n    const p = i / last;\n    const edge = TRACK_INSET + THUMB_WIDTH / 2;\n    return `calc(${edge}px + ${p} * (100% - ${edge * 2}px))`;\n  };\n  const thumbLeft = stopLeft(index);\n  const fillWidth = (left: string) => `calc(${left} + ${THUMB_WIDTH / 2 - TRACK_INSET}px)`;\n\n  // Thumb and fill share one spring on the stop position, from wherever they\n  // are when the value changes; they mount in place.\n  const thumbRef = useRef<HTMLDivElement>(null);\n  const fillRef = useRef<HTMLDivElement>(null);\n  const [mounted] = useState(() => ({ left: thumbLeft, width: fillWidth(thumbLeft) }));\n  const shown = useRef({ stop: index / last });\n  useLayoutEffect(() => {\n    const thumb = thumbRef.current;\n    const fill = fillRef.current;\n    if (!thumb || !fill) return;\n    const at = shown.current;\n    const paint = () => {\n      const left = stopLeft(at.stop * last);\n      thumb.style.left = left;\n      fill.style.width = fillWidth(left);\n    };\n    const to = index / last;\n    if (at.stop === to) {\n      paint();\n      return;\n    }\n    gsap.to(at, { stop: to, ...SLIDER_SPRING, overwrite: true, onUpdate: paint });\n    // stopLeft is rebuilt each render from `last`; the tween only needs the fraction.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [index, last]);\n  useEffect(() => {\n    const at = shown.current;\n    return () => {\n      gsap.killTweensOf(at);\n    };\n  }, []);\n\n  return (\n    <div\n      className={cn(\n        \"relative h-7 sm:h-8 w-full select-none\",\n        isLiquid ? \"text-white\" : theme.primaryText,\n      )}\n    >\n      <div\n        className={cn(\n          \"absolute inset-0 rounded-full\",\n          isLiquid ? \"bg-white/15\" : \"bg-muted\",\n        )}\n      />\n      {/* Fill runs from the track's start to the thumb's trailing edge */}\n      <div\n        ref={fillRef}\n        className={cn(\n          \"absolute rounded-full\",\n          isLiquid ? \"bg-white/40\" : \"bg-current opacity-40\",\n        )}\n        style={{ top: TRACK_INSET, bottom: TRACK_INSET, left: TRACK_INSET, width: mounted.width }}\n      />\n      {efforts.map((effort, i) => (\n        <span\n          key={effort.id}\n          className={cn(\n            \"absolute top-1/2 size-[5px] -translate-x-1/2 -translate-y-1/2 rounded-full transition-colors duration-300\",\n            i <= index\n              ? isLiquid\n                ? \"bg-white\"\n                : \"bg-background/80\"\n              : isLiquid\n                ? \"bg-white/30\"\n                : \"bg-foreground/20\",\n          )}\n          style={{ left: stopLeft(i) }}\n        />\n      ))}\n      <div\n        ref={thumbRef}\n        className={cn(\n          \"absolute top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full shadow-sm\",\n          isLiquid ? \"bg-white\" : \"bg-current\",\n        )}\n        style={{\n          width: THUMB_WIDTH,\n          height: `calc(100% - ${TRACK_INSET * 2}px)`,\n          left: mounted.left,\n        }}\n      />\n      <input\n        type=\"range\"\n        min={0}\n        max={last}\n        step={1}\n        value={index}\n        onChange={(e) => onChange(Number(e.target.value))}\n        aria-label=\"Effort\"\n        aria-valuetext={efforts[index]?.label}\n        className=\"absolute inset-0 w-full h-full opacity-0 cursor-pointer m-0\"\n      />\n    </div>\n  );\n}\n\nconst PARTICLE_COUNT = 26;\n\n/** Deterministic 0–1 noise so server and client render the same sky. */\nconst noise = (i: number, salt: number) => {\n  const x = Math.sin(i * 12.9898 + salt * 78.233) * 43758.5453;\n  return x - Math.floor(x);\n};\n\n/**\n * The \"Max\" sky: a soft glow rising from the bottom of the prompt bar and a\n * scatter of twinkling specks, denser near the floor. Pure decoration — it\n * never intercepts the pointer.\n */\nfunction MaxEffortGlow({\n  active,\n  className,\n}: {\n  active: boolean;\n  className?: string;\n}) {\n  return (\n    <Presence\n      show={active}\n      hidden={{ opacity: 0 }}\n      shown={{ opacity: 1 }}\n      duration={0.5}\n      ease={EASE_OUT}\n    >\n      {(ref, style) => (\n        <div\n          ref={ref}\n          style={style}\n          aria-hidden\n          className={cn(\n            \"pointer-events-none absolute inset-0 overflow-hidden rounded-2xl\",\n            className,\n          )}\n        >\n          <div className=\"absolute inset-x-0 bottom-0 h-3/4 bg-[radial-gradient(ellipse_at_bottom,currentColor,transparent_65%)] opacity-15\" />\n          <div className=\"aichat-glow-pulse absolute inset-x-6 bottom-0 h-1/2 bg-[radial-gradient(ellipse_at_bottom,currentColor,transparent_60%)] opacity-20 blur-xl\" />\n          {Array.from({ length: PARTICLE_COUNT }).map((_, i) => {\n            const x = noise(i, 1) * 100;\n            // Square the vertical noise so most specks sit low, like the reference.\n            const y = 100 - Math.pow(noise(i, 2), 2) * 95;\n            const size = 1.5 + noise(i, 3) * 2;\n            const duration = 1.8 + noise(i, 4) * 2.4;\n            const delay = noise(i, 5) * 3;\n            return (\n              <span\n                key={i}\n                className=\"aichat-speck absolute rounded-full bg-current\"\n                style={{\n                  left: `${x}%`,\n                  top: `${y}%`,\n                  width: size,\n                  height: size,\n                  boxShadow: \"0 0 6px 1px currentColor\",\n                  animationDuration: `${duration}s`,\n                  animationDelay: `${delay}s`,\n                }}\n              />\n            );\n          })}\n        </div>\n      )}\n    </Presence>\n  );\n}\n\n/**\n * Paid tiers wear their own colour whatever the accent — gold for Premium,\n * electric blue for Pro — so choosing one reads apart from the accent-tinted\n * Max-effort glow, and the two tiers read apart from each other.\n */\nconst PREMIUM = {\n  badge:\n    \"bg-gradient-to-r from-amber-300 to-yellow-200 text-amber-900 dark:from-amber-400/25 dark:to-yellow-300/15 dark:text-amber-200\",\n  pill: \"bg-amber-500/10 text-amber-600 dark:text-amber-300\",\n  /** `currentColor` for the flourishes. */\n  ink: \"text-amber-400\",\n};\n\nconst PRO = {\n  badge:\n    \"bg-gradient-to-r from-sky-200 to-cyan-100 text-sky-900 dark:from-sky-400/25 dark:to-cyan-300/15 dark:text-sky-200\",\n  pill: \"bg-sky-500/10 text-sky-600 dark:text-sky-300\",\n  ink: \"text-sky-400\",\n};\n\nconst TIERS: Record<\n  ModelTier,\n  {\n    label: string;\n    Icon: typeof Crown;\n    badge: string;\n    pill: string;\n    /** Entrance for the pill's icon when the tier is picked. */\n    iconPop: string;\n    Sweep: (props: { onDone: () => void }) => React.ReactNode;\n    PillFlash: () => React.ReactNode;\n  }\n> = {\n  premium: {\n    label: \"Premium\",\n    Icon: Crown,\n    badge: PREMIUM.badge,\n    pill: PREMIUM.pill,\n    iconPop: \"aichat-crown-pop\",\n    Sweep: PremiumSweep,\n    PillFlash: PremiumPillFlash,\n  },\n  pro: {\n    label: \"Pro\",\n    Icon: Zap,\n    badge: PRO.badge,\n    pill: PRO.pill,\n    iconPop: \"aichat-zap-strike\",\n    Sweep: ProSurge,\n    PillFlash: ProPillFlash,\n  },\n};\n\n/** Shows only a 2px ring at the padding edge — the track the beam runs in. */\nconst RING_MASK: React.CSSProperties = {\n  WebkitMask: \"linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)\",\n  WebkitMaskComposite: \"xor\",\n  mask: \"linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)\",\n  maskComposite: \"exclude\",\n};\n\n/** Two gold comets on opposite sides of the lap. */\nconst BEAM_GRADIENT =\n  \"conic-gradient(from 0deg, transparent 0deg, currentColor 50deg, transparent 90deg, transparent 180deg, currentColor 230deg, transparent 270deg)\";\n\nfunction TierBadge({ tier }: { tier: ModelTier }) {\n  const { label, Icon, badge } = TIERS[tier];\n  return (\n    <span\n      className={cn(\n        \"inline-flex items-center gap-0.5 shrink-0 text-[9px] font-semibold uppercase tracking-wide px-1.5 py-px rounded-full\",\n        badge,\n      )}\n    >\n      <Icon className=\"w-2.5 h-2.5\" strokeWidth={2.5} />\n      {label}\n    </span>\n  );\n}\n\n/**\n * The prompt bar's premium hand-off, played once per pick: two gold beams run\n * one lap of the edge, a sheen crosses the bar and a halo blooms out behind\n * it. Calls `onDone` when the lap ends so the caller can unmount it.\n */\nfunction PremiumSweep({ onDone }: { onDone: () => void }) {\n  return (\n    <div\n      aria-hidden\n      onAnimationEnd={(e) => {\n        if (e.target === e.currentTarget) onDone();\n      }}\n      className={cn(\n        \"aichat-premium-life pointer-events-none absolute inset-0 rounded-2xl\",\n        PREMIUM.ink,\n      )}\n    >\n      <span className=\"aichat-premium-bloom absolute inset-0 rounded-2xl shadow-[0_0_24px_6px_currentColor]\" />\n      <span className=\"absolute inset-0 overflow-hidden rounded-2xl\">\n        <span className=\"aichat-premium-sheen absolute inset-y-0 left-0 w-1/4 bg-gradient-to-r from-transparent via-current to-transparent opacity-25\" />\n      </span>\n      <span\n        className=\"absolute inset-0 overflow-hidden rounded-2xl p-[2px]\"\n        style={RING_MASK}\n      >\n        <span\n          className=\"aichat-premium-orbit absolute left-1/2 top-1/2 aspect-square w-[150%]\"\n          style={{ background: BEAM_GRADIENT }}\n        />\n      </span>\n    </div>\n  );\n}\n\n/** The model pill's side of the flourish: a gold ring pings out and a glint crosses it. */\nfunction PremiumPillFlash() {\n  return (\n    <span\n      aria-hidden\n      className={cn(\"pointer-events-none absolute inset-0\", PREMIUM.ink)}\n    >\n      <span className=\"aichat-premium-ping absolute inset-0 rounded-lg border-2 border-current\" />\n      <span className=\"absolute inset-0 overflow-hidden rounded-lg\">\n        <span className=\"aichat-premium-shine absolute inset-y-0 left-0 w-1/3 bg-gradient-to-r from-transparent via-white/80 to-transparent dark:via-white/40\" />\n      </span>\n    </span>\n  );\n}\n\n/**\n * The prompt bar's Pro hand-off, played once per pick — a charge rather than\n * Premium's orbit: the edge draws itself out from the centre, flickers like a\n * live wire, a scan line rises through the bar and it glows from within. Calls\n * `onDone` when it ends so the caller can unmount it.\n */\nfunction ProSurge({ onDone }: { onDone: () => void }) {\n  return (\n    <div\n      aria-hidden\n      onAnimationEnd={(e) => {\n        if (e.target === e.currentTarget) onDone();\n      }}\n      className={cn(\n        \"aichat-pro-life pointer-events-none absolute inset-0 rounded-2xl\",\n        PRO.ink,\n      )}\n    >\n      <span className=\"aichat-pro-charge absolute inset-0 rounded-2xl shadow-[inset_0_0_20px_2px_currentColor]\" />\n      <span className=\"absolute inset-0 overflow-hidden rounded-2xl\">\n        <span className=\"aichat-pro-scan absolute inset-0 bg-gradient-to-t from-transparent via-current to-transparent opacity-20\" />\n      </span>\n      <span\n        className=\"absolute inset-0 overflow-hidden rounded-2xl p-[2px]\"\n        style={RING_MASK}\n      >\n        <span className=\"aichat-pro-trace absolute inset-0 bg-current\" />\n      </span>\n    </div>\n  );\n}\n\n/** Where the Pro sparks fly, in px from the pill's icon. */\nconst PRO_SPARKS = [\n  [14, 0],\n  [7, -12],\n  [-7, -12],\n  [-14, 0],\n  [-7, 12],\n  [7, 12],\n];\n\n/** The model pill's side of the Pro flourish: the pill flickers and sparks burst off the bolt. */\nfunction ProPillFlash() {\n  return (\n    <span\n      aria-hidden\n      className={cn(\"pointer-events-none absolute inset-0\", PRO.ink)}\n    >\n      <span className=\"aichat-pro-flash absolute inset-0 rounded-lg bg-current\" />\n      {PRO_SPARKS.map(([x, y]) => (\n        <span\n          key={`${x},${y}`}\n          className=\"aichat-pro-spark absolute left-[13px] sm:left-[15px] top-1/2 size-[3px] rounded-full bg-current\"\n          style={\n            {\n              \"--aichat-spark-x\": `${x}px`,\n              \"--aichat-spark-y\": `${y}px`,\n            } as React.CSSProperties\n          }\n        />\n      ))}\n    </span>\n  );\n}\n\nconst BAR_COUNT = 22;\n\n/**\n * The waveform shown while dictating. With a live microphone the bars follow\n * the analyser through refs (no re-render per frame); without one they run a\n * soft idle animation so the state still reads as \"listening\".\n */\nfunction ListeningWave({\n  barsRef,\n  live,\n  className,\n}: {\n  barsRef: React.MutableRefObject<(HTMLSpanElement | null)[]>;\n  live: boolean;\n  className?: string;\n}) {\n  return (\n    <div\n      className={cn(\"flex items-center gap-[3px] h-8 shrink-0\", className)}\n      aria-hidden\n    >\n      {Array.from({ length: BAR_COUNT }).map((_, i) => {\n        // Taller in the middle so the idle shape reads as a voice, not noise.\n        const envelope =\n          0.35 + 0.65 * Math.sin((i / (BAR_COUNT - 1)) * Math.PI);\n        return live ? (\n          <span\n            key={i}\n            ref={(el) => {\n              barsRef.current[i] = el;\n            }}\n            className=\"w-[3px] h-full rounded-full bg-current origin-center will-change-transform\"\n            style={{ transform: \"scaleY(0.15)\" }}\n          />\n        ) : (\n          <span\n            key={i}\n            className=\"aichat-wave w-[3px] h-full rounded-full bg-current origin-center\"\n            style={\n              {\n                \"--aichat-wave-peak\": envelope,\n                \"--aichat-wave-echo\": envelope * 0.8,\n                animationDuration: `${0.9 + (i % 5) * 0.12}s`,\n                animationDelay: `${(i % 7) * 0.07}s`,\n              } as React.CSSProperties\n            }\n          />\n        );\n      })}\n    </div>\n  );\n}\n\nfunction ComposerMenu({\n  open,\n  onOpenChange,\n  icon,\n  label,\n  heading,\n  highlighted = false,\n  highlightClassName,\n  flourish,\n  iconOnly = false,\n  width = \"w-60 sm:w-64\",\n  boundaryRef,\n  theme,\n  children,\n}: {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  icon: React.ReactNode;\n  label: React.ReactNode;\n  /** Small caps title above the items; omit when the panel draws its own. */\n  heading?: string;\n  /** Tints the trigger even while closed — used when effort is at Max. */\n  highlighted?: boolean;\n  /** The tint `highlighted` applies; the accent colour when omitted. */\n  highlightClassName?: string;\n  /** Decoration layered over the trigger, e.g. a one-off flash. */\n  flourish?: React.ReactNode;\n  /** Square icon trigger with `label` as its accessible name — the \"+\" button. */\n  iconOnly?: boolean;\n  width?: string;\n  /** The panel is nudged left and narrowed to stay inside this element. */\n  boundaryRef?: React.RefObject<HTMLElement | null>;\n  theme: Theme;\n  children: React.ReactNode;\n}) {\n  const surface = useSurface();\n  const isLiquid = surface === \"liquid-glass\";\n  const ref = useRef<HTMLDivElement>(null);\n\n  // A trigger near the right of a narrow composer would push its panel past\n  // the edge, so the panel is slid back (and capped) to fit the boundary.\n  useLayoutEffect(() => {\n    if (!open || !boundaryRef) return;\n    const place = () => {\n      const wrap = ref.current;\n      const panel = wrap?.querySelector<HTMLElement>('[role=\"menu\"]');\n      const bounds = boundaryRef.current?.getBoundingClientRect();\n      if (!wrap || !panel || !bounds) return;\n      panel.style.maxWidth = `${bounds.width}px`;\n      const from = wrap.getBoundingClientRect().left;\n      const overflow = from + panel.offsetWidth - bounds.right;\n      panel.style.left = `${Math.max(-Math.max(overflow, 0), bounds.left - from)}px`;\n    };\n    place();\n    window.addEventListener(\"resize\", place);\n    return () => window.removeEventListener(\"resize\", place);\n  }, [open, boundaryRef]);\n\n  useEffect(() => {\n    if (!open) return;\n    const onPointerDown = (e: MouseEvent | TouchEvent) => {\n      if (!ref.current?.contains(e.target as Node)) onOpenChange(false);\n    };\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") onOpenChange(false);\n    };\n    document.addEventListener(\"mousedown\", onPointerDown);\n    document.addEventListener(\"touchstart\", onPointerDown);\n    document.addEventListener(\"keydown\", onKey);\n    return () => {\n      document.removeEventListener(\"mousedown\", onPointerDown);\n      document.removeEventListener(\"touchstart\", onPointerDown);\n      document.removeEventListener(\"keydown\", onKey);\n    };\n  }, [open, onOpenChange]);\n\n  return (\n    <div ref={ref} className={cn(\"relative\", iconOnly ? \"shrink-0\" : \"min-w-0\")}>\n      <button\n        type=\"button\"\n        onClick={() => onOpenChange(!open)}\n        aria-haspopup=\"menu\"\n        aria-expanded={open}\n        title={iconOnly && typeof label === \"string\" ? label : undefined}\n        aria-label={iconOnly && typeof label === \"string\" ? label : undefined}\n        className={cn(\n          \"relative flex items-center rounded-lg text-xs font-semibold transition-colors cursor-pointer\",\n          iconOnly\n            ? \"size-7 sm:size-8 justify-center\"\n            : \"gap-1 sm:gap-1.5 h-7 sm:h-8 px-1.5 sm:pl-2 max-w-full sm:max-w-[160px] text-[11px] sm:text-xs\",\n          highlighted\n            ? (highlightClassName ?? (isLiquid ? \"bg-white/20 text-white\" : cn(theme.lightBg, theme.primaryText)))\n            : open\n              ? (isLiquid ? \"bg-white/20 text-white\" : theme.lightBg)\n              : (isLiquid ? \"text-white/80 hover:bg-white/15 hover:text-white\" : cn(\"text-muted-foreground\", theme.primaryHover)),\n        )}\n      >\n        {flourish}\n        <span className=\"shrink-0\">{icon}</span>\n        {!iconOnly && (\n          <>\n            <span className=\"truncate\">{label}</span>\n            <ChevronDown\n              className={cn(\n                \"hidden sm:block w-3.5 h-3.5 shrink-0 transition-transform duration-200\",\n                open && \"rotate-180\",\n              )}\n            />\n          </>\n        )}\n      </button>\n\n      <Presence\n        show={open}\n        hidden={{ opacity: 0, y: 6, scale: 0.96 }}\n        shown={{ opacity: 1, y: 0, scale: 1 }}\n        duration={0.16}\n        ease={EASE_OUT}\n      >\n        {(ref, style) => (\n          <div\n            ref={ref}\n            role=\"menu\"\n            style={{ transformOrigin: \"bottom left\", ...style }}\n            className={cn(\n              \"absolute bottom-full left-0 mb-2 rounded-xl p-1 z-50 transition-all\",\n              isLiquid\n                ? \"bg-black/75 backdrop-blur-2xl border border-white/30 text-white shadow-[0_20px_50px_rgba(0,0,0,0.5),inset_0_1px_1px_rgba(255,255,255,0.3)]\"\n                : \"border border-border bg-popover text-popover-foreground shadow-xl\",\n              width,\n            )}\n          >\n            {heading && (\n              <p\n                className={cn(\n                  \"px-2.5 pt-1.5 pb-1 text-[10px] font-semibold uppercase tracking-wider\",\n                  isLiquid ? \"text-white/60\" : \"text-muted-foreground\",\n                )}\n              >\n                {heading}\n              </p>\n            )}\n            {children}\n          </div>\n        )}\n      </Presence>\n    </div>\n  );\n}\n\nfunction MenuItem({\n  active,\n  theme,\n  onClick,\n  children,\n}: {\n  active: boolean;\n  theme: Theme;\n  onClick: () => void;\n  children: React.ReactNode;\n}) {\n  const surface = useSurface();\n  const isLiquid = surface === \"liquid-glass\";\n\n  return (\n    <button\n      type=\"button\"\n      role=\"menuitemradio\"\n      aria-checked={active}\n      onClick={onClick}\n      className={cn(\n        \"w-full flex items-center gap-2.5 px-2.5 py-1.5 sm:py-2 rounded-lg text-left transition-colors cursor-pointer\",\n        isLiquid\n          ? active\n            ? \"bg-white/20 text-white font-medium\"\n            : \"text-white/80 hover:bg-white/10 hover:text-white\"\n          : active\n            ? theme.lightBg\n            : \"hover:bg-muted\",\n      )}\n    >\n      {children}\n      <Check\n        className={cn(\n          \"w-4 h-4 shrink-0 transition-opacity\",\n          isLiquid\n            ? active\n              ? \"opacity-100 text-white\"\n              : \"opacity-0 text-white\"\n            : cn(theme.primaryText, active ? \"opacity-100\" : \"opacity-0\"),\n        )}\n      />\n    </button>\n  );\n}\n\n// ==========================================\n// VOICE INPUT\n// ==========================================\ntype SpeechResultEvent = {\n  results: ArrayLike<ArrayLike<{ transcript: string }> & { isFinal: boolean }>;\n};\n\ntype SpeechRecognitionLike = {\n  continuous: boolean;\n  interimResults: boolean;\n  lang: string;\n  onresult: ((e: SpeechResultEvent) => void) | null;\n  onend: (() => void) | null;\n  onerror: (() => void) | null;\n  start: () => void;\n  stop: () => void;\n};\n\nconst getSpeechRecognition = () => {\n  if (typeof window === \"undefined\") return null;\n  const w = window as unknown as {\n    SpeechRecognition?: new () => SpeechRecognitionLike;\n    webkitSpeechRecognition?: new () => SpeechRecognitionLike;\n  };\n  return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;\n};\n\n/**\n * Microphone for the composer. Opens the mic for a live level meter (driving\n * `barsRef` each frame), and runs the Web Speech API alongside it for the\n * transcript. Either half degrades on its own: no analyser → idle wave, no\n * recognition → the wave still shows so the user knows the button did something.\n */\nfunction useVoiceInput(\n  onTranscript: (text: string) => void,\n  getCurrentText: () => string,\n) {\n  const [isListening, setIsListening] = useState(false);\n  const [hasLiveAudio, setHasLiveAudio] = useState(false);\n  const barsRef = useRef<(HTMLSpanElement | null)[]>([]);\n\n  const wantListening = useRef(false);\n  const recognitionRef = useRef<SpeechRecognitionLike | null>(null);\n  const streamRef = useRef<MediaStream | null>(null);\n  const audioCtxRef = useRef<AudioContext | null>(null);\n  const rafRef = useRef<number | null>(null);\n  const baseTextRef = useRef(\"\");\n\n  const supportsDictation =\n    typeof window !== \"undefined\" && getSpeechRecognition() !== null;\n\n  const stop = useCallback(() => {\n    wantListening.current = false;\n    setIsListening(false);\n    setHasLiveAudio(false);\n\n    if (rafRef.current) cancelAnimationFrame(rafRef.current);\n    rafRef.current = null;\n    recognitionRef.current?.stop();\n    recognitionRef.current = null;\n    streamRef.current?.getTracks().forEach((t) => t.stop());\n    streamRef.current = null;\n    audioCtxRef.current?.close().catch(() => {});\n    audioCtxRef.current = null;\n  }, []);\n\n  const start = useCallback(async () => {\n    wantListening.current = true;\n    setIsListening(true);\n    baseTextRef.current = getCurrentText();\n\n    // 1. Transcript\n    const SR = getSpeechRecognition();\n    if (SR) {\n      const rec = new SR();\n      rec.continuous = true;\n      rec.interimResults = true;\n      rec.lang =\n        typeof navigator !== \"undefined\" ? navigator.language : \"en-US\";\n      rec.onresult = (e) => {\n        let finalText = \"\";\n        let interim = \"\";\n        for (let i = 0; i < e.results.length; i++) {\n          const res = e.results[i];\n          if (res.isFinal) finalText += res[0].transcript;\n          else interim += res[0].transcript;\n        }\n        const base = baseTextRef.current;\n        const joiner = base && !/\\s$/.test(base) ? \" \" : \"\";\n        onTranscript(`${base}${joiner}${finalText}${interim}`.trimStart());\n      };\n      // Chrome ends the session after a pause; keep going until the user stops.\n      rec.onend = () => {\n        if (wantListening.current && recognitionRef.current === rec) {\n          try {\n            rec.start();\n          } catch {\n            /* already restarting */\n          }\n        }\n      };\n      rec.onerror = () => {};\n      recognitionRef.current = rec;\n      try {\n        rec.start();\n      } catch {\n        recognitionRef.current = null;\n      }\n    }\n\n    // 2. Level meter\n    try {\n      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });\n      if (!wantListening.current) {\n        stream.getTracks().forEach((t) => t.stop());\n        return;\n      }\n      const ctx = new AudioContext();\n      const analyser = ctx.createAnalyser();\n      analyser.fftSize = 64;\n      analyser.smoothingTimeConstant = 0.75;\n      ctx.createMediaStreamSource(stream).connect(analyser);\n      const data = new Uint8Array(analyser.frequencyBinCount);\n\n      streamRef.current = stream;\n      audioCtxRef.current = ctx;\n      setHasLiveAudio(true);\n\n      const draw = () => {\n        analyser.getByteFrequencyData(data);\n        const bars = barsRef.current;\n        const n = bars.length;\n        for (let i = 0; i < n; i++) {\n          const bar = bars[i];\n          if (!bar) continue;\n          // Mirror around the centre so the wave is symmetrical like a voice meter.\n          const dist = Math.abs(i - (n - 1) / 2) / ((n - 1) / 2);\n          const bin = Math.floor(dist * (data.length - 1));\n          const v = data[bin] / 255;\n          bar.style.transform = `scaleY(${(0.15 + v * 0.85).toFixed(3)})`;\n        }\n        rafRef.current = requestAnimationFrame(draw);\n      };\n      draw();\n    } catch {\n      // Mic denied or unavailable — the idle wave stands in.\n      setHasLiveAudio(false);\n    }\n  }, [getCurrentText, onTranscript]);\n\n  const toggle = useCallback(() => {\n    if (wantListening.current) stop();\n    else void start();\n  }, [start, stop]);\n\n  useEffect(() => stop, [stop]);\n\n  return {\n    isListening,\n    hasLiveAudio,\n    supportsDictation,\n    barsRef,\n    toggle,\n    stop,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/custom/blocks/Ai-chat.tsx"
    },
    {
      "path": "src/components/custom/blocks/glass-panel-context.ts",
      "content": "\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n/**\n * The page's surface treatment. `glass` is frosted panels over an aurora;\n * `solid` is plain theme cards with an ordinary shadow on a flat ground.\n */\nexport type SurfaceVariant = \"glass\" | \"solid\" | \"liquid-glass\";\n\n/** Set by `GlassBackdrop` for every `GlassPanel` inside it. */\nexport const SurfaceContext = createContext<SurfaceVariant>(\"glass\");\n\n/** The surface variant of the enclosing `GlassBackdrop`. */\nexport const useSurface = () => useContext(SurfaceContext);\n",
      "type": "registry:component",
      "target": "components/custom/blocks/glass-panel-context.ts"
    },
    {
      "path": "src/components/custom/blocks/gsap-motion.ts",
      "content": "import gsap from \"gsap\";\nimport { cubicBezier, type FrameTicker } from \"./motion-curves\";\n\n/**\n * GSAP-side glue for the GSAP builds of components that also ship a Motion\n * Motion twin. Kept apart from motion-curves.ts so the library-free curves\n * never pull GSAP into a CSS or Motion build.\n */\n\n/** `gsap.ticker` as a FrameTicker, so spring followers run on GSAP's loop. */\nexport const gsapTicker: FrameTicker = {\n  add(callback) {\n    const tick = (_time: number, deltaTime: number) => callback(deltaTime);\n    gsap.ticker.add(tick);\n    return () => gsap.ticker.remove(tick);\n  },\n};\n\n/** A Motion / CSS cubic-bezier array as a GSAP ease. */\nexport const bezierEase = (curve: readonly [number, number, number, number] | readonly number[]) =>\n  cubicBezier(curve[0], curve[1], curve[2], curve[3]);\n\n/** `(prefers-reduced-motion: reduce)` right now. */\nexport const prefersReducedMotion = () =>\n  typeof window !== \"undefined\" &&\n  window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches === true;\n",
      "type": "registry:component",
      "target": "components/custom/blocks/gsap-motion.ts"
    },
    {
      "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 exports: AIChat, plus ChatThread, Message, ChatModel, EffortOption, ComposerTool, SendPayload and UploadHandler types. Responses are mocked — wire `onSend` ({ content, attachments, model, effort, tools }) to your endpoint and `uploadFile` (file, onProgress, signal) to your storage. The composer ships with a + menu (`tools`: one upload row opens the picker, the rest insert @Label mentions), drag-and-drop attachments (rocket progress indicator), a `models` picker, a Faster↔Smarter `efforts` slider that lights the prompt bar at the top level, and mic dictation via getUserMedia + the Web Speech API with graceful fallbacks. Variants: default | minimal | glass | compact (no history sidebar — opens as a hero with `heroTitle` over the prompt bar until the first message; `showSidebar={false}` does the same for any variant).",
  "categories": [
    "communication"
  ],
  "type": "registry:component"
}
