import {
  AssistantRuntimeProvider,
  ThreadPrimitive,
  ComposerPrimitive,
  MessagePrimitive,
  useLocalRuntime,
} from "@assistant-ui/react";
import "@assistant-ui/styles/index.css";
import "@assistant-ui/styles/markdown.css";

function flattenContent(content: any): string {
  if (typeof content === "string") return content;
  if (Array.isArray(content)) {
    return content
      .map((p) => (typeof p === "string" ? p : p?.text ?? p?.content ?? ""))
      .filter(Boolean)
      .join("\n");
  }
  if (content && typeof content === "object" && "text" in content) return content.text as string;
  return "";
}

function stripThinkTags(s: string) {
  // срежем <think>...</think> если модель прислала размышления
  return s.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
}


export default function App() {
  const runtime = useLocalRuntime({
    async run({ messages, abortSignal }) {
      const wireMessages = messages.map((m: any) => ({
        role: m.role,
        content: flattenContent(m.content),
      }));

      const res = await fetch("/api/assistant/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: wireMessages }),
        signal: abortSignal,
      });
      if (!res.ok) throw new Error(await res.text());

      const data = await res.json(); // ожидаем { role, content: string }
      const cleaned = stripThinkTags(typeof data.content === "string" ? data.content : flattenContent(data.content));

      // ВАЖНО: ассистенту возвращаем parts c типом "text"
      return {
        role: data.role ?? "assistant",
        content: [{ type: "text", text: cleaned }],
      };
    },
  });

  return (
    <AssistantRuntimeProvider runtime={runtime}>
      <div style={{ height: "70vh", maxWidth: 960, margin: "0 auto" }}>
        <ThreadPrimitive.Root className="aui-root aui-thread-root" style={{ height: "100%" }}>
          <ThreadPrimitive.Viewport className="aui-thread-viewport">
            <ThreadPrimitive.Messages
              components={{
                AssistantMessage: () => (
                  <MessagePrimitive.Root className="aui-assistant-message-root">
                    <div className="aui-assistant-message-content">
                      <MessagePrimitive.Parts />
                    </div>
                  </MessagePrimitive.Root>
                ),
                UserMessage: () => (
                  <MessagePrimitive.Root className="aui-user-message-root">
                    <div className="aui-user-message-content">
                      <MessagePrimitive.Parts />
                    </div>
                  </MessagePrimitive.Root>
                ),
              }}
            />
            <div className="aui-thread-viewport-footer">
              <ComposerPrimitive.Root className="aui-composer-root">
                <ComposerPrimitive.Input
                  className="aui-composer-input"
                  rows={1}
                  placeholder="Напиши сообщение…"
                />
                <ComposerPrimitive.Send>Send</ComposerPrimitive.Send>
              </ComposerPrimitive.Root>
            </div>
          </ThreadPrimitive.Viewport>
        </ThreadPrimitive.Root>
      </div>
    </AssistantRuntimeProvider>
  );
}
