import { jsx, jsxs, Fragment as Fragment$1 } from "react/jsx-runtime";
import { createContext, useState, useMemo, useContext, useEffect, Fragment } from "react";
import curry from "lodash/curry.js";
import { darkMode } from "../css/atoms/sprinkles.css.mjs";
import { BraidProvider, makeLinkComponent } from "../../../side-effects/lib/components/BraidProvider/BraidProvider.mjs";
import { ToastProvider } from "../components/private/Placeholder/Placeholder.mjs";
import { useResponsiveValue } from "../components/Autosuggest/Autosuggest.mjs";
const unwrapValue = (value) => {
  let actualValue = value;
  if (typeof value === "object" && value !== null && "currentTarget" in value) {
    const { currentTarget } = value;
    actualValue = currentTarget.type === "checkbox" ? currentTarget.checked : currentTarget.value;
  }
  return actualValue;
};
const makeStoreConsumer = (defaultState, store, setStore) => {
  const setDefaultState = (key, value) => {
    defaultState.set(key, value);
  };
  const getState = (key) => store.get(key) ?? defaultState.get(key);
  const setState = curry(
    (key, value) => setStore(new Map(store.set(key, unwrapValue(value))))
  );
  const toggleState = (key) => setState(key, !getState(key));
  const resetState = (...keys) => {
    if (keys.length) {
      keys.forEach((key) => {
        store.delete(key);
      });
      setStore(new Map(store));
    } else {
      setStore(/* @__PURE__ */ new Map());
    }
  };
  return {
    setDefaultState,
    getState,
    setState,
    toggleState,
    resetState
  };
};
const PlayroomStateContext = createContext(null);
const PlayroomStateProvider = ({
  defaultState: defaultStateProp,
  children
}) => {
  const [fallbackDefaultState] = useState(() => /* @__PURE__ */ new Map());
  const defaultState = defaultStateProp ?? fallbackDefaultState;
  const state = useState(/* @__PURE__ */ new Map());
  const storeConsumer = useMemo(
    () => makeStoreConsumer(defaultState, ...state),
    [state, defaultState]
  );
  return /* @__PURE__ */ jsx(PlayroomStateContext.Provider, { value: storeConsumer, children });
};
const usePlayroomStore = () => {
  const storeConsumer = useContext(PlayroomStateContext);
  if (storeConsumer === null) {
    throw new Error("Must be within a PlayroomStateProvider");
  }
  return storeConsumer;
};
const noop = () => {
};
function useFallbackState(stateKey, value, onChange, defaultValue) {
  const playroomState = usePlayroomStore();
  const [internalStateValue, setInternalStateValue] = useState(defaultValue);
  const wrapChangeHandler = (handler) => (...args) => {
    if (value === void 0) {
      (stateKey ? playroomState.setState(stateKey) : setInternalStateValue)(
        unwrapValue(args[0])
      );
    }
    return (handler || noop)(...args);
  };
  const handleChange = wrapChangeHandler(onChange || noop);
  const resolvedValue = value ?? (stateKey ? playroomState.getState(stateKey) ?? defaultValue : internalStateValue);
  return [resolvedValue, handleChange];
}
const PlayroomLink = makeLinkComponent(
  ({ href, onClick, ...restProps }, ref) => /* @__PURE__ */ jsx(
    "a",
    {
      ref,
      href: href ?? "#",
      onClick: (e) => {
        if (!href) {
          e.preventDefault();
        }
        if (onClick) {
          onClick(e);
        }
      },
      ...restProps
    }
  )
);
const ResponsiveReady = ({ children }) => {
  const responsiveReady = useResponsiveValue()({ mobile: true }) ?? false;
  return /* @__PURE__ */ jsx(Fragment$1, { children: responsiveReady ? children : null });
};
const FrameComponent = ({ theme, children }) => {
  useEffect(() => {
    let code = "";
    const darkTrigger = "braiddark";
    const lightTrigger = "braidlight";
    const longestTrigger = Math.max(lightTrigger.length, darkTrigger.length);
    const colorModeToggle = (ev) => {
      code += ev.key;
      if (code.substr(code.length - darkTrigger.length) === darkTrigger) {
        document.documentElement.classList.add(darkMode);
        code = "";
      }
      if (code.substr(code.length - lightTrigger.length) === lightTrigger) {
        document.documentElement.classList.remove(darkMode);
        code = "";
      }
      if (code.length > longestTrigger) {
        code = code.substr(code.length - longestTrigger);
      }
    };
    window.addEventListener("keydown", colorModeToggle);
    return () => {
      window.removeEventListener("keydown", colorModeToggle);
    };
  }, []);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        dangerouslySetInnerHTML: {
          __html: theme.webFonts.map((font) => font.linkTag).join("")
        }
      }
    ),
    /* @__PURE__ */ jsx(PlayroomStateProvider, { children: /* @__PURE__ */ jsx(BraidProvider, { theme, linkComponent: PlayroomLink, children: /* @__PURE__ */ jsx(ToastProvider, { children: /* @__PURE__ */ jsx(ResponsiveReady, { children }) }) }) })
  ] });
};
export {
  FrameComponent,
  useFallbackState,
  usePlayroomStore
};
