import { jsx as r, jsxs as m } from "react/jsx-runtime";
import { use as ke, useMemo as Pe, isValidElement as te, cloneElement as ie, Children as Se } from "react";
import { Box as l, Typography as U, CircularProgress as Me, Divider as De } from "@mui/material";
import { useMemoizedFn as P, useCreation as u, useRequest as oe } from "ahooks";
import Fe from "p-wait-for";
import ne from "react-helmet";
import { SessionContext as Te } from "@arcblock/did-connect-react/lib/Session";
import ze from "@arcblock/ux/lib/Tabs";
import B from "@arcblock/ux/lib/Empty";
import We from "@arcblock/ux/lib/Button";
import Ae from "@arcblock/ux/lib/Result";
import { useConfirm as Le } from "@arcblock/ux/lib/Dialog";
import { translate as Ue } from "@arcblock/ux/lib/Locale/util";
import { useLocaleContext as Be } from "@arcblock/ux/lib/Locale/context";
import { ErrorFallback as Ie } from "@arcblock/ux/lib/ErrorBoundary";
import { styled as pe } from "@arcblock/ux/lib/Theme";
import Ne from "lodash/cloneDeep";
import { joinURL as S, getQuery as je, withoutTrailingSlash as se, withQuery as le } from "ufo";
import { isSupportFollow as He } from "@arcblock/ux/lib/Util";
import { PROFILE_URL as M } from "@arcblock/ux/lib/Util/constant";
import Ee from "../../Footer/index.js";
import ae from "../../Header/index.js";
import { translations as _e } from "../libs/locales.js";
import de from "./user-info/user-basic-info.js";
import "@mui/icons-material";
import "@iconify/react";
import "@arcblock/ux/lib/DID";
import "@iconify-icons/material-symbols/schedule-outline-rounded";
import "@iconify-icons/material-symbols/more-time-rounded";
import "@iconify-icons/material-symbols/captive-portal-rounded";
import "@iconify-icons/material-symbols/settings-input-antenna-rounded";
import "@arcblock/ux/lib/RelativeTime";
import "@arcblock/ux/lib/UserCard/Content/shorten-label";
import "./user-info/switch-role.js";
import { formatBlockletInfo as Oe, getLink as D, getLocalizedNavigation as Re } from "../../blocklets.js";
import $e from "./passport.js";
import qe from "./settings.js";
import { client as ue } from "../../libs/client.js";
import Ge from "../../hooks/use-mobile.js";
import { ConfigUserSpaceProvider as Qe } from "../../contexts/config-user-space.js";
import Ve from "./storage/index.js";
import Je from "./nft.js";
import { UserFollowersProvider as ce } from "../../contexts/user-followers.js";
import Ke from "./fallback.js";
const F = S(M, "/nfts"), T = S(M, "/settings"), z = S(M, "/did-spaces"), N = S(M, "/user-followers"), Xe = (b) => b.some(
  (y) => ["/userCenter/nfts", "/userCenter/user-followers", "/userCenter/settings", "/userCenter/did-spaces"].includes(
    y.id
  ) || [F, T, z, N].includes(y.link)
), fe = pe(l)(({ theme: b }) => ({
  flex: 1,
  boxSizing: "border-box",
  padding: "0 16px",
  width: "100%",
  maxWidth: 1600,
  margin: "0 auto",
  display: "flex",
  alignItems: "stretch",
  gap: 2.5,
  flexDirection: "column",
  [b.breakpoints.up("md")]: {
    flexDirection: "row"
  }
})), I = pe(l)(({ theme: b }) => ({
  overflow: "hidden",
  flex: "revert",
  [b.breakpoints.up("md")]: {
    flex: 1
  },
  "@media (min-width: 960px) and (max-width: 1050px)": {
    "& .user-center-tabs": {
      maxWidth: "500px"
    }
  }
}));
function $r({
  children: b,
  notLoginContent: y = null,
  currentTab: v,
  contentProps: j = {},
  disableAutoRedirect: H = !1,
  hideFooter: me = !1,
  headerProps: he = {},
  footerProps: xe = {},
  userDid: W = void 0,
  stickySidebar: E = !1,
  embed: _ = !1,
  onlyProfile: C = !1,
  // 只显示 profile 页面，用于 ArcSphere 只需要显示 Profile 的内容
  onDestroySelf: ge = void 0
}) {
  const { locale: x, defaultLocale: k } = Be(), a = Ge({ key: "md" }), f = P((e, t = {}) => Ue(_e, e, x, "en", t)), o = ke(Te)?.session, h = u(() => {
    if (W)
      return W;
    const e = window.location.href, t = je(e);
    return t?.did ? Array.isArray(t.did) ? t.did[0] : t.did : o?.user?.did;
  }, [o?.user?.did, W]), i = u(() => o?.user ? h === o?.user?.did : !1, [h, o?.user?.did]), w = Pe(() => He(), []), n = oe(
    // eslint-disable-next-line consistent-return
    async () => {
      if (await Fe(() => o?.initialized), i)
        return o.user;
      if (h)
        return ue.user.getUserPublicInfo({ did: h });
    },
    {
      refreshDeps: [h, i, o?.initialized, o?.user]
    }
  ), O = P(() => i ? o.refresh() : n.refresh()), g = oe(
    async () => n.data && v ? await ue.user.getUserPrivacyConfig({ did: h }) : null,
    {
      refreshDeps: [h, n.data, v],
      loadingDelay: 300
    }
  ), { confirmHolder: R } = Le({
    fullScreen: a,
    sx: {
      ".MuiDialog-paper": {
        borderRadius: 1,
        maxWidth: 1200
      },
      ".ux-dialog_title": {
        fontWeight: 600
      },
      ".ux-dialog_closeButton": {
        p: 1
      },
      ".MuiDialogActions-root": {
        display: {
          xs: "none",
          md: "flex"
        }
      }
    }
  }), $ = u(() => {
    const e = Ne(window.blocklet);
    try {
      return Oe(e);
    } catch (t) {
      return console.error("Failed to format blocklet info", t, e), e;
    }
  }, []), q = u(() => {
    const e = {
      label: f("common.nft"),
      protected: !1,
      isPrivate: !1,
      // true: 隐私数据，仅自己可见
      value: F,
      url: D(F, x, k)
    }, t = {
      label: f("userFollowers"),
      protected: !1,
      isPrivate: !1,
      value: N,
      url: D(N, x, k)
    };
    let p = w ? [e, t] : [e];
    if (i) {
      const L = [
        e,
        {
          label: f("common.setting"),
          protected: !0,
          isPrivate: !0,
          value: T,
          url: D(T, x, k)
        },
        {
          label: f("storageManagement"),
          protected: !0,
          isPrivate: !0,
          value: z,
          url: D(z, x, k)
        }
      ];
      p = w ? [...L, t] : L;
    }
    return p;
  }, [i, x, w]), d = u(() => {
    const e = $?.navigation?.userCenter || [], t = Xe(e);
    return (Re({ navigation: e, locale: x, defaultLocale: k }) || []).concat(t ? [] : q).map((c) => {
      const re = c.value ?? c._rawLink ?? c.link ?? c.url;
      return {
        value: re,
        label: c.title || c.label,
        url: c.link || c.url,
        protected: g?.data?.[re] ?? !1,
        isPrivate: c.isPrivate || c.private || (c?._rawLink?.includes("/customer") ?? !1),
        // FIXME: HACK: 隐藏 /customer 菜单, 需要一个通用的解决方案，在嵌入的时候就决定是否是私有的
        followersOnly: c.component === "did-comments"
        // 是否开启仅粉丝可查看的功能，目前只对 discuss kit 开启
        // icon: x.icon,
      };
    }).filter((c) => i || !c.isPrivate);
  }, [$, n.data, g?.data, x, q, i]), s = u(() => d.find((e) => se(e.value) === se(v)), [d]), G = u(() => {
    const e = window.blocklet?.appName, p = [s?.label, f("userCenter.title")].filter(Boolean).join("-");
    return e ? `${p} | ${e}` : p;
  }, [s, f]), be = P((e) => e && (te(e) ? ie(e, {
    ...e.props || {},
    userCenterTabs: d
  }) : Se.map(e, (t) => te(t) ? ie(t, {
    ...t.props || {},
    userCenterTabs: d
  }) : t))), ve = P((e) => {
    const t = d.find((p) => p.value === e);
    t && (window.location.href = le(t.url, {
      did: i ? void 0 : h
    }));
  }), Q = u(() => /* @__PURE__ */ r(
    qe,
    {
      user: n.data,
      settings: { userCenterTabs: d },
      onSave: async (e) => e === "privacy" ? (await g.runAsync(), g.data) : (e === "profile" && await o.refresh(), null),
      isMobile: a,
      onDestroySelf: ge
    }
  ), [n.data, d, g.data, g.runAsync]), V = u(() => s && s?.value === T, [s]), J = u(() => s && s?.value === S(M, "/profile") || s?.value === F, [s]), we = u(() => s && s?.value === z, [s]), ye = o.useOAuth(), Ce = o.usePasskey(), K = P(() => {
    o?.user?.sourceProvider === "passkey" ? Ce.switchPassport(o.user) : ["google", "apple", "email", "github"].includes(o?.user?.sourceProvider ?? "") ? ye.switchOAuthPassport(o.user) : o && o.switchPassport();
  }), A = u(() => J ? /* @__PURE__ */ m(
    l,
    {
      sx: {
        display: "flex",
        flexDirection: "column",
        gap: 2.5
      },
      children: [
        i ? /* @__PURE__ */ m(l, { sx: { border: "1px solid", borderColor: "divider", borderRadius: 1.5, p: 2 }, children: [
          /* @__PURE__ */ r(
            U,
            {
              sx: {
                color: "text.primary",
                fontWeight: 600,
                mb: 2.5
              },
              children: f("passport")
            }
          ),
          /* @__PURE__ */ r($e, { user: n.data })
        ] }) : null,
        /* @__PURE__ */ r(Je, { user: n.data })
      ]
    }
  ) : V && i ? Q : we && i ? /* @__PURE__ */ r(Qe, { children: /* @__PURE__ */ r(Ve, {}) }) : null, [V, J, n, i, E, Q]), X = u(() => /* @__PURE__ */ r(
    l,
    {
      sx: {
        display: {
          xs: i ? "none" : "block",
          md: "block"
        },
        py: 3
      },
      children: /* @__PURE__ */ r(B, { children: f("emptyContent") })
    }
  ), [i, x]), Y = u(() => !g.data || g.loading ? /* @__PURE__ */ r(
    l,
    {
      sx: {
        height: "100%",
        minWidth: "160px",
        minHeight: "160px",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        flex: 1
      },
      children: /* @__PURE__ */ r(Me, {})
    }
  ) : /* @__PURE__ */ r(l, { sx: { flex: 1 }, children: /* @__PURE__ */ r(
    Ke,
    {
      isSupportFollow: w,
      currentActiveTab: s,
      isMyself: i,
      children: b ? /* @__PURE__ */ r(l, { ...j, children: be(b) }) : A
    }
  ) }), [g, s, i, b, j, A, x]), Z = u(() => {
    if (n.loading || o.loading)
      return null;
    if (n.error) {
      if (n.error?.response?.status === 404)
        return /* @__PURE__ */ r(l, { sx: { width: "100%" }, children: /* @__PURE__ */ r(Ae, { status: 404, description: f("noUserFound") }) });
      const p = {
        message: n.error.response?.data?.error || n.error.message || "error occurred"
      };
      return /* @__PURE__ */ r(l, { sx: { width: "100%" }, children: /* @__PURE__ */ r(Ie, { error: p }) });
    }
    return !h && !n.data ? y || /* @__PURE__ */ r(l, { sx: { width: "100%" }, children: /* @__PURE__ */ m(
      l,
      {
        sx: {
          display: "flex",
          flexDirection: "column",
          justifyContent: "center",
          alignItems: "center",
          gap: 1
        },
        children: [
          /* @__PURE__ */ r(B, { children: f("viewAfterLogin") }),
          /* @__PURE__ */ r(We, { size: "small", variant: "contained", onClick: () => o.login(), children: f("loginNow") })
        ]
      }
    ) }) : h && !n.data && !n.loading ? /* @__PURE__ */ r(B, { style: { width: "100%", paddingTop: 16 }, children: /* @__PURE__ */ m(l, { sx: { textAlign: "center", width: "100%" }, children: [
      /* @__PURE__ */ r(U, { variant: "body1", sx: { fontSize: 18, fontWeight: 500 }, children: f("userNotFound") }),
      /* @__PURE__ */ r(U, { variant: "body1", color: "text.secondary", children: f("userNotFoundDescription") })
    ] }) }) : _ ? /* @__PURE__ */ m(I, { children: [
      d.length > 0 && v ? /* @__PURE__ */ r(
        l,
        {
          sx: {
            display: a ? "block" : "flex",
            height: "100%",
            overflow: "auto",
            padding: "1px"
          },
          children: Y
        }
      ) : null,
      d.length === 0 && X
    ] }) : C ? /* @__PURE__ */ r(I, { display: "flex", flexDirection: a ? "column" : "row", children: /* @__PURE__ */ r(
      de,
      {
        isMobile: a,
        order: a ? 1 : "unset",
        isMyself: i,
        switchPassport: K,
        switchProfile: o.switchProfile,
        user: n.data,
        showFullDid: !1,
        onlyProfile: C,
        refreshProfile: O,
        isShowSocialActions: w,
        sx: {
          padding: a ? "16px 0 0 0" : "40px 24px 24px 40px",
          ...a ? {} : { width: 320, maxWidth: 320, flexShrink: 0 },
          boxSizing: "content-box"
        }
      }
    ) }) : /* @__PURE__ */ m(I, { display: "flex", flexDirection: a ? "column" : "row", children: [
      /* @__PURE__ */ m(
        l,
        {
          className: "user-center-tabs",
          sx: {
            flex: "1",
            order: a ? 2 : "unset",
            width: a ? "unset" : "calc(100% - 424px)"
          },
          children: [
            d.length > 0 && v ? /* @__PURE__ */ m(
              l,
              {
                sx: {
                  display: "flex",
                  flexDirection: "column",
                  height: "100%",
                  overflow: "auto",
                  padding: "1px"
                },
                children: [
                  /* @__PURE__ */ r(
                    ze,
                    {
                      orientation: "horizontal",
                      variant: "line",
                      tabs: d,
                      current: s?.value ?? v,
                      onChange: ve,
                      enableTabClick: !0,
                      sx: {
                        mb: (e) => `${e.spacing(3)} !important`,
                        ".MuiTabs-flexContainer": {
                          gap: 3,
                          ".MuiButtonBase-root": {
                            padding: a ? "16px 4px" : "32px 4px 16px 4px",
                            fontSize: 16
                          },
                          ".MuiTab-root": {
                            display: "block",
                            textAlign: "left",
                            alignItems: "flex-start",
                            justifyContent: "flex-start",
                            fontWeight: 400,
                            mr: 0
                          }
                        },
                        ".MuiTabs-indicator": {
                          zIndex: 2
                        },
                        ".MuiTabs-scroller": {
                          "&:after": {
                            content: '""',
                            display: "block",
                            position: "sticky",
                            left: 0,
                            zIndex: 1,
                            width: "100%",
                            height: "1px",
                            backgroundColor: "divider"
                          }
                        }
                      }
                    }
                  ),
                  Y
                ]
              }
            ) : null,
            d.length === 0 && X
          ]
        }
      ),
      !a && /* @__PURE__ */ r(De, { orientation: "vertical", sx: { ml: 5 } }),
      /* @__PURE__ */ r(
        de,
        {
          isMobile: a,
          order: a ? 1 : "unset",
          isMyself: i,
          switchPassport: K,
          switchProfile: o.switchProfile,
          user: n.data,
          refreshProfile: O,
          showFullDid: !1,
          isShowSocialActions: w,
          sx: {
            padding: a ? "16px 0 0 0" : "40px 24px 24px 40px",
            ...a ? {} : { width: 320, maxWidth: 320, flexShrink: 0 },
            boxSizing: "content-box"
          }
        }
      )
    ] });
  }, [
    n,
    d,
    i,
    s,
    g,
    v,
    E,
    A
  ]), ee = u(() => i ? !1 : s?.isPrivate, [i, s]);
  if (u(() => C ? !1 : !H && !v && d?.length > 0 || !s || ee, [H, v, d, s, ee, C])) {
    const e = d[0]?.url, t = d.find((p) => p.value === e);
    return e && !t?.isPrivate && window.location.replace(
      le(e, {
        did: i ? void 0 : h
      })
    ), null;
  }
  return _ || C ? /* @__PURE__ */ m(l, { children: [
    /* @__PURE__ */ r(ne, { children: /* @__PURE__ */ r("title", { children: G }) }),
    /* @__PURE__ */ r(ae, { style: { display: "none" } }),
    /* @__PURE__ */ m(fe, { children: [
      /* @__PURE__ */ r(ce, { isMySelf: i, userDid: n.data?.did ?? "", children: Z }),
      R
    ] })
  ] }) : /* @__PURE__ */ m(
    l,
    {
      sx: {
        minHeight: "100vh",
        display: "flex",
        flexDirection: "column"
      },
      children: [
        /* @__PURE__ */ r(ne, { children: /* @__PURE__ */ r("title", { children: G }) }),
        /* @__PURE__ */ r(ae, { bordered: !0, ...he, maxWidth: "100%" }),
        /* @__PURE__ */ m(fe, { children: [
          /* @__PURE__ */ r(ce, { isMySelf: i, userDid: n.data?.did ?? "", children: Z }),
          R
        ] }),
        me ? null : /* @__PURE__ */ r(
          Ee,
          {
            bordered: !0,
            ...xe,
            sx: {
              ".MuiContainer-root": {
                maxWidth: 1600
              }
            }
          }
        )
      ]
    }
  );
}
export {
  $r as default
};
