import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  ReactNode,
} from "react";

export type KGDisplayMode = "single" | "multiple";

interface KGDisplayModeContextType {
  mode: KGDisplayMode;
  setMode: (mode: KGDisplayMode) => void;
  toggleMode: () => void;
}

const KGDisplayModeContext = createContext<
  KGDisplayModeContextType | undefined
>(undefined);

export function KGDisplayModeProvider({ children }: { children: ReactNode }) {
  const [mode, setModeState] = useState<KGDisplayMode>("multiple");

  // Load saved mode from localStorage on mount
  useEffect(() => {
    const savedMode = localStorage.getItem("kg-display-mode") as KGDisplayMode;
    if (savedMode && (savedMode === "single" || savedMode === "multiple")) {
      setModeState(savedMode);
    }
  }, []);

  // Save mode to localStorage when it changes
  const setMode = (newMode: KGDisplayMode) => {
    setModeState(newMode);
    localStorage.setItem("kg-display-mode", newMode);
  };

  const toggleMode = () => {
    const newMode = mode === "single" ? "multiple" : "single";
    setMode(newMode);
  };

  return (
    <KGDisplayModeContext.Provider value={{ mode, setMode, toggleMode }}>
      {children}
    </KGDisplayModeContext.Provider>
  );
}

export function useKGDisplayMode() {
  const context = useContext(KGDisplayModeContext);
  if (context === undefined) {
    throw new Error(
      "useKGDisplayMode must be used within a KGDisplayModeProvider"
    );
  }
  return context;
}
