'use client'; import { useRef, useState, type ChangeEvent } from 'react'; import { VALIDATION } from '@/lib/constants'; import { formatBytes } from '@/lib/format'; export interface TryDocument { id: string; name: string; content: string; size: number; } interface TryDocumentsPanelProps { documents: TryDocument[]; onDocumentsChange: (updater: (prev: TryDocument[]) => TryDocument[]) => void; onError: (msg: string) => void; onSuccess: (msg: string) => void; } export const TryDocumentsPanel = ({ documents, onDocumentsChange, onError, onSuccess, }: TryDocumentsPanelProps) => { const [uploading, setUploading] = useState(false); const fileInputRef = useRef(null); const handleFileUpload = async (e: ChangeEvent) => { const files = e.target.files; if (!files || files.length === 0) return; setUploading(true); onError(''); onSuccess(''); const newDocs: TryDocument[] = []; for (const file of Array.from(files)) { try { // Check file type const validTypes = ['text/plain', 'text/markdown', 'application/pdf']; const validExtensions = ['.txt', '.md', '.pdf']; const hasValidExtension = validExtensions.some((ext) => file.name.toLowerCase().endsWith(ext), ); if (!validTypes.includes(file.type) && !hasValidExtension) { onError(`Invalid file type: ${file.name}. Please upload TXT, MD, or PDF files.`); continue; } // Check file size if (file.size > VALIDATION.DEMO_MAX_FILE_SIZE) { onError(`File too large: ${file.name}. Maximum size is 5MB.`); continue; } let content = ''; if (file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf')) { const formData = new FormData(); formData.append('file', file); const response = await fetch('/api/demo/parse-pdf', { method: 'POST', body: formData, }); const data = await response.json(); if (!data.success) { onError(data.error || `Failed to parse PDF: ${file.name}`); continue; } content = data.data.text; } else { content = await file.text(); } if (content.trim().length === 0) { onError(`File is empty: ${file.name}`); continue; } newDocs.push({ id: `doc-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, name: file.name, content, size: file.size, }); } catch { onError(`Failed to read file: ${file.name}`); } } if (newDocs.length > 0) { onDocumentsChange((prev) => [...prev, ...newDocs]); onSuccess( `Uploaded ${newDocs.length} document${newDocs.length > 1 ? 's' : ''}. You can now ask questions!`, ); } setUploading(false); if (fileInputRef.current) { fileInputRef.current.value = ''; } }; const handleRemoveDocument = (id: string) => { onDocumentsChange((prev) => prev.filter((doc) => doc.id !== id)); }; return (

Your Documents

{/* Upload Area */}
{/* Document List */} {documents.length === 0 ? (

No documents yet

) : (
{documents.map((doc) => (

{doc.name}

{formatBytes(doc.size)}

))}
)} {documents.length > 0 && (

{documents.length} document{documents.length > 1 ? 's' : ''} loaded

)}
); };