import { createContext, useContext, useState, useCallback, ReactNode } from 'react';

export interface ForgeState {
  forging: boolean;
  stage: string;
  progress: number; // 0–100
}

interface ForgeContextValue extends ForgeState {
  startForge: () => void;
  endForge: () => void;
  setStage: (stage: string, progress: number) => void;
}

const ForgeContext = createContext<ForgeContextValue>({
  forging: false,
  stage: '',
  progress: 0,
  startForge: () => {},
  endForge: () => {},
  setStage: () => {},
});

export function ForgeProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<ForgeState>({ forging: false, stage: '', progress: 0 });

  const startForge = useCallback(() =>
    setState({ forging: true, stage: 'Initializing forge...', progress: 0 }), []);

  const endForge = useCallback(() =>
    setState({ forging: false, stage: '', progress: 0 }), []);

  const setStage = useCallback((stage: string, progress: number) =>
    setState((s) => ({ ...s, stage, progress })), []);

  return (
    <ForgeContext.Provider value={{ ...state, startForge, endForge, setStage }}>
      {children}
    </ForgeContext.Provider>
  );
}

export function useForge() {
  return useContext(ForgeContext);
}
