{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-chat-motion",
  "title": "AI Chat (Motion)",
  "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": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://avaraui.com/r/ui-liquid-glass.json",
    "utils"
  ],
  "files": [
    {
      "path": "src/components/custom/blocks/motion/Ai-chat.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport {\n  AnimatePresence,\n  motion,\n  useReducedMotion,\n  type TargetAndTransition,\n  type Transition,\n} from \"motion/react\";\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  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\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\";\nimport { SurfaceContext, useSurface } from \"../glass-panel-context\";\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  const reduceMotion = useReducedMotion();\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      setTierFx((n) => (modelTier(model) && !reduceMotion ? n + 1 : 0));\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          <AnimatePresence>\n            {isDragging && (\n              <motion.div\n                initial={{ opacity: 0 }}\n                animate={{ opacity: 1 }}\n                exit={{ opacity: 0 }}\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              </motion.div>\n            )}\n          </AnimatePresence>\n\n          {/* Attachments */}\n          <AnimatePresence initial={false}>\n            {attachments.length > 0 && (\n              <motion.div\n                key=\"attachments\"\n                initial={{ opacity: 0, height: 0 }}\n                animate={{ opacity: 1, height: \"auto\" }}\n                exit={{ opacity: 0, height: 0 }}\n                transition={{ duration: 0.25, ease: \"easeOut\" }}\n                className=\"overflow-hidden\"\n              >\n                <div className=\"flex flex-wrap gap-2 px-1 pt-1.5 pb-1\">\n                  <AnimatePresence initial={false}>\n                    {attachments.map((att) => (\n                      <AttachmentChip\n                        key={att.id}\n                        attachment={att}\n                        theme={theme}\n                        onRemove={() => removeAttachment(att.id)}\n                      />\n                    ))}\n                  </AnimatePresence>\n                </div>\n              </motion.div>\n            )}\n          </AnimatePresence>\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            <AnimatePresence>\n              {voice.isListening && (\n                <motion.div\n                  initial={{ opacity: 0, y: 4 }}\n                  animate={{ opacity: 1, y: 0 }}\n                  exit={{ opacity: 0, y: 4 }}\n                  transition={{ duration: 0.2 }}\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                </motion.div>\n              )}\n            </AnimatePresence>\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                    <motion.span\n                      key={tierFx}\n                      className=\"block\"\n                      initial={tierFx > 0 ? tierLook.iconPop.initial : false}\n                      animate={tierLook.iconPop.animate}\n                      transition={tierLook.iconPop.transition}\n                    >\n                      <tierLook.Icon className=\"w-3.5 h-3.5 mb-0.25\" />\n                    </motion.span>\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      <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            <motion.div\n              initial={{ opacity: 0, y: 10 }}\n              animate={{ opacity: 1, y: 0 }}\n              transition={{ duration: 0.4, ease: \"easeOut\" }}\n              className=\"w-full max-w-3xl px-4 sm:px-6 text-center\"\n            >\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            </motion.div>\n            <motion.div\n              initial={{ opacity: 0, y: 14 }}\n              animate={{ opacity: 1, y: 0 }}\n              transition={{ duration: 0.4, ease: \"easeOut\", delay: 0.08 }}\n              className=\"w-full\"\n            >\n              {composer}\n            </motion.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 * 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  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      <AnimatePresence>\n        {!done && !failed && (\n          <motion.div\n            key=\"rocket\"\n            className={cn(\"absolute top-1/2 z-10\", theme.primaryText)}\n            style={{ left: `${progress}%`, transition: glide }}\n            exit={{ left: \"100%\", transition: { duration: 0.2 } }}\n          >\n            <motion.div\n              className=\"relative -translate-x-1/2 -translate-y-1/2\"\n              initial={{ scale: 0, y: 8, opacity: 0, rotate: 60 }}\n              animate={{ scale: 1, y: 0, opacity: 1, rotate: 45 }}\n              exit={{\n                x: 14,\n                y: -18,\n                scale: 0.4,\n                opacity: 0,\n                rotate: 20,\n                transition: { duration: 0.35, ease: \"easeIn\" },\n              }}\n              transition={{ type: \"spring\", stiffness: 260, damping: 16 }}\n            >\n              {/* Bob while in flight */}\n              <motion.div\n                animate={{ y: [0, -1.5, 0, 1.5, 0] }}\n                transition={{\n                  duration: 1.4,\n                  repeat: Infinity,\n                  ease: \"easeInOut\",\n                }}\n                className=\"relative\"\n              >\n                {/* Exhaust: sits behind the tail (bottom-left of the rotated icon) */}\n                <motion.span\n                  className=\"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                  style={{ rotate: -45 }}\n                  animate={{\n                    scaleX: [0.6, 1.3, 0.8, 1.1, 0.6],\n                    opacity: [0.7, 1, 0.8, 1, 0.7],\n                  }}\n                  transition={{\n                    duration: 0.35,\n                    repeat: Infinity,\n                    ease: \"easeInOut\",\n                  }}\n                />\n                <Rocket className=\"w-3.5 h-3.5 drop-shadow-sm\" />\n              </motion.div>\n            </motion.div>\n          </motion.div>\n        )}\n      </AnimatePresence>\n\n      {/* Landing */}\n      <AnimatePresence>\n        {done && (\n          <motion.span\n            key=\"landed\"\n            className=\"absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 z-10 flex items-center justify-center\"\n          >\n            <motion.span\n              className=\"absolute size-4 rounded-full bg-emerald-500/40\"\n              initial={{ scale: 0.4, opacity: 0.9 }}\n              animate={{ scale: 2.6, opacity: 0 }}\n              transition={{ duration: 0.6, ease: \"easeOut\" }}\n            />\n            <motion.span\n              className=\"relative size-4 rounded-full bg-emerald-500 text-white flex items-center justify-center shadow-sm\"\n              initial={{ scale: 0, rotate: -90 }}\n              animate={{ scale: 1, rotate: 0 }}\n              transition={{\n                type: \"spring\",\n                stiffness: 380,\n                damping: 14,\n                delay: 0.15,\n              }}\n            >\n              <Check className=\"w-2.5 h-2.5\" strokeWidth={3.5} />\n            </motion.span>\n          </motion.span>\n        )}\n        {failed && (\n          <motion.span\n            key=\"failed\"\n            initial={{ scale: 0 }}\n            animate={{ scale: 1 }}\n            className=\"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          >\n            <X className=\"w-2.5 h-2.5\" strokeWidth={3.5} />\n          </motion.span>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nfunction AttachmentChip({\n  attachment,\n  theme,\n  onRemove,\n}: {\n  attachment: PendingAttachment;\n  theme: Theme;\n  onRemove: () => void;\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    <motion.div\n      layout\n      initial={{ opacity: 0, scale: 0.85, y: 6 }}\n      animate={{ opacity: 1, scale: 1, y: 0 }}\n      exit={{ opacity: 0, scale: 0.85, y: 6 }}\n      transition={{ type: \"spring\", stiffness: 320, damping: 24 }}\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    </motion.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 spring = { type: \"spring\" as const, stiffness: 400, damping: 30 };\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      <motion.div\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 }}\n        initial={false}\n        animate={{\n          width: `calc(${thumbLeft} + ${THUMB_WIDTH / 2 - TRACK_INSET}px)`,\n        }}\n        transition={spring}\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      <motion.div\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        }}\n        initial={false}\n        animate={{ left: thumbLeft }}\n        transition={spring}\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    <AnimatePresence>\n      {active && (\n        <motion.div\n          key=\"max-glow\"\n          initial={{ opacity: 0 }}\n          animate={{ opacity: 1 }}\n          exit={{ opacity: 0 }}\n          transition={{ duration: 0.5 }}\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          <motion.div\n            className=\"absolute inset-x-6 bottom-0 h-1/2 bg-[radial-gradient(ellipse_at_bottom,currentColor,transparent_60%)] opacity-20 blur-xl\"\n            animate={{ opacity: [0.12, 0.26, 0.12] }}\n            transition={{ duration: 3.2, repeat: Infinity, ease: \"easeInOut\" }}\n          />\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              <motion.span\n                key={i}\n                className=\"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                }}\n                animate={{\n                  opacity: [0, 0.9, 0],\n                  scale: [0.4, 1.3, 0.4],\n                  y: [0, -6, -12],\n                }}\n                transition={{\n                  duration,\n                  delay,\n                  repeat: Infinity,\n                  ease: \"easeInOut\",\n                }}\n              />\n            );\n          })}\n        </motion.div>\n      )}\n    </AnimatePresence>\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: {\n      initial: TargetAndTransition;\n      animate: TargetAndTransition;\n      transition: Transition;\n    };\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: {\n      initial: { scale: 0, rotate: -45 },\n      animate: { scale: [0, 1.3, 1], rotate: [-45, 12, 0] },\n      transition: { duration: 0.55, times: [0, 0.6, 1], ease: \"easeOut\" },\n    },\n    Sweep: PremiumSweep,\n    PillFlash: PremiumPillFlash,\n  },\n  pro: {\n    label: \"Pro\",\n    Icon: Zap,\n    badge: PRO.badge,\n    pill: PRO.pill,\n    // Strikes down, overshoots and flickers once before it settles.\n    iconPop: {\n      initial: { opacity: 0, y: -8, scale: 0.6 },\n      animate: {\n        opacity: [0, 1, 0.35, 1, 1],\n        y: [-8, 0, 0, 0, 0],\n        scale: [0.6, 1.3, 1.15, 1, 1],\n      },\n      transition: {\n        duration: 0.5,\n        times: [0, 0.35, 0.5, 0.65, 1],\n        ease: \"easeOut\",\n      },\n    },\n    Sweep: ProSurge,\n    PillFlash: ProPillFlash,\n  },\n};\n\n/** The premium flourish on the prompt bar: one lap of the edge beam. */\nconst PREMIUM_SWEEP_S = 1.6;\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    <motion.div\n      aria-hidden\n      initial={{ opacity: 0 }}\n      animate={{ opacity: [0, 1, 1, 0] }}\n      transition={{\n        duration: PREMIUM_SWEEP_S,\n        times: [0, 0.1, 0.7, 1],\n        ease: \"linear\",\n      }}\n      onAnimationComplete={onDone}\n      className={cn(\n        \"pointer-events-none absolute inset-0 rounded-2xl\",\n        PREMIUM.ink,\n      )}\n    >\n      <motion.span\n        className=\"absolute inset-0 rounded-2xl shadow-[0_0_24px_6px_currentColor]\"\n        initial={{ opacity: 0, scale: 0.98 }}\n        animate={{ opacity: [0, 0.6, 0], scale: 1.03 }}\n        transition={{\n          duration: 1.1,\n          delay: 0.1,\n          ease: \"easeOut\",\n          opacity: {\n            duration: 1.1,\n            delay: 0.1,\n            times: [0, 0.35, 1],\n            ease: \"easeOut\",\n          },\n        }}\n      />\n      <span className=\"absolute inset-0 overflow-hidden rounded-2xl\">\n        <motion.span\n          className=\"absolute inset-y-0 left-0 w-1/4 bg-gradient-to-r from-transparent via-current to-transparent opacity-25\"\n          initial={{ x: \"-120%\", skewX: -20 }}\n          animate={{ x: \"420%\" }}\n          transition={{ duration: 1, delay: 0.15, ease: \"easeInOut\" }}\n        />\n      </span>\n      <span\n        className=\"absolute inset-0 overflow-hidden rounded-2xl p-[2px]\"\n        style={RING_MASK}\n      >\n        <motion.span\n          className=\"absolute left-1/2 top-1/2 aspect-square w-[150%]\"\n          style={{ x: \"-50%\", y: \"-50%\", background: BEAM_GRADIENT }}\n          initial={{ rotate: 0 }}\n          animate={{ rotate: 360 }}\n          transition={{ duration: PREMIUM_SWEEP_S, ease: [0.45, 0, 0.2, 1] }}\n        />\n      </span>\n    </motion.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      <motion.span\n        className=\"absolute inset-0 rounded-lg border-2 border-current\"\n        initial={{ opacity: 0.8, scaleX: 1, scaleY: 1 }}\n        animate={{ opacity: 0, scaleX: 1.12, scaleY: 1.45 }}\n        transition={{ duration: 0.6, ease: \"easeOut\" }}\n      />\n      <span className=\"absolute inset-0 overflow-hidden rounded-lg\">\n        <motion.span\n          className=\"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          initial={{ x: \"-100%\", skewX: -20 }}\n          animate={{ x: \"320%\" }}\n          transition={{ duration: 0.7, delay: 0.1, ease: \"easeInOut\" }}\n        />\n      </span>\n    </span>\n  );\n}\n\n/** The Pro flourish on the prompt bar: trace, flicker and fade. */\nconst PRO_SURGE_S = 1.3;\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    <motion.div\n      aria-hidden\n      initial={{ opacity: 0 }}\n      animate={{ opacity: [0, 1, 1, 0] }}\n      transition={{\n        duration: PRO_SURGE_S,\n        times: [0, 0.06, 0.72, 1],\n        ease: \"linear\",\n      }}\n      onAnimationComplete={onDone}\n      className={cn(\n        \"pointer-events-none absolute inset-0 rounded-2xl\",\n        PRO.ink,\n      )}\n    >\n      <motion.span\n        className=\"absolute inset-0 rounded-2xl shadow-[inset_0_0_20px_2px_currentColor]\"\n        initial={{ opacity: 0 }}\n        animate={{ opacity: [0, 0.55, 0] }}\n        transition={{\n          duration: 0.7,\n          delay: 0.45,\n          times: [0, 0.4, 1],\n          ease: \"easeOut\",\n        }}\n      />\n      <span className=\"absolute inset-0 overflow-hidden rounded-2xl\">\n        <motion.span\n          className=\"absolute inset-0 bg-gradient-to-t from-transparent via-current to-transparent opacity-20\"\n          initial={{ y: \"100%\" }}\n          animate={{ y: \"-100%\" }}\n          transition={{ duration: 0.9, delay: 0.2, ease: \"easeInOut\" }}\n        />\n      </span>\n      <span\n        className=\"absolute inset-0 overflow-hidden rounded-2xl p-[2px]\"\n        style={RING_MASK}\n      >\n        <motion.span\n          className=\"absolute inset-0 bg-current\"\n          initial={{ clipPath: \"inset(0% 50%)\", opacity: 1 }}\n          animate={{\n            clipPath: \"inset(0% 0%)\",\n            opacity: [1, 1, 0.25, 1, 0.45, 1],\n          }}\n          transition={{\n            clipPath: { duration: 0.5, ease: \"easeOut\" },\n            opacity: {\n              duration: 0.95,\n              times: [0, 0.53, 0.62, 0.72, 0.81, 1],\n              ease: \"linear\",\n            },\n          }}\n        />\n      </span>\n    </motion.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      <motion.span\n        className=\"absolute inset-0 rounded-lg bg-current\"\n        initial={{ opacity: 0 }}\n        animate={{ opacity: [0, 0.3, 0.05, 0.25, 0] }}\n        transition={{\n          duration: 0.6,\n          times: [0, 0.15, 0.3, 0.45, 1],\n          ease: \"linear\",\n        }}\n      />\n      {PRO_SPARKS.map(([x, y]) => (\n        <motion.span\n          key={`${x},${y}`}\n          className=\"absolute left-[13px] sm:left-[15px] top-1/2 size-[3px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-current\"\n          initial={{ opacity: 0, x: 0, y: 0, scale: 1 }}\n          animate={{ opacity: [0, 1, 0], x, y, scale: 0.3 }}\n          transition={{\n            duration: 0.5,\n            delay: 0.15,\n            ease: \"easeOut\",\n            opacity: { duration: 0.5, delay: 0.15, times: [0, 0.1, 1] },\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          <motion.span\n            key={i}\n            className=\"w-[3px] h-full rounded-full bg-current origin-center\"\n            animate={{\n              scaleY: [0.15, envelope, 0.3, envelope * 0.8, 0.15],\n            }}\n            transition={{\n              duration: 0.9 + (i % 5) * 0.12,\n              repeat: Infinity,\n              ease: \"easeInOut\",\n              delay: (i % 7) * 0.07,\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      <AnimatePresence>\n        {open && (\n          <motion.div\n            role=\"menu\"\n            initial={{ opacity: 0, y: 6, scale: 0.96 }}\n            animate={{ opacity: 1, y: 0, scale: 1 }}\n            exit={{ opacity: 0, y: 6, scale: 0.96 }}\n            transition={{ duration: 0.16, ease: \"easeOut\" }}\n            style={{ transformOrigin: \"bottom left\" }}\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          </motion.div>\n        )}\n      </AnimatePresence>\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"
    }
  ],
  "docs": "Motion build of `ai-chat` — same props, markup and install path; install one or the other. 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"
}
