import { BLOCKLET_SERVICE_PATH_PREFIX as k } from "@arcblock/did-connect-react/lib/constant";
import { useState as b, useRef as C, useMemo as h, useEffect as I } from "react";
import { joinURL as w } from "ufo";
const c = (e) => typeof e == "string" ? new Set(e.split(";;")) : new Set(e);
function y({ did: e, onInstalled: u, onError: f }) {
  const o = Array.isArray(e) ? e.join(";;") : e, [S, a] = b({}), i = C({ onInstalled: u, onError: f });
  i.current = { onInstalled: u, onError: f };
  const { optionalComponents: s, componentMountPoints: p } = window.blocklet, r = h(() => {
    if (!s || !s.length)
      return [];
    const t = c(o), n = s.filter((l) => t.has(l.meta.did));
    return (n ? i.current.onError : i.current.onInstalled)?.(n), n;
  }, [o, s]), m = h(() => {
    if (r.length)
      return !0;
    const t = c(o);
    return (p || []).find((n) => t.has(n.did));
  }, [r, p, o]);
  return r.forEach((t) => {
    t.storeUrl = w(t.meta.homepage, "blocklets", t.meta.did), t.installUrl = w(
      window.blocklet.appUrl,
      k,
      `/admin/components?install-component=${t.meta.did}`
    );
  }), I(() => {
    const t = (n) => {
      if (n.origin === window.blocklet.appUrl && n.data?.kind === "component-installer" && n.data?.blocklet?.children) {
        let l = !1;
        const g = c(o);
        n.data?.blocklet?.children.forEach((d) => {
          g.has(d.meta?.did) && (l = !0, a((E) => ({
            ...E,
            [d.meta?.did]: d.status || "waiting"
          })));
        }), l || a({});
      }
    };
    return window.addEventListener("message", t), () => {
      window.removeEventListener("message", t);
    };
  }, [o]), {
    optComponents: r,
    installed: !r.length && m,
    installStatus: S,
    setInstallStatus: a,
    definedInBlockletYML: m
  };
}
export {
  y as default
};
