'use strict';

const jsxRuntime = require('react/jsx-runtime');
const client = require('@btst/stack/plugins/client');
const yar = require('@btst/yar');
const plugins_kanban_queryKeys = require('../../../../../../plugins/kanban/query-keys.cjs');
const boardsListPage = require('./components/pages/boards-list-page.cjs');
const newBoardPage = require('./components/pages/new-board-page.cjs');
const boardPage = require('./components/pages/board-page.cjs');

function createBoardsLoader(config) {
  return async () => {
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, hooks, headers } = config;
      const context = {
        path: "/kanban",
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadBoards) {
          const canLoad = await hooks.beforeLoadBoards(context);
          if (!canLoad) {
            throw new Error("Load prevented by beforeLoadBoards hook");
          }
        }
        const client$1 = client.createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = plugins_kanban_queryKeys.createKanbanQueryKeys(client$1, headers);
        const listQuery = queries.boards.list({});
        await queryClient.prefetchQuery(listQuery);
        if (hooks?.afterLoadBoards) {
          const boards = queryClient.getQueryData(
            listQuery.queryKey
          );
          const canContinue = await hooks.afterLoadBoards(
            boards || null,
            context
          );
          if (canContinue === false) {
            throw new Error("Load prevented by afterLoadBoards 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 createBoardLoader(boardId, config) {
  return async () => {
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, hooks, headers } = config;
      const context = {
        path: `/kanban/${boardId}`,
        params: { boardId },
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadBoard) {
          const canLoad = await hooks.beforeLoadBoard(boardId, context);
          if (!canLoad) {
            throw new Error("Load prevented by beforeLoadBoard hook");
          }
        }
        const client$1 = client.createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = plugins_kanban_queryKeys.createKanbanQueryKeys(client$1, headers);
        const boardQuery = queries.boards.detail(boardId);
        await queryClient.prefetchQuery(boardQuery);
        if (hooks?.afterLoadBoard) {
          const board = queryClient.getQueryData(
            boardQuery.queryKey
          );
          const canContinue = await hooks.afterLoadBoard(
            board || null,
            boardId,
            context
          );
          if (canContinue === false) {
            throw new Error("Load prevented by afterLoadBoard hook");
          }
        }
        const queryState = queryClient.getQueryState(boardQuery.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 createNewBoardLoader(config) {
  return async () => {
    if (typeof window === "undefined") {
      const { apiBasePath, apiBaseURL, hooks, headers } = config;
      const context = {
        path: "/kanban/new",
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadNewBoard) {
          const canLoad = await hooks.beforeLoadNewBoard(context);
          if (!canLoad) {
            throw new Error("Load prevented by beforeLoadNewBoard hook");
          }
        }
        if (hooks?.afterLoadNewBoard) {
          const canContinue = await hooks.afterLoadNewBoard(context);
          if (canContinue === false) {
            throw new Error("Load prevented by afterLoadNewBoard hook");
          }
        }
      } catch (error) {
        if (hooks?.onLoadError) {
          await hooks.onLoadError(error, context);
        }
      }
    }
  };
}
function createBoardsListMeta(config) {
  return () => {
    const { siteBaseURL, siteBasePath, seo } = config;
    const fullUrl = `${siteBaseURL}${siteBasePath}/kanban`;
    const title = "Kanban Boards";
    const description = seo?.description || "Manage your projects with kanban boards";
    return [
      { title },
      { name: "title", content: title },
      { name: "description", content: description },
      { name: "robots", content: "index, follow" },
      { 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 }] : [],
      { name: "twitter:card", content: "summary" },
      { name: "twitter:title", content: title },
      { name: "twitter:description", content: description }
    ];
  };
}
function createBoardMeta(boardId, config) {
  return () => {
    const {
      queryClient,
      apiBaseURL,
      apiBasePath,
      siteBaseURL,
      siteBasePath,
      seo
    } = config;
    const queries = plugins_kanban_queryKeys.createKanbanQueryKeys(
      client.createApiClient({
        baseURL: apiBaseURL,
        basePath: apiBasePath
      })
    );
    const board = queryClient.getQueryData(
      queries.boards.detail(boardId).queryKey
    );
    if (!board) {
      return [
        { title: "Board Not Found" },
        { name: "robots", content: "noindex" }
      ];
    }
    const fullUrl = `${siteBaseURL}${siteBasePath}/kanban/${board.id}`;
    const title = board.name;
    const description = board.description || `Kanban board: ${board.name}`;
    return [
      { title },
      { name: "title", content: title },
      { name: "description", content: description },
      { name: "robots", content: "index, follow" },
      { 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?.defaultImage ? [{ property: "og:image", content: seo.defaultImage }] : [],
      { name: "twitter:card", content: "summary" },
      { name: "twitter:title", content: title }
    ];
  };
}
function createNewBoardMeta(config) {
  return () => {
    const { siteBaseURL, siteBasePath } = config;
    const fullUrl = `${siteBaseURL}${siteBasePath}/kanban/new`;
    const title = "Create New Board";
    return [
      { title },
      { name: "title", content: title },
      { name: "description", content: "Create a new kanban board" },
      { name: "robots", content: "noindex, nofollow" },
      { property: "og:type", content: "website" },
      { property: "og:title", content: title },
      { property: "og:url", content: fullUrl },
      { name: "twitter:card", content: "summary" },
      { name: "twitter:title", content: title }
    ];
  };
}
const kanbanClientPlugin = (config) => client.defineClientPlugin({
  name: "kanban",
  routes: () => ({
    boards: yar.createRoute("/kanban", () => {
      return {
        PageComponent: () => /* @__PURE__ */ jsxRuntime.jsx(boardsListPage.BoardsListPageComponent, {}),
        loader: createBoardsLoader(config),
        meta: createBoardsListMeta(config)
      };
    }),
    newBoard: yar.createRoute("/kanban/new", () => {
      return {
        PageComponent: newBoardPage.NewBoardPageComponent,
        loader: createNewBoardLoader(config),
        meta: createNewBoardMeta(config)
      };
    }),
    board: yar.createRoute("/kanban/:boardId", ({ params: { boardId } }) => {
      return {
        PageComponent: () => /* @__PURE__ */ jsxRuntime.jsx(boardPage.BoardPageComponent, { boardId }),
        loader: createBoardLoader(boardId, config),
        meta: createBoardMeta(boardId, config)
      };
    })
  }),
  sitemap: async () => {
    const origin = `${config.siteBaseURL}${config.siteBasePath}`;
    const indexUrl = `${origin}/kanban`;
    const client$1 = client.createApiClient({
      baseURL: config.apiBaseURL,
      basePath: config.apiBasePath
    });
    let boards = [];
    try {
      const res = await client$1("/boards", {
        method: "GET",
        query: { limit: 100 }
      });
      boards = res.data ?? [];
    } catch {
    }
    const entries = [
      {
        url: indexUrl,
        lastModified: /* @__PURE__ */ new Date(),
        changeFrequency: "daily",
        priority: 0.7
      },
      ...boards.map((b) => ({
        url: `${origin}/kanban/${b.id}`,
        lastModified: b.updatedAt ? new Date(b.updatedAt) : void 0,
        changeFrequency: "weekly",
        priority: 0.6
      }))
    ];
    return entries;
  }
});

exports.kanbanClientPlugin = kanbanClientPlugin;
