'use client';
import { cache } from '@keystar/ui/style';
import { VoussoirProvider } from '@keystar/ui/core';
import { useServerInsertedHTML } from 'next/navigation';
import { useRef } from 'react';
import { U as UniversalNextLink } from './UniversalNextLink-5d3a16d7.esm.js';
import { ColorSchemeProvider, useRootColorScheme } from './useRootColorScheme-750bd034.esm.js';
import { jsx } from 'react/jsx-runtime';
import 'next/link';
import '@keystar/ui/link';

cache.compat = true;
function NextRootProvider(props) {
  return /*#__PURE__*/jsx(ColorSchemeProvider, {
    children: /*#__PURE__*/jsx(InnerProvider, {
      ...props
    })
  });
}
const insertedKeys = Object.keys(cache.inserted);
const prevInsert = cache.insert;
cache.insert = function () {
  const serialized = arguments.length <= 1 ? undefined : arguments[1];
  if (cache.inserted[serialized.name] === undefined) {
    insertedKeys.push(serialized.name);
  }
  return prevInsert(...arguments);
};
function InnerProvider(props) {
  let lastIndexRef = useRef(0);
  let {
    colorScheme
  } = useRootColorScheme();
  useServerInsertedHTML(() => {
    const names = insertedKeys.slice(lastIndexRef.current);
    lastIndexRef.current = insertedKeys.length;
    if (names.length === 0) return null;
    let styles = '';
    for (const name of names) {
      styles += cache.inserted[name];
    }
    return /*#__PURE__*/jsx("style", {
      "data-emotion": `${cache.key} ${names.join(' ')}`,
      dangerouslySetInnerHTML: {
        __html: styles
      }
    }, Math.random().toString(36));
  });
  return /*#__PURE__*/jsx(VoussoirProvider, {
    ...props,
    UNSAFE_className: props.fontClassName,
    colorScheme: colorScheme,
    elementType: "html",
    linkComponent: UniversalNextLink
  });
}

export { NextRootProvider };
