import { jsx as n, jsxs as $, Fragment as q } from "react/jsx-runtime";
import { useRef as H, useState as S, useEffect as D } from "react";
import J from "clsx";
import { Buffer as C } from "buffer";
import M from "lodash/get";
import K from "pako";
import Q from "base64-url";
import P from "is-svg";
import X from "lodash/noop";
import { Box as Y } from "@mui/material";
import Z from "./aspect-ratio-container.js";
import ee from "./svg-embedder/img.js";
import te from "./svg-embedder/inline-svg.js";
import re from "./loading.js";
import A from "./broken.js";
import { styled as oe } from "../Theme/index.js";
import ne from "./displayApi.js";
import se from "./render-svg.js";
function Ue(r) {
  return r?.display || r?.data?.value;
}
function ie(r) {
  if (typeof r != "string")
    throw new Error("fromBase64 requires input to be a string");
  return C.from(Q.unescape(r), "base64");
}
const B = (r) => ({
  img: ee,
  svg: te
})[r];
function ae({
  data: r,
  address: i,
  inset: f,
  aspect: m,
  component: v = "span",
  className: L = "",
  renderError: T,
  renderLoading: b,
  preferredSvgEmbedder: j = "img",
  checkSvg: E = !1,
  minimumLoadingTime: d = 0,
  onCompleted: O = X,
  imageFilter: x = null,
  ...z
}) {
  const I = (p) => (
    // @ts-expect-error
    /* @__PURE__ */ n(le, { component: v, ...z, className: J(L, { "nft-display--inset": f }), children: p })
  ), a = H({});
  try {
    typeof r == "string" ? a.current = JSON.parse(r) : a.current = r;
    const { vcId: p } = a.current, F = a.current.credentialSubject ? M(a.current, "credentialSubject.display") : a.current, { content: c, type: g } = F, W = g === "url", [e, l] = S({
      loading: W,
      error: !1,
      loadingUrlType: !0,
      urlType: null
    }), [h, k] = S(d <= 0), u = ({ useImageFilter: t = !1, t: s } = {}) => {
      const o = new URL(c);
      return window.location.protocol === "https:" && o.protocol === "http:" && (o.protocol = "https:"), o.searchParams.has("assetId") || o.searchParams.append("assetId", i), !o.searchParams.has("vcId") && p && o.searchParams.append("vcId", p), t && x && Object.entries(x).forEach(([N, w]) => {
        o.searchParams.append(N, w);
      }), s && o.searchParams.append("t", s), o.href;
    }, G = async () => {
      try {
        const s = (await ne({
          url: u({ useImageFilter: !1, t: "nftdisplay" }),
          method: "HEAD"
        }))?.headers?.get("Content-Type");
        l({ ...e, loadingUrlType: !1, urlType: s });
      } catch (t) {
        if (console.error("Failed to fetch url content type", t), t?.message?.includes("timeout")) {
          l({ ...e, loadingUrlType: !1, loading: !1, error: !0 });
          return;
        }
        l({ ...e, loadingUrlType: !1, urlType: null });
      }
    };
    if (D(() => {
      let t;
      return d > 0 && (t = setTimeout(() => k(!0), d)), g === "url" && G(), () => clearTimeout(t);
    }, []), D(() => {
      (!e.loading && h || e.error) && O();
    }, [e, h]), e.error)
      throw new Error("Failed to render NFT Display.");
    const y = () => {
      e.loading && l({ ...e, loading: !1 });
    }, R = () => {
      l({ ...e, error: !0, loading: !1 });
    }, U = () => {
      const t = u({ useImageFilter: !0 });
      return /* @__PURE__ */ n("img", { src: t, onError: R, onLoad: y, alt: "NFT Display", style: { width: "auto", height: "auto" } });
    }, V = () => {
      const t = e.urlType || "image/svg+xml", s = u(), o = new URL(s).pathname.toLowerCase();
      return [
        ".jpg",
        ".jpeg",
        ".png",
        ".gif",
        ".bmp",
        ".webp",
        ".svg",
        ".tiff",
        ".tif",
        ".ico",
        ".jfif",
        ".pjpeg",
        ".pjp",
        ".avif"
      ].some((w) => o.endsWith(w)) ? U() : t.includes("text/html;") ? /* @__PURE__ */ n(A, {}) : (
        // eslint-disable-next-line jsx-a11y/alt-text
        /* @__PURE__ */ n(
          "object",
          {
            type: t,
            data: s,
            onErrorCapture: R,
            onLoad: y,
            style: { width: "100%", height: "100%", pointerEvents: "none" }
          },
          s
        )
      );
    }, _ = () => {
      if (c)
        switch (g) {
          case "url":
            return e.loadingUrlType ? null : e.urlType?.startsWith("image/svg+xml") ? /* @__PURE__ */ n(se, { src: u(), onLoad: y }) : e.urlType?.startsWith("image") ? U() : V();
          case "uri":
            return /* @__PURE__ */ n(
              "img",
              {
                src: c,
                onError: () => l({ ...e, error: !0 }),
                onLoad: () => l({ ...e, loading: !1 }),
                alt: "NFT Display"
              }
            );
          case "svg_gzipped": {
            const t = K.ungzip(ie(c), {}), s = C.from(t).toString("utf8");
            if (E && !P(s))
              throw new Error("Invalid SVG of type svg_gzipped");
            const o = B(j);
            return /* @__PURE__ */ n(o, { svg: s });
          }
          case "svg": {
            if (E && !P(c))
              throw new Error("Invalid SVG of type svg");
            const t = B(j);
            return /* @__PURE__ */ n(t, { svg: c });
          }
          // TODO: 准备测试数据
          case "html":
            break;
          default:
        }
      throw new Error(`unsupported display protocol: ${F.type}`);
    };
    return I(
      /* @__PURE__ */ $(q, { children: [
        (e.loading || !h) && (b ? b() : /* @__PURE__ */ n(re, {})),
        _()
      ] })
    );
  } catch (p) {
    return console.error(p?.message, {
      nftId: i,
      vcId: a?.current?.vcId
    }), I(T ? T() : /* @__PURE__ */ n(A, {}));
  }
}
const le = oe(Y)`
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  /* 默认尺寸 */
  width: 150px;
  height: 150px;
  overflow: hidden;

  &,
  img,
  object {
    max-width: 100%;
    max-height: 100%;
  }

  img,
  object {
    width: 100%;
    height: 100%;
  }

  &.nft-display--inset {
    width: 100%;
    height: 100%;
  }
`;
function pe(r) {
  return function({ aspect: i = void 0, inset: f = !1, ...m }) {
    return i && i > 0 && !f ? /* @__PURE__ */ n(Z, { aspect: i, children: /* @__PURE__ */ n(r, { inset: !0, ...m }) }) : /* @__PURE__ */ n(r, { inset: f, ...m });
  };
}
const Ne = pe(ae);
export {
  Ne as default,
  Ue as getNFTData
};
