import { useEffect, useRef, useState } from 'react' const API=(p:string)=>'/api'+p type Msg={role:'user'|'assistant',content:string} export default function ChatBox(){const [messages,setMessages]=useState([]);const [text,setText]=useState('');const [mode,setMode]=useState<'file'|'mic'|'video'>('file');const pressTimer=useRef(undefined);const feedRef=useRef(null);const token=localStorage.getItem('token')||'';const headers={'Content-Type':'application/json','Authorization':'Bearer '+token};useEffect(()=>{fetch(API('/chat/history'),{headers}).then(r=>r.json()).then((data)=>{setMessages(data.map((m:any)=>({role:m.role,content:m.content})))})},[]);useEffect(()=>{feedRef.current?.scrollTo({top:feedRef.current.scrollHeight})},[messages]);const send=async()=>{if(!text.trim()) return; setMessages(m=>[...m,{role:'user',content:text}]); setText(''); const r=await fetch(API('/chat'),{method:'POST',headers,body:JSON.stringify({message:text})}); const data=await r.json(); setMessages(m=>[...m,{role:'assistant',content:data.reply}])} const cycle=()=>setMode(m=> m==='file'?'mic': m==='mic'?'video':'file') const onMouseDown=()=>{pressTimer.current=window.setTimeout(cycle,450)} const onMouseUp=()=>{if(pressTimer.current){clearTimeout(pressTimer.current); pressTimer.current=undefined}} return (
{messages.map((m,i)=>(
{m.content}
))}
setText((e.target as any).value)} placeholder="Type a message" className="px-3 py-2 rounded-xl border border-slate-700 bg-slate-800 outline-none"/>
)}