import { jsxs as T, jsx as s, Fragment as le } from "react/jsx-runtime";
import I, { useState as M, useEffect as U, useCallback as ce, useMemo as H } from "react";
import { f as D, g as de, C as ue, q as pe, a as X, b as ie, c as O, e as G, B as L, u as se, k as me, n as fe, z as he, A as ge, D as be, E as ye, F as xe } from "./chunks/PrizeCard-C2El3VOB.js";
import { a as Y } from "./chunks/AlertMessage-BKksUsV9.js";
import { createPortal as Ce } from "react-dom";
import { F as ve } from "./chunks/FormLabel-D1-amwv5.js";
import { T as A, I as Q, B as q } from "./chunks/Button-DPGn5NZd.js";
import { S as Te, a as Pe } from "./chunks/Select-BtID79ha.js";
import { S as Se, T as we, P as J } from "./chunks/Person-B4_Qrd55.js";
import { h as B, s as Re } from "./chunks/helpers-uh28Hksw.js";
import { S as Ee } from "./chunks/Spinner-DWJCKaY5.js";
import { A as K } from "./chunks/Avatar-Cm5QOeVC.js";
import { C as Ae, a as Le } from "./chunks/chevrons-right-CRIN5sOe.js";
import { C as ze, a as Ie } from "./chunks/chevron-right-B3IZtaMT.js";
const Me = (e) => e.split("_").map((t) => t.charAt(0) + t.slice(1).toLowerCase()).join(" "), Be = ({
  options: e,
  selectedId: t,
  onChange: l
}) => {
  const { t: r } = D(), { shadowRootElement: n } = de(ue), g = pe(), p = X(), d = ie(), m = O().primary, h = G(), P = p.textColor, i = {
    background: {
      surface: g.colorSchemes.light.palette.background.surface,
      popup: g.colorSchemes.light.palette.background.popup
    },
    neutral: {
      outlinedBorder: g.colorSchemes.light.palette.neutral.outlinedBorder,
      outlinedColor: g.colorSchemes.light.palette.neutral.outlinedColor,
      outlinedHoverBg: g.colorSchemes.light.palette.neutral.outlinedHoverBg,
      plainActiveBg: g.colorSchemes.light.palette.neutral.plainActiveBg,
      plainHoverBg: g.colorSchemes.light.palette.neutral.plainHoverBg,
      plainHoverColor: g.colorSchemes.light.palette.neutral.plainHoverColor
    }
  }, x = {
    flexShrink: 0,
    fontFamily: m,
    fontSize: "0.65em",
    fontWeight: 600,
    letterSpacing: "0.05em",
    textTransform: "uppercase",
    color: i.neutral.outlinedColor,
    bgcolor: i.neutral.plainHoverBg,
    border: `1px solid ${i.neutral.outlinedBorder}`,
    borderRadius: d.sm,
    px: h["2xs"],
    py: h["3xs"]
  }, C = (b) => /* @__PURE__ */ T(
    L,
    {
      sx: {
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        width: "100%",
        gap: h.sm
      },
      children: [
        /* @__PURE__ */ s("span", { children: b.label }),
        b.type && /* @__PURE__ */ s(L, { sx: x, children: Me(b.type) })
      ]
    }
  ), z = {
    root: {
      sx: {
        fontFamily: m,
        borderRadius: d.sm,
        bgcolor: i.background.surface,
        borderColor: i.neutral.outlinedBorder,
        color: i.neutral.outlinedColor,
        fontSize: "1em",
        "&:hover": { bgcolor: i.neutral.outlinedHoverBg }
      }
    },
    listbox: {
      container: n,
      sx: {
        zIndex: 10,
        bgcolor: i.background.popup,
        border: `1px solid ${i.neutral.outlinedBorder}`,
        borderRadius: d.sm,
        boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)"
      }
    }
  }, S = {
    fontFamily: m,
    color: `${i.neutral.outlinedColor} !important`,
    bgcolor: "transparent",
    "&:hover": {
      bgcolor: `${i.neutral.plainHoverBg} !important`,
      color: `${i.neutral.plainHoverColor} !important`
    },
    "&.Mui-selected": {
      bgcolor: `${i.neutral.plainActiveBg} !important`,
      color: `${i.neutral.outlinedColor} !important`
    },
    "&.Mui-selected:hover": {
      bgcolor: `${i.neutral.plainActiveBg} !important`,
      color: `${i.neutral.outlinedColor} !important`
    }
  };
  return /* @__PURE__ */ T(L, { sx: { display: "flex", flexDirection: "column", gap: h["2xs"] }, children: [
    /* @__PURE__ */ s(
      ve,
      {
        sx: {
          color: `${P} !important`,
          fontFamily: m,
          fontSize: "0.875em"
        },
        children: /* @__PURE__ */ s(
          A,
          {
            sx: {
              fontFamily: m,
              fontSize: "0.875em",
              color: P
            },
            children: r("leaderboard.selectLabel")
          }
        )
      }
    ),
    /* @__PURE__ */ s(
      Te,
      {
        value: t,
        onChange: (b, w) => w && l(w),
        slotProps: z,
        renderValue: (b) => {
          if (!b) return null;
          const w = e.find((u) => u.id === b.value);
          return w ? C(w) : b.label;
        },
        children: e.map((b) => /* @__PURE__ */ s(Pe, { value: b.id, sx: S, children: C(b) }, b.id))
      }
    )
  ] });
}, Fe = ({
  leaderboard: e,
  userRank: t,
  showHeading: l,
  title: r,
  description: n,
  isSplitVariant: g,
  brandingColors: p
}) => {
  const { t: d } = D(), m = se(), h = X(), P = (p == null ? void 0 : p.primaryColor) || h.palette.primary.plainColor, i = (p == null ? void 0 : p.contentColor) || h.textColor, x = h.textColor, C = O().primary, z = O().secondary, S = ie(), b = G(), w = me(), u = h.surfaceVariant, c = m.colorSchemes.light.palette.primary.onPrimary, o = h.outlineEnabledBorder, a = {
    leaderboardContainer: {
      display: "flex",
      flexDirection: "column",
      gap: b.md
    },
    leaderboardTitle: {
      fontFamily: C,
      fontWeight: 700,
      lineHeight: "133%",
      letterSpacing: "0px",
      fontSize: "1.5em",
      color: i,
      textAlign: "center"
    },
    tableContainer: {
      overflowX: "auto",
      borderRadius: S.md,
      border: `1px solid ${o}`
    },
    table: {
      backgroundColor: u,
      "--TableCell-paddingX": "0.5rem",
      "--TableCell-paddingY": "0.375rem",
      cursor: "default",
      "& > tbody > tr:hover": {
        backgroundColor: "transparent"
      },
      "& > thead > tr > th": {
        backgroundColor: `rgba(${B(u)}, 0.8)`,
        color: i,
        fontFamily: C,
        fontWeight: 600,
        fontSize: "0.875em",
        textAlign: "center",
        borderBottom: `1px solid ${o}`
      }
    },
    headerCellPosition: {
      backgroundColor: `rgba(${B(u)}, 0.8)`,
      color: i,
      fontFamily: C,
      fontWeight: 600,
      fontSize: "0.875em",
      textAlign: "center",
      padding: "0.375rem 0.5rem",
      width: "10%"
    },
    headerCellName: {
      backgroundColor: `rgba(${B(u)}, 0.8)`,
      color: i,
      fontFamily: C,
      fontWeight: 600,
      fontSize: "0.875em",
      textAlign: "left",
      padding: "0.375rem 0.5rem",
      width: "80%"
    },
    headerCellPoints: {
      backgroundColor: `rgba(${B(u)}, 0.8)`,
      color: i,
      fontFamily: C,
      fontWeight: 600,
      fontSize: "0.875em",
      textAlign: "center",
      padding: "0.375rem 0.5rem",
      width: "10%"
    },
    tableCellPosition: {
      padding: "0.375rem 0.5rem",
      width: "10%",
      textAlign: "center"
    },
    tableCellName: {
      padding: "0.375rem 0.5rem",
      width: "80%"
    },
    tableCellPoints: {
      padding: "0.375rem 0.5rem",
      width: "10%",
      textAlign: "center"
    },
    userRow: {
      backgroundColor: `rgba(${B(P)}, 0.1)`
    },
    nameCell: {
      display: "flex",
      alignItems: "center",
      gap: b.sm
    },
    leaderboardAvatar: {
      width: "32px",
      height: "32px",
      fontSize: "0.875em",
      fontWeight: 600,
      backgroundColor: P,
      color: c
    },
    nameText: {
      fontFamily: C,
      fontWeight: 500,
      fontSize: "0.875em",
      color: i,
      overflow: "hidden",
      textOverflow: "ellipsis",
      whiteSpace: "nowrap"
    },
    positionText: {
      fontFamily: C,
      fontWeight: 600,
      fontSize: "0.875em",
      color: i
    },
    pointsText: {
      fontFamily: C,
      fontWeight: 600,
      fontSize: "0.875em",
      color: i
    },
    avatarIcon: {
      fontSize: "1em",
      color: c
    },
    noLeaderboardText: {
      fontFamily: z,
      fontSize: "1.25em",
      color: i,
      textAlign: "center",
      marginY: b.md
    }
  };
  if (!e)
    return /* @__PURE__ */ s(Ee, { my: 10 });
  if (e.length === 0)
    return /* @__PURE__ */ s(A, { level: "body-lg", sx: a.noLeaderboardText, children: d("leaderboard.noLeaderboardAvailable") });
  const f = t, y = f == null ? void 0 : f.position, R = y && e.some((E) => E.position === y);
  return /* @__PURE__ */ T(L, { sx: a.leaderboardContainer, children: [
    l && /* @__PURE__ */ T(
      L,
      {
        sx: {
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          textAlign: "center"
        },
        children: [
          /* @__PURE__ */ s(
            A,
            {
              level: "body-sm",
              sx: {
                fontWeight: 500,
                lineHeight: "166%",
                letterSpacing: "1px",
                textTransform: "uppercase",
                fontSize: "0.75em",
                color: x,
                opacity: "60%",
                fontFamily: z
              },
              children: d("leaderboard.heading")
            }
          ),
          /* @__PURE__ */ T(
            L,
            {
              sx: {
                display: "flex",
                flexDirection: "column",
                gap: b["3xs"]
              },
              children: [
                r && /* @__PURE__ */ s(A, { level: "h4", sx: a.leaderboardTitle, children: r }),
                n && /* @__PURE__ */ s(
                  A,
                  {
                    sx: {
                      fontWeight: 400,
                      lineHeight: "140%",
                      letterSpacing: "0.15px",
                      fontSize: "1.25em",
                      color: x,
                      opacity: "60%",
                      fontFamily: C
                    },
                    children: Re(n)
                  }
                )
              ]
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ s(Se, { sx: a.tableContainer, children: /* @__PURE__ */ T(
      we,
      {
        variant: "outlined",
        hoverRow: !1,
        borderAxis: "bothBetween",
        size: "sm",
        sx: a.table,
        children: [
          /* @__PURE__ */ s("thead", { children: /* @__PURE__ */ T("tr", { children: [
            /* @__PURE__ */ s("th", { style: a.headerCellPosition, children: w || g ? "" : d("leaderboard.position") }),
            /* @__PURE__ */ s("th", { style: a.headerCellName, children: d("leaderboard.name") }),
            /* @__PURE__ */ s("th", { style: a.headerCellPoints, children: w || g ? "🎯" : d("leaderboard.points") })
          ] }) }),
          /* @__PURE__ */ T("tbody", { children: [
            f && !R && /* @__PURE__ */ T("tr", { style: a.userRow, children: [
              /* @__PURE__ */ s("td", { style: a.tableCellPosition, children: /* @__PURE__ */ T(A, { sx: a.positionText, children: [
                "#",
                f.position
              ] }) }),
              /* @__PURE__ */ s("td", { style: a.tableCellName, children: /* @__PURE__ */ T(L, { sx: a.nameCell, children: [
                /* @__PURE__ */ s(K, { sx: a.leaderboardAvatar, children: /* @__PURE__ */ s(J, { sx: a.avatarIcon }) }),
                /* @__PURE__ */ s(A, { sx: a.nameText, children: d("leaderboard.you") })
              ] }) }),
              /* @__PURE__ */ s("td", { style: a.tableCellPoints, children: /* @__PURE__ */ s(A, { sx: a.pointsText, children: f.points }) })
            ] }),
            e.map((E) => {
              var $, k, N, V;
              const v = y === E.position;
              return /* @__PURE__ */ T(
                "tr",
                {
                  style: v ? a.userRow : void 0,
                  children: [
                    /* @__PURE__ */ s("td", { style: a.tableCellPosition, children: /* @__PURE__ */ T(A, { sx: a.positionText, children: [
                      "#",
                      E.position
                    ] }) }),
                    /* @__PURE__ */ s("td", { style: a.tableCellName, children: /* @__PURE__ */ T(L, { sx: a.nameCell, children: [
                      /* @__PURE__ */ s(
                        K,
                        {
                          src: (($ = E.profileModel) == null ? void 0 : $.avatar) || void 0,
                          sx: a.leaderboardAvatar,
                          children: (k = E.profileModel) != null && k.avatar ? /* @__PURE__ */ s(le, {}) : /* @__PURE__ */ s(J, { sx: a.avatarIcon })
                        }
                      ),
                      /* @__PURE__ */ s(A, { sx: a.nameText, children: v ? d("leaderboard.you") : ((N = E.profileModel) == null ? void 0 : N.nickname) || ((V = E.profileModel) == null ? void 0 : V.name) || d("leaderboard.anonymous") })
                    ] }) }),
                    /* @__PURE__ */ s("td", { style: a.tableCellPoints, children: /* @__PURE__ */ s(A, { sx: a.pointsText, children: E.points }) })
                  ]
                },
                E.profileId
              );
            })
          ] })
        ]
      }
    ) })
  ] });
}, Ue = ({
  count: e = 10,
  page: t = 1,
  onChange: l,
  siblingCount: r = 1,
  boundaryCount: n = 1,
  showFirstButton: g = !0,
  showLastButton: p = !0,
  size: d = "md",
  disabled: m = !1,
  isOverlayVariant: h = !1
}) => {
  const P = se(), i = (c) => {
    l && c >= 1 && c <= e && l(c);
  }, x = (c, o) => {
    const a = [];
    for (let f = c; f <= o; f++) a.push(f);
    return a;
  }, z = (() => {
    if (e <= 0) return [];
    const c = x(1, Math.min(n, e)), o = x(
      Math.max(e - n + 1, n + 1),
      e
    ), a = Math.max(n + 1, t - r), f = Math.min(e - n, t + r), y = [...c];
    if (a > n + 1 && y.push("ellipsis-start"), a <= f)
      for (let R = a; R <= f; R++)
        y.push(R);
    f < e - n && y.push("ellipsis-end");
    for (const R of o)
      y.includes(R) || y.push(R);
    return y;
  })(), S = d === "sm" ? "sm" : d === "lg" ? "lg" : "md", b = d === "sm" ? 16 : d === "lg" ? 24 : 20, w = (c = !1) => {
    if (!h)
      return {
        borderRadius: "8px",
        minWidth: "32px",
        minHeight: "32px",
        fontWeight: c ? 600 : 400
      };
    const o = P.colorSchemes.dark;
    return {
      borderRadius: "8px",
      minWidth: "32px",
      minHeight: "32px",
      fontWeight: c ? 600 : 400,
      backgroundColor: c ? o.palette.neutral.solidBg : "transparent",
      color: c ? o.palette.neutral.solidColor : o.textColor,
      border: "none",
      "&:hover": {
        backgroundColor: o.palette.neutral.solidBg,
        color: c ? o.palette.neutral.solidColor : o.textColor
      },
      "&:active": {
        backgroundColor: o.palette.neutral.plainActiveBg
      },
      "&.Mui-disabled": {
        backgroundColor: "transparent",
        color: o.textDisabled,
        opacity: 0.5
      }
    };
  }, u = () => {
    if (!h)
      return {
        borderRadius: "8px",
        minWidth: "32px",
        minHeight: "32px"
      };
    const c = P.colorSchemes.dark;
    return {
      borderRadius: "8px",
      minWidth: "32px",
      minHeight: "32px",
      backgroundColor: "transparent",
      color: c.textColor,
      border: "none",
      "&:hover": {
        backgroundColor: c.palette.neutral.solidBg,
        color: c.textColor
      },
      "&:active": {
        backgroundColor: c.palette.neutral.plainActiveBg
      },
      "&.Mui-disabled": {
        backgroundColor: "transparent",
        color: c.textDisabled,
        opacity: 0.5
      }
    };
  };
  return /* @__PURE__ */ T(
    L,
    {
      sx: {
        display: "flex",
        gap: 0.5,
        alignItems: "center",
        flexWrap: "wrap"
      },
      children: [
        g && /* @__PURE__ */ s(
          Q,
          {
            size: S,
            variant: "plain",
            color: "neutral",
            onClick: () => i(1),
            disabled: m || t === 1,
            sx: u(),
            children: /* @__PURE__ */ s(Ae, { size: b })
          }
        ),
        /* @__PURE__ */ s(
          Q,
          {
            size: S,
            variant: "plain",
            color: "neutral",
            onClick: () => i(t - 1),
            disabled: m || t === 1,
            sx: u(),
            children: /* @__PURE__ */ s(ze, { size: b })
          }
        ),
        z.map((c, o) => {
          if (typeof c == "string" && c.startsWith("ellipsis"))
            return /* @__PURE__ */ s(
              q,
              {
                size: S,
                variant: "plain",
                color: "neutral",
                disabled: !0,
                sx: {
                  ...w(!1),
                  cursor: "default",
                  "&.Mui-disabled": h ? {
                    backgroundColor: "transparent",
                    color: P.colorSchemes.dark.textDisabled,
                    opacity: 0.5
                  } : {
                    opacity: 1,
                    color: "text.secondary"
                  }
                },
                children: "..."
              },
              `${c}-${o}`
            );
          const a = c === t;
          return /* @__PURE__ */ s(
            q,
            {
              size: S,
              variant: a ? "solid" : "plain",
              color: "neutral",
              onClick: () => i(c),
              disabled: m,
              sx: w(a),
              children: c
            },
            c
          );
        }),
        /* @__PURE__ */ s(
          Q,
          {
            size: S,
            variant: "plain",
            color: "neutral",
            onClick: () => i(t + 1),
            disabled: m || t === e,
            sx: u(),
            children: /* @__PURE__ */ s(Ie, { size: b })
          }
        ),
        p && /* @__PURE__ */ s(
          Q,
          {
            size: S,
            variant: "plain",
            color: "neutral",
            onClick: () => i(e),
            disabled: m || t === e,
            sx: u(),
            children: /* @__PURE__ */ s(Le, { size: b })
          }
        )
      ]
    }
  );
}, F = "ALL", j = (e) => ({
  currentPage: e.currentPage,
  totalPages: e.numberOfPages,
  totalItems: e.totalItems,
  itemsPerPage: e.itemsPerPage
}), Z = (e) => e.map((t) => ({
  position: t.position,
  profileId: t.profileId,
  profileModel: t.profileModel,
  points: t.points
})), $e = async (e) => {
  try {
    return await e.profile.getOwn().getInfo();
  } catch {
    return null;
  }
}, ee = async (e, t) => e.length === 0 ? [] : (await t.topX.getGames({ gameIds: e })).data.map((r) => {
  var n;
  return {
    id: r.id,
    title: r.title,
    description: r.description || null,
    branding: ((n = r.branding) == null ? void 0 : n.colors) || null
  };
}), te = async (e, t) => e.length === 0 ? [] : (await t.matchQuiz.getGames({ gameIds: e })).data.map((r) => {
  var n;
  return {
    id: r.id,
    title: r.title,
    description: r.description || null,
    branding: ((n = r.branding) == null ? void 0 : n.colors) || null
  };
}), re = async (e, t) => e.length === 0 ? [] : (await t.loyalty.getTemplates()).data.filter((r) => e.includes(r.id)).map((r) => {
  var n;
  return {
    id: r.id,
    title: r.title || r.name,
    description: r.description || null,
    branding: ((n = r.branding) == null ? void 0 : n.colors) || null
  };
}), oe = async (e, t) => e.length === 0 ? [] : (await t.miniGames.getClassicQuizzes({
  classicQuizIds: e
})).data.map((r) => {
  var n;
  return {
    id: r.id,
    title: r.title || r.name,
    description: r.description || null,
    branding: ((n = r.branding) == null ? void 0 : n.colors) || null
  };
}), ke = async (e, t, l, r) => {
  const n = await t.loyalty.getLeaderboardForGame(e, { page: l, limit: r });
  return {
    leaderboard: Z(n.data),
    pagination: j(n.meta.pagination)
  };
}, Qe = async (e, t, l, r) => {
  const n = await t.loyalty.getLeaderboard(
    e,
    { page: l, limit: r }
  );
  return {
    leaderboard: Z(n.data),
    pagination: j(n.meta.pagination)
  };
}, W = async (e, t, l, r) => {
  const n = await t.miniGames.getLeaderboardForClassicQuizzes({
    classicQuizIds: e,
    page: l,
    limit: r
  });
  return {
    leaderboard: Z(n.data),
    pagination: j(n.meta.pagination)
  };
}, ne = (e, t, l, r) => {
  const n = e.type.toUpperCase();
  return n === "TOP_X" || n === "MATCH_QUIZ" ? ke(e.id, t, l, r) : n === "TEMPLATE" ? Qe(e.id, t, l, r) : W([e.id], t, l, r);
}, He = async (e, t, l) => {
  const n = l.toUpperCase() === "TEMPLATE" ? { rankType: "TEMPLATE", leaderboardIds: [e] } : { rankType: "GAME", gameType: l.toUpperCase(), leaderboardIds: [e] }, d = (await t.loyalty.getOwnRankings(n, !0)).data[0] ?? null;
  return d ? {
    position: d.position,
    profileId: d.profileId,
    profileModel: d.profileModel,
    points: d.points
  } : null;
}, _e = async (e, t, l) => {
  const g = (await t.miniGames.getClassicQuizzesUserRanking(
    l,
    void 0,
    !0
  )).data.find((p) => p.classicQuizId === e) ?? null;
  return g ? {
    position: g.position,
    profileId: l,
    profileModel: null,
    points: g.points
  } : null;
}, Oe = (e, t, l) => {
  const r = e.type.toUpperCase();
  return r === "TOP_X" || r === "MATCH_QUIZ" || r === "TEMPLATE" ? He(e.id, t, e.type) : _e(e.id, t, l);
}, We = (e, t, l, r = 10) => {
  const [n, g] = M({}), [p, d] = M(null), [m, h] = M(!1), [P, i] = M(!1), [x, C] = M(
    null
  ), [z, S] = M(null);
  U(() => {
    const u = {
      topX: e.filter((o) => o.type.toUpperCase() === "TOP_X").map((o) => o.id),
      matchQuiz: e.filter((o) => o.type.toUpperCase() === "MATCH_QUIZ").map((o) => o.id),
      template: e.filter((o) => o.type.toUpperCase() === "TEMPLATE").map((o) => o.id),
      classicQuiz: e.filter((o) => o.type.toUpperCase() === "CLASSIC_QUIZ").map((o) => o.id)
    }, c = (o) => o.catch(() => []);
    Promise.all([
      c(ee(u.topX, t)),
      c(te(u.matchQuiz, t)),
      c(re(u.template, t)),
      c(oe(u.classicQuiz, t))
    ]).then((o) => {
      const a = {};
      o.flat().forEach((f) => {
        a[f.id] = f;
      }), g(a);
    });
  }, [e, t]), U(() => {
    $e(t).then(C);
  }, [t]), U(() => {
    if (!l || !x) {
      S(null);
      return;
    }
    let u = !1, c;
    if (l === F) {
      const o = e.map((a) => a.id);
      c = t.miniGames.getClassicQuizzesUserRanking(x.id, void 0, !0).then((a) => {
        const y = a.data.find((R) => o.includes(R.classicQuizId)) ?? null;
        return y ? {
          position: y.position,
          profileId: x.id,
          profileModel: null,
          points: y.points
        } : null;
      });
    } else {
      const o = e.find((a) => a.id === l);
      if (!o) return;
      c = Oe(o, t, x.id);
    }
    return c.then((o) => {
      u || S(o);
    }).catch(() => {
      u || S(null);
    }), () => {
      u = !0;
    };
  }, [l, e, t, x]), U(() => {
    if (!l) return;
    let u = !1;
    return h(!0), i(!1), d(null), (async () => {
      try {
        const o = e.length > 1 && e.every((v) => v.type.toUpperCase() === "CLASSIC_QUIZ");
        if (l === F && o) {
          const v = e.map((k) => k.id), $ = await W(
            v,
            t,
            1,
            r
          );
          u || d({
            id: F,
            title: F,
            description: null,
            branding: null,
            ...$
          });
          return;
        }
        const a = e.find((v) => v.id === l);
        if (!a) return;
        const f = a.type.toUpperCase(), y = f === "TOP_X" ? ee([l], t) : f === "MATCH_QUIZ" ? te([l], t) : f === "TEMPLATE" ? re([l], t) : oe([l], t), [R, E] = await Promise.all([
          ne(a, t, 1, r),
          y.catch(() => [])
        ]);
        if (!u) {
          const v = E[0];
          d({
            id: l,
            title: (v == null ? void 0 : v.title) || l,
            description: (v == null ? void 0 : v.description) || null,
            branding: (v == null ? void 0 : v.branding) || null,
            ...R
          });
        }
      } catch (o) {
        console.error("Failed to fetch leaderboard:", o), u || i(!0);
      } finally {
        u || h(!1);
      }
    })(), () => {
      u = !0;
    };
  }, [l, e, t, r]);
  const b = ce(
    async (u) => {
      if (l) {
        h(!0);
        try {
          let c;
          if (l === F) {
            const o = e.map((a) => a.id);
            c = await W(o, t, u, r);
          } else {
            const o = e.find((a) => a.id === l);
            if (!o) return;
            c = await ne(o, t, u, r);
          }
          d((o) => o ? { ...o, ...c } : null);
        } catch (c) {
          console.error("Failed to fetch page:", c);
        } finally {
          h(!1);
        }
      }
    },
    [l, e, t, r]
  ), w = Object.fromEntries(
    Object.entries(n).map(([u, c]) => [u, c.title])
  );
  return { data: p, entityTitles: w, loading: m, error: P, setPage: b, userRank: z };
}, _ = "ALL", ae = ["TOP_X", "MATCH_QUIZ", "TEMPLATE", "CLASSIC_QUIZ"], De = (e, t) => {
  if (!Array.isArray(e) || e.length === 0)
    return "The 'entities' setting is required and must be a non-empty array.";
  const l = /* @__PURE__ */ new Set();
  for (let r = 0; r < e.length; r++) {
    const n = e[r];
    if (!n || typeof n != "object")
      return `Entity at index ${r} must be an object with 'id' and 'type' fields.`;
    if (!n.id || typeof n.id != "string")
      return `Entity at index ${r} is missing a required 'id' string field.`;
    if (l.has(n.id))
      return `Duplicate entity id '${n.id}' found at index ${r}. Each entity must have a unique id.`;
    if (l.add(n.id), !n.type || typeof n.type != "string")
      return `Entity at index ${r} is missing a required 'type' string field.`;
    if (!ae.includes(n.type.toUpperCase()))
      return `Entity at index ${r} has an invalid type '${n.type}'. Valid values are: ${ae.join(", ")} (case-insensitive).`;
  }
  return t !== void 0 && (typeof t != "number" || !Number.isInteger(t) || t < 1 || t > 50) ? "The 'pageSize' setting must be an integer between 1 and 50." : null;
}, Xe = ({
  entities: e,
  sdk: t,
  pageSize: l
}) => {
  var a;
  const { t: r } = D(), n = G(), g = X().surface, p = H(
    () => De(e, l),
    [e, l]
  ), d = H(
    () => !p && e.length > 1 && e.every((f) => f.type.toUpperCase() === "CLASSIC_QUIZ"),
    [e, p]
  ), m = d ? _ : ((a = e[0]) == null ? void 0 : a.id) || "", [h, P] = M(m);
  U(() => {
    h === _ || e.some((y) => y.id === h) || P(m);
  }, [e]);
  const { data: i, entityTitles: x, loading: C, error: z, setPage: S, userRank: b } = We(
    p ? [] : e,
    t,
    p ? "" : h,
    l
  ), w = H(() => {
    if (p) return [];
    const f = [];
    return d && f.push({ id: _, label: r("leaderboard.overall") }), e.forEach((y) => {
      f.push({
        id: y.id,
        label: x[y.id] ?? "",
        type: y.type.toUpperCase()
      });
    }), f;
  }, [e, d, r, x, p]), u = e.every((f) => x[f.id] !== void 0), c = !p && (e.length > 1 || d) && u, o = (i == null ? void 0 : i.pagination) || null;
  return p ? /* @__PURE__ */ s(
    Y,
    {
      variant: "error",
      title: "Configuration Error",
      message: p
    }
  ) : z ? /* @__PURE__ */ s(
    Y,
    {
      variant: "error",
      title: "Failed to Load Leaderboard",
      message: "One or more entity IDs could not be found. Please verify the provided IDs and try again."
    }
  ) : /* @__PURE__ */ T(
    L,
    {
      sx: {
        display: "flex",
        flexDirection: "column",
        gap: n.md,
        backgroundColor: g,
        padding: n.md
      },
      children: [
        c && /* @__PURE__ */ s(
          Be,
          {
            options: w,
            selectedId: h,
            onChange: P
          }
        ),
        /* @__PURE__ */ s(
          Fe,
          {
            leaderboard: C ? null : (i == null ? void 0 : i.leaderboard) || null,
            userRank: C ? null : b,
            showHeading: !c,
            title: (i == null ? void 0 : i.title) || null,
            description: (i == null ? void 0 : i.description) || null,
            brandingColors: (i == null ? void 0 : i.branding) || null
          }
        ),
        !C && o && o.totalPages > 1 && /* @__PURE__ */ s(
          Ue,
          {
            count: o.totalPages,
            page: o.currentPage,
            onChange: S
          }
        )
      ]
    }
  );
}, Ge = (e) => {
  var x;
  const [t, l] = I.useState(!1), [r, n] = I.useState(!1), g = I.useRef(
    `leaderboard-shadow-root-${Math.random().toString(36).substring(2, 11)}`
  ), p = I.useRef(null), d = I.useRef(null), m = I.useRef(null), h = I.useRef(null);
  I.useEffect(() => {
    fe(e.language || "en").finally(() => n(!0));
  }, [e.language]), I.useEffect(() => {
    if (p.current)
      return p.current.shadowRoot ? (d.current = p.current.shadowRoot, m.current = d.current.getElementById(
        g.current
      ), m.current || (m.current = document.createElement("div"), m.current.id = g.current, d.current.appendChild(m.current))) : (d.current = p.current.attachShadow({ mode: "open" }), m.current = document.createElement("div"), m.current.id = g.current, d.current.appendChild(m.current)), h.current || (h.current = he({
        key: "leaderboard-css",
        prepend: !0,
        container: d.current
      })), l(!0), () => {
        l(!1);
      };
  }, []);
  const P = /* @__PURE__ */ s(L, { ref: p }), i = t && r && m.current && h.current ? Ce(
    /* @__PURE__ */ s(ge, { value: h.current, children: /* @__PURE__ */ s(be, { containerRef: p, children: /* @__PURE__ */ s(
      ye,
      {
        customTheme: e.themeOptions,
        mode: (x = e.themeOptions) == null ? void 0 : x.mode,
        shadowRootElement: m.current,
        children: /* @__PURE__ */ s(
          xe,
          {
            shadowRootElement: m.current,
            leadPhoneCountryCode: null,
            language: e.language,
            optionsLayout: null,
            children: e.children
          }
        )
      }
    ) }) }),
    m.current
  ) : null;
  return /* @__PURE__ */ T(le, { children: [
    P,
    i
  ] });
}, je = (e) => /* @__PURE__ */ s(Ge, { ...e, children: /* @__PURE__ */ s(Xe, { ...e }) }), it = je;
export {
  it as Leaderboard
};
