import { jsx as a, jsxs as K } from "react/jsx-runtime";
import { createContext as O, use as V, useState as $, useRef as W, useMemo as g, useCallback as y, useEffect as f } from "react";
import { useTheme as A, CssBaseline as B, StyledEngineProvider as q, ThemeProvider as z, GlobalStyles as Y } from "@mui/material";
import { deepmerge as J } from "@mui/utils";
import M from "lodash/set";
import Q from "lodash/isUndefined";
import { useDebounceFn as X, useCreation as P } from "ahooks";
import { getBlockletThemeOptions as Z, BLOCKLET_THEME_PREFER_KEY as h, isValidThemeMode as ee, getDefaultThemePrefer as _ } from "@blocklet/theme";
import { useLocationState as te } from "../hooks/use-location-state.js";
import { createTheme as T, lazyCreateDefaultTheme as oe, isUxTheme as re, isTheme as ne } from "./theme.js";
const se = T(), N = O({});
function U() {
  return V(N);
}
const D = (c) => c ? c === "system" ? _({ theme: { prefer: "system" } }) : c : _();
function L({ className: c = void 0 }) {
  const o = A(), n = "transparent", s = o.palette.grey[300], t = (c || "").trim().split(/\s+/).filter(Boolean).map((m) => m.startsWith(".") ? m : `.${m}`).join(" "), d = t ? `${t}::-webkit-scrollbar, ${t} *::-webkit-scrollbar` : "*::-webkit-scrollbar", r = t ? `${t}::-webkit-scrollbar-track, ${t} *::-webkit-scrollbar-track` : "*::-webkit-scrollbar-track", i = t ? `${t}::-webkit-scrollbar-thumb, ${t} *::-webkit-scrollbar-thumb` : "*::-webkit-scrollbar-thumb", u = t ? `${t}::-webkit-scrollbar-corner, ${t} *::-webkit-scrollbar-corner` : "*::-webkit-scrollbar-corner", k = t ? `${t}, ${t} *` : "*";
  return /* @__PURE__ */ a(
    Y,
    {
      styles: {
        // Chrome, Safari, Edge
        "@supports selector(::-webkit-scrollbar)": {
          [d]: {
            width: "12px",
            height: "12px"
          },
          [r]: {
            background: n
          },
          [i]: {
            background: s,
            borderRadius: "6px",
            border: "2px solid",
            borderColor: n,
            backgroundClip: "padding-box",
            "&:hover": {
              background: o.palette.grey[400],
              backgroundClip: "padding-box"
            }
          },
          [u]: {
            background: n
          }
        },
        // Firefox
        "@supports not selector(::-webkit-scrollbar)": {
          [k]: {
            scrollbarWidth: "auto",
            scrollbarColor: `${s} ${n}`
          }
        }
      }
    }
  );
}
let R = !1;
const j = {};
function F({
  children: c = null,
  theme: o = se,
  injectFirst: n = !0,
  darkSchemeClass: s = "",
  disableStyleCache: t = !1
}) {
  const d = g(() => typeof o == "function" || ne(o) ? o : T(o), [o]), r = P(() => t ? /* @__PURE__ */ a(B, {}) : R ? null : (R = !0, /* @__PURE__ */ a(B, {})), [t]), i = P(() => t ? /* @__PURE__ */ a(L, { className: s }) : j[s] ? null : (j[s] = !0, /* @__PURE__ */ a(L, { className: s })), [s, t]);
  return (
    // injectFirst 会影响 makeStyles 自定义样式和 mui styles 覆盖问题
    /* @__PURE__ */ a(q, { injectFirst: n, children: /* @__PURE__ */ K(z, { theme: d, children: [
      r,
      i,
      c
    ] }) })
  );
}
function le({
  children: c = null,
  theme: o = void 0,
  prefer: n = void 0,
  disableBlockletTheme: s = !1,
  ...t
}) {
  const d = U(), [r, i] = $(() => D(n)), [u, k] = $(null), m = A(), p = te(), b = W(null), C = Q(d.toggleMode), { run: S } = X(
    (e) => {
      k(e);
    },
    {
      wait: 200
    }
  ), v = g(() => {
    let e = {};
    if (o) {
      const H = oe(r);
      if (typeof o == "function") {
        const I = H();
        re(m) ? e = { ...o(m, { mode: r }) } : e = { ...o(I, { mode: r }) };
      } else
        e = { ...o };
    }
    let l = r;
    return u && (l = u.mode || "light", e = J(e, Z(l, u))), M(e, "palette.mode", l), M(e, "mode", l), e;
  }, [r, o, m, u]), w = g(() => T({ ...v, disableBlockletTheme: !!u || s }), [v, s, u]), E = y(() => {
    const e = r === "light" ? "dark" : "light";
    i(e), sessionStorage.removeItem(h), localStorage.setItem(h, e);
  }, [r, i]), x = y(
    (e) => {
      r !== e && (i(e), sessionStorage.removeItem(h), localStorage.setItem(h, e));
    },
    [r, i]
  ), G = g(
    () => ({
      mode: r,
      toggleMode: E,
      changeMode: x,
      prefer: n
    }),
    [r, n, E, x]
  );
  return f(() => {
    i(D(n));
  }, [n, i, p.search]), f(() => {
    const e = new URLSearchParams(p.search).get("theme");
    ee(e) && sessionStorage.setItem(h, e);
  }, [p.search]), f(() => {
    b.current || (b.current = document.querySelector('meta[name="theme-color"]'));
    const e = w.palette.background.default;
    if (b.current)
      b.current.setAttribute("content", e);
    else {
      const l = document.createElement("meta");
      l.name = "theme-color", l.content = e, document.head.appendChild(l), b.current = l;
    }
  }, [w.palette.background.default]), f(() => {
    const e = (l) => {
      l.origin === window.origin && l.data.type === "THEME_BUILDER_CONFIG_CHANGED" && S(l.data.payload);
    };
    return window.addEventListener("message", e), () => window.removeEventListener("message", e);
  }, [S]), f(() => {
    C && (r === "dark" ? document.documentElement.setAttribute("data-theme", "dark") : document.documentElement.removeAttribute("data-theme"));
  }, [C, r]), /* @__PURE__ */ a(N, { value: G, children: /* @__PURE__ */ a(F, { theme: w, ...t, children: c }) });
}
function ke({
  children: c = null,
  prefer: o = void 0,
  enableColorScheme: n = !1,
  ...s
}) {
  const { toggleMode: t } = U();
  return n || o || !t ? /* @__PURE__ */ a(le, { prefer: o, ...s, children: c }) : /* @__PURE__ */ a(F, { ...s, children: c });
}
export {
  N as ColorSchemeContext,
  ke as default,
  U as useColorScheme
};
