import * as React from 'react';
import { useChat } from '@ai-sdk/react';

var COMPATIBLE_ROLES = /* @__PURE__ */ new Set([
  "user",
  "assistant",
  "system",
  "tool"
]);
function narrowRole(role) {
  return typeof role === "string" && COMPATIBLE_ROLES.has(role) ? role : "assistant";
}
function extractText(parts) {
  if (!Array.isArray(parts)) return "";
  let out = "";
  for (const part of parts) {
    if (typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string") {
      out += part.text;
    }
  }
  return out;
}
function useAIChat(options = {}) {
  const [value, setValue] = React.useState("");
  const sdkOptions = options.sdkOptions ?? {};
  const sdk = useChat({
    ...sdkOptions,
    ...options.api ? { api: options.api } : {},
    ...options.initialMessages ? { messages: options.initialMessages } : {}
  });
  const status = (() => {
    const s = sdk.status;
    if (s === "submitted" || s === "streaming" || s === "error" || s === "ready") {
      return s;
    }
    return "ready";
  })();
  const sdkMessages = sdk.messages;
  const messages = React.useMemo(() => {
    if (!Array.isArray(sdkMessages)) return [];
    return sdkMessages.map((m) => {
      const msg = m;
      return {
        id: typeof msg.id === "string" ? msg.id : "",
        role: narrowRole(msg.role),
        content: extractText(msg.parts),
        parts: Array.isArray(msg.parts) ? msg.parts : void 0
      };
    });
  }, [sdkMessages]);
  const sendMessage = sdk.sendMessage;
  const stop = sdk.stop;
  const regenerate = sdk.regenerate;
  const error = sdk.error;
  const composer = React.useMemo(
    () => ({
      value,
      onValueChange: setValue,
      onSubmit: (next) => {
        const trimmed = next.trim();
        if (!trimmed) return;
        sendMessage?.({ text: trimmed });
        setValue("");
      },
      disabled: status === "submitted" || status === "streaming"
    }),
    [value, sendMessage, status]
  );
  return {
    messages,
    status,
    composer,
    stop: () => stop?.(),
    reload: () => regenerate?.(),
    error
  };
}

export { useAIChat };
//# sourceMappingURL=use-ai-chat.js.map
//# sourceMappingURL=use-ai-chat.js.map