import { useState as y, useRef as m, useCallback as B, useEffect as D } from "react";
import { getMFObservableLoader as c, cleanUpMFInstance as R, setMFObservableLoader as J, getMFRenderFunction as K } from "../../helpers/mfWindowRegistry/mfWindowRegistry.js";
import { createObservableLoaderMF as N } from "../../helpers/createObservableLoaderMF/createObservableLoaderMF.js";
function X({
  activeHost: g,
  cache: a,
  createTelemetryContext: v,
  environmentIsLocalhost: F,
  hasValidLocalDebugPort: L,
  mountedScriptRef: t,
  networkOperation: M,
  prefix: r,
  requestedScript: s,
  requestedScriptRef: C,
  activeSwapRef: f,
  emitSwapFailedTelemetry: E,
  emitSwapStartedTelemetry: G
}) {
  const [j, o] = y("progress"), [k, O] = y(-1), u = m(0), l = m(null), A = m(null), P = B(() => {
    t.current.moduleId !== s.moduleId && f.current === null && G(
      t.current.moduleId,
      s.moduleId,
      r
    ), c(r, s.moduleId)?.tryAgain();
  }, [
    f,
    G,
    t,
    r,
    s.moduleId
  ]);
  return D(() => {
    const n = { ...s };
    let b = !0;
    u.current += 1;
    const i = u.current;
    l.current = null, A.current = null, O(-1), o("progress");
    const I = (e, d) => {
      !b || u.current !== i || (e === "complete" && (l.current = i), O(d), o(e));
    }, _ = typeof K(r, n.moduleId) == "function";
    if (!_ && !L)
      return E("unknown", "invalid_local_debug_port"), o("error"), () => {
        b = !1, c(r, n.moduleId)?.unsubscribe(
          I
        );
        const e = R(n, r, a);
        e && (console.error(e), o("error"));
      };
    if (_)
      l.current = i, o("complete");
    else {
      let e;
      const d = c(
        r,
        n.moduleId
      );
      d ? e = d : (e = N(
        g,
        n.scriptId,
        M,
        !F,
        {
          context: v(n.moduleId, r),
          loadSource: "script-injection"
        }
      ), J(r, n.moduleId, e)), e.subscribe(I);
    }
    const U = () => n.divContainerId === t.current.divContainerId, z = () => n.divContainerId === C.current.divContainerId;
    return () => {
      if (b = !1, c(r, n.moduleId)?.unsubscribe(
        I
      ), !U() && !z()) {
        const e = R(n, r, a);
        e && (console.error(e), o("error"));
      }
    };
  }, [
    g,
    a,
    v,
    E,
    F,
    L,
    t,
    M,
    r,
    s,
    C
  ]), {
    statusLoader: j,
    setStatusLoader: o,
    loadingProgress: k,
    tryAgainOnError: P,
    loadGeneration: u,
    completedGeneration: l,
    renderedGeneration: A
  };
}
export {
  X as useMFLifecycle
};
