import { useState, useRef, useEffect } from "react"; import { ChatMessage, sendChatMessage, getChatHistory } from "../api/client"; import { useAuth } from "../hooks/useAuth"; import { isPaidPlan } from "../lib/plan"; import UpgradeModal from "./UpgradeModal"; interface Props { projectId: number; onScenesUpdated: () => void; } export default function ChatPanel({ projectId, onScenesUpdated }: Props) { const { user } = useAuth(); const isPro = isPaidPlan(user?.plan); const [messages, setMessages] = useState([]); const [input, setInput] = useState(""); const [loading, setLoading] = useState(false); const [showUpgrade, setShowUpgrade] = useState(false); const messagesEndRef = useRef(null); useEffect(() => { loadHistory(); }, [projectId]); useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages]); const loadHistory = async () => { try { const res = await getChatHistory(projectId); setMessages(res.data); } catch { // No history yet } }; const handleSend = async () => { if (!isPro) { setShowUpgrade(true); return; } const msg = input.trim(); if (!msg || loading) return; const userMsg: ChatMessage = { id: Date.now(), role: "user", content: msg, created_at: new Date().toISOString(), }; setMessages((prev) => [...prev, userMsg]); setInput(""); setLoading(true); try { const res = await sendChatMessage(projectId, msg); const assistantMsg: ChatMessage = { id: Date.now() + 1, role: "assistant", content: res.data.reply, created_at: new Date().toISOString(), }; setMessages((prev) => [...prev, assistantMsg]); onScenesUpdated(); } catch (err: any) { const errorMsg: ChatMessage = { id: Date.now() + 1, role: "assistant", content: `Error: ${err?.response?.data?.detail || "Failed to process your request."}`, created_at: new Date().toISOString(), }; setMessages((prev) => [...prev, errorMsg]); } finally { setLoading(false); } }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSend(); } }; const handleInputFocus = () => { if (!isPro) { setShowUpgrade(true); } }; return ( <>
{/* Messages */}
{messages.length === 0 && (

Edit with AI

"Make scene 2 more dramatic" or "Add an introduction"

)} {messages.map((msg) => (

{msg.content}

))} {loading && (
)}
{/* Input */}
{!isPro && ( )}