import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import { useState, useMemo, useEffect } from "react";
import { getAssetUrl } from "../../utils/assetBase.js";
import { Tooltip } from "../Tooltip/index.js";
import { BookMarkPanel } from "./bookMarkPanel.js";
import { ChatBotFooter } from "./chatBotFooter.js";
import ChatBotLandingScreen from "./chatBotLandingScreen.js";
import { ChatbotModuleMenu } from "./chatbotModuleMenu.js";
import { newChatMenuItem, mandatoryTabList, menuItems } from "./constant.js";
import { ConversationScreen } from "./conversationScreen.js";
import { CustomScreen } from "./customScreen.js";
import { HistoryPanel } from "./historyPanel.js";
import { NewChatComponent } from "./newChatComponent.js";
/* empty css                   */
const BookMarkIcon = getAssetUrl("icons/bookmarkIcon.svg");
function Chatbot({
  onClose,
  userName,
  isChatBotOpen,
  setIsChatBotOpen,
  conversation = {},
  preDefinedQuestions,
  addedByYouQuestions,
  onSendIconClick = () => {
  },
  assistantChats = [],
  isAssistantThinking = false,
  moduleList = [],
  onModuleClick = () => {
  },
  tabList,
  handleSavedChat,
  threadList = ["Home", "Thread 1", "Thread 2"],
  activeThread = null,
  isCustomScreen = false,
  customScreenJsx = null,
  onLikeClick = () => {
  },
  onDislikeClick = () => {
  },
  handleNewChatClick = () => {
  },
  inputText = "",
  handleRefresh,
  handleMicClick,
  hideMenuArrow = false,
  newChatScreen = false,
  isModuleListLoading = false,
  suggestionBanner = {
    freeTextHeading: "Try adding more details:",
    freeTextContent: "Alan works best when your input has context and pointed questions"
  },
  isStopIcon = false,
  onStopIconClick = () => {
  },
  landingScreen = false,
  footerText = "AI-generated responses may contain errors—please verify important information",
  onCloseSuggestionBanner = () => {
  },
  showSuggestionBanner = false,
  utilityList = [],
  customInputComponent = null,
  onHistoryPanelClick = () => {
  },
  historyPanelData = [],
  onHistorySearchChange = () => {
  },
  onHistorySelectConversation = () => {
  },
  onHistoryToggleGroup = () => {
  },
  historyOpenGroups,
  onHistoryMenuAction = () => {
  },
  showHistoryPanel = true,
  isFullWidth = false
}) {
  var _a;
  const [isNewChat, setIsNewChat] = useState(
    (tabList == null ? void 0 : tabList.find((tab) => tab.isActive)) ? false : newChatScreen ? true : false
  );
  const [inputValue, setInputValue] = useState(inputText);
  const [containerWidth, setContainerWidth] = useState(
    isFullWidth ? "calc(100vw - 64px)" : "690px"
  );
  const [activeList, setActiveList] = useState((_a = tabList == null ? void 0 : tabList.find((tab) => tab.initialClick)) == null ? void 0 : _a.name);
  const [isBookMarkPanelOpen, setIsBookMarkPanelOpen] = useState(false);
  const [isHistoryPanelOpen, setIsHistoryPanelOpen] = useState(false);
  const [isPagePanelOpen, setIsPagePanelOpen] = useState(false);
  const [userChats, setUserChats] = useState(assistantChats);
  const [menuItems$1, setMenuItems] = useState([]);
  const [localHistoryOpenGroups, setLocalHistoryOpenGroups] = useState({});
  const panelsOpen = useMemo(
    () => isBookMarkPanelOpen || isHistoryPanelOpen || isPagePanelOpen,
    [isBookMarkPanelOpen, isHistoryPanelOpen, isPagePanelOpen]
  );
  useEffect(() => {
    setInputValue(inputText);
  }, [inputText]);
  useEffect(() => {
    if (tabList && Array.isArray(tabList)) {
      setMenuItems([
        newChatMenuItem,
        ...tabList.map((tab, idx) => {
          var _a2, _b;
          return {
            ...tab,
            key: ((_a2 = tab.name) == null ? void 0 : _a2.toLowerCase()) || `tab${idx}`,
            icon: tab.icon || BookMarkIcon,
            className: `chatbot-component-menu-container-icon-${(_b = tab.name) == null ? void 0 : _b.toLowerCase()}`,
            label: tab.name,
            onClick: tab.onClick
          };
        }),
        ...showHistoryPanel ? mandatoryTabList : []
      ]);
    } else {
      setMenuItems([newChatMenuItem, ...menuItems]);
    }
  }, [tabList, showHistoryPanel]);
  useEffect(() => {
    var _a2, _b;
    if (!isChatBotOpen) return;
    const resizer = document.querySelector(".resizer");
    let startX = 0;
    let startWidth = 0;
    const onMouseMove = (e) => {
      const dx = e.clientX - startX;
      let newWidth = startWidth - dx;
      const minAllowed = panelsOpen ? 690 + 360 : 690;
      const maxAllowed = window.innerWidth - 100;
      if (newWidth <= minAllowed) newWidth = minAllowed;
      if (newWidth > maxAllowed) newWidth = maxAllowed;
      setContainerWidth(`${newWidth}px`);
    };
    const onMouseUp = () => {
      document.body.classList.remove("no-select");
      document.removeEventListener("mousemove", onMouseMove);
      document.removeEventListener("mouseup", onMouseUp);
    };
    const onMouseDown = (e) => {
      startX = e.clientX;
      const el = document.querySelector(".chatbot-component-container");
      startWidth = (el == null ? void 0 : el.getBoundingClientRect().width) ?? 690;
      document.body.classList.add("no-select");
      document.addEventListener("mousemove", onMouseMove);
      document.addEventListener("mouseup", onMouseUp);
    };
    setActiveList((_a2 = tabList == null ? void 0 : tabList.find((tab) => tab.initialClick)) == null ? void 0 : _a2.name);
    const initialItem = menuItems$1.find((tab) => tab.initialClick);
    (_b = initialItem == null ? void 0 : initialItem.onClick) == null ? void 0 : _b.call(initialItem, initialItem);
    if (resizer && !isFullWidth) {
      resizer.addEventListener("mousedown", onMouseDown);
    } else if (isFullWidth) {
      setContainerWidth("calc(100vw - 64px)");
    }
    return () => {
      resizer == null ? void 0 : resizer.removeEventListener("mousedown", onMouseDown);
    };
  }, [isChatBotOpen, panelsOpen, isFullWidth, tabList, menuItems$1]);
  useEffect(() => {
    if (panelsOpen) {
      setContainerWidth(
        (prev) => `${Math.min(parseInt(prev, 10) + 360, window.innerWidth - 100)}px`
      );
    } else {
      setContainerWidth((prev) => `${Math.max(parseInt(prev, 10) - 360, 690)}px`);
    }
  }, [panelsOpen]);
  const handleCloseChatBot = () => {
    setIsChatBotOpen(false);
    setIsHistoryPanelOpen(false);
    setIsBookMarkPanelOpen(false);
    setIsPagePanelOpen(false);
    onClose == null ? void 0 : onClose();
  };
  const handleMenuClick = (item) => {
    var _a2, _b, _c;
    if (item.key === "newchat") {
      setInputValue("");
      const tabDetails = handleNewChatClick(item);
      if (tabDetails == null ? void 0 : tabDetails.isInitialClickPresent) {
        const initialClickItem = tabList == null ? void 0 : tabList.find(
          (i) => {
            var _a3, _b2;
            return ((_a3 = i.name) == null ? void 0 : _a3.toLowerCase()) === ((_b2 = tabDetails.tabName) == null ? void 0 : _b2.toLowerCase());
          }
        );
        (_a2 = initialClickItem == null ? void 0 : initialClickItem.onClick) == null ? void 0 : _a2.call(initialClickItem, initialClickItem);
      }
      setActiveList(
        (_b = tabList == null ? void 0 : tabList.find((i) => {
          var _a3, _b2;
          return ((_a3 = i.name) == null ? void 0 : _a3.toLowerCase()) === ((_b2 = tabDetails == null ? void 0 : tabDetails.tabName) == null ? void 0 : _b2.toLowerCase());
        })) == null ? void 0 : _b.name
      );
      setIsNewChat(true);
    } else if (item.key === "history") {
      const next = !isHistoryPanelOpen;
      setIsHistoryPanelOpen(next);
      onHistoryPanelClick(item, next);
    } else {
      setActiveList(item.key);
      (_c = item.onClick) == null ? void 0 : _c.call(item, item);
      setIsNewChat(false);
    }
  };
  const handleCloseLeftPanel = () => {
    setIsBookMarkPanelOpen(false);
    setIsHistoryPanelOpen(false);
    setIsPagePanelOpen(false);
  };
  return isChatBotOpen ? /* @__PURE__ */ jsxs("div", { className: "chatbot-modal-wrapper", children: [
    /* @__PURE__ */ jsx("div", { className: "resizer" }),
    /* @__PURE__ */ jsx("div", { className: "chatbot-component-container", style: { width: containerWidth }, children: landingScreen ? /* @__PURE__ */ jsx(ChatBotLandingScreen, { isFullWidth, onClose: handleCloseChatBot }) : /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(
        "div",
        {
          className: `chatbot-component-left-side ${panelsOpen ? "chatbot-component-left-side-open" : ""}`,
          children: /* @__PURE__ */ jsxs(
            "div",
            {
              className: `chatbot-component-menu-container ${panelsOpen ? "chatbot-component-menu-container-open" : ""}`,
              children: [
                /* @__PURE__ */ jsxs(
                  "div",
                  {
                    className: `chatbot-component-menu-container-icon ${panelsOpen ? "chatbot-component-menu-container-icon-open" : ""}`,
                    children: [
                      /* @__PURE__ */ jsx("ul", { className: "chatbot-component-menu-list", children: menuItems$1.map((item, idx) => {
                        var _a2, _b, _c;
                        return /* @__PURE__ */ jsx(
                          Tooltip,
                          {
                            orientation: "left",
                            title: `${(_a2 = item.key) == null ? void 0 : _a2.charAt(0).toUpperCase()}${(_b = item.key) == null ? void 0 : _b.slice(1)}`,
                            variant: "tertiary",
                            children: /* @__PURE__ */ jsx(
                              "li",
                              {
                                className: `${item.className} ${(activeList == null ? void 0 : activeList.toLowerCase()) === ((_c = item.key) == null ? void 0 : _c.toLowerCase()) ? "active" : ""}`,
                                onClick: () => {
                                  handleMenuClick(item);
                                },
                                children: typeof item.icon === "string" ? /* @__PURE__ */ jsx("img", { alt: item.key, className: item.iconClassName, src: item.icon }) : item.icon
                              }
                            )
                          },
                          `${item.key ?? idx}`
                        );
                      }) }),
                      /* @__PURE__ */ jsx("ul", { className: "chatbot-component-menu-list utility-list", children: utilityList.map((item) => /* @__PURE__ */ jsx(
                        Tooltip,
                        {
                          orientation: "left",
                          title: `${item.key.charAt(0).toUpperCase()}${item.key.slice(1)}`,
                          variant: "tertiary",
                          children: /* @__PURE__ */ jsx("li", { onClick: item.onClick, children: typeof item.icon === "string" ? /* @__PURE__ */ jsx("img", { alt: item.key, src: item.icon }) : item.icon })
                        },
                        item.key
                      )) })
                    ]
                  }
                ),
                isBookMarkPanelOpen && !isHistoryPanelOpen && !isPagePanelOpen && /* @__PURE__ */ jsx(
                  BookMarkPanel,
                  {
                    addedByYouQuestions,
                    preDefinedQuestions,
                    onClose: handleCloseLeftPanel
                  }
                ),
                isHistoryPanelOpen && !isBookMarkPanelOpen && !isPagePanelOpen && /* @__PURE__ */ jsx(
                  HistoryPanel,
                  {
                    historyPanelData,
                    openGroups: historyOpenGroups ?? localHistoryOpenGroups,
                    onClose: handleCloseLeftPanel,
                    onMenuAction: onHistoryMenuAction,
                    onSearchChange: onHistorySearchChange,
                    onSelectConversation: onHistorySelectConversation,
                    onToggleGroup: (groupName, isOpen) => {
                      if (historyOpenGroups == null) {
                        setLocalHistoryOpenGroups((prev) => ({ ...prev, [groupName]: isOpen }));
                      }
                      onHistoryToggleGroup(groupName, isOpen);
                    }
                  }
                )
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsxs(
        "div",
        {
          className: `chatbot-component-right-side ${panelsOpen ? "chatbot-component-right-side-open" : ""}`,
          children: [
            !isCustomScreen && /* @__PURE__ */ jsx("div", { className: "conversation-screen-container", children: /* @__PURE__ */ jsx(
              ChatbotModuleMenu,
              {
                activeList,
                activeThread,
                handleSavedChat,
                hideCenterOptions: newChatScreen,
                hideChildren: !newChatScreen,
                hideMenuArrow,
                isFullWidth,
                isModuleListLoading,
                moduleList,
                threadList,
                onClose: handleCloseChatBot,
                onModuleClick
              }
            ) }),
            isNewChat ? /* @__PURE__ */ jsx(
              NewChatComponent,
              {
                activeList,
                customInputComponent,
                handleMicClick,
                handleRefresh,
                inputValue,
                isStopIcon,
                setInputValue,
                setIsNewChat,
                setUserChats,
                showSuggestionBanner,
                suggestionBanner,
                userChats,
                userName,
                onCloseSuggestionBanner,
                onSendIconClick,
                onStopIconClick
              }
            ) : isCustomScreen ? /* @__PURE__ */ jsx(
              CustomScreen,
              {
                activeList,
                customInputComponent,
                customScreenJsx,
                handleMicClick,
                handleRefresh,
                isFullWidth,
                isStopIcon,
                setUserChats,
                showSuggestionBanner,
                suggestionBanner,
                userChats,
                onClose: handleCloseChatBot,
                onCloseSuggestionBanner,
                onSendIconClick,
                onStopIconClick
              }
            ) : /* @__PURE__ */ jsx(
              ConversationScreen,
              {
                activeList,
                conversation,
                customInputComponent,
                handleMicClick,
                handleRefresh,
                inputText,
                isAssistantThinking,
                isStopIcon,
                setUserChats,
                showSuggestionBanner,
                suggestionBanner,
                userChats,
                onCloseSuggestionBanner,
                onDislikeClick,
                onLikeClick,
                onSendIconClick,
                onStopIconClick
              }
            ),
            /* @__PURE__ */ jsx(ChatBotFooter, { footerText })
          ]
        }
      )
    ] }) })
  ] }) : null;
}
Chatbot.displayName = "Chatbot";
export {
  Chatbot
};
