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

interface CounterContextProps {
    count: number,
    increment: () => void,
    decrement: () => void,
}

const CounterContext = createContext<CounterContextProps | undefined>(undefined);

export const CounterProvider: React.FC<{children: React.ReactNode}> = ({children}) => {
    const [count, setCount] = useState(0);

    const increment = () => setCount(count + 1);
    const decrement = () => setCount(count - 1);

    return (
        <CounterContext.Provider value={{ count, increment, decrement }}>
            {children}
        </CounterContext.Provider>
    );
};

export const useCounter = () => {
    const context = useContext(CounterContext);
    if(!context) {
        throw new Error("useContext must be used within a CounterProvider");
    }

    return context;
};