import { useEffect, useReducer, useState, type Dispatch, type Reducer, type StateUpdater } from "preact/hooks";

export const storedStateKey = (key: string) => `useStoredState.${GAME}.${key}`;
export const storedReducerKey = (key: string) => `useStoredReducer.${GAME}.${key}`;

export const useStoredState = <T>(key: string, initialValue: T) => {
    const storedKey = storedStateKey(key);

    const [value, setValue] = useState<T>(() => {
        try {
            const storedValue = localStorage.getItem(storedKey);
            return storedValue ? JSON.parse(storedValue) : initialValue;
        } catch {
            return initialValue;
        }
    });

    useEffect(() => {
        localStorage.setItem(storedKey, JSON.stringify(value));
    }, [storedKey, value]);

    return [value, setValue] as [T, Dispatch<StateUpdater<T>>];
};

export const useStoredReducer = <T, A>(key: string, reducer: Reducer<T, A>, initialValue: T) => {
    const storedKey = storedReducerKey(key);

    const getInitialValue = (): T => {
        try {
            const storedValue = localStorage.getItem(storedKey);
            return storedValue ? JSON.parse(storedValue) : initialValue;
        } catch {
            return initialValue;
        }
    };

    const [state, dispatch] = useReducer(reducer, undefined, getInitialValue);

    useEffect(() => {
        localStorage.setItem(storedKey, JSON.stringify(state));
    }, [storedKey, state]);

    return [state, dispatch] as [T, Dispatch<A>];
};
