"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');

const PageAIAPIContext = React.createContext(null);
const PageAIVersionContext = React.createContext(0);
function PageAIContextProvider({
  children
}) {
  const registrationsRef = React.useRef(/* @__PURE__ */ new Map());
  const insertionOrderRef = React.useRef([]);
  const [version, setVersion] = React.useState(0);
  const bumpVersion = React.useCallback(() => setVersion((v) => v + 1), []);
  const register = React.useCallback(
    (id, config) => {
      registrationsRef.current.set(id, config);
      insertionOrderRef.current = insertionOrderRef.current.filter(
        (k) => k !== id
      );
      insertionOrderRef.current.push(id);
      bumpVersion();
    },
    [bumpVersion]
  );
  const unregister = React.useCallback(
    (id) => {
      registrationsRef.current.delete(id);
      insertionOrderRef.current = insertionOrderRef.current.filter(
        (k) => k !== id
      );
      bumpVersion();
    },
    [bumpVersion]
  );
  const getActive = React.useCallback(() => {
    const order = insertionOrderRef.current;
    if (order.length === 0) return null;
    const lastId = order[order.length - 1];
    if (!lastId) return null;
    return registrationsRef.current.get(lastId) ?? null;
  }, []);
  const api = React.useMemo(
    () => ({ register, unregister, getActive }),
    [register, unregister, getActive]
  );
  return /* @__PURE__ */ jsxRuntime.jsx(PageAIAPIContext.Provider, { value: api, children: /* @__PURE__ */ jsxRuntime.jsx(PageAIVersionContext.Provider, { value: version, children }) });
}
function useRegisterPageAIContext(config) {
  const ctx = React.useContext(PageAIAPIContext);
  const id = React.useId();
  const configRef = React.useRef(config);
  configRef.current = config;
  React.useEffect(() => {
    if (!ctx || !configRef.current) return;
    ctx.register(id, {
      get routeName() {
        return configRef.current?.routeName ?? "";
      },
      get pageDescription() {
        return configRef.current?.pageDescription ?? "";
      },
      get suggestions() {
        return configRef.current?.suggestions;
      },
      get clientTools() {
        return configRef.current?.clientTools;
      }
    });
    return () => {
      ctx.unregister(id);
    };
  }, [
    ctx,
    id,
    config === null,
    config?.routeName,
    config?.pageDescription,
    JSON.stringify(config?.suggestions)
  ]);
}
function usePageAIContext() {
  React.useContext(PageAIVersionContext);
  const ctx = React.useContext(PageAIAPIContext);
  if (!ctx) return null;
  return ctx.getActive();
}

exports.PageAIContextProvider = PageAIContextProvider;
exports.usePageAIContext = usePageAIContext;
exports.useRegisterPageAIContext = useRegisterPageAIContext;
