import { useState as q, useRef as d, useCallback as $, useEffect as C } from "react";
import { buildMFInstanceIds as F } from "../../helpers/mfRuntimeUtils/mfRuntimeUtils.js";
import { emitFrontendTelemetry as b } from "../../helpers/emitFrontendTelemetry/emitFrontendTelemetry.js";
import { cleanUpMFInstance as g } from "../../helpers/mfWindowRegistry/mfWindowRegistry.js";
function U({
  activeSwapRef: o,
  cache: a,
  createTelemetryContext: m,
  emitAbandonedLoadTelemetry: I,
  emitSwapFailedTelemetry: p,
  emitSwapStartedTelemetry: M,
  moduleId: r,
  prefix: t,
  reportLoaderError: f
}) {
  const [e, _] = q(() => F(t, r)), [s, R] = q(e), n = d(e), u = d(s), l = d({ prefix: t, moduleId: r }), i = d(null);
  n.current = e, u.current = s;
  const v = $(() => {
    if (n.current.divContainerId !== u.current.divContainerId) {
      if (n.current.moduleId !== u.current.moduleId) {
        const c = o.current;
        b({
          type: "module_swap_succeeded",
          context: m(u.current.moduleId, t),
          fromModuleId: n.current.moduleId,
          toModuleId: u.current.moduleId,
          totalDurationMs: c === null ? 0 : performance.now() - c.startedAt
        }), o.current = null;
      }
      i.current = n.current, _(u.current);
    }
  }, [o, m, t]);
  return C(() => {
    l.current.moduleId === r && l.current.prefix === t || (I(u.current, "swap_race"), l.current = { prefix: t, moduleId: r }, n.current.moduleId !== r && (o.current && p("swap_race"), M(n.current.moduleId, r, t)), R(F(t, r)));
  }, [
    o,
    I,
    p,
    M,
    r,
    t
  ]), C(() => {
    const c = i.current;
    if (!c)
      return;
    i.current = null;
    const S = g(c, t, a);
    S && f(
      `MFLoader cleanup failed for ${t}/${c.moduleId}`,
      S
    );
  }, [a, e, t, f]), {
    mountedScript: e,
    requestedScript: s,
    isSwappingModule: e.divContainerId !== s.divContainerId,
    mountedScriptRef: n,
    requestedScriptRef: u,
    promoteRequestedScript: v
  };
}
export {
  U as useMFSwap
};
