'use strict';

const jsxRuntime = require('react/jsx-runtime');
const client = require('@btst/stack/plugins/client');
const yar = require('@btst/yar');
const plugins_aiChat_queryKeys = require('../../../../../../plugins/ai-chat/query-keys.cjs');
const chatLayout = require('./components/chat-layout.cjs');

function createConversationsLoader(config) {
  return async () => {
    if (config.mode === "public") {
      return;
    }
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, hooks, headers } = config;
      const context = {
        path: "/chat",
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadConversations) {
          await client.runClientHookWithShim(
            () => hooks.beforeLoadConversations(context),
            "Load prevented by beforeLoadConversations hook"
          );
        }
        const client$1 = client.createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = plugins_aiChat_queryKeys.createAiChatQueryKeys(client$1, headers);
        const listQuery = queries.conversations.list();
        await queryClient.prefetchQuery(listQuery);
        if (hooks?.afterLoadConversations) {
          const conversations = queryClient.getQueryData(
            listQuery.queryKey
          ) || null;
          await client.runClientHookWithShim(
            () => hooks.afterLoadConversations(conversations, context),
            "Load prevented by afterLoadConversations hook"
          );
        }
        const queryState = queryClient.getQueryState(listQuery.queryKey);
        if (queryState?.error && hooks?.onLoadError) {
          const error = queryState.error instanceof Error ? queryState.error : new Error(String(queryState.error));
          await hooks.onLoadError(error, context);
        }
      } catch (error) {
        if (hooks?.onLoadError) {
          await hooks.onLoadError(error, context);
        }
      }
    }
  };
}
function createConversationLoader(id, config) {
  return async () => {
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, hooks, headers } = config;
      const context = {
        path: `/chat/${id}`,
        params: { id },
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadConversation) {
          await client.runClientHookWithShim(
            () => hooks.beforeLoadConversation(id, context),
            "Load prevented by beforeLoadConversation hook"
          );
        }
        const client$1 = client.createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = plugins_aiChat_queryKeys.createAiChatQueryKeys(client$1, headers);
        const conversationQuery = queries.conversations.detail(id);
        const listQuery = queries.conversations.list();
        await Promise.all([
          queryClient.prefetchQuery(conversationQuery),
          queryClient.prefetchQuery(listQuery)
        ]);
        if (hooks?.afterLoadConversation) {
          const conversation = queryClient.getQueryData(conversationQuery.queryKey) || null;
          await client.runClientHookWithShim(
            () => hooks.afterLoadConversation(conversation, id, context),
            "Load prevented by afterLoadConversation hook"
          );
        }
        const queryState = queryClient.getQueryState(
          conversationQuery.queryKey
        );
        if (queryState?.error && hooks?.onLoadError) {
          const error = queryState.error instanceof Error ? queryState.error : new Error(String(queryState.error));
          await hooks.onLoadError(error, context);
        }
      } catch (error) {
        if (hooks?.onLoadError) {
          await hooks.onLoadError(error, context);
        }
      }
    }
  };
}
function createChatHomeMeta(config) {
  return () => {
    const { siteBaseURL, siteBasePath, seo } = config;
    const fullUrl = `${siteBaseURL}${siteBasePath}/chat`;
    const title = "Chat";
    const description = seo?.description || "Start a conversation with AI";
    return [
      { title },
      { name: "title", content: title },
      { name: "description", content: description },
      { name: "robots", content: "noindex, nofollow" },
      // Chat pages typically shouldn't be indexed
      // Open Graph
      { property: "og:type", content: "website" },
      { property: "og:title", content: title },
      { property: "og:description", content: description },
      { property: "og:url", content: fullUrl },
      ...seo?.siteName ? [{ property: "og:site_name", content: seo.siteName }] : [],
      ...seo?.locale ? [{ property: "og:locale", content: seo.locale }] : [],
      ...seo?.defaultImage ? [{ property: "og:image", content: seo.defaultImage }] : [],
      // Twitter
      { name: "twitter:card", content: "summary" },
      { name: "twitter:title", content: title },
      { name: "twitter:description", content: description }
    ];
  };
}
function createConversationMeta(id, config) {
  return () => {
    const {
      queryClient,
      apiBaseURL,
      apiBasePath,
      siteBaseURL,
      siteBasePath,
      seo
    } = config;
    const queries = plugins_aiChat_queryKeys.createAiChatQueryKeys(
      client.createApiClient({
        baseURL: apiBaseURL,
        basePath: apiBasePath
      })
    );
    const conversation = queryClient.getQueryData(queries.conversations.detail(id).queryKey);
    const fullUrl = `${siteBaseURL}${siteBasePath}/chat/${id}`;
    const title = conversation?.title || "Chat";
    const description = seo?.description || "AI conversation";
    return [
      { title },
      { name: "title", content: title },
      { name: "description", content: description },
      { name: "robots", content: "noindex, nofollow" },
      // Open Graph
      { property: "og:type", content: "website" },
      { property: "og:title", content: title },
      { property: "og:description", content: description },
      { property: "og:url", content: fullUrl },
      ...seo?.siteName ? [{ property: "og:site_name", content: seo.siteName }] : [],
      // Twitter
      { name: "twitter:card", content: "summary" },
      { name: "twitter:title", content: title }
    ];
  };
}
const aiChatClientPlugin = (config) => {
  const isPublicMode = config.mode === "public";
  if (isPublicMode) {
    return client.defineClientPlugin({
      name: "ai-chat",
      routes: () => ({
        // Chat home - simple chat interface without history
        chat: yar.createRoute("/chat", () => {
          const CustomChat = config.pageComponents?.chat;
          return {
            PageComponent: CustomChat ?? (() => /* @__PURE__ */ jsxRuntime.jsx(
              chatLayout.ChatLayout,
              {
                apiBaseURL: config.apiBaseURL,
                apiBasePath: config.apiBasePath,
                showSidebar: false
              }
            )),
            loader: createConversationsLoader(config),
            meta: createChatHomeMeta(config)
          };
        })
      }),
      sitemap: async () => []
    });
  }
  return client.defineClientPlugin({
    name: "ai-chat",
    routes: () => ({
      // Chat home - new conversation or list
      chat: yar.createRoute("/chat", () => {
        const CustomChat = config.pageComponents?.chat;
        return {
          PageComponent: CustomChat ?? (() => /* @__PURE__ */ jsxRuntime.jsx(
            chatLayout.ChatLayout,
            {
              apiBaseURL: config.apiBaseURL,
              apiBasePath: config.apiBasePath
            }
          )),
          loader: createConversationsLoader(config),
          meta: createChatHomeMeta(config)
        };
      }),
      // Existing conversation
      chatConversation: yar.createRoute("/chat/:id", ({ params }) => {
        const CustomConversation = config.pageComponents?.chatConversation;
        return {
          PageComponent: CustomConversation ? () => /* @__PURE__ */ jsxRuntime.jsx(CustomConversation, { conversationId: params.id }) : () => /* @__PURE__ */ jsxRuntime.jsx(
            chatLayout.ChatLayout,
            {
              apiBaseURL: config.apiBaseURL,
              apiBasePath: config.apiBasePath,
              conversationId: params.id
            }
          ),
          loader: createConversationLoader(params.id, config),
          meta: createConversationMeta(params.id, config)
        };
      })
    }),
    // Chat pages typically shouldn't be in sitemap, but we provide the option
    sitemap: async () => {
      return [];
    }
  });
};

exports.aiChatClientPlugin = aiChatClientPlugin;
