import { c as create_ssr_component, b as get_store_value, a as subscribe$1, v as validate_component, d as each, e as escape, g as getContext, m as missing_component, f as spread, h as escape_object, i as is_void, j as add_attribute, k as compute_rest_props, l as escape_attribute_value } from "../../chunks/index3.js";
import { SSE } from "sse.js";
import { w as writable, d as derived } from "../../chunks/index2.js";
import { marked } from "marked";
import DOMPurify from "isomorphic-dompurify";
const Chat = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  return `<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>`;
});
const Pencil = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  return `<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path></svg>`;
});
const Plus = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  return `<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>`;
});
const Trash = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  return `<svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" class="h-4 w-4" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>`;
});
const { subscribe, update, ...store } = writable({
  messages: [
    { role: "assistant", content: "Welcome! Please introduce yourself to your AI competitor." }
  ],
  chatState: "idle"
});
const set = async (query) => {
  updateMessages(query, "user", "loading");
  request();
};
const request = async (query) => {
  const eventSource = new SSE("/api/chat", {
    headers: {
      "Content-Type": "application/json"
    },
    payload: JSON.stringify({ messages: get_store_value(chatMessages).messages })
  });
  eventSource.addEventListener("error", handleError);
  eventSource.addEventListener("message", streamMessage);
  eventSource.stream();
};
const replace = (messages) => {
  store.set(messages);
};
const reset = () => store.set({
  messages: [
    { role: "assistant", content: "Welcome! Please introduce yourself to your AI competitor." }
  ],
  chatState: "idle"
});
const updateMessages = (content, role, state) => {
  chatMessages.update((messages) => {
    return { messages: [...messages.messages, { role, content }], chatState: state };
  });
};
const handleError = (err) => {
  updateMessages(err, "system", "error");
  console.error(err);
};
const streamMessage = (e) => {
  try {
    if (e.data === "[DONE]") {
      updateMessages(get_store_value(answer), "assistant", "idle");
      return answer.set("");
    }
    if (get_store_value(answer) === "...")
      answer.set("");
    const completionResponse = JSON.parse(e.data);
    const [{ delta }] = completionResponse.choices;
    if (delta.content) {
      answer.update((_a) => _a + delta.content);
    }
  } catch (err) {
    handleError(err);
  }
};
const chatMessages = { subscribe, set, update, reset, replace };
const answer = writable("");
const chatHistory = derived(chatMessages, ($chatMessages) => {
  return null;
});
const ChatHistory = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let $$unsubscribe_chatHistory;
  $$unsubscribe_chatHistory = subscribe$1(chatHistory, (value) => value);
  let chatHistoryKeys = [];
  $$unsubscribe_chatHistory();
  return `<div class="h-[700px] w-[350px] bg-black bg-opacity-20 rounded-md py-4 px-2 overflow-y-auto flex flex-col gap-2"><button class="flex py-3 px-3 items-center gap-3 rounded-md hover:bg-gray-500/10 transition-colors duration-200 text-white cursor-pointer text-sm mb-2 flex-shrink-0 border border-white/20">${validate_component(Plus, "Plus").$$render($$result, {}, {}, {})} New Game
	</button>

	${chatHistoryKeys.length > 0 ? `${each(chatHistoryKeys, (message) => {
    return `
			<div class="flex py-3 px-3 items-center gap-3 relative rounded-md cursor-pointer break-all pr-14 bg-opacity-40 hover:bg-white/5 bg-black group animate-flash text-sm">${validate_component(Chat, "Chat").$$render($$result, {}, {}, {})}
				<div class="flex-1 text-ellipsis max-h-5 overflow-hidden break-all relative">${escape(message)}</div>

				<div class="absolute flex right-1 z-10 text-gray-300 visible"><button class="p-1 hover:text-white">${validate_component(Pencil, "Pencil").$$render($$result, {}, {}, {})}</button>
					<button class="p-1 hover:text-white">${validate_component(Trash, "Trash").$$render($$result, {}, {}, {})}
					</button></div>
			</div>`;
  })}` : ``}</div>`;
});
const componentsContextKey = {};
const getComponentsContext = () => getContext(componentsContextKey);
const Renderer = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let $components, $$unsubscribe_components;
  let { astNode } = $$props;
  let { __index = 0 } = $$props;
  let { type = void 0 } = $$props;
  let { position = void 0 } = $$props;
  const components = getComponentsContext();
  $$unsubscribe_components = subscribe$1(components, (value) => $components = value);
  if ($$props.astNode === void 0 && $$bindings.astNode && astNode !== void 0)
    $$bindings.astNode(astNode);
  if ($$props.__index === void 0 && $$bindings.__index && __index !== void 0)
    $$bindings.__index(__index);
  if ($$props.type === void 0 && $$bindings.type && type !== void 0)
    $$bindings.type(type);
  if ($$props.position === void 0 && $$bindings.position && position !== void 0)
    $$bindings.position(position);
  $$unsubscribe_components();
  return `${astNode.type === "root" ? `${validate_component(Children, "Children").$$render($$result, Object.assign({}, astNode), {}, {})}` : `${astNode.type === "element" ? `${validate_component($components[astNode.tagName] || missing_component, "svelte:component").$$render($$result, Object.assign({}, astNode, { __index }), {}, {})}` : `${$components[astNode.type] !== void 0 ? `${validate_component($components[astNode.type] || missing_component, "svelte:component").$$render($$result, Object.assign({}, astNode, { __index }), {}, {})}` : ``}`}`}`;
});
const Children = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { children } = $$props;
  let { type = void 0 } = $$props;
  let { position = void 0 } = $$props;
  let { __index = void 0 } = $$props;
  if ($$props.children === void 0 && $$bindings.children && children !== void 0)
    $$bindings.children(children);
  if ($$props.type === void 0 && $$bindings.type && type !== void 0)
    $$bindings.type(type);
  if ($$props.position === void 0 && $$bindings.position && position !== void 0)
    $$bindings.position(position);
  if ($$props.__index === void 0 && $$bindings.__index && __index !== void 0)
    $$bindings.__index(__index);
  return `${each(children, (child, __index2) => {
    return `${validate_component(Renderer, "Renderer").$$render($$result, { astNode: child, __index: __index2 }, {}, {})}`;
  })}`;
});
const Default = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { tagName } = $$props;
  let { children } = $$props;
  let { properties } = $$props;
  let { type = void 0 } = $$props;
  let { position = void 0 } = $$props;
  let { __index = void 0 } = $$props;
  if ($$props.tagName === void 0 && $$bindings.tagName && tagName !== void 0)
    $$bindings.tagName(tagName);
  if ($$props.children === void 0 && $$bindings.children && children !== void 0)
    $$bindings.children(children);
  if ($$props.properties === void 0 && $$bindings.properties && properties !== void 0)
    $$bindings.properties(properties);
  if ($$props.type === void 0 && $$bindings.type && type !== void 0)
    $$bindings.type(type);
  if ($$props.position === void 0 && $$bindings.position && position !== void 0)
    $$bindings.position(position);
  if ($$props.__index === void 0 && $$bindings.__index && __index !== void 0)
    $$bindings.__index(__index);
  return `${Array.isArray(children) && children.length !== 0 ? `
	${((tag) => {
    return tag ? `<${tagName}${spread([escape_object(properties)], {})}>${is_void(tag) ? "" : `${validate_component(Children, "Children").$$render($$result, { children }, {}, {})}`}${is_void(tag) ? "" : `</${tag}>`}` : "";
  })(tagName)}` : `
	${((tag) => {
    return tag ? `<${tagName}${spread([escape_object(properties)], {})}>${is_void(tag) ? "" : ``}${is_void(tag) ? "" : `</${tag}>`}` : "";
  })(tagName)}`}`;
});
const defaultTags = [
  // Content sectioning
  "address",
  "article",
  "aside",
  "footer",
  "header",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "main",
  "nav",
  "section",
  // Text content
  "blockquote",
  "dd",
  "div",
  "dl",
  "dt",
  "figcaption",
  "figure",
  "hr",
  "li",
  "menu",
  "ol",
  "p",
  "pre",
  "ul",
  // Inline text semantics
  "a",
  "abbr",
  "b",
  "bdi",
  "bdo",
  "br",
  "cite",
  "code",
  "data",
  "dfn",
  "em",
  "i",
  "kbd",
  "mark",
  "q",
  "rp",
  "rt",
  "ruby",
  "s",
  "samp",
  "small",
  "span",
  "strong",
  "sub",
  "sup",
  "time",
  "u",
  "var",
  "wbr",
  // Image and multimedia
  "area",
  "audio",
  "img",
  "map",
  "track",
  "video",
  // Embedded content
  "embed",
  "iframe",
  "object",
  "param",
  "picture",
  "portal",
  "source",
  // SVG and MathML
  "svg",
  "math",
  // Demarcating edits
  "del",
  "ins",
  // Table content
  "caption",
  "col",
  "colgroup",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "tr",
  // Forms
  "button",
  "datalist",
  "fieldset",
  "form",
  "input",
  "label",
  "legend",
  "meter",
  "optgroup",
  "option",
  "output",
  "progress",
  "select",
  "textarea",
  // Interactive elements
  "details",
  "dialog",
  "summary"
];
const htmlComponents = defaultTags.reduce((acc, tag) => ({ ...acc, [tag]: Default }), {});
const Text = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { value = "" } = $$props;
  let { type = void 0 } = $$props;
  let { position = void 0 } = $$props;
  let { __index = void 0 } = $$props;
  if ($$props.value === void 0 && $$bindings.value && value !== void 0)
    $$bindings.value(value);
  if ($$props.type === void 0 && $$bindings.type && type !== void 0)
    $$bindings.type(type);
  if ($$props.position === void 0 && $$bindings.position && position !== void 0)
    $$bindings.position(position);
  if ($$props.__index === void 0 && $$bindings.__index && __index !== void 0)
    $$bindings.__index(__index);
  return `${escape(value)}`;
});
({
  ...htmlComponents,
  text: Text,
  raw: Text
});
const ChatMessage = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { type } = $$props;
  let { message = "" } = $$props;
  let { class: classes = "" } = $$props;
  let scrollToDiv;
  const classSet = {
    user: "justify-end text-rose-700",
    assistant: "justify-start text-teal-400",
    system: "justify-center text-gray-400"
  };
  if ($$props.type === void 0 && $$bindings.type && type !== void 0)
    $$bindings.type(type);
  if ($$props.message === void 0 && $$bindings.message && message !== void 0)
    $$bindings.message(message);
  if ($$props.class === void 0 && $$bindings.class && classes !== void 0)
    $$bindings.class(classes);
  return `<div class="${"flex items-center " + escape(classSet[type], true)}"><p class="text-xs px-2">${escape(type === "user" ? "Me" : "Bot")}</p></div>

<div class="${"flex " + escape(classSet[type], true)}"><div class="${"bg-black py-0.5 px-4 max-w-2xl rounded leading-loose " + escape(classes, true) + " " + escape(classSet[type], true)}"><!-- HTML_TAG_START -->${DOMPurify.sanitize(marked.parse(message))}<!-- HTML_TAG_END --></div>
  <div${add_attribute("this", scrollToDiv, 0)}></div></div>`;
});
const Input = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let $$restProps = compute_rest_props($$props, ["value", "placeholder", "name", "type", "label", "class"]);
  let { value } = $$props;
  let { placeholder = "" } = $$props;
  let { name = "" } = $$props;
  let { type = "text" } = $$props;
  let { label = "" } = $$props;
  let { class: classes = "" } = $$props;
  if ($$props.value === void 0 && $$bindings.value && value !== void 0)
    $$bindings.value(value);
  if ($$props.placeholder === void 0 && $$bindings.placeholder && placeholder !== void 0)
    $$bindings.placeholder(placeholder);
  if ($$props.name === void 0 && $$bindings.name && name !== void 0)
    $$bindings.name(name);
  if ($$props.type === void 0 && $$bindings.type && type !== void 0)
    $$bindings.type(type);
  if ($$props.label === void 0 && $$bindings.label && label !== void 0)
    $$bindings.label(label);
  if ($$props.class === void 0 && $$bindings.class && classes !== void 0)
    $$bindings.class(classes);
  return `<div class="${"flex flex-col min-w-xl " + escape(classes, true)}"><label class="text-xs"${add_attribute("for", name, 0)}>${escape(label)}</label>
  <input${spread(
    [
      { name: escape_attribute_value(name) },
      {
        placeholder: escape_attribute_value(placeholder)
      },
      {
        class: "shadow bg-white/10 rounded-md px-4 py-1.5 min-w-xl text-teal-300 border border-transparent focus:outline-none focus:ring-1 focus:ring-teal-300 focus:border-transparent"
      },
      escape_object($$restProps)
    ],
    {}
  )}${add_attribute("value", value, 0)}></div>`;
});
const Page = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let $chatMessages, $$unsubscribe_chatMessages;
  let $answer, $$unsubscribe_answer;
  $$unsubscribe_chatMessages = subscribe$1(chatMessages, (value) => $chatMessages = value);
  $$unsubscribe_answer = subscribe$1(answer, (value) => $answer = value);
  let query = "";
  let $$settled;
  let $$rendered;
  do {
    $$settled = true;
    $$rendered = `<section class="flex max-w-6xl w-full pt-4 justify-center"><div class="flex flex-col gap-2">${validate_component(ChatHistory, "ChatHistory").$$render($$result, {}, {}, {})}</div>

  <div class="flex flex-col w-full px-8 items-center gap-2"><div class="h-[700px] w-full bg-black bg-opacity-20 rounded-md p-4 overflow-y-auto flex flex-col gap-4"><div class="flex flex-col gap-2">${each($chatMessages.messages, (message) => {
      return `${validate_component(ChatMessage, "ChatMessage").$$render(
        $$result,
        {
          type: message.role,
          message: message.content
        },
        {},
        {}
      )}`;
    })}

        ${$answer ? `${validate_component(ChatMessage, "ChatMessage").$$render($$result, { type: "assistant", message: $answer }, {}, {})}` : ``}</div></div>
    <form class="flex w-full rounded-md gap-4 bg-black bg-opacity-20 p-2">${validate_component(Input, "Input").$$render(
      $$result,
      {
        type: "text",
        class: "w-full",
        value: query
      },
      {
        value: ($$value) => {
          query = $$value;
          $$settled = false;
        }
      },
      {}
    )}
      <button type="submit" class="bg-black bg-opacity-40 hover:bg-white/5 px-8 py-1.5 border border-black/40 ml-[-0.5rem] rounded-md text-teal-300">Send
      </button></form></div></section>`;
  } while (!$$settled);
  $$unsubscribe_chatMessages();
  $$unsubscribe_answer();
  return $$rendered;
});
export {
  Page as default
};
