"use client";

import React, { createContext, FC, PropsWithChildren, useContext } from "react";

export default function makeContext<State, HookArgs = {}>(
    useValue: (args: HookArgs) => State,
    displayName?: string
) {
    const Context = createContext<State | undefined>(undefined);
    Context.displayName = displayName ?? "Custom";

    const Provider: FC<PropsWithChildren<HookArgs>> = ({
        children,
        ...hookArgs
    }) => {
        const value = useValue(hookArgs as HookArgs);
        return <Context.Provider value={value}>{children}</Context.Provider>;
    };

    const useContextHook = () => {
        const context = useContext(Context);
        if (!context) {
            throw new Error(
                `${Context.displayName}Context must be used within ${Context.displayName}ContextProvider`
            );
        }
        return context;
    };

    return [Provider, useContextHook] as const;
}
