'use client' import { Bot, Mic, Send, Square, User } from 'lucide-react' import Link from 'next/link' import { useEffect, useMemo, useRef, useState } from 'react' import type { Components } from 'react-markdown' import ReactMarkdown from 'react-markdown' import remarkGfm from 'remark-gfm' import { Bubble, BubbleContent } from '@/components/ui/bubble' import { InputGroup, InputGroupButton } from '@/components/ui/input-group' import { Marker, MarkerContent } from '@/components/ui/marker' import { Message, MessageAvatar, MessageContent } from '@/components/ui/message' import { Spinner } from '@/components/ui/Spinner' import { externalLinkTarget } from '@/lib/ai/markdownLinks' import { cn } from '@/lib/utils' import { useAISidebar } from '@/components/campaign/shell/ai/CampaignAISidebarContext' import { ChatChipGroup } from '@/components/campaign/shell/ai/ChatChipGroup' import { useMicTranscript } from '@/components/campaign/shell/ai/useMicTranscript' import { getSollinhaOpeningQuestions } from '@/lib/sollinhaOpeningQuestions' import { splitSollinhaFollowUpBlock } from '@/lib/sollinhaFollowUpSuggestions' /** * B187+B188 — links in the assistant's markdown must look like links: brand * primary color + always-visible underline, hover thickens the underline and * keyboard focus shows a ring (BubbleContent's own `[button,a]:focus-visible:*` * only applies when the bubble content ITSELF is the anchor). External http(s) * links open in a new tab; app-internal destinations — the B162 link catalog * only ever emits `/campanha…` paths — navigate through `next/link` (B188), so * following a Sollinha link keeps the layout (and the conversation) mounted * instead of reloading the page. Anything else keeps the plain anchor. */ const APP_INTERNAL_LINK = /^\/campanha(?:\/|$)/ /** B192 — narrower drawer surface: fewer follow-up chips than on desktop. */ const FOLLOW_UP_MOBILE_LIMIT = 2 const markdownComponents: Components = { a: ({ node: _node, href, children, ...rest }) => { const external = typeof href === 'string' ? externalLinkTarget(href) : null if (typeof href === 'string' && APP_INTERNAL_LINK.test(href)) { return ( {children} ) } return ( {children} ) }, } export const CampaignAIChat = ({ className }: { className?: string }) => { const ctx = useAISidebar() const [input, setInput] = useState('') const bottomRef = useRef(null) const mic = useMicTranscript() const textareaRef = useRef(null) const messages = useMemo(() => ctx?.messages ?? [], [ctx]) // B192 — follow-up suggestions of the LATEST assistant message (the final // response of the turn — older answers never feed the slot). Derived before // the `ctx` early return so the hooks stay unconditional; only rendered once // the chat is idle (during streaming the input is locked, so dead chips // would confuse; the new ones appear the moment the answer lands). const latestAssistantSuggestionText = useMemo(() => { if (ctx?.status !== 'ready' || messages.length === 0) return null const lastAssistant = [...messages].reverse().find((message) => message.role === 'assistant') return lastAssistant?.parts.filter((part) => part.type === 'text').at(-1)?.text ?? null }, [messages, ctx?.status]) const followUpSuggestions = useMemo(() => { if (!latestAssistantSuggestionText) return [] const { suggestions } = splitSollinhaFollowUpBlock(latestAssistantSuggestionText) // Viewport cap mirrors the opening catalog: fewer chips on narrow surfaces. return suggestions.slice(0, ctx?.isMobile ? FOLLOW_UP_MOBILE_LIMIT : suggestions.length) }, [latestAssistantSuggestionText, ctx?.isMobile]) const showFollowUpChips = followUpSuggestions.length > 0 // Auto-scroll to bottom on new messages useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [messages]) // A completed transcript becomes an editable draft in the input — never an // auto-sent message (voices mishear proper nouns; the person reviews first). useEffect(() => { if (!mic.transcript) return setInput(mic.transcript) textareaRef.current?.focus() }, [mic.transcript]) if (!ctx) return null const { sendMessage, status, role, isMobile } = ctx const busy = status !== 'ready' const handleSubmit = (e: React.FormEvent) => { e.preventDefault() if (!input.trim() || busy) return sendMessage({ text: input }) setInput('') } const isRecording = mic.status === 'recording' const isTranscribing = mic.status === 'transcribing' const micDisabled = busy || isTranscribing // B191 — the empty conversation offers curated opening questions as chips // above the input. They disappear on the first send because `messages` grows // past zero (the slot renders only while empty). const showOpeningChips = messages.length === 0 && status === 'ready' const openingQuestions = getSollinhaOpeningQuestions(role, isMobile) return (
{/* Messages area */}
{messages.length === 0 ? (

Olá! Eu sou o Sollinha, assistente virtual da campanha. Pergunte sobre votações, municípios, dobradinhas, lideranças e muito mais.

) : (
{messages.map((message) => ( {message.role === 'user' ? ( ) : ( )} {message.parts.map((part, index) => { if (part.type === 'text') { if (message.role === 'user') { return ( {part.text} ) } // B192 — the follow-up block is a format directive // for the chip slot, never chat content: strip it // BEFORE markdown/link rendering so it never shows // as prose (fail-closed: no marker → unchanged). const { body } = splitSollinhaFollowUpBlock(part.text) return (
{body}
) } if (part.type === 'tool-invocation') { return ( 🔍 Buscando dados... ) } return null })}
))} {busy && messages.length > 0 && ( )}
)}
{/* Input area */}
{/* B191+B192 — one chip slot above the input, fed by two sources: the curated opening catalog while the conversation is empty, and the follow-ups extracted from the latest answer afterwards. */} {(showOpeningChips || showFollowUpChips) && ( ({ text })) } onPick={({ text }) => { if (busy) return sendMessage({ text }) }} className="mb-2" /> )}