import React, { useState, useMemo, useEffect, useRef, useCallback } from 'react';

var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});

// 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 = useRef(options.systemPrompt);
  const templateRef = useRef(options.template);
  const [messages, setMessages] = useState(
    () => buildBaseMessages(systemPromptRef.current, options.initialMessages)
  );
  const messagesRef = useRef(messages);
  const [status, setStatus] = useState("idle");
  const [error, setError] = useState(null);
  const [lastResponse, setLastResponse] = useState(null);
  const syncMessages = (nextMessages) => {
    messagesRef.current = nextMessages;
    setMessages(nextMessages);
  };
  const reset = useCallback(() => {
    syncMessages(buildBaseMessages(systemPromptRef.current, options.initialMessages));
    setStatus("idle");
    setError(null);
    setLastResponse(null);
  }, [options.initialMessages]);
  const setSystemPrompt = useCallback(
    (prompt) => {
      systemPromptRef.current = prompt;
      reset();
    },
    [reset]
  );
  const sendMessage = 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/rn/components/AiChatDialog.tsx
var ReactNative = __require("react-native");
var {
  Modal,
  View,
  Text,
  TextInput,
  Pressable,
  ScrollView,
  SafeAreaView,
  KeyboardAvoidingView,
  Platform,
  StyleSheet
} = ReactNative;
var styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: "rgba(15, 23, 42, 0.45)",
    justifyContent: "center",
    padding: 16
  },
  container: {
    backgroundColor: "#ffffff",
    borderRadius: 16,
    maxHeight: "90%",
    overflow: "hidden"
  },
  header: {
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: "#e2e8f0",
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center"
  },
  title: {
    fontSize: 16,
    fontWeight: "600",
    color: "#0f172a"
  },
  closeText: {
    fontSize: 12,
    color: "#64748b"
  },
  list: {
    paddingHorizontal: 16,
    paddingVertical: 12
  },
  placeholder: {
    alignItems: "center",
    paddingVertical: 24
  },
  placeholderText: {
    fontSize: 12,
    color: "#94a3b8"
  },
  bubbleUser: {
    alignSelf: "flex-end",
    backgroundColor: "#0f172a",
    borderRadius: 16,
    paddingHorizontal: 12,
    paddingVertical: 8,
    marginBottom: 8
  },
  bubbleAssistant: {
    alignSelf: "flex-start",
    backgroundColor: "#ffffff",
    borderWidth: 1,
    borderColor: "#e2e8f0",
    borderRadius: 16,
    paddingHorizontal: 12,
    paddingVertical: 8,
    marginBottom: 8
  },
  bubbleTextUser: {
    color: "#ffffff",
    fontSize: 12
  },
  bubbleText: {
    color: "#1f2937",
    fontSize: 12
  },
  loadingText: {
    color: "#64748b",
    fontSize: 12
  },
  inputContainer: {
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: "#e2e8f0"
  },
  textInput: {
    minHeight: 96,
    borderWidth: 1,
    borderColor: "#e2e8f0",
    borderRadius: 12,
    padding: 10,
    textAlignVertical: "top",
    fontSize: 12,
    color: "#0f172a"
  },
  helperRow: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    marginTop: 8
  },
  helperText: {
    flex: 1,
    fontSize: 10,
    color: "#94a3b8",
    paddingRight: 8
  },
  sendButton: {
    backgroundColor: "#0f172a",
    paddingHorizontal: 14,
    paddingVertical: 8,
    borderRadius: 12
  },
  sendButtonDisabled: {
    backgroundColor: "#94a3b8"
  },
  sendButtonText: {
    color: "#ffffff",
    fontSize: 12,
    fontWeight: "600"
  },
  error: {
    marginTop: 8,
    borderWidth: 1,
    borderColor: "#fecdd3",
    backgroundColor: "#fff1f2",
    padding: 8,
    borderRadius: 8
  },
  errorText: {
    color: "#e11d48",
    fontSize: 10
  }
});
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] = useState("");
  const helperText = 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]);
  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);
    }
  };
  return /* @__PURE__ */ React.createElement(
    Modal,
    {
      visible: open,
      transparent: true,
      animationType: "fade",
      onRequestClose: () => onOpenChange?.(false)
    },
    /* @__PURE__ */ React.createElement(SafeAreaView, { style: styles.overlay }, /* @__PURE__ */ React.createElement(
      KeyboardAvoidingView,
      {
        behavior: Platform.OS === "ios" ? "padding" : void 0,
        style: styles.container
      },
      /* @__PURE__ */ React.createElement(View, { style: styles.header }, /* @__PURE__ */ React.createElement(Text, { style: styles.title }, title), /* @__PURE__ */ React.createElement(Pressable, { onPress: () => onOpenChange?.(false) }, /* @__PURE__ */ React.createElement(Text, { style: styles.closeText }, "\u5173\u95ED"))),
      /* @__PURE__ */ React.createElement(ScrollView, { contentContainerStyle: styles.list }, messages.length === 0 && /* @__PURE__ */ React.createElement(View, { style: styles.placeholder }, /* @__PURE__ */ React.createElement(Text, { style: styles.placeholderText }, "\u6682\u65E0\u5BF9\u8BDD\u5185\u5BB9"), /* @__PURE__ */ React.createElement(Text, { style: styles.placeholderText }, "\u8F93\u5165\u6D88\u606F\u5F00\u59CB\u4F53\u9A8C AI \u5BF9\u8BDD\u3002")), messages.map((message, index) => {
        const isUser = message.role === "user";
        return /* @__PURE__ */ React.createElement(
          View,
          {
            key: `${message.role}-${index}`,
            style: isUser ? styles.bubbleUser : styles.bubbleAssistant
          },
          /* @__PURE__ */ React.createElement(Text, { style: isUser ? styles.bubbleTextUser : styles.bubbleText }, message.content)
        );
      }), isLoading && /* @__PURE__ */ React.createElement(View, { style: styles.bubbleAssistant }, /* @__PURE__ */ React.createElement(Text, { style: styles.loadingText }, "AI \u6B63\u5728\u601D\u8003..."))),
      /* @__PURE__ */ React.createElement(View, { style: styles.inputContainer }, /* @__PURE__ */ React.createElement(
        TextInput,
        {
          value: input,
          onChangeText: setInput,
          placeholder,
          multiline: true,
          style: styles.textInput
        }
      ), /* @__PURE__ */ React.createElement(View, { style: styles.helperRow }, /* @__PURE__ */ React.createElement(Text, { style: styles.helperText }, helperText), /* @__PURE__ */ React.createElement(
        Pressable,
        {
          onPress: handleSend,
          disabled: !input.trim() || isLoading,
          style: [
            styles.sendButton,
            (!input.trim() || isLoading) && styles.sendButtonDisabled
          ]
        },
        /* @__PURE__ */ React.createElement(Text, { style: styles.sendButtonText }, isLoading ? "\u53D1\u9001\u4E2D..." : "\u53D1\u9001")
      )), error && /* @__PURE__ */ React.createElement(View, { style: styles.error }, /* @__PURE__ */ React.createElement(Text, { style: styles.errorText }, error.message || "\u5BF9\u8BDD\u51FA\u9519\uFF0C\u8BF7\u91CD\u8BD5\u3002")))
    ))
  );
};

export { AiChatDialog };
//# sourceMappingURL=index.mjs.map
//# sourceMappingURL=index.mjs.map