import React, { PropsWithChildren } from "react";

const localStorageKey = "public-mode";

interface PublicModeContext {
  enabled: boolean;
  setEnabled: (enabled: boolean) => void;
}

const PublicModeContextK = React.createContext<PublicModeContext | null>(null);

export function PublicModeProvider(p: PropsWithChildren): React.ReactElement {
  const [enabled, setEnabled] = React.useState(
    localStorage.getItem(localStorageKey) === "true"
  );

  return (
    <PublicModeContextK
      value={{
        enabled: enabled,
        setEnabled(enabled) {
          localStorage.setItem(localStorageKey, enabled ? "true" : "false");
          setEnabled(enabled);
        },
      }}
    >
      {p.children}
    </PublicModeContextK>
  );
}

export function usePublicMode(): PublicModeContext {
  return React.use(PublicModeContextK)!;
}
