"use client";
/**
 * Stable event callback: returns a function whose identity never changes but always
 * invokes the latest `callback`. Avoids stale closures without re‑creating handlers.
 *
 * Why not `useCallback`? Its identity depends on a deps array:
 * - omit deps -> stale; include deps -> new function each render.
 * - This hook decouples identity from freshness.
 *
 * How it works: a single stable "trampoline" function delegates to a mutable ref. The current
 * `callback` is promoted from `next` in an insertion/layout phase effect so abandoned concurrent
 * renders cannot leak outdated handlers.
 *
 * Guarantees: stable identity; latest logic executed; no calls from uncommitted renders; dev
 * error if invoked during render; safe when `callback` is undefined (no-op).
 *
 * This hook is a more permissive version of React 19.2's `React.useEffectEvent` in that it can be passed through contexts and called in event handler props, not just effects.
 */
import React, { useLayoutEffect } from "react";
import { useRefWithInit } from "./useRefWithInit.js";
/* https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379 */
const useInsertionEffect = React[`useInsertionEffect${Math.random().toFixed(1)}`.slice(0, -3)];
const useSafeInsertionEffect = 
// React 17 doesn't have useInsertionEffect.
useInsertionEffect &&
    // Preact replaces useInsertionEffect with useLayoutEffect and fires too late.
    useInsertionEffect !== useLayoutEffect
    ? useInsertionEffect
    : (fn) => fn();
function useEventCallback(callback) {
    const stable = useRefWithInit(createStableCallback).current;
    stable.next = callback; // eslint-disable-line react-hooks/immutability
    useSafeInsertionEffect(stable.effect);
    return stable.trampoline;
}
function createStableCallback() {
    const stable = {
        next: undefined,
        callback: assertNotCalled,
        trampoline: (...args) => { var _a; return (_a = stable.callback) === null || _a === void 0 ? void 0 : _a.call(stable, ...args); },
        effect: () => {
            stable.callback = stable.next;
        },
    };
    return stable;
}
function assertNotCalled() {
    if (process.env.NODE_ENV !== "production") {
        throw new Error("Aksel: Cannot call an event handler while rendering.");
    }
}
export { useEventCallback };
//# sourceMappingURL=useEventCallback.js.map