"use client"; import { useEffect, useRef, useState } from "react"; import { useConsent } from "../ConsentProvider"; import type { WindowLabels } from "./types"; interface Message { id: string; text: string; from: "user" | "bot"; } const STORE_ID = "chatSessionId"; const STORE_MESSAGES = "chatMessages"; /** * KI-Chat im Fenster. Schickt erst etwas an n8n, wenn der Chatbot im * Datenschutz-Banner (oder hier) erlaubt wurde. */ export default function ChatBody({ labels }: { labels: WindowLabels }) { const { consent, ready, setConsent } = useConsent(); const allowed = !!consent?.chat; const [messages, setMessages] = useState([]); const [input, setInput] = useState(""); const [busy, setBusy] = useState(false); const [conversationId, setConversationId] = useState("default"); const listRef = useRef(null); const inputRef = useRef(null); useEffect(() => { if (!allowed) return; try { let id = localStorage.getItem(STORE_ID); if (!id) { id = crypto.randomUUID(); localStorage.setItem(STORE_ID, id); } setConversationId(id); const stored = localStorage.getItem(STORE_MESSAGES); const parsed = stored ? (JSON.parse(stored) as { id: string; text: string; sender?: string; from?: string }[]) : []; setMessages( parsed.length ? parsed.map((m) => ({ id: m.id, // Begrüßung immer in der aktuellen Sprache, auch wenn noch eine alte gespeichert ist text: m.id === "welcome" ? labels.chat.welcome : m.text, from: (m.from ?? m.sender) === "user" ? "user" : "bot", })) : [{ id: "welcome", text: labels.chat.welcome, from: "bot" }], ); } catch { setMessages([{ id: "welcome", text: labels.chat.welcome, from: "bot" }]); } inputRef.current?.focus({ preventScroll: true }); }, [allowed, labels.chat.welcome]); useEffect(() => { if (!allowed || messages.length === 0) return; try { localStorage.setItem(STORE_MESSAGES, JSON.stringify(messages)); } catch {} listRef.current?.scrollTo({ top: listRef.current.scrollHeight }); }, [messages, allowed]); const send = async () => { const text = input.trim(); if (!text || busy) return; const mine: Message = { id: String(Date.now()), text, from: "user" }; const history = messages.slice(-5).map((m) => ({ role: m.from === "user" ? "user" : "assistant", content: m.text })); setMessages((prev) => [...prev, mine]); setInput(""); setBusy(true); try { const res = await fetch("/api/n8n/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: text, conversationId, history }), }); const data = await res.json(); setMessages((prev) => [...prev, { id: `${Date.now()}-bot`, text: data.reply || labels.chat.error, from: "bot" }]); } catch { setMessages((prev) => [...prev, { id: `${Date.now()}-bot`, text: labels.chat.error, from: "bot" }]); } finally { setBusy(false); } }; if (!ready) return