import React, { createContext, useContext, useMemo, useReducer } from "react";
import { appModeReducer } from "./reducer";
import { initialAppModeState } from "./types";
import type { AppModeEvent, AppModeState } from "./types";

type AppModeContextValue = {
  state: AppModeState;
  dispatch: React.Dispatch<AppModeEvent>;
};

const AppModeContext = createContext<AppModeContextValue | undefined>(
  undefined
);

export function AppModeProvider({
  children,
}: {
  children: React.ReactNode;
}): React.JSX.Element {
  const [state, dispatch] = useReducer(appModeReducer, initialAppModeState);
  const value = useMemo(() => ({ state, dispatch }), [state]);
  return (
    <AppModeContext.Provider value={value}>{children}</AppModeContext.Provider>
  );
}

export function useAppMode(): AppModeContextValue {
  const ctx = useContext(AppModeContext);
  if (!ctx) {
    throw new Error("useAppMode must be used within an AppModeProvider");
  }
  return ctx;
}
