'use strict';
'use client';
import { c } from 'react/compiler-runtime';
import { jsx } from 'react/jsx-runtime';
import { createContext, useRef, useContext } from 'react';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", {
  value,
  configurable: true
});
const ElementIdContext = createContext(void 0);
function ElementIdProvider({
  children
}) {
  const registryRef = useRef(void 0);
  registryRef.current ??= /* @__PURE__ */new Map();
  return /* @__PURE__ */jsx(ElementIdContext.Provider, {
    value: registryRef.current,
    children
  });
}
__name(ElementIdProvider, "ElementIdProvider");
function useElementIdFactory(prefix) {
  const $ = c(3);
  const registry = useContext(ElementIdContext);
  if (!registry) {
    return void 0;
  }
  if (!registry.has(prefix)) {
    registry.set(prefix, createElementIdFactory());
  }
  let t0;
  if ($[0] !== prefix || $[1] !== registry) {
    t0 = registry.get(prefix);
    $[0] = prefix;
    $[1] = registry;
    $[2] = t0;
  } else {
    t0 = $[2];
  }
  return t0;
}
__name(useElementIdFactory, "useElementIdFactory");
function createElementIdFactory() {
  let nextAvailableIndex = 0;
  const freedIndices = [];
  const reactIdToIndexMap = /* @__PURE__ */new Map();
  return {
    /**
     * Maps a React useId() string to a stable sequential index (0, 1, 2...).
     * This prevents ID shifting when other components are added/removed from the page.
     */
    getMappedIndex(reactId) {
      if (reactIdToIndexMap.has(reactId)) {
        return reactIdToIndexMap.get(reactId);
      }
      let index;
      if (freedIndices.length > 0) {
        index = freedIndices.shift();
      } else {
        index = nextAvailableIndex++;
      }
      reactIdToIndexMap.set(reactId, index);
      return index;
    },
    releaseIndex(index, reactId) {
      if (reactId) {
        reactIdToIndexMap.delete(reactId);
      }
      if (freedIndices.includes(index)) {
        return;
      }
      let low = 0;
      let high = freedIndices.length;
      while (low < high) {
        const mid = low + high >>> 1;
        if (freedIndices[mid] < index) {
          low = mid + 1;
        } else {
          high = mid;
        }
      }
      freedIndices.splice(low, 0, index);
    },
    reset() {
      nextAvailableIndex = 0;
      freedIndices.length = 0;
      reactIdToIndexMap.clear();
    },
    getCurrentIndex() {
      return nextAvailableIndex;
    }
  };
}
__name(createElementIdFactory, "createElementIdFactory");

export { ElementIdProvider, useElementIdFactory };
