"use client";
import { jsx } from 'react/jsx-runtime';
import { createContext, useRef, useState, useCallback, useMemo, useContext, useId, useEffect } from 'react';

const PageAIAPIContext = createContext(null);
const PageAIVersionContext = createContext(0);
function PageAIContextProvider({
  children
}) {
  const registrationsRef = useRef(/* @__PURE__ */ new Map());
  const insertionOrderRef = useRef([]);
  const [version, setVersion] = useState(0);
  const bumpVersion = useCallback(() => setVersion((v) => v + 1), []);
  const register = useCallback(
    (id, config) => {
      registrationsRef.current.set(id, config);
      insertionOrderRef.current = insertionOrderRef.current.filter(
        (k) => k !== id
      );
      insertionOrderRef.current.push(id);
      bumpVersion();
    },
    [bumpVersion]
  );
  const unregister = useCallback(
    (id) => {
      registrationsRef.current.delete(id);
      insertionOrderRef.current = insertionOrderRef.current.filter(
        (k) => k !== id
      );
      bumpVersion();
    },
    [bumpVersion]
  );
  const getActive = 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 = useMemo(
    () => ({ register, unregister, getActive }),
    [register, unregister, getActive]
  );
  return /* @__PURE__ */ jsx(PageAIAPIContext.Provider, { value: api, children: /* @__PURE__ */ jsx(PageAIVersionContext.Provider, { value: version, children }) });
}
function useRegisterPageAIContext(config) {
  const ctx = useContext(PageAIAPIContext);
  const id = useId();
  const configRef = useRef(config);
  configRef.current = config;
  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() {
  useContext(PageAIVersionContext);
  const ctx = useContext(PageAIAPIContext);
  if (!ctx) return null;
  return ctx.getActive();
}

export { PageAIContextProvider, usePageAIContext, useRegisterPageAIContext };
