'use strict';

var chunkQP2LHBCZ_cjs = require('../../chunk-QP2LHBCZ.cjs');
require('../../chunk-PZPCRXSV.cjs');
var aipCore = require('@osdk/aip-core');
var aip = require('@osdk/react/experimental/aip');
var React6 = require('react');
var classNames5 = require('classnames');
var icons = require('@blueprintjs/icons');
var input = require('@base-ui/react/input');

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

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var React6__namespace = /*#__PURE__*/_interopNamespace(React6);
var classNames5__default = /*#__PURE__*/_interopDefault(classNames5);

// src/base-components/callout/Callout.module.css
var Callout_default = {};

// src/base-components/callout/Callout.tsx
var DEFAULT_ICONS = {
  error: icons.Error,
  warning: icons.WarningSign,
  success: icons.Tick,
  info: icons.InfoSign
};
var INTENT_STYLES = {
  error: Callout_default.error,
  warning: Callout_default.warning,
  success: Callout_default.success,
  info: Callout_default.info
};
var Callout = /* @__PURE__ */ React6__namespace.memo(function Callout2({
  intent,
  title,
  children,
  actions,
  icon,
  className
}) {
  const IconComponent = icon ?? DEFAULT_ICONS[intent];
  return /* @__PURE__ */ React6__namespace.createElement("div", {
    "aria-live": "polite",
    className: classNames5__default.default(Callout_default.callout, INTENT_STYLES[intent], className),
    role: "alert"
  }, IconComponent != null && /* @__PURE__ */ React6__namespace.createElement("span", {
    className: Callout_default.icon
  }, /* @__PURE__ */ React6__namespace.createElement(IconComponent, {
    size: 16
  })), /* @__PURE__ */ React6__namespace.createElement("div", {
    className: Callout_default.body
  }, title != null && /* @__PURE__ */ React6__namespace.createElement("div", {
    className: Callout_default.title
  }, title), children != null && /* @__PURE__ */ React6__namespace.createElement("div", {
    className: Callout_default.message
  }, children)), actions != null && /* @__PURE__ */ React6__namespace.createElement("div", {
    className: Callout_default.actions
  }, actions));
});

// src/aip-agent-chat/AipAgentChat.module.css
var AipAgentChat_default = {};

// src/aip-agent-chat/components/AipAgentChatComposer.tsx
function _extends() {
  return _extends = Object.assign ? Object.assign.bind() : function(n) {
    for (var e = 1; e < arguments.length; e++) {
      var t = arguments[e];
      for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
    }
    return n;
  }, _extends.apply(null, arguments);
}
function AipAgentChatComposer({
  isInFlight,
  onSendMessage,
  onStop,
  placeholder,
  className,
  footerLeft
}) {
  const [draft, setDraft] = React6__namespace.useState("");
  const canSend = !isInFlight && draft.trim().length > 0;
  const handleSend = React6__namespace.useCallback(() => {
    const trimmed = draft.trim();
    if (trimmed.length === 0) {
      return;
    }
    try {
      const result = onSendMessage(trimmed);
      if (result instanceof Promise) {
        result.catch(noop);
      }
    } catch {
    }
    setDraft("");
  }, [draft, onSendMessage]);
  const handleKeyDown = React6__namespace.useCallback((event) => {
    if (event.key === "Enter" && !event.shiftKey) {
      event.preventDefault();
      if (!isInFlight) {
        handleSend();
      }
    }
  }, [handleSend, isInFlight]);
  const renderTextarea = React6__namespace.useCallback((props) => /* @__PURE__ */ React6__namespace.createElement("textarea", _extends({}, props, {
    onKeyDown: handleKeyDown,
    rows: 3
  })), [handleKeyDown]);
  return /* @__PURE__ */ React6__namespace.createElement("div", {
    className: classNames5__default.default(AipAgentChat_default.composer, className)
  }, /* @__PURE__ */ React6__namespace.createElement("div", {
    className: AipAgentChat_default.inputWrapper
  }, /* @__PURE__ */ React6__namespace.createElement(input.Input, {
    "aria-label": "Message input",
    className: AipAgentChat_default.textarea,
    onValueChange: setDraft,
    placeholder,
    value: draft,
    render: renderTextarea
  }), /* @__PURE__ */ React6__namespace.createElement("div", {
    className: AipAgentChat_default.inputActions
  }, isInFlight && onStop != null ? /* @__PURE__ */ React6__namespace.createElement(chunkQP2LHBCZ_cjs.ActionButton, {
    onClick: onStop,
    type: "button"
  }, "Stop") : /* @__PURE__ */ React6__namespace.createElement(chunkQP2LHBCZ_cjs.ActionButton, {
    disabled: !canSend,
    onClick: handleSend,
    type: "button",
    variant: "primary"
  }, "Send"))), footerLeft != null && /* @__PURE__ */ React6__namespace.createElement("div", {
    className: AipAgentChat_default.composerFooterLeft
  }, footerLeft));
}
function noop() {
}
function useChatAutoScroll(signal, enabled) {
  const elRef = React6__namespace.useRef(null);
  const cleanupRef = React6__namespace.useRef(null);
  const isPinnedRef = React6__namespace.useRef(true);
  const setRef = React6__namespace.useCallback((el) => {
    cleanupRef.current?.();
    cleanupRef.current = null;
    elRef.current = el;
    if (el == null) {
      return;
    }
    const onScroll = () => {
      const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
      isPinnedRef.current = distanceFromBottom <= NEAR_BOTTOM_THRESHOLD_PX;
    };
    el.addEventListener("scroll", onScroll, {
      passive: true
    });
    cleanupRef.current = () => el.removeEventListener("scroll", onScroll);
  }, []);
  React6__namespace.useEffect(() => {
    if (!enabled) {
      return;
    }
    const el = elRef.current;
    if (el == null || !isPinnedRef.current) {
      return;
    }
    el.scrollTop = el.scrollHeight;
  }, [signal, enabled]);
  return setRef;
}
var NEAR_BOTTOM_THRESHOLD_PX = 32;
function AipAgentChatLoader({
  className,
  label = "Assistant is responding"
}) {
  return /* @__PURE__ */ React6__namespace.createElement("div", {
    "aria-label": label,
    "aria-live": "polite",
    className: classNames5__default.default(AipAgentChat_default.loader, className),
    role: "status"
  }, /* @__PURE__ */ React6__namespace.createElement("span", {
    "aria-hidden": "true",
    className: AipAgentChat_default.loaderDot
  }), /* @__PURE__ */ React6__namespace.createElement("span", {
    "aria-hidden": "true",
    className: AipAgentChat_default.loaderDot
  }), /* @__PURE__ */ React6__namespace.createElement("span", {
    "aria-hidden": "true",
    className: AipAgentChat_default.loaderDot
  }));
}
function AipAgentChatMessage({
  message
}) {
  const text = aipCore.getUIMessageText(message);
  const role = message.role;
  const styling = ROLE_STYLING[role];
  return /* @__PURE__ */ React6__namespace.createElement("div", {
    "aria-label": styling.label,
    className: classNames5__default.default(AipAgentChat_default.message, styling.container),
    role: "group"
  }, /* @__PURE__ */ React6__namespace.createElement("div", {
    className: classNames5__default.default(AipAgentChat_default.bubble, styling.bubble)
  }, text.length > 0 ? text : /* @__PURE__ */ React6__namespace.createElement("span", {
    className: AipAgentChat_default.streamingPlaceholder
  }, "\u2026")));
}
var ROLE_STYLING = {
  user: {
    container: AipAgentChat_default.userMessage,
    bubble: AipAgentChat_default.userBubble,
    label: "User message"
  },
  assistant: {
    container: AipAgentChat_default.assistantMessage,
    bubble: AipAgentChat_default.assistantBubble,
    label: "Assistant message"
  },
  system: {
    container: AipAgentChat_default.systemMessage,
    bubble: AipAgentChat_default.systemBubble,
    label: "System message"
  }
};

// src/aip-agent-chat/components/AipAgentChatMessageList.tsx
var DEFAULT_EMPTY_STATE = /* @__PURE__ */ React6__namespace.createElement(React6__namespace.Fragment, null, /* @__PURE__ */ React6__namespace.createElement(icons.Chat, {
  className: AipAgentChat_default.emptyIcon,
  size: 64
}), /* @__PURE__ */ React6__namespace.createElement("div", {
  className: AipAgentChat_default.emptyTitle
}, "Start a conversation"), /* @__PURE__ */ React6__namespace.createElement("div", null, "Type a message below to chat with the assistant."));
function AipAgentChatMessageList({
  messages,
  isStreaming,
  enableAutoScroll,
  className,
  renderEmptyState,
  renderMessage
}) {
  const lastMessage = messages.at(-1);
  const lastMessageTextLength = lastMessage != null ? aipCore.getUIMessageText(lastMessage).length : 0;
  const scrollSignal = `${messages.length}:${lastMessageTextLength}`;
  const setContainerRef = useChatAutoScroll(scrollSignal, enableAutoScroll);
  const isEmpty = messages.length === 0 && !isStreaming;
  const showLoader = isStreaming && lastMessage?.role !== "assistant";
  return /* @__PURE__ */ React6__namespace.createElement("div", {
    "aria-live": isEmpty ? void 0 : "polite",
    className: classNames5__default.default(AipAgentChat_default.messageList, isEmpty && AipAgentChat_default.empty, className),
    ref: setContainerRef,
    role: isEmpty ? void 0 : "log"
  }, isEmpty ? renderEmptyState != null ? renderEmptyState() : DEFAULT_EMPTY_STATE : /* @__PURE__ */ React6__namespace.createElement(React6__namespace.Fragment, null, messages.map((message) => /* @__PURE__ */ React6__namespace.createElement(React6__namespace.Fragment, {
    key: message.id
  }, renderMessage != null ? renderMessage(message) : /* @__PURE__ */ React6__namespace.createElement(AipAgentChatMessage, {
    message
  }))), showLoader && /* @__PURE__ */ React6__namespace.createElement("div", {
    className: classNames5__default.default(AipAgentChat_default.message, AipAgentChat_default.assistantMessage)
  }, /* @__PURE__ */ React6__namespace.createElement("div", {
    className: classNames5__default.default(AipAgentChat_default.bubble, AipAgentChat_default.assistantBubble)
  }, /* @__PURE__ */ React6__namespace.createElement(AipAgentChatLoader, null)))));
}

// src/aip-agent-chat/BaseAipAgentChat.tsx
var BaseAipAgentChat = /* @__PURE__ */ React6__namespace.memo(function BaseAipAgentChat2({
  messages,
  status,
  error,
  onSendMessage,
  onStop,
  onClearError,
  composerFooter,
  className,
  placeholder = "Type a message...",
  enableAutoScroll = true,
  renderEmptyState,
  renderMessage
}) {
  const isInFlight = status === "submitted" || status === "streaming";
  return /* @__PURE__ */ React6__namespace.createElement("div", {
    className: classNames5__default.default(AipAgentChat_default.chat, className)
  }, error != null && /* @__PURE__ */ React6__namespace.createElement(Callout, {
    actions: /* @__PURE__ */ React6__namespace.createElement(chunkQP2LHBCZ_cjs.ActionButton, {
      onClick: onClearError,
      type: "button"
    }, "Dismiss"),
    intent: "error",
    title: "Something went wrong"
  }, error.message.length > 0 ? error.message : "An unknown error occurred. Try again, or dismiss to keep the conversation."), /* @__PURE__ */ React6__namespace.createElement(AipAgentChatMessageList, {
    enableAutoScroll,
    isStreaming: isInFlight,
    messages,
    renderEmptyState,
    renderMessage
  }), /* @__PURE__ */ React6__namespace.createElement(AipAgentChatComposer, {
    footerLeft: composerFooter,
    isInFlight,
    onSendMessage,
    onStop,
    placeholder
  }));
});
function AipAgentChatModelPicker({
  models,
  activeModel,
  onModelChange,
  disabled,
  className
}) {
  const handleChange = React6__namespace.useCallback((event) => {
    onModelChange(event.target.value);
  }, [onModelChange]);
  if (models.length === 0) {
    return null;
  }
  if (models.length === 1) {
    return /* @__PURE__ */ React6__namespace.createElement("span", {
      className: classNames5__default.default(AipAgentChat_default.modelPickerLabel, className)
    }, "Model: ", activeModel);
  }
  return /* @__PURE__ */ React6__namespace.createElement("select", {
    "aria-label": "Active model",
    className: classNames5__default.default(AipAgentChat_default.modelPicker, className),
    disabled,
    onChange: handleChange,
    value: activeModel
  }, models.map((modelName) => /* @__PURE__ */ React6__namespace.createElement("option", {
    key: modelName,
    value: modelName
  }, modelName)));
}

// src/aip-agent-chat/AipAgentChat.tsx
var FALLBACK_MODEL_API_NAME = "gpt-4o";
function AipAgentChat({
  client,
  model: controlledModel,
  defaultModel,
  availableModels,
  onModelChange,
  system,
  initialMessages,
  className,
  placeholder,
  enableAutoScroll,
  onError,
  onFinish,
  renderEmptyState,
  renderMessage
}) {
  const [internalModel, setInternalModel] = React6__namespace.useState(() => controlledModel ?? defaultModel ?? availableModels?.[0] ?? FALLBACK_MODEL_API_NAME);
  const isControlled = controlledModel != null;
  const activeModel = isControlled ? controlledModel : internalModel;
  const handleModelChange = React6__namespace.useCallback((next) => {
    if (!isControlled) {
      setInternalModel(next);
    }
    onModelChange?.(next);
  }, [isControlled, onModelChange]);
  const model = React6__namespace.useMemo(() => aipCore.foundryModel({
    client,
    model: activeModel
  }), [client, activeModel]);
  const {
    messages,
    status,
    error,
    sendMessage,
    stop,
    clearError
  } = aip.useChat({
    model,
    system,
    messages: initialMessages,
    onError,
    onFinish
  });
  React6__namespace.useEffect(() => {
    if (isControlled || availableModels == null || availableModels.length === 0) {
      return;
    }
    if (!availableModels.includes(internalModel)) {
      setInternalModel(availableModels[0]);
    }
  }, [isControlled, availableModels, internalModel]);
  const handleSendMessage = React6__namespace.useCallback((text) => {
    return sendMessage({
      text
    });
  }, [sendMessage]);
  const isInFlight = status === "submitted" || status === "streaming";
  const composerFooter = availableModels != null && availableModels.length > 0 ? /* @__PURE__ */ React6__namespace.createElement(AipAgentChatModelPicker, {
    activeModel,
    models: availableModels,
    onModelChange: handleModelChange,
    disabled: isInFlight
  }) : void 0;
  return /* @__PURE__ */ React6__namespace.createElement(BaseAipAgentChat, {
    className,
    composerFooter,
    enableAutoScroll,
    messages,
    status,
    error,
    onClearError: clearError,
    onSendMessage: handleSendMessage,
    onStop: stop,
    placeholder,
    renderEmptyState,
    renderMessage
  });
}

Object.defineProperty(exports, "getUIMessageText", {
  enumerable: true,
  get: function () { return aipCore.getUIMessageText; }
});
exports.AipAgentChat = AipAgentChat;
exports.BaseAipAgentChat = BaseAipAgentChat;
//# sourceMappingURL=aip-agent-chat.cjs.map
//# sourceMappingURL=aip-agent-chat.cjs.map