'use client'; import { useEffect, useRef, useState } from 'react'; import { toast } from 'sonner'; import { Bot, RotateCcw, Send, Loader2, UserCircle2, ArrowRight } from 'lucide-react'; import { cn } from '@/lib/utils'; import { Button } from '@/components/ui/button'; interface Turn { role: 'user' | 'assistant'; content: string; /** assistant-only: the agent signalled a human handoff on this turn. */ handoff?: boolean; } export function AiPlayground({ onGoToSetup }: { onGoToSetup?: () => void }) { const [turns, setTurns] = useState([]); const [input, setInput] = useState(''); const [sending, setSending] = useState(false); const scrollRef = useRef(null); useEffect(() => { scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight }); }, [turns, sending]); const send = async () => { const text = input.trim(); if (!text || sending) return; const next: Turn[] = [...turns, { role: 'user', content: text }]; setTurns(next); setInput(''); setSending(true); try { const res = await fetch('/api/ai/playground', { method: 'POST', headers: { 'Content-Type': 'application/json' }, // Send only role+content — the server ignores anything else. body: JSON.stringify({ messages: next.map((t) => ({ role: t.role, content: t.content })), }), }); const data = await res.json().catch(() => ({})); if (!res.ok) { if (data.code === 'ai_not_configured') { toast.error('No agent configured yet — finish Setup first.'); } else { toast.error(data.error ?? "Couldn't get a reply."); } // Roll the unsent user turn back so the transcript stays clean. setTurns(turns); setInput(text); return; } setTurns([ ...next, { role: 'assistant', content: typeof data.reply === 'string' && data.reply.trim() ? data.reply : '', handoff: Boolean(data.handoff), }, ]); } catch { toast.error("Couldn't reach the agent."); setTurns(turns); setInput(text); } finally { setSending(false); } }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void send(); } }; return (
{/* Header */}
Playground — test replies as if you were a customer
{/* Transcript */}
{turns.length === 0 && (

Send a message to see how your agent would reply.

It uses your knowledge base and behaves exactly like the auto-reply bot — including handoff.

{onGoToSetup && ( )}
)} {turns.map((t, i) => (
{t.role === 'assistant' && ( )}
{t.content &&

{t.content}

} {t.role === 'assistant' && t.handoff && (

Would hand off to a human here

)}
{t.role === 'user' && ( )}
))} {sending && (
Thinking…
)}
{/* Composer */}