'use strict';

var React = require('react');
var components = require('@tarojs/components');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

// src/ai/llm/ui/miniapp/components/AiChatDialog.tsx

// src/ai/llm/prompt/variables.ts
var normalizePromptVariables = (variables = {}) => {
  const normalized = {};
  Object.entries(variables).forEach(([key, value]) => {
    if (value === null || value === void 0) {
      normalized[key] = "";
    } else {
      normalized[key] = String(value);
    }
  });
  return normalized;
};

// src/ai/llm/prompt/template.ts
var applyPromptTemplate = (template, variables = {}, options = {}) => {
  if (!template) {
    return "";
  }
  const resolved = normalizePromptVariables(variables);
  const missingValue = options.missingValue ?? "";
  return template.replace(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g, (_match, key) => {
    if (Object.prototype.hasOwnProperty.call(resolved, key)) {
      return resolved[key] ?? "";
    }
    return options.preserveUnknown ? `{{${key}}}` : missingValue;
  });
};

// src/ai/llm/hooks/useAiChat.ts
var buildBaseMessages = (systemPrompt, initialMessages) => {
  const baseMessages = [];
  if (systemPrompt) {
    baseMessages.push({ role: "system", content: systemPrompt });
  }
  if (initialMessages?.length) {
    baseMessages.push(...initialMessages);
  }
  return baseMessages;
};
var useAiChat = (options) => {
  const systemPromptRef = React.useRef(options.systemPrompt);
  const templateRef = React.useRef(options.template);
  const [messages, setMessages] = React.useState(
    () => buildBaseMessages(systemPromptRef.current, options.initialMessages)
  );
  const messagesRef = React.useRef(messages);
  const [status, setStatus] = React.useState("idle");
  const [error, setError] = React.useState(null);
  const [lastResponse, setLastResponse] = React.useState(null);
  const syncMessages = (nextMessages) => {
    messagesRef.current = nextMessages;
    setMessages(nextMessages);
  };
  const reset = React.useCallback(() => {
    syncMessages(buildBaseMessages(systemPromptRef.current, options.initialMessages));
    setStatus("idle");
    setError(null);
    setLastResponse(null);
  }, [options.initialMessages]);
  const setSystemPrompt = React.useCallback(
    (prompt) => {
      systemPromptRef.current = prompt;
      reset();
    },
    [reset]
  );
  const sendMessage = React.useCallback(
    async (input, requestOptions = {}) => {
      const { template, variables, ...chatOptions } = requestOptions;
      const activeTemplate = template ?? templateRef.current;
      const mergedVariables = { input, ...variables ?? {} };
      const content = activeTemplate ? applyPromptTemplate(activeTemplate, mergedVariables) : input;
      const userMessage = { role: "user", content };
      const nextMessages = [...messagesRef.current, userMessage];
      syncMessages(nextMessages);
      setStatus("loading");
      setError(null);
      try {
        const response = await options.client.sendChat({
          messages: nextMessages,
          ...chatOptions
        });
        const assistantMessage = response.message ?? {
          role: "assistant",
          content: response.content,
          toolCalls: response.toolCalls
        };
        const updatedMessages = [...nextMessages, assistantMessage];
        syncMessages(updatedMessages);
        setStatus("success");
        setLastResponse(response);
        return response;
      } catch (err) {
        const nextError = err instanceof Error ? err : new Error(String(err));
        setStatus("error");
        setError(nextError);
        throw nextError;
      }
    },
    [options.client]
  );
  return {
    status,
    isLoading: status === "loading",
    error,
    messages,
    lastResponse,
    sendMessage,
    reset,
    setSystemPrompt
  };
};

// src/ai/llm/ui/miniapp/components/AiChatDialog.tsx
var AiChatDialog = ({
  open,
  onOpenChange,
  client,
  title = "AI \u5BF9\u8BDD",
  placeholder = "\u8F93\u5165\u4F60\u60F3\u54A8\u8BE2\u7684\u95EE\u9898...",
  systemPrompt,
  template,
  templateVariables,
  initialMessages,
  requestOptions,
  onResponse,
  onError
}) => {
  const { messages, sendMessage, isLoading, error } = useAiChat({
    client,
    systemPrompt,
    template,
    initialMessages
  });
  const [input, setInput] = React.useState("");
  const helperText = React.useMemo(() => {
    return template ? "\u6A21\u677F\u5DF2\u542F\u7528\uFF0C\u652F\u6301 {{input}} \u53D8\u91CF\u3002" : "\u76F4\u63A5\u8F93\u5165\u5373\u53EF\u5F00\u59CB\u5BF9\u8BDD\u3002";
  }, [template]);
  React.useEffect(() => {
    if (!open) {
      setInput("");
    }
  }, [open]);
  const handleSend = async () => {
    const content = input.trim();
    if (!content || isLoading) return;
    setInput("");
    try {
      const response = await sendMessage(content, {
        ...requestOptions,
        template,
        variables: templateVariables
      });
      onResponse?.(response);
    } catch (err) {
      const nextError = err instanceof Error ? err : new Error(String(err));
      onError?.(nextError);
    }
  };
  if (!open) {
    return null;
  }
  return /* @__PURE__ */ React__default.default.createElement(components.View, { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4" }, /* @__PURE__ */ React__default.default.createElement(components.View, { className: "w-full max-w-[640px] rounded-2xl bg-white p-4 shadow-lg" }, /* @__PURE__ */ React__default.default.createElement(components.View, { className: "flex items-center justify-between" }, /* @__PURE__ */ React__default.default.createElement(components.Text, { className: "text-base font-semibold text-slate-900" }, title), /* @__PURE__ */ React__default.default.createElement(
    components.Text,
    {
      className: "text-xs text-slate-500",
      onClick: () => onOpenChange?.(false)
    },
    "\u5173\u95ED"
  )), /* @__PURE__ */ React__default.default.createElement(
    components.ScrollView,
    {
      scrollY: true,
      className: "mt-3 max-h-[60vh] rounded-xl border border-slate-100 bg-slate-50/60 p-3"
    },
    messages.length === 0 && /* @__PURE__ */ React__default.default.createElement(components.View, { className: "flex flex-col items-center justify-center py-8 text-xs text-slate-400" }, /* @__PURE__ */ React__default.default.createElement(components.Text, null, "\u6682\u65E0\u5BF9\u8BDD\u5185\u5BB9"), /* @__PURE__ */ React__default.default.createElement(components.Text, null, "\u8F93\u5165\u6D88\u606F\u5F00\u59CB\u4F53\u9A8C AI \u5BF9\u8BDD\u3002")),
    /* @__PURE__ */ React__default.default.createElement(components.View, { className: "flex flex-col gap-3" }, messages.map((message, index) => {
      const isUser = message.role === "user";
      return /* @__PURE__ */ React__default.default.createElement(
        components.View,
        {
          key: `${message.role}-${index}`,
          className: `max-w-[85%] rounded-2xl px-3 py-2 text-xs leading-relaxed ${isUser ? "ml-auto bg-slate-900 text-white" : "mr-auto border border-slate-200 bg-white text-slate-800"}`
        },
        /* @__PURE__ */ React__default.default.createElement(components.Text, null, message.content)
      );
    }), isLoading && /* @__PURE__ */ React__default.default.createElement(components.View, { className: "mr-auto max-w-[70%] rounded-2xl border border-slate-200 bg-white px-3 py-2 text-xs text-slate-500" }, /* @__PURE__ */ React__default.default.createElement(components.Text, null, "AI \u6B63\u5728\u601D\u8003...")))
  ), /* @__PURE__ */ React__default.default.createElement(components.View, { className: "mt-3 rounded-xl border border-slate-100 bg-white p-3" }, /* @__PURE__ */ React__default.default.createElement(
    components.Textarea,
    {
      value: input,
      onInput: (event) => setInput(event.detail.value),
      placeholder,
      className: "min-h-[88px] w-full rounded-lg border border-slate-200 px-3 py-2 text-xs"
    }
  ), /* @__PURE__ */ React__default.default.createElement(components.View, { className: "mt-2 flex items-center justify-between" }, /* @__PURE__ */ React__default.default.createElement(components.Text, { className: "text-[10px] text-slate-400" }, helperText), /* @__PURE__ */ React__default.default.createElement(
    components.Button,
    {
      size: "mini",
      className: "bg-slate-900 text-white",
      disabled: !input.trim() || isLoading,
      onClick: handleSend
    },
    isLoading ? "\u53D1\u9001\u4E2D..." : "\u53D1\u9001"
  )), error && /* @__PURE__ */ React__default.default.createElement(components.View, { className: "mt-2 rounded-md border border-rose-200 bg-rose-50 px-2 py-1 text-[10px] text-rose-600" }, /* @__PURE__ */ React__default.default.createElement(components.Text, null, error.message || "\u5BF9\u8BDD\u51FA\u9519\uFF0C\u8BF7\u91CD\u8BD5\u3002")))));
};

exports.AiChatDialog = AiChatDialog;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map