import React, { useEffect, useRef, useState } from 'react' import { api } from '../api.js' const SUGGESTIONS = [ "What's the termination notice period?", "Who bears liability for data breaches?", "When does this contract expire?", "What are the payment terms?", "Is there an auto-renewal clause?", ] export default function ContractChat({ contractId, onSelectClause }) { const [messages, setMessages] = useState([ { role: 'bot', text: "Ask me anything about this contract — I'll search the clauses and cite my sources.", citations: [], }, ]) const [input, setInput] = useState('') const [loading, setLoading] = useState(false) const bottomRef = useRef(null) useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [messages, loading]) async function send(question) { const q = (question || input).trim() if (!q || loading) return setInput('') setMessages((m) => [...m, { role: 'user', text: q, citations: [] }]) setLoading(true) try { const res = await api(`/api/contracts/${contractId}/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ question: q }), }) const data = await res.json() setMessages((m) => [ ...m, { role: 'bot', text: data.answer || 'No answer returned.', citations: data.citations || [] }, ]) } catch { setMessages((m) => [ ...m, { role: 'bot', text: 'Error contacting the server. Please try again.', citations: [] }, ]) } finally { setLoading(false) } } const showSuggestions = messages.length === 1 return (
{messages.map((m, i) => (
{m.text.split('\n\n').map((para, j) => (

{para}

))}
{m.citations.length > 0 && (
Sources: {m.citations.map((c, j) => ( ))}
)}
))} {showSuggestions && (
{SUGGESTIONS.map((s, i) => ( ))}
)} {loading && (
)}
setInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && send()} disabled={loading} />
) }