import { jsx } from "react/jsx-runtime";
import { forwardRef, memo, useMemo } from "react";
import { useGlobalElement, useLocalizedGlobalElement } from "../hooks/makeswift-api";
import { useDocument } from "../hooks/use-document";
import { DocumentCyclesContext, useDocumentCycles } from "../hooks/use-document-cycles";
import { FallbackComponent } from "../../../components/shared/FallbackComponent";
import { Element } from "./Element";
import { Document } from "./Document";
import { DisableRegisterElement } from "../hooks/use-disable-register-element";
import { useDocumentLocale } from "../hooks/use-document-context";
const ElementReference = memo(
  forwardRef(function ElementReference2({ elementReference }, ref) {
    const globalElement = useGlobalElement(elementReference.value);
    const locale = useDocumentLocale();
    const localizedGlobalElement = useLocalizedGlobalElement(locale, elementReference.value);
    const globalElementData = localizedGlobalElement?.data ?? globalElement?.data;
    const elementReferenceDocument = useDocument(elementReference.key);
    const documentKey = elementReference.key;
    const documentKeys = useDocumentCycles();
    const providedDocumentKeys = useMemo(
      () => [...documentKeys, documentKey],
      [documentKeys, documentKey]
    );
    if (globalElementData == null) {
      return /* @__PURE__ */ jsx(
        FallbackComponent,
        {
          ref,
          text: "This global component doesn't exist"
        }
      );
    }
    if (documentKeys.includes(documentKey)) {
      return /* @__PURE__ */ jsx(
        FallbackComponent,
        {
          ref,
          text: "This global component contains itself!"
        }
      );
    }
    return /* @__PURE__ */ jsx(DocumentCyclesContext.Provider, { value: providedDocumentKeys, children: elementReferenceDocument != null ? /* @__PURE__ */ jsx(Document, { document: elementReferenceDocument, ref }) : /* @__PURE__ */ jsx(DisableRegisterElement.Provider, { value: true, children: /* @__PURE__ */ jsx(Element, { element: globalElementData, ref }) }) });
  })
);
export {
  ElementReference
};
//# sourceMappingURL=ElementReference.js.map