import { jsx } from 'react/jsx-runtime';
import { defineClientPlugin, createApiClient, runClientHookWithShim, isConnectionError } from '@btst/stack/plugins/client';
import { createRoute } from '@btst/yar';
import { createKanbanQueryKeys } from '../../../../../../plugins/kanban/query-keys.mjs';
import { BoardsListPageComponent } from './components/pages/boards-list-page.mjs';
import { NewBoardPageComponent } from './components/pages/new-board-page.mjs';
import { BoardPageComponent } from './components/pages/board-page.mjs';

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) {
          await runClientHookWithShim(
            () => hooks.beforeLoadBoards(context),
            "Load prevented by beforeLoadBoards hook"
          );
        }
        const client = createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = createKanbanQueryKeys(client, headers);
        const listQuery = queries.boards.list({});
        await queryClient.prefetchQuery(listQuery);
        if (hooks?.afterLoadBoards) {
          const boards = queryClient.getQueryData(
            listQuery.queryKey
          );
          await runClientHookWithShim(
            () => hooks.afterLoadBoards(boards || null, context),
            "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 (isConnectionError(error)) {
          console.warn(
            "[btst/kanban] route.loader() failed \u2014 no server running at build time. Use myStack.api.kanban.prefetchForRoute() for SSG data prefetching."
          );
        }
        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) {
          await runClientHookWithShim(
            () => hooks.beforeLoadBoard(boardId, context),
            "Load prevented by beforeLoadBoard hook"
          );
        }
        const client = createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = createKanbanQueryKeys(client, headers);
        const boardQuery = queries.boards.detail(boardId);
        await queryClient.prefetchQuery(boardQuery);
        if (hooks?.afterLoadBoard) {
          const board = queryClient.getQueryData(
            boardQuery.queryKey
          );
          await runClientHookWithShim(
            () => hooks.afterLoadBoard(board || null, boardId, context),
            "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 (isConnectionError(error)) {
          console.warn(
            "[btst/kanban] route.loader() failed \u2014 no server running at build time. Use myStack.api.kanban.prefetchForRoute() for SSG data prefetching."
          );
        }
        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) {
          await runClientHookWithShim(
            () => hooks.beforeLoadNewBoard(context),
            "Load prevented by beforeLoadNewBoard hook"
          );
        }
        if (hooks?.afterLoadNewBoard) {
          await runClientHookWithShim(
            () => hooks.afterLoadNewBoard(context),
            "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 = createKanbanQueryKeys(
      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) => defineClientPlugin({
  name: "kanban",
  routes: () => ({
    boards: createRoute("/kanban", () => {
      return {
        PageComponent: () => /* @__PURE__ */ jsx(BoardsListPageComponent, {}),
        loader: createBoardsLoader(config),
        meta: createBoardsListMeta(config)
      };
    }),
    newBoard: createRoute("/kanban/new", () => {
      return {
        PageComponent: NewBoardPageComponent,
        loader: createNewBoardLoader(config),
        meta: createNewBoardMeta(config)
      };
    }),
    board: createRoute("/kanban/:boardId", ({ params: { boardId } }) => {
      return {
        PageComponent: () => /* @__PURE__ */ jsx(BoardPageComponent, { boardId }),
        loader: createBoardLoader(boardId, config),
        meta: createBoardMeta(boardId, config)
      };
    })
  }),
  sitemap: async () => {
    const origin = `${config.siteBaseURL}${config.siteBasePath}`;
    const indexUrl = `${origin}/kanban`;
    const client = createApiClient({
      baseURL: config.apiBaseURL,
      basePath: config.apiBasePath
    });
    let boards = [];
    try {
      const res = await client("/boards", {
        method: "GET",
        query: { limit: 100 }
      });
      boards = res.data?.items ?? [];
    } 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;
  }
});

export { kanbanClientPlugin };
