'use client';
import { jsxs, jsx } from 'react/jsx-runtime';
import { getDocument, getWindow } from '@zag-js/dom-query';
import { useState, useMemo } from 'react';
import { runIfFn } from '../../utils/run-if-fn.js';
import { EnvironmentContextProvider } from './use-environment-context.js';

const EnvironmentProvider = (props) => {
  const { value, children } = props;
  const [spanRef, setSpanRef] = useState();
  const getRootNode = useMemo(() => {
    return () => runIfFn(value) ?? spanRef?.getRootNode() ?? document;
  }, [value, spanRef]);
  const environment = useMemo(
    () => ({
      getRootNode,
      getWindow: () => getWindow(getRootNode()),
      getDocument: () => getDocument(getRootNode())
    }),
    [getRootNode]
  );
  return /* @__PURE__ */ jsxs(EnvironmentContextProvider, { value: environment, children: [
    children,
    !value && /* @__PURE__ */ jsx("span", { hidden: true, ref: setSpanRef })
  ] });
};

export { EnvironmentProvider };
