import React, { useState, useEffect, useRef } from 'react'; import { Send, Sparkles, MessageSquare, Compass, ShieldAlert } from 'lucide-react'; export default function Chatbot({ metrics, scores }) { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [loading, setLoading] = useState(false); const messagesEndRef = useRef(null); // Reset chat messages when metrics change (user clicks new location) useEffect(() => { if (metrics) { setMessages([ { role: 'assistant', content: `สวัสดีครับ! ผมเป็นผู้ช่วยซินแสปัญญาประดิษฐ์และวิศวกรสิ่งแวดล้อม GIS ผมพร้อมช่วยวิเคราะห์ฮวงจุ้ยและโครงสร้างสิ่งแวดล้อมของ **${metrics.location_name}** (พิกัด: ${metrics.elevation_m}m, NDVI: ${metrics.ndvi}) ให้คุณแล้วครับ มีอะไรต้องการสอบถามเพิ่มเติมเกี่ยวกับการปรับสมดุล Yin-Yang, ปัญหา Sha Qi หรือแนวทางวิศวกรรมป้องกันในจุดนี้ไหมครับ?` } ]); } }, [metrics]); const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToBottom(); }, [messages, loading]); const handleSend = async (e) => { e.preventDefault(); if (!input.trim() || loading) return; const userMessage = input; setInput(''); setMessages((prev) => [...prev, { role: 'user', content: userMessage }]); setLoading(true); // Prepare history (limit to last 6 messages to keep tokens optimal) const history = messages .slice(-6) .map((msg) => ({ role: msg.role, content: msg.content })); try { const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: userMessage, history: history, metrics: metrics, scores: scores }) }); if (!response.ok) throw new Error('API server returned error'); const data = await response.json(); setMessages((prev) => [...prev, { role: 'assistant', content: data.response }]); } catch (err) { console.error(err); setMessages((prev) => [ ...prev, { role: 'assistant', content: 'ขออภัยครับ เกิดข้อผิดพลาดในการเชื่อมต่อระบบวิเคราะห์ AI กรุณาตรวจสอบว่าเซิร์ฟเวอร์ยังเปิดอยู่' } ]); } finally { setLoading(false); } }; return (
{/* Chat Header */}
Typhoon Feng Shui Master AI
{/* Messages Terminal Area */}
{messages.map((msg, index) => { const isUser = msg.role === 'user'; return (
{!isUser && index === 0 && (
CONTEXTUAL ANALYSIS
)} {msg.content}
); })} {/* Loading Bubble */} {loading && (
)}
{/* Input Message Form */}
setInput(e.target.value)} placeholder="Ask about Sha Qi, Yin-Yang, or remedies for this spot..." disabled={loading} style={{ flex: 1, padding: '8px 12px', backgroundColor: 'rgba(0,0,0,0.4)', border: '1px solid var(--border-glass)', borderRadius: '6px', color: 'var(--text-primary)', fontSize: '12.5px', fontFamily: 'var(--font-sans)', outline: 'none' }} />
); }