import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { SnippetLocation } from "../../../../client";
import deepEqual from "../../../../utils/deepEqual";
import { useIsInBuilder } from "../../hooks/use-is-in-builder";
import { useMakeswiftHostApiClient } from "../../host-api-client";
const filterUsedSnippetProperties = ({
  code,
  builderEnabled,
  liveEnabled,
  location,
  cleanup
}) => ({
  code,
  builderEnabled,
  liveEnabled,
  location,
  cleanup
});
function usePageSnippets({ page }) {
  const isInBuilder = useIsInBuilder();
  const [snippets, setSnippets] = useState(page.snippets);
  const cachedPage = useCachedPage(isInBuilder ? page.id : null);
  useEffect(() => {
    if (cachedPage == null)
      return;
    const oldSnippets = snippets.map(filterUsedSnippetProperties);
    const newSnippets = cachedPage.snippets.map(filterUsedSnippetProperties);
    if (deepEqual(newSnippets, oldSnippets))
      return;
    setSnippets(cachedPage.snippets);
  }, [cachedPage]);
  const filteredSnippets = useMemo(
    () => snippets.filter((snippet) => isInBuilder ? snippet.builderEnabled : snippet.liveEnabled),
    [snippets, isInBuilder]
  );
  const headSnippets = useMemo(
    () => filteredSnippets.filter((snippet) => snippet.location === SnippetLocation.Head),
    [filteredSnippets]
  );
  const bodySnippets = useMemo(
    () => filteredSnippets.filter((snippet) => snippet.location === SnippetLocation.Body),
    [filteredSnippets]
  );
  return { headSnippets, bodySnippets };
}
function useCachedPage(pageId) {
  const client = useMakeswiftHostApiClient();
  const getSnapshot = () => pageId == null ? null : client.readPage(pageId);
  const page = useSyncExternalStore(client.subscribe, getSnapshot, getSnapshot);
  return page;
}
export {
  usePageSnippets
};
//# sourceMappingURL=use-page-snippets.js.map