import React, {useEffect, useRef, useState} from "react"; export default function AIAssistantDrawer({ open, onClose, computers, scope, setScope, apiBase = "", // ако сакаш можеш да пратиш VITE_API_BASE тука }) { const [messages, setMessages] = useState([ { role: "assistant", text: "Постави прашање за Sysmon, процеси, мрежа. Можеш да избереш компјутер (scope) горе.", }, ]); const [input, setInput] = useState(""); const [sending, setSending] = useState(false); const bottomRef = useRef(null); useEffect(() => { if (open) { // затвори со Escape const onKey = (e) => { if (e.key === "Escape") onClose?.(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); } }, [open, onClose]); useEffect(() => { if (bottomRef.current) bottomRef.current.scrollIntoView({behavior: "smooth"}); }, [messages, open]); async function send() { const q = input.trim(); if (!q || sending) return; setInput(""); setMessages((m) => [...m, {role: "user", text: q}]); setSending(true); try { const base = (apiBase || "").replace(/\/$/, ""); // тргни trailing / const url = `${base}/api/chat`; const r = await fetch(url, { method: "POST", headers: {"Content-Type": "application/json"}, credentials: "include", body: JSON.stringify({question: q, computer_name: scope || null}), }); const data = await r.json().catch(() => ({})); // if (!r.ok) { // setMessages((m) => [...m, { // role: "assistant", // text: `Error ${r.status}: ${data.error || "Request failed"}` // }]); // } else { // setMessages((m) => [...m, {role: "assistant", text: data.answer || "(no answer)"}]); // } // setMessages((m) => [ // ...m, // {role: "assistant", text: data.answer || "(no answer)"}, // ]); if (!r.ok) { setMessages((m) => [ ...m, {role: "assistant", text: `Error ${r.status}: ${data.error || "Request failed"}`}, ]); } else { const qs = Array.isArray(data.queries) ? data.queries : []; const notes = data.notes || ""; const text = qs.length ? `SQL queries:\n\n${qs.map((q, i) => `${i + 1}) ${q}`).join("\n\n")}\n\nNotes: ${notes}` : `Notes: ${notes || "No queries returned."}`; setMessages((m) => [...m, {role: "assistant", text}]); } } catch (e) { setMessages((m) => [ ...m, {role: "assistant", text: `Грешка: ${String(e?.message || e)}`}, ]); } finally { setSending(false); } } if (!open) return null; return ( <>