"use client";

import { createContext, useContext, useState, useEffect, type ReactNode } from "react";
import { getCurrentEnvironment, setCurrentEnvironment } from "@/lib/api";

type EnvironmentContextType = {
  environment: string | null;
  setEnvironment: (env: string) => void;
};

const EnvironmentContext = createContext<EnvironmentContextType>({
  environment: null,
  setEnvironment: () => {},
});

export function EnvironmentProvider({ children }: { children: ReactNode }) {
  const [environment, setEnv] = useState<string | null>(null);

  useEffect(() => {
    setEnv(getCurrentEnvironment());
  }, []);

  function setEnvironment(env: string) {
    setCurrentEnvironment(env);
    setEnv(env);
  }

  return (
    <EnvironmentContext.Provider value={{ environment, setEnvironment }}>
      {children}
    </EnvironmentContext.Provider>
  );
}

export function useEnvironment() {
  return useContext(EnvironmentContext);
}
