'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const client = require('@btst/stack/plugins/client');
const yar = require('@btst/yar');
const plugins_cms_queryKeys = require('../../../../../../plugins/cms/query-keys.cjs');
const schemas = require('../schemas.cjs');

const PageListPageComponent = React.lazy(
  () => import('./components/pages/page-list-page.cjs').then((m) => ({
    default: m.PageListPage
  }))
);
const PageBuilderPageComponent = React.lazy(
  () => import('./components/pages/page-builder-page.cjs').then((m) => ({
    default: m.PageBuilderPage
  }))
);
function createPageListLoader(config) {
  return async () => {
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, headers, hooks } = config;
      const typeSlug = schemas.UI_BUILDER_TYPE_SLUG;
      const context = {
        path: "/ui-builder",
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadPageList) {
          const canLoad = await hooks.beforeLoadPageList(context);
          if (!canLoad) {
            throw new Error("Load prevented by beforeLoadPageList hook");
          }
        }
        const client$1 = client.createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = plugins_cms_queryKeys.createCMSQueryKeys(client$1, headers);
        const limit = 20;
        const listQuery = queries.cmsContent.list({
          typeSlug,
          limit,
          offset: 0
        });
        await queryClient.prefetchInfiniteQuery({
          queryKey: [...listQuery.queryKey, "ui-builder"],
          queryFn: async ({ pageParam = 0 }) => {
            const response = await client$1("/content/:typeSlug", {
              method: "GET",
              params: { typeSlug },
              query: { limit, offset: pageParam },
              headers
            });
            if (typeof response === "object" && response !== null && "error" in response && response.error) {
              throw new Error(String(response.error));
            }
            return response.data;
          },
          initialPageParam: 0
        });
        if (hooks?.afterLoadPageList) {
          await hooks.afterLoadPageList(context);
        }
        const queryState = queryClient.getQueryState([
          ...listQuery.queryKey,
          "ui-builder"
        ]);
        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 createPageBuilderLoader(id, config) {
  return async () => {
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, headers, hooks } = config;
      const typeSlug = schemas.UI_BUILDER_TYPE_SLUG;
      const context = {
        path: id ? `/ui-builder/${id}/edit` : "/ui-builder/new",
        params: id ? { id } : {},
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadPageBuilder) {
          const canLoad = await hooks.beforeLoadPageBuilder(id, context);
          if (!canLoad) {
            throw new Error("Load prevented by beforeLoadPageBuilder hook");
          }
        }
        const client$1 = client.createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = plugins_cms_queryKeys.createCMSQueryKeys(client$1, headers);
        if (id) {
          await queryClient.prefetchQuery(
            queries.cmsContent.detail(typeSlug, id)
          );
        }
        if (hooks?.afterLoadPageBuilder) {
          await hooks.afterLoadPageBuilder(id, context);
        }
        if (id) {
          const queryState = queryClient.getQueryState(
            queries.cmsContent.detail(typeSlug, id).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 createPageListMeta() {
  return () => {
    const title = "UI Builder Pages";
    return [
      { title },
      { name: "title", content: title },
      { name: "robots", content: "noindex" }
    ];
  };
}
function createPageBuilderMeta(id, config) {
  return () => {
    const { queryClient, apiBasePath, apiBaseURL, headers } = config;
    const typeSlug = schemas.UI_BUILDER_TYPE_SLUG;
    let pageSlug = "";
    if (id) {
      const client$1 = client.createApiClient({
        baseURL: apiBaseURL,
        basePath: apiBasePath
      });
      const queries = plugins_cms_queryKeys.createCMSQueryKeys(client$1, headers);
      const page = queryClient.getQueryData(
        queries.cmsContent.detail(typeSlug, id).queryKey
      );
      pageSlug = page?.slug || "";
    }
    const title = id ? `Edit ${pageSlug || "Page"}` : "New Page";
    return [
      { title },
      { name: "title", content: title },
      { name: "robots", content: "noindex" }
    ];
  };
}
const uiBuilderClientPlugin = (config) => client.defineClientPlugin({
  name: "ui-builder",
  routes: () => ({
    pageList: yar.createRoute("/ui-builder", () => ({
      PageComponent: () => /* @__PURE__ */ jsxRuntime.jsx(PageListPageComponent, {}),
      loader: createPageListLoader(config),
      meta: createPageListMeta()
    })),
    newPage: yar.createRoute("/ui-builder/new", () => ({
      PageComponent: () => /* @__PURE__ */ jsxRuntime.jsx(PageBuilderPageComponent, {}),
      loader: createPageBuilderLoader(void 0, config),
      meta: createPageBuilderMeta(void 0, config)
    })),
    editPage: yar.createRoute("/ui-builder/:id/edit", ({ params }) => ({
      PageComponent: () => /* @__PURE__ */ jsxRuntime.jsx(PageBuilderPageComponent, { id: params.id }),
      loader: createPageBuilderLoader(params.id, config),
      meta: createPageBuilderMeta(params.id, config)
    }))
  }),
  sitemap: async () => {
    return [];
  }
});

exports.uiBuilderClientPlugin = uiBuilderClientPlugin;
