'use client' import { useState, useRef, useEffect } from 'react' import { useChat } from '@ai-sdk/react' import { DefaultChatTransport } from 'ai' import { useLanguage } from '@/lib/i18n' import { X, Send, FileText, Sparkles, Loader2, User, Plus, Square } from 'lucide-react' interface Attachment { id: string fileName: string } interface DocumentQAOverlayProps { attachment: Attachment noteId: string noteContent?: string onClose: () => void onApplyToNote?: (content: string) => void } function getMessageContent(msg: any): string { if (typeof msg.content === 'string') return msg.content if (msg.parts && Array.isArray(msg.parts)) { return msg.parts .filter((p: any) => p.type === 'text' && typeof p.text === 'string') .map((p: any) => p.text) .join('') } return '' } export function DocumentQAOverlay({ attachment, noteId, noteContent, onClose, onApplyToNote }: DocumentQAOverlayProps) { const { t } = useLanguage() const messagesEndRef = useRef(null) const textareaRef = useRef(null) const [input, setInput] = useState('') const pdfUrl = `/api/notes/${noteId}/attachments/${attachment.id}?download=true` const transport = useRef(new DefaultChatTransport({ api: '/api/chat', body: { noteId, noteContext: { title: attachment.fileName, content: noteContent || '', tone: 'professional', }, webSearch: false, }, })).current const { messages, sendMessage, status, stop } = useChat({ transport }) const isLoading = status === 'submitted' || status === 'streaming' const lastAssistantContent = [...messages].reverse().find(m => m.role === 'assistant') const lastAssistantText = lastAssistantContent ? getMessageContent(lastAssistantContent) : '' useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [messages]) useEffect(() => { const handleEsc = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() } document.addEventListener('keydown', handleEsc) return () => document.removeEventListener('keydown', handleEsc) }, [onClose]) const handleSend = async () => { const text = input.trim() if (!text || isLoading) return setInput('') try { await sendMessage({ text }) } catch { } } const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault() handleSend() } } return (
e.stopPropagation()} className="fixed inset-0 z-[100] flex items-center justify-center p-6 bg-black/40 backdrop-blur-sm" >
{/* Left: PDF Preview */}

{attachment.fileName}

PDF