"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var site_pages_fetch_context_exports = {};
__export(site_pages_fetch_context_exports, {
  SitePagesFetchContext: () => SitePagesFetchContext,
  SitePagesFetchContextProvider: () => SitePagesFetchContextProvider,
  useSitePagesFetchContext: () => useSitePagesFetchContext
});
module.exports = __toCommonJS(site_pages_fetch_context_exports);
var import_react = __toESM(require("react"));
var import_use_fetch_site_pages = require("./site-pages-fetch-context/use-fetch-site-pages.js");
var import_types = require("./types.js");
const expireTime = 6e4;
const pagingLimit = 100;
const getCacheId = (pageType, query, itemPagePrefix) => itemPagePrefix ? itemPagePrefix : `${pageType} ${query.trim()}`.trim();
const SitePagesFetchContext = (0, import_react.createContext)({
  cache: {},
  expireCache: () => {
  },
  initialFetch: () => {
  },
  loadMore: () => {
  },
  preload: () => {
  },
  sitePublished: null
});
const SitePagesFetchContextProvider = ({ children }) => {
  const fetchSitePages = (0, import_use_fetch_site_pages.useFetchSitePages)();
  const [cache, setCache] = (0, import_react.useState)({});
  const [expireTimeout, setExpireTimeout] = (0, import_react.useState)(void 0);
  const [sitePublished, setSitePublished] = (0, import_react.useState)(null);
  const expireCache = (0, import_react.useCallback)(() => {
    setExpireTimeout((oldTimeout) => {
      clearTimeout(oldTimeout);
      return setTimeout(() => setCache({}), expireTime);
    });
  }, []);
  const updateState = (0, import_react.useCallback)(
    (pageType, query, fn, itemPagePrefix) => {
      setCache((cache2) => {
        const cacheId = getCacheId(pageType, query, itemPagePrefix);
        const oldState = cache2[cacheId];
        const newState = fn(oldState);
        return newState && newState !== oldState ? { ...cache2, [cacheId]: newState } : cache2;
      });
    },
    []
  );
  const initialFetch = (0, import_react.useCallback)(
    (pageType, query, itemPagePrefix) => {
      const initialState = { type: "loading" };
      clearTimeout(expireTimeout);
      queueMicrotask(
        () => updateState(
          pageType,
          query,
          (oldState) => {
            if (oldState) {
              return;
            }
            fetchSitePages(pageType, {
              query: query.trim(),
              itemPagePrefix,
              paging: { limit: pagingLimit }
            }).then((result) => {
              updateState(
                pageType,
                query,
                (oldState2) => oldState2 === initialState && {
                  type: "ready",
                  items: result.items,
                  cursor: result.paging?.cursors?.next
                },
                itemPagePrefix
              );
              setSitePublished(
                (sitePublished2) => "published" in result ? result.published : sitePublished2
              );
            }).catch(
              (error) => updateState(
                pageType,
                query,
                (oldState2) => oldState2 === initialState && {
                  type: "loading-error",
                  error
                }
              )
            );
            return initialState;
          },
          itemPagePrefix
        )
      );
      return initialState;
    },
    [fetchSitePages, updateState]
  );
  const loadMore = (0, import_react.useCallback)(
    (pageType, query, itemPagePrefix) => {
      clearTimeout(expireTimeout);
      updateState(
        pageType,
        query,
        (oldState) => {
          if (!oldState || oldState.type !== "ready" || !oldState.cursor) {
            return;
          }
          const loadingState = {
            type: "loading-more",
            items: oldState.items,
            cursor: oldState.cursor
          };
          fetchSitePages(pageType, {
            query: query.trim(),
            itemPagePrefix,
            paging: { limit: pagingLimit, cursor: oldState.cursor }
          }).then((result) => {
            updateState(
              pageType,
              query,
              (oldState2) => oldState2 === loadingState && {
                type: "ready",
                items: [...oldState2.items, ...result.items],
                cursor: result.paging.cursors?.next
              },
              itemPagePrefix
            );
            setSitePublished(
              (sitePublished2) => "published" in result ? result.published : sitePublished2
            );
          }).catch(
            (error) => updateState(
              pageType,
              query,
              (oldState2) => oldState2 === loadingState && {
                type: "ready",
                error,
                cursor: oldState2.cursor,
                items: oldState2.items
              }
            )
          );
          return loadingState;
        },
        itemPagePrefix
      );
    },
    [fetchSitePages, updateState]
  );
  const preload = (0, import_react.useCallback)(() => {
    setExpireTimeout((oldTimeout) => {
      clearTimeout(oldTimeout);
      return void 0;
    });
    for (const pageType of Object.values(import_types.sitePagesPageType)) {
      initialFetch(pageType, "");
    }
  }, [initialFetch]);
  const value = (0, import_react.useMemo)(
    () => ({
      cache,
      expireCache,
      initialFetch,
      loadMore,
      preload,
      sitePublished
    }),
    [cache, expireCache, initialFetch, loadMore, preload, sitePublished]
  );
  return /* @__PURE__ */ import_react.default.createElement(SitePagesFetchContext.Provider, { children, value });
};
const useSitePagesFetchContext = (pageType, query, itemPagePrefix) => {
  const value = (0, import_react.useContext)(SitePagesFetchContext);
  const cacheId = getCacheId(pageType, query, itemPagePrefix);
  const fetchState = value.cache[cacheId] || value.initialFetch(pageType, query, itemPagePrefix);
  const loadMore = (0, import_react.useMemo)(
    () => fetchState && fetchState.type === "ready" && fetchState.cursor ? () => value.loadMore(pageType, query, itemPagePrefix) : void 0,
    [fetchState, value.loadMore]
  );
  return { fetchState, loadMore };
};
//# sourceMappingURL=site-pages-fetch-context.js.map
