import { j as e } from "../../../../../_virtual/jsx-runtime.js";
import { tx as a, css as p } from "../../../../style-system/dist/twind.js";
import { useRef as g, useState as E, useCallback as P, useEffect as B, useMemo as M, Suspense as U, lazy as X } from "react";
import "../../../../../node_modules/.pnpm/@formkit_auto-animate@0.8.2/node_modules/@formkit/auto-animate/index.js";
import "../../../../../node_modules/.pnpm/react-hot-toast@2.5.2_react-dom@18.3.0-canary-3d9b20132-20240124_react@18.3.0-canary-3d_c02c1e17bf76c343fd22d1f22394ecf5/node_modules/react-hot-toast/dist/index.js";
import { TbSend2 as Z } from "../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/tb/index.js";
import { IoIosAttach as ee } from "../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/io/index.js";
import { useChat as te } from "../../../../../node_modules/.pnpm/@ai-sdk_react@1.2.12_react@18.3.0-canary-3d9b20132-20240124_zod@3.24.4/node_modules/@ai-sdk/react/dist/index.js";
import "../../../../../node_modules/.pnpm/ai@4.3.16_react@18.3.0-canary-3d9b20132-20240124_zod@3.24.4/node_modules/ai/dist/index.js";
import { useSitePrompt as se, useDraftHelpers as re, useGenerationState as ae, useSiteAndPages as oe, useThemes as ie } from "../../../../../use-page-data.js";
import { MdDone as ne } from "../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/md/index.js";
import { useDebounceCallback as le } from "../../../../../node_modules/.pnpm/usehooks-ts@3.1.1_react@18.3.0-canary-3d9b20132-20240124/node_modules/usehooks-ts/dist/index.js";
import { BiStopCircle as ce } from "../../../../../node_modules/.pnpm/react-icons@5.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/react-icons/bi/index.js";
import { f as de } from "../../../../sdk/dist/shared/chunk-HHO3ONTQ.js";
import "@sinclair/typebox";
import { useDeepCompareEffect as q } from "../../../../../node_modules/.pnpm/use-deep-compare@1.3.0_react@18.3.0-canary-3d9b20132-20240124/node_modules/use-deep-compare/dist-web/index.js";
import { useEditorHelpers as ue } from "../../../../../use-editor.js";
import { createIdGenerator as me } from "../../../../../node_modules/.pnpm/@ai-sdk_provider-utils@2.2.8_zod@3.24.4/node_modules/@ai-sdk/provider-utils/dist/index.js";
import { Spinner as T } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/spinner.js";
import { AnimatePresence as I } from "../../../../../node_modules/.pnpm/motion@12.17.0_@emotion_is-prop-valid@1.3.1_react-dom@18.3.0-canary-3d9b20132-20240124__f50e5637f6378e4858c0300964199324/node_modules/motion/dist/es/framer-motion/dist/es/components/AnimatePresence/index.js";
import { motion as b } from "../../../../../node_modules/.pnpm/motion@12.17.0_@emotion_is-prop-valid@1.3.1_react-dom@18.3.0-canary-3d9b20132-20240124__f50e5637f6378e4858c0300964199324/node_modules/motion/dist/es/framer-motion/dist/es/render/components/motion/proxy.js";
import { Text as j } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/text.js";
import { TextArea as ge } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/text-area.js";
import { Button as W } from "../../../../../node_modules/.pnpm/@radix-ui_themes@3.1.4_@types_react-dom@18.3.6_@types_react@18.3.3__@types_react@18.3.3_46b1dabc193c5ff5696ee783983c694e/node_modules/@radix-ui/themes/dist/esm/components/button.js";
const pe = !1, y = X(() => import("./Markdown.js")), $ = a(
  "rounded-lg px-2.5 py-2 text-pretty transition-all duration-300 flex flex-col gap-1.5",
  p({
    // whiteSpace: "pre-line",
    "& p": {
      marginTop: ".5rem"
      // marginBottom: ".5rem",
    },
    "& p:first-child": {
      marginTop: "0"
    },
    "& p:last-child": {
      marginBottom: "0"
    },
    "& code": {
      fontSize: "88%"
    },
    "& ul, ol": {
      listStyle: "outside",
      listStyleType: "square",
      paddingLeft: "1rem",
      // marginTop: "0.25rem",
      marginBottom: "0.2rem"
    },
    "& li": {
      marginBottom: "0.25rem"
    },
    "& div.choices": {
      display: "flex",
      flexWrap: "wrap",
      justifyContent: "space-between",
      gap: ".5rem",
      marginTop: "1rem",
      // "&:not(:last-child)": {
      //   marginBottom: "1rem",
      // },
      "& > button": {
        backgroundColor: "var(--violet-10)",
        color: "#fff",
        flexGrow: "1",
        padding: "0.3rem 0.7rem",
        borderRadius: "0.5rem",
        border: "none",
        fontSize: "0.8rem",
        fontWeight: "500",
        "&:hover": {
          backgroundColor: "var(--violet-9)"
        }
      }
    }
  })
), fe = a(
  "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 Ke() {
  const r = se(), l = g(!1), n = re(), { setImagesSearchResults: z } = ue(), o = ae(), c = oe(), f = ie(), [w, H] = E(), [h, we] = E(
    new URL(window.location.href).searchParams.get("action") === "generate" ? "setup" : "edit"
  ), v = g(null), N = g(/* @__PURE__ */ new Set()), _ = a(
    " text-sm text-black/80 dark:text-upstart-200",
    o.isReady ? "bg-gradient-to-tr from-upstart-200/80 to-upstart-100" : "bg-white/80 dark:bg-dark-800"
  ), F = P(
    (s, t) => {
      console.log("message finished", s, t), console.log("Generation state after message finish", o);
    },
    [o]
  ), {
    messages: d,
    handleInputChange: K,
    handleSubmit: D,
    error: k,
    status: m,
    reload: L,
    append: O,
    stop: J,
    data: C,
    addToolResult: V
  } = te({
    api: "/editor/chat",
    // sendExtraMessageFields: true,
    // maxSteps: 30,
    initialMessages: h === "setup" ? [
      {
        id: "init-generate",
        role: "user",
        content: `Create a website based on this prompt:
${r}`
      }
    ] : [
      {
        id: "init-edit",
        role: "assistant",
        content: `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? 🤖`
      }
    ],
    credentials: "include",
    experimental_prepareRequestBody({ requestData: s, ...t }) {
      return {
        ...t,
        requestData: { ...c, flow: h, generationState: o, userLanguage: w }
      };
    },
    generateId: me({
      prefix: "ups",
      separator: "_",
      size: 16
    }),
    onFinish: F,
    onError: (s) => {
      console.error("ERROR", s);
    },
    key: `chat-${h}-${c.site.id}`,
    /**
     * For tools that should be called client-side
     */
    onToolCall: ({ toolCall: s }) => {
      if (console.log("Tool call: %s: ", s.toolName, s), s.toolName === "done")
        return !0;
    }
  }), x = g(null), Y = g(null), A = P(
    (s) => {
      s.preventDefault(), D(), x?.current && (x.current.value = "", x.current.focus());
    },
    [D]
  ), Q = le(() => {
    v.current && v.current.scrollIntoView({ behavior: "smooth" });
  }, 200);
  B(Q, [m, C, d]), q(() => {
    C?.forEach((s) => {
      typeof s == "object" && !Array.isArray(s) && s?.userLanguage && H(s.userLanguage);
    });
  }, [C]), B(() => {
    l.current || (l.current = !0, h === "setup" && (console.log("Chat initialized"), L()));
  }, []);
  const G = M(() => d.filter((t) => t.role === "assistant").flatMap((t) => t.parts).filter((t) => t.type === "tool-invocation").map((t) => t.toolInvocation).filter(
    (t) => t.state === "result" && !N.current.has(t.toolCallId)
  ), [d]), R = M(() => d.filter((t) => t.role === "assistant").flatMap((t) => t.parts).filter((t) => t.type === "tool-invocation").map((t) => t.toolInvocation).filter((t) => t.state !== "result").length > 0, [d]), S = m === "streaming" || m === "submitted" || R;
  return q(() => {
    for (const s of G.filter((t) => t.state === "result"))
      if (!N.current.has(s.toolCallId))
        switch (N.current.add(s.toolCallId), s.toolName) {
          case "generatePage": {
            const t = s.result;
            if ("error" in t) {
              console.error("Error generating page:", t.error);
              return;
            }
            console.log("Generated page", t.page), n.addPage(t.page);
            break;
          }
          case "generateThemes": {
            const i = s.result.map(de);
            console.log("Generated themes", i), n.setThemes(i);
            break;
          }
          case "generateDatasource": {
            const t = s.result;
            console.log("Generated datasource", t), n.addDatasource(t);
            break;
          }
          case "generateDatarecord": {
            const t = s.result;
            console.log("Generated data record", t), n.addDatarecord(t);
            break;
          }
          case "generateSitemap": {
            const t = s.result;
            console.log("Generated sitemap", t), n.setSitemap(t);
            break;
          }
          case "searchImages": {
            const t = s.result;
            console.log("Generated images", t), z(t);
            break;
          }
          default:
            console.log("Default tool invocation", s.toolName, s);
            break;
        }
  }, [G, n, f]), /* @__PURE__ */ e.jsxs(
    "div",
    {
      className: a(
        "flex flex-col mx-auto w-full",
        {
          "rounded-xl animate-border my-auto h-full max-h-[calc(100dvh-100px)]": o.isReady === !1,
          "rounded-tr-xl bg-gray-50 max-h-[inherit]": o.isReady === !0
        },
        p({
          gridArea: "chat",
          maxWidth: o.isReady ? "none" : "clamp(500px, 40dvw, 650px)"
        }),
        o.isReady === !1 && p({
          scrollbarColor: "var(--violet-4) var(--violet-2)",
          border: "2px solid transparent",
          boxShadow: "rgba(100, 100, 111, 0.3) 0px 0px 36px 0px",
          // padding: "12px",
          background: "linear-gradient(#ffffff, #ffffff) padding-box, linear-gradient(var(--border-angle), transparent 15%, #9291e7, #7270c6, #c050c2, #ef50a2, #ff6285, #ff806b, #ffa25a, #ffc358, transparent 85%) border-box"
        })
      ),
      children: [
        /* @__PURE__ */ e.jsxs(
          "div",
          {
            ref: Y,
            className: a(
              // h-full max-h-[calc(100cqh-250px)]
              ` overflow-y-auto h-full max-h-[inherit] p-2
            flex flex-col gap-y-2.5 flex-grow scroll-smooth scrollbar-thin relative`,
              {
                "rounded-tr-xl shadow-inner": o.isReady === !0
              },
              p({
                scrollbarColor: "var(--violet-a8) var(--violet-a2)"
                // scrollbarColor: "var(--violet-4) var(--violet-2)",
                // scrollbarGutter: "stable",
              })
            ),
            children: [
              d.filter((s) => s.id !== "init-generate" && s.parts.length > 0).map((s, t) => /* @__PURE__ */ e.jsx("div", { className: a(s.role === "assistant" ? _ : fe, $), children: s.parts.map((i, u) => {
                switch (i.type) {
                  case "text":
                    return /* @__PURE__ */ e.jsx(U, { children: /* @__PURE__ */ e.jsx(y, { content: i.text }, u) }, u);
                  case "source":
                    return i.source.sourceType === "images" ? /* @__PURE__ */ e.jsx(be, { images: i.source.images }, u) : /* @__PURE__ */ e.jsx("p", { children: JSON.stringify(i) }, u);
                  case "reasoning":
                    return t !== d.length - 1 || s.parts.length - 1 !== u ? null : /* @__PURE__ */ e.jsxs("p", { className: "flex items-center gap-1.5", children: [
                      /* @__PURE__ */ e.jsx(T, { size: "1" }),
                      /* @__PURE__ */ e.jsx(j, { as: "p", size: "1", className: "text-black/60", children: /* @__PURE__ */ e.jsxs("details", { children: [
                        /* @__PURE__ */ e.jsxs("summary", { className: "cursor-pointer list-none flex gap-1 items-center", children: [
                          /* @__PURE__ */ e.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__ */ e.jsx("title", { children: "Arrow" }),
                                /* @__PURE__ */ e.jsx("polyline", { points: "6 9 12 15 18 9" })
                              ]
                            }
                          ),
                          /* @__PURE__ */ e.jsx("span", { className: "text-xs font-normal", children: "Thinking..." })
                        ] }),
                        /* @__PURE__ */ e.jsx(j, { size: "2", className: "text-gray-500", children: i.reasoning })
                      ] }) })
                    ] }, u);
                  case "tool-invocation":
                    return /* @__PURE__ */ e.jsx(
                      je,
                      {
                        toolInvocation: i.toolInvocation,
                        addToolResult: V,
                        append: O,
                        error: k
                      },
                      u
                    );
                  case "file":
                    return /* @__PURE__ */ e.jsx("img", { alt: "", src: `data:${i.mimeType};base64,${i.data}` }, u);
                }
              }) }, s.id)),
              !R && (m === "submitted" || m === "streaming") && /* @__PURE__ */ e.jsxs("div", { className: a("h-6 px-2 text-sm text-gray-600 flex items-center justify-center gap-1.5"), children: [
                /* @__PURE__ */ e.jsx(T, { size: "2" }),
                " Please wait..."
              ] }),
              k && /* @__PURE__ */ e.jsxs("div", { className: a($, "bg-red-200 text-red-800 text-sm"), children: [
                /* @__PURE__ */ e.jsxs("p", { children: [
                  "An error occured: ",
                  k.message
                ] }),
                /* @__PURE__ */ e.jsx(
                  "button",
                  {
                    type: "button",
                    className: a(
                      "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: () => {
                      L();
                    },
                    children: "Retry"
                  }
                )
              ] }),
              /* @__PURE__ */ e.jsx("div", { ref: v, className: a("h-2"), "aria-label": "separator", "aria-hidden": !0 })
            ]
          }
        ),
        /* @__PURE__ */ e.jsxs(
          "form",
          {
            onSubmit: A,
            className: a(
              "flex flex-col flex-1 min-h-[150px] max-h-[150px] gap-1.5 p-2 justify-center ",
              "bg-upstart-100 border-t border-upstart-300 relative",
              // generationState.isReady === false && "hidden",
              o.isReady === !1 && "rounded-b-xl"
              // "[&:has(textarea:focus)]:(ring-2 ring-upstart-700)",
            ),
            children: [
              /* @__PURE__ */ e.jsx(
                ge,
                {
                  ref: x,
                  autoFocus: !0,
                  onChange: K,
                  onKeyDown: (s) => {
                    s.key === "Enter" && !s.shiftKey && A(s);
                  },
                  name: "prompt",
                  disabled: S,
                  spellCheck: !1,
                  autoComplete: "off",
                  autoCorrect: "off",
                  placeholder: d.some((s) => s.role === "user") ? void 0 : "Add a section just below the navbar containing a paragraph with a short description of the site.",
                  size: "2",
                  className: a(
                    "h-full w-full scrollbar-thin p-2 !bg-white !pb-9 !border-0 !outline-0 !box-shadow-none [&>textarea]:focus:(!outline-0 !shadow-none !ring-0 !border-0)"
                  )
                }
              ),
              /* @__PURE__ */ e.jsxs(
                "div",
                {
                  className: a(
                    "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": !S, "bg-transparent": S }
                  ),
                  children: [
                    /* @__PURE__ */ e.jsx("button", { type: "button", className: a("hover:bg-upstart-200 p-1 rounded inline-flex text-sm gap-1"), children: /* @__PURE__ */ e.jsx(ee, { className: "h-5 w-5" }) }),
                    o.isReady && pe,
                    m === "submitted" || m === "streaming" ? /* @__PURE__ */ e.jsx(
                      W,
                      {
                        type: "button",
                        size: "1",
                        className: a("flex items-center justify-center gap-0.5"),
                        onClick: J,
                        children: /* @__PURE__ */ e.jsx(ce, { className: "text-lg" })
                      }
                    ) : /* @__PURE__ */ e.jsx(
                      W,
                      {
                        type: "submit",
                        size: "1",
                        className: a("flex items-center gap-0.5"),
                        disabled: R,
                        children: /* @__PURE__ */ e.jsx(Z, { className: "text-lg" })
                      }
                    )
                  ]
                }
              )
            ]
          }
        )
      ]
    }
  );
}
const he = {
  generateThemes: "Generating color themes",
  generateSitemap: "Generating site map",
  generateImages: "Generating images",
  setTheme: "Applying theme",
  searchImages: "Searching images"
};
function xe(r) {
  if (r.args?.waitingMessage)
    return r.args.waitingMessage;
  switch (r.toolName) {
    case "generatePage":
      return `Generating page '${r.args.pageLabel}', this can take a while`;
    default:
      return he[r.toolName];
  }
}
function be({ images: r }) {
  return /* @__PURE__ */ e.jsx("div", { className: "grid grid-cols-3 gap-1 max-h-60 overflow-y-auto", children: r.map((l, n) => /* @__PURE__ */ e.jsx(
    "img",
    {
      src: l.url,
      alt: l.description,
      className: a(
        "rounded-md h-auto !object-cover object-center w-full aspect-video animate-fade-in",
        p({
          // animation delay
          animationDelay: `${n * 100}ms`
        })
      ),
      loading: "lazy"
    },
    l.url
  )) });
}
const ye = ["setUserLanguage", "getUserLanguage"];
function je({
  toolInvocation: r,
  addToolResult: l,
  error: n,
  append: z
}) {
  if (ye.includes(r.toolName) || n)
    return null;
  if (r.toolName === "askUserChoice") {
    const c = r.args;
    return /* @__PURE__ */ e.jsx(U, { children: /* @__PURE__ */ e.jsx(I, { initial: !1, children: r.state !== "result" ? /* @__PURE__ */ e.jsxs(
      b.div,
      {
        className: "choices",
        initial: { opacity: 0, height: 0 },
        animate: { opacity: 1, height: "auto" },
        exit: { opacity: 0, height: 0 },
        transition: { duration: 0.4 },
        children: [
          c.question && /* @__PURE__ */ e.jsx("div", { className: "basis-full", children: /* @__PURE__ */ e.jsx(y, { content: c.question }) }),
          c.choices.map((f, w) => /* @__PURE__ */ e.jsx(
            "button",
            {
              type: "button",
              onClick: () => {
                l({
                  toolCallId: r.toolCallId,
                  result: f
                });
              },
              children: f
            },
            w
          ))
        ]
      }
    ) : /* @__PURE__ */ e.jsxs(
      b.div,
      {
        className: "choices",
        initial: { opacity: 0, height: 0 },
        animate: { opacity: 1, height: "auto" },
        exit: { opacity: 0, height: 0 },
        transition: { duration: 0.4 },
        children: [
          c.question && /* @__PURE__ */ e.jsx("div", { className: "basis-full", children: /* @__PURE__ */ e.jsx(y, { content: c.question }) }),
          /* @__PURE__ */ e.jsx("div", { className: "basis-full text-right italic text-gray-800", children: r.result })
        ]
      }
    ) }) }, r.toolCallId);
  }
  const o = xe(r);
  return o ? /* @__PURE__ */ e.jsx(I, { initial: !1, children: r.state !== "result" ? /* @__PURE__ */ e.jsxs(
    b.div,
    {
      className: "flex items-center gap-1.5",
      initial: { opacity: 0, height: 0 },
      animate: { opacity: 1, height: "auto" },
      exit: { opacity: 0, height: 0 },
      children: [
        /* @__PURE__ */ e.jsx(T, { size: "1", className: "w-4" }),
        /* @__PURE__ */ e.jsx(j, { size: "2", children: o })
      ]
    }
  ) : /* @__PURE__ */ e.jsxs(
    b.div,
    {
      className: "flex items-center gap-1.5",
      initial: { opacity: 0, height: 0 },
      animate: { opacity: 1, height: "auto" },
      exit: { opacity: 0, height: 0 },
      children: [
        /* @__PURE__ */ e.jsx(ne, { className: "w-4 h-4 text-green-600" }),
        /* @__PURE__ */ e.jsx(j, { size: "2", children: o })
      ]
    }
  ) }) : r.args.message ? /* @__PURE__ */ e.jsx(y, { content: r.args.message }) : null;
}
export {
  Ke as default
};
//# sourceMappingURL=Chat.js.map
