import { j as jsxRuntimeExports } from "../../../../../_virtual/jsx-runtime.js";
import { tx as D, css as E } from "../../../../style-system/dist/twind.js";
import { useRef, useState, useEffect, useMemo, Suspense } from "react";
import "../../../../../node_modules/.pnpm/@formkit_auto-animate@0.8.2/node_modules/@formkit/auto-animate/index.js";
import { toast as c } from "../../../../../node_modules/.pnpm/react-hot-toast@2.5.2_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/react-hot-toast/dist/index.js";
import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls } from "../../../../../node_modules/.pnpm/ai@5.0.39_zod@4.1.5/node_modules/ai/dist/index.js";
import { TbSend2 } from "../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/tb/index.js";
import { IoIosAttach } from "../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/io/index.js";
import { useChat } from "../../../../../node_modules/.pnpm/@ai-sdk_react@2.0.39_react@19.1.1_zod@4.1.5/node_modules/@ai-sdk/react/dist/index.js";
import { useSitePrompt, useDraftHelpers, useAdditionalAssets, useGenerationState, useSite, usePage, useThemes } from "../../../../../use-page-data.js";
import { MdDone } from "../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/md/index.js";
import { useDebounceCallback } from "../../../../../node_modules/.pnpm/usehooks-ts@3.1.1_react@19.1.1/node_modules/usehooks-ts/dist/index.js";
import { BiStopCircle } from "../../../../../node_modules/.pnpm/react-icons@5.5.0_react@19.1.1/node_modules/react-icons/bi/index.js";
import { defineDataRecord as r } from "../../../../sdk/dist/shared/datarecords.js";
import { useDeepCompareEffect } from "../../../../../node_modules/.pnpm/use-deep-compare@1.3.0_react@19.1.1/node_modules/use-deep-compare/dist-web/index.js";
import { useDebugMode } from "../../../../../use-editor.js";
import { defineDatasource as o$1 } from "../../../../sdk/dist/shared/datasources.js";
import Markdown from "./Markdown.js";
import { AnimatePresence } from "../../../../../node_modules/.pnpm/motion@12.17.0_@emotion_is-prop-valid@1.4.0_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/motion/dist/es/framer-motion/dist/es/components/AnimatePresence/index.js";
import { motion } from "../../../../../node_modules/.pnpm/motion@12.17.0_@emotion_is-prop-valid@1.4.0_react-dom@19.1.1_react@19.1.1__react@19.1.1/node_modules/motion/dist/es/framer-motion/dist/es/render/components/motion/proxy.js";
import { Spinner as s } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/spinner.js";
import { Button as o } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/button.js";
import { Text as p } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.2.1_@types_react-dom@19.1.9_@types_react@19.1.13__@types_react@19.1._832fa1fef691e6e9510ada03948dc85c/node_modules/@radix-ui/themes/dist/esm/components/text.js";
const WEB_SEARCH_ENABLED = false;
const msgCommon = D(
  "rounded-lg p-6 text-pretty transition-all duration-300 flex flex-col gap-1.5",
  E({
    // whiteSpace: "pre-line",
    "& p": {
      marginBlock: ".5rem",
      lineHeight: "1.625"
    },
    "& p:first-child": {
      marginTop: "0"
    },
    "& p:last-child": {
      marginBottom: "0"
    },
    "& code": {
      fontSize: "88%"
    },
    "& ul, ol": {
      listStyle: "outside",
      listStyleType: "square",
      paddingLeft: "1.6rem",
      marginTop: "0.5rem",
      marginBottom: "0.2rem"
    },
    "& li": {
      marginBottom: "0.25rem",
      paddingLeft: ".3rem"
    },
    "& div.choices": {
      display: "flex",
      flexWrap: "wrap",
      justifyContent: "space-between",
      gap: ".5rem",
      marginBlock: "1rem",
      "& > button": {
        backgroundColor: "var(--violet-10)",
        color: "#fff",
        flexGrow: "1",
        padding: "0.4rem 0.7rem",
        borderRadius: "0.5rem",
        border: "none",
        fontSize: ".95em",
        fontWeight: "500",
        "&:hover": {
          backgroundColor: "var(--violet-9)"
        }
      }
    }
  })
);
const userMsgClass = D(
  "text-gray-800 text-[0.8rem] opacity-70 bg-gradient-to-tr from-gray-200/20 to-gray-100/20 w-fit max-w-[90%] dark:(bg-dark-900 text-white/70) self-end"
);
function Chat() {
  const sitePrompt = useSitePrompt();
  const setupRef = useRef(false);
  const draftHelpers = useDraftHelpers();
  const additionalAssets = useAdditionalAssets();
  const generationState = useGenerationState();
  const site = useSite();
  const page = usePage();
  const siteThemes = useThemes();
  const [userLanguage, setUserLanguage] = useState();
  const [input, setInput] = useState("");
  const debug = useDebugMode();
  const [showToastWorking, setShowToastWorking] = useState(generationState.isSetup);
  const [hasScrolledUp, setHasScrolledUp] = useState(false);
  useEffect(() => {
    const onScroll = (e) => {
      const target = e.target;
      if (target && messagesListRef.current) {
        const { scrollTop, scrollHeight, clientHeight } = messagesListRef.current;
        const isNearBottom = scrollTop + clientHeight >= scrollHeight - 100;
        setHasScrolledUp(!isNearBottom);
      }
    };
    const messagesContainer = messagesListRef.current;
    if (messagesContainer) {
      messagesContainer.addEventListener("scroll", onScroll);
      return () => {
        messagesContainer.removeEventListener("scroll", onScroll);
      };
    }
  }, []);
  useEffect(() => {
    if (showToastWorking) {
      c.loading("Setting up your site...", { duration: Infinity, id: "chat-setup" });
    } else {
      c.dismiss("chat-setup");
    }
  }, [showToastWorking]);
  const listPlaceholderRef = useRef(null);
  const handledToolResults = useRef(/* @__PURE__ */ new Set());
  const aiMsgClass = D(
    "text-black/80 dark:text-upstart-200",
    generationState.isReady ? "bg-gradient-to-tr from-upstart-200/80 to-upstart-100 text-sm" : "bg-white/80 dark:bg-dark-800 text-fluid-sm backdrop-blur-md"
  );
  const siteRef = useRef(site);
  const pageRef = useRef(page);
  const generationStateRef = useRef(generationState);
  const userLanguageRef = useRef(userLanguage);
  const assetsRef = useRef(additionalAssets);
  useEffect(() => {
    siteRef.current = site;
    pageRef.current = page;
    generationStateRef.current = generationState;
    userLanguageRef.current = userLanguage;
    assetsRef.current = additionalAssets;
  }, [site, page, generationState, userLanguage, additionalAssets]);
  const initialMessages = useMemo(() => {
    if (generationState.isSetup) {
      return [
        {
          id: "init-setup",
          role: "user",
          parts: [
            {
              type: "text",
              text: `Create a website based on this prompt:
${sitePrompt}`
            }
          ]
        }
      ];
    } else {
      return [
        {
          id: "init-edit",
          role: "assistant",
          parts: [
            {
              type: "text",
              text: `Hey! 👋

Ready to keep building? You can:
- Chat with me to make changes
- Use the visual editor for direct editing

What should we work on together? 🤖`
            }
          ]
        }
      ];
    }
  }, [generationState.isSetup, sitePrompt]);
  const onToolCall = ({ toolCall }) => {
    console.log("Tool call: %s: ", toolCall.toolName, toolCall);
    const toolResult = { tool: toolCall.toolName, toolCallId: toolCall.toolCallId };
    switch (toolCall.toolName) {
      case "listThemes": {
        console.debug(
          "Cient tool call %s",
          toolCall.toolName,
          " replying with themes",
          siteRef.current.themes
        );
        addToolResult({
          ...toolResult,
          output: siteRef.current.themes
        });
        break;
      }
      case "getCurrentTheme": {
        console.debug(
          "Client tool call %s",
          toolCall.toolName,
          " replying with current theme ",
          siteRef.current.theme
        );
        addToolResult({
          ...toolResult,
          output: siteRef.current.theme
        });
        break;
      }
      case "listImages": {
        console.debug("Client tool call %s", toolCall.toolName, " replying with images ", assetsRef.current);
        addToolResult({
          ...toolResult,
          output: assetsRef.current ?? []
        });
        break;
      }
      case "getSitemap": {
        console.debug(
          "Client tool call %s",
          toolCall.toolName,
          " replying with sitemap ",
          siteRef.current.sitemap
        );
        addToolResult({
          ...toolResult,
          output: siteRef.current.sitemap
        });
        break;
      }
      case "getSiteAttributes": {
        console.debug(
          "Client tool call %s",
          toolCall.toolName,
          " replying with site attributes ",
          siteRef.current.attributes
        );
        addToolResult({
          ...toolResult,
          output: siteRef.current.attributes
        });
        break;
      }
      case "getSection": {
        const input2 = toolCall.input;
        console.debug(
          "Client tool call %s",
          toolCall.toolName,
          " replying with section ",
          input2.id,
          pageRef.current.sections
        );
        addToolResult({
          ...toolResult,
          output: pageRef.current.sections.find((s2) => s2.id === input2.id) ?? `Section with id '${input2.id}' not found`
        });
        break;
      }
      case "listSections": {
        console.debug(
          "Client tool call %s",
          toolCall.toolName,
          " replying with sections ",
          pageRef.current.sections
        );
        addToolResult({
          ...toolResult,
          output: pageRef.current.sections
        });
        break;
      }
      case "deleteBrick": {
        const input2 = toolCall.input;
        draftHelpers.deleteBrick(input2.id);
        addToolResult({
          ...toolResult,
          output: true
        });
        break;
      }
      default:
        if (toolCall.toolName.startsWith("get") || toolCall.toolName.startsWith("list")) {
          console.log("UNHANDLED TOOL CALL client-side", toolCall.toolName);
        }
    }
  };
  const { messages, sendMessage, error, status, regenerate, stop, addToolResult } = useChat(
    {
      // resume: generationState.isReady === false,
      transport: new DefaultChatTransport({
        api: "/editor/chat",
        credentials: "include",
        body: () => ({
          callContext: {
            site: siteRef.current,
            page: pageRef.current,
            generationState: generationStateRef.current,
            userLanguage: userLanguageRef.current,
            assets: assetsRef.current
          }
        })
      }),
      sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
      messages: initialMessages,
      // generateId: createIdGenerator({
      //   prefix: "ups",
      //   separator: "_",
      //   size: 16,
      // }),
      onError: (error2) => {
        console.error("ERROR", error2);
      },
      // id: `chat-${site.id}`,
      /**
       * For tools that should be called client-side
       */
      onToolCall
    }
  );
  const promptRef = useRef(null);
  const messagesListRef = useRef(null);
  const onSubmit = (e) => {
    e.preventDefault();
    sendMessage({ text: input });
    setInput("");
    if (promptRef?.current) {
      promptRef.current.focus();
    }
  };
  const debouncedScroll = useDebounceCallback(() => {
    if (listPlaceholderRef.current && !hasScrolledUp) {
      listPlaceholderRef.current?.scrollIntoView({ behavior: "smooth" });
    }
  }, 300);
  useEffect(debouncedScroll, [status, messages, hasScrolledUp]);
  useEffect(() => {
    if (userLanguage) return;
    for (const msg of messages) {
      if (msg.metadata?.userLanguage) {
        console.log("Setting user language to", msg.metadata.userLanguage);
        setUserLanguage(msg.metadata.userLanguage);
        break;
      }
    }
  }, [messages, userLanguage]);
  useEffect(() => {
    if (setupRef.current) return;
    setupRef.current = true;
    if (generationState.isReady === false) {
      console.log("Chat initialized", { sitePrompt });
      regenerate();
    }
  }, []);
  const toolInvocations = useMemo(() => {
    const results = messages.filter((msg) => msg.role === "assistant").flatMap((msg) => msg.parts).filter((part) => part.type.startsWith("tool-")).filter(
      (part) => part.state === "output-available" && !handledToolResults.current.has(part.toolCallId)
    );
    return results;
  }, [messages]);
  const hasRunningTools = useMemo(() => {
    const results = messages.filter((msg) => msg.role === "assistant").flatMap((msg) => msg.parts).filter((part) => part.type.startsWith("tool-")).filter((part) => part.state !== "output-available" && part.state !== "output-error");
    return results.length > 0;
  }, [messages]);
  useDeepCompareEffect(() => {
    for (const toolInvocation of toolInvocations.filter((t) => t.state === "output-available")) {
      if (handledToolResults.current.has(toolInvocation.toolCallId)) {
        continue;
      }
      handledToolResults.current.add(toolInvocation.toolCallId);
      switch (toolInvocation.type) {
        case "tool-createPage": {
          const page2 = toolInvocation.output;
          console.log("Generated page", page2);
          draftHelpers.addPage({ ...page2, version: crypto.randomUUID(), sections: [] });
          break;
        }
        case "tool-createNavbar":
          console.log("Generated navbar", toolInvocation.output);
          draftHelpers.updateSiteAttributes({
            navbar: toolInvocation.output
          });
          break;
        case "tool-createFooter":
          console.log("Generated footer", toolInvocation.output);
          draftHelpers.updateSiteAttributes({
            footer: toolInvocation.output
          });
          break;
        case "tool-createThemes": {
          const themes = toolInvocation.output;
          console.log("Generated themes", themes);
          draftHelpers.setThemes(themes);
          break;
        }
        case "tool-createDatasource": {
          const datasource = toolInvocation.output;
          console.log("Generated datasource", datasource);
          draftHelpers.addDatasource(o$1(datasource));
          break;
        }
        case "tool-createDatarecord": {
          const datarecord = toolInvocation.output;
          console.log("Generated data record", datarecord);
          draftHelpers.addDatarecord(r(datarecord));
          break;
        }
        case "tool-createSitemap": {
          const sitemap = toolInvocation.output;
          console.log("Generated sitemap", sitemap);
          draftHelpers.setSitemap(sitemap);
          break;
        }
        case "tool-createSiteAttributes": {
          const siteAttributes = toolInvocation.output;
          console.log("Generated site attributes", siteAttributes);
          draftHelpers.updateSiteAttributes(siteAttributes);
          break;
        }
        case "tool-createSiteQueries": {
          const queries = toolInvocation.output;
          console.log("Generated site queries", queries);
          draftHelpers.updateSiteAttributes({
            queries: [...site.attributes.queries ?? [], ...queries]
          });
          break;
        }
        case "tool-editSiteQueries": {
          const queries = toolInvocation.output;
          console.log("Edited site queries", queries);
          draftHelpers.updateSiteAttributes({
            queries: [...site.attributes.queries ?? [], ...queries]
          });
          break;
        }
        case "tool-createPageQueries": {
          const queries = toolInvocation.output;
          console.log("Generated page queries", queries);
          draftHelpers.updatePageAttributes({
            ...page.attributes,
            queries: [...page.attributes.queries ?? [], ...queries]
          });
          break;
        }
        case "tool-editPageQueries": {
          const queries = toolInvocation.output;
          console.log("Edited page queries", queries);
          draftHelpers.updatePageAttributes({
            ...page.attributes,
            queries: [...page.attributes.queries ?? [], ...queries]
          });
          break;
        }
        case "tool-createSection": {
          const section = toolInvocation.output;
          console.log("Generated section", section);
          draftHelpers.addSection({ bricks: [], ...section });
          break;
        }
        case "tool-createBrick": {
          const brick = toolInvocation.output;
          console.log("Generated brick", brick);
          const { sectionId, index } = toolInvocation.input;
          draftHelpers.addBrick(brick, sectionId, index);
          break;
        }
        case "tool-editBrick": {
          draftHelpers.updateBrickProps(toolInvocation.input.id, toolInvocation.output.props);
          break;
        }
        case "tool-deleteBrick": {
          const { id } = toolInvocation.input;
          draftHelpers.deleteBrick(id);
          break;
        }
        case "tool-searchImages": {
          const images = toolInvocation.output;
          console.log("Generated images", images);
          draftHelpers.addAdditionalAssets(images);
          break;
        }
        default:
          console.log("Default tool invocation", toolInvocation.type, toolInvocation);
          break;
      }
    }
  }, [toolInvocations, draftHelpers, siteThemes]);
  const displayedMessages = messages.filter((msg) => msg.id !== "init-setup" && msg.parts.length > 0);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      className: D(
        "flex flex-col mx-auto w-full",
        {
          "rounded-xl h-[calc(100%-6rem)] max-h-[calc(100%-6rem)] my-[3rem] ": generationState.isReady === false,
          "rounded-tr-xl bg-gray-50 max-h-[inherit]": generationState.isReady === true
        },
        E({
          gridArea: "chat",
          maxWidth: generationState.isReady ? "none" : "clamp(500px, 60dvw, 740px)"
        }),
        generationState.isReady === false && E({
          // boxShadow: "rgba(100, 100, 111, 0.3) 0px 0px 36px 0px",
          // padding: "12px",
        })
      ),
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            ref: messagesListRef,
            className: D(
              ` overflow-y-auto h-[calc(100cqh-250px-6rem)]
            flex flex-col gap-y-2.5 flex-grow scroll-smooth relative transition-all duration-300`,
              {
                "rounded-tr-xl shadow-inner": generationState.isReady === true,
                "rounded-xl": generationState.isReady === false,
                "p-2": generationState.isReady === true,
                "p-0": generationState.isReady === false
              },
              E({
                scrollbarWidth: "none"
                // scrollbarColor: "var(--violet-a8) var(--violet-a2)",
                // scrollbarColor: "var(--violet-4) var(--violet-2)",
                // scrollbarGutter: "stable",
              })
            ),
            children: [
              displayedMessages.map((msg, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  "data-message-id": msg.id,
                  className: D(msg.role === "assistant" ? aiMsgClass : userMsgClass, msgCommon, "empty:hidden"),
                  children: msg.parts.map((part, i) => {
                    if (part.type.startsWith("tool-")) {
                      return /* @__PURE__ */ jsxRuntimeExports.jsx(
                        ToolRenderer,
                        {
                          toolPart: part,
                          addToolResult,
                          sendMessage,
                          error
                        },
                        i
                      );
                    }
                    switch (part.type) {
                      case "dynamic-tool": {
                        return null;
                      }
                      case "text":
                        return /* @__PURE__ */ jsxRuntimeExports.jsx(Suspense, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(Markdown, { content: part.text }, i) }, i);
                      // case "source":
                      //   // @ts-ignore
                      //   if (part.sourceType === "images") {
                      //     return (
                      //       <ImagesPreview
                      //         key={i}
                      //         // @ts-ignore
                      //         query={part.source.query as string}
                      //         // @ts-ignore
                      //         images={part.source.images as SimpleImageMetadata[]}
                      //       />
                      //     );
                      //   }
                      //   return <p key={i}>{JSON.stringify(part)}</p>;
                      case "reasoning":
                        if (!debug) {
                          return null;
                        }
                        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "flex items-center gap-1.5", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("details", { children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("summary", { className: "cursor-pointer list-none flex gap-1 items-center", children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsxs(
                              "svg",
                              {
                                className: "-rotate-90 transform opacity-60 transition-all duration-300",
                                fill: "none",
                                height: "14",
                                width: "14",
                                stroke: "currentColor",
                                strokeLinecap: "round",
                                strokeLinejoin: "round",
                                strokeWidth: "2",
                                viewBox: "0 0 24 24",
                                children: [
                                  /* @__PURE__ */ jsxRuntimeExports.jsx("title", { children: "Arrow" }),
                                  /* @__PURE__ */ jsxRuntimeExports.jsx("polyline", { points: "6 9 12 15 18 9" })
                                ]
                              }
                            ),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-normal", children: "Thinking..." })
                          ] }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            p,
                            {
                              as: "div",
                              size: "2",
                              className: "text-gray-500 mt-2 ml-2 border-l-2 border-gray-300 pl-3",
                              children: /* @__PURE__ */ jsxRuntimeExports.jsx(Markdown, { content: part.text })
                            }
                          )
                        ] }) }, i);
                    }
                  })
                },
                msg.id
              )),
              /* @__PURE__ */ jsxRuntimeExports.jsx(AnimatePresence, { initial: false, children: !hasRunningTools && (status === "submitted" || status === "streaming") && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                motion.div,
                {
                  initial: { opacity: 0, height: 0 },
                  animate: { opacity: 1, height: "1.5rem" },
                  exit: { opacity: 0, height: 0 },
                  transition: { duration: 0.2 },
                  className: D(
                    "p-4 my-4 text-fluid-sm text-gray-600 flex items-center justify-center gap-1.5 backdrop-blur-md bg-white/80 max-w-fit mx-auto rounded-lg"
                  ),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(s, { size: "2" }),
                    " Please wait..."
                  ]
                }
              ) }),
              error && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: D(msgCommon, "bg-red-200 text-red-800 text-sm"), children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { children: [
                  "An error occured. ",
                  error.message ?? "Please retry."
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: D(
                      "rounded bg-red-700 text-white border border-red-600 hover:opacity-90 block w-full text-center font-semibold py-1 px-2"
                    ),
                    onClick: () => {
                      regenerate();
                    },
                    children: "Retry"
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: listPlaceholderRef, className: D("h-2"), "aria-label": "separator", "aria-hidden": true })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "form",
          {
            onSubmit,
            className: D(
              "flex flex-col flex-1 min-h-[150px] max-h-[150px] gap-1.5 p-2 justify-center mt-2",
              "bg-upstart-100 border-t border-upstart-300 relative",
              // generationState.isReady === false && "hidden",
              generationState.isReady === false && "rounded-lg"
              // "[&:has(textarea:focus)]:(ring-2 ring-upstart-700)",
            ),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "textarea",
                {
                  onChange: (e) => setInput(e.target.value),
                  ref: promptRef,
                  value: input,
                  autoFocus: true,
                  onKeyDown: (e) => {
                    if (e.key === "Enter" && !e.shiftKey) onSubmit(e);
                  },
                  name: "prompt",
                  spellCheck: false,
                  autoComplete: "off",
                  autoCorrect: "off",
                  placeholder: messages.some((m) => m.role === "user") ? void 0 : "Add a section just below the navbar containing a paragraph with a short description of the site.",
                  className: D(
                    "form-textarea ",
                    generationState.isReady === false ? "!text-fluid-sm" : "text-sm",
                    "h-full w-full rounded scrollbar-thin p-2 !bg-white !pb-9 border-upstart-300 shadow-inner focus:(!outline-0 !ring-upstart-500 !border-upstart-500)"
                  )
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "div",
                {
                  className: D(
                    "flex justify-between items-center h-9 text-gray-500 absolute left-[9px] right-[9px] rounded bottom-2.5 px-2 z-50 bg-white"
                  ),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: D("hover:bg-upstart-200 p-1 rounded inline-flex text-sm gap-1"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(IoIosAttach, { className: "h-5 w-5" }) }),
                    generationState.isReady && WEB_SEARCH_ENABLED,
                    status === "submitted" || status === "streaming" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                      o,
                      {
                        type: "button",
                        size: "1",
                        className: D("flex items-center justify-center gap-0.5"),
                        onClick: stop,
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx(BiStopCircle, { className: "text-lg" })
                      }
                    ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                      o,
                      {
                        type: "submit",
                        size: "1",
                        className: D("flex items-center gap-0.5"),
                        disabled: hasRunningTools,
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx(TbSend2, { className: "text-lg" })
                      }
                    )
                  ]
                }
              )
            ]
          }
        )
      ]
    }
  );
}
const hiddenTools = ["setUserLanguage", "getUserLanguage"];
function ToolRenderer({
  toolPart,
  sendMessage,
  addToolResult,
  error
}) {
  const debug = useDebugMode();
  if (hiddenTools.includes(toolPart.type)) {
    return null;
  }
  if (error) {
    return null;
  }
  if (toolPart.type === "tool-askUserChoice" && toolPart.state !== "input-streaming") {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Suspense, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(AnimatePresence, { initial: false, children: toolPart.state === "input-available" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
      motion.div,
      {
        className: "choices",
        initial: { opacity: 0, height: 0 },
        animate: { opacity: 1, height: "auto" },
        exit: { opacity: 0, height: 0 },
        transition: { duration: 0.4 },
        children: [
          toolPart.input.question && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "basis-full", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Markdown, { content: toolPart.input.question }) }),
          toolPart.input.choices.map((choice, i) => {
            return /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                onClick: () => {
                  console.log("addtoolresult to part", toolPart);
                  addToolResult({
                    tool: "askUserChoice",
                    toolCallId: toolPart.toolCallId,
                    output: choice
                  });
                },
                children: choice
              },
              i
            );
          })
        ]
      }
    ) : /* @__PURE__ */ jsxRuntimeExports.jsxs(
      motion.div,
      {
        className: "choices",
        initial: { opacity: 0, height: 0 },
        animate: { opacity: 1, height: "auto" },
        exit: { opacity: 0, height: 0 },
        transition: { duration: 0.4 },
        children: [
          toolPart.input?.question && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "basis-full", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Markdown, { content: toolPart.input.question }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "basis-full text-right italic text-gray-800", children: toolPart.output })
        ]
      }
    ) }) }, toolPart.toolCallId);
  }
  if (toolPart.type !== "tool-askUserChoice" && toolPart.input && "waitingMessage" in toolPart.input) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(AnimatePresence, { initial: false, children: toolPart.state === "input-available" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
      motion.div,
      {
        className: "flex items-center gap-1.5 font-medium flex-wrap",
        initial: { opacity: 0, height: 0 },
        animate: { opacity: 1, height: "auto" },
        exit: { opacity: 0, height: 0 },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(s, { size: "1", className: "w-4 mx-0.5" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: toolPart.input.waitingMessage })
        ]
      }
    ) : toolPart.state === "output-available" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
      motion.div,
      {
        className: "flex items-center gap-1.5 flex-wrap font-medium",
        initial: { opacity: 0, height: 0 },
        animate: { opacity: 1, height: "auto" },
        exit: { opacity: 0, height: 0 },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(MdDone, { className: "w-4 h-4 text-green-600" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: toolPart.input.waitingMessage }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("details", { className: "cursor-pointer basis-full", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("summary", { className: "cursor-pointer list-none flex gap-1 items-center", children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "svg",
                {
                  className: "-rotate-90 transform opacity-60 transition-all duration-300",
                  fill: "none",
                  height: "14",
                  width: "14",
                  stroke: "currentColor",
                  strokeLinecap: "round",
                  strokeLinejoin: "round",
                  strokeWidth: "2",
                  viewBox: "0 0 24 24",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("title", { children: "Arrow" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("polyline", { points: "6 9 12 15 18 9" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: "text-xs font-normal", children: "View tool call" })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: "whitespace-pre-wrap text-xs", children: JSON.stringify({ input: toolPart.input, output: toolPart.output }, null, 2) })
          ] })
        ]
      }
    ) : toolPart.state === "output-error" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
      motion.div,
      {
        className: "flex items-center gap-1.5 font-medium",
        initial: { opacity: 0, height: 0 },
        animate: { opacity: 1, height: "auto" },
        exit: { opacity: 0, height: 0 },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(MdDone, { className: "w-4 h-4 text-red-600" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
            toolPart.input.waitingMessage,
            " (Error: ",
            toolPart.errorText,
            ")"
          ] })
        ]
      }
    ) : null });
  }
  if (debug) {
    const codeClassName = D(
      E({
        display: "block",
        fontFamily: "monospace",
        fontSize: "0.7rem",
        lineHeight: "1.3",
        wordWrap: "break-word",
        whiteSpace: "pre-wrap"
      })
    );
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("details", { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("summary", { className: "cursor-pointer list-none flex gap-1 items-center", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "svg",
          {
            className: "-rotate-90 transform opacity-60 transition-all duration-300",
            fill: "none",
            height: "14",
            width: "14",
            stroke: "currentColor",
            strokeLinecap: "round",
            strokeLinejoin: "round",
            strokeWidth: "2",
            viewBox: "0 0 24 24",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("title", { children: "Arrow" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("polyline", { points: "6 9 12 15 18 9" })
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: "text-xs font-normal", children: [
          "Tool: ",
          toolPart.type,
          " (",
          toolPart.state,
          ")"
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("pre", { className: codeClassName, children: JSON.stringify(toolPart, null, 2) })
    ] });
  }
  return null;
}
export {
  Chat as default
};
//# sourceMappingURL=Chat.js.map
