import { useEffect, useMemo, useState } from "react";
import { useSitePagesFetchContext } from "./../../../site-pages/site-pages-fetch-context.js";
import { unreachable } from "./../../../uncreachable.js";
const areAllFetched = (fetchQuery, fetchState, loadMore) => fetchQuery === "" && fetchState.type === "ready" && !loadMore;
const search = (query, items) => items.filter((item) => item.title.toLowerCase().includes(query.trim().toLowerCase()));
const useSitePages = (pageType, itemPagePrefix) => {
  const [query, setQuery] = useState("");
  const [fetchQuery, setFetchQuery] = useState(query);
  const { fetchState, loadMore } = useSitePagesFetchContext(pageType, fetchQuery, itemPagePrefix);
  const items = useMemo(
    () => "items" in fetchState ? search(query, fetchState.items) : [],
    [fetchQuery, fetchState, !!loadMore, query]
  );
  useEffect(() => {
    const skipChange = fetchQuery === query || fetchState.type === "loading" || fetchQuery === "" && fetchState.type === "loading-error" || areAllFetched(fetchQuery, fetchState, loadMore);
    if (!skipChange) {
      setFetchQuery(query);
    }
  }, [fetchQuery, fetchState, !!loadMore, query]);
  const result = {
    items,
    query,
    setQuery
  };
  switch (fetchState.type) {
    case "loading":
    case "loading-more":
      return {
        ...result,
        areAllFetched: false,
        isLoading: true
      };
    case "loading-error":
      return {
        ...result,
        areAllFetched: false,
        error: fetchState.error,
        isLoading: false
      };
    case "ready":
      if (areAllFetched(fetchQuery, fetchState, loadMore)) {
        return {
          ...result,
          areAllFetched: true,
          hasMore: false,
          isLoading: false
        };
      } else if (loadMore) {
        return {
          ...result,
          areAllFetched: false,
          error: fetchState.error,
          hasMore: true,
          isLoading: false,
          loadMore
        };
      } else {
        return {
          ...result,
          areAllFetched: false,
          error: fetchState.error,
          hasMore: false,
          isLoading: false
        };
      }
    default:
      unreachable(fetchState);
      return {};
  }
};
export {
  useSitePages
};
//# sourceMappingURL=use-site-pages.js.map
