'use client';

import { createContext, useContext, useState, useEffect } from 'react';
import { Member } from '@/types/account/member';
import { useAuthContext } from '@/contexts/authProvider';

const MemberContext = createContext<{
	member: Member|null;
	setMember: (member: Member|null) => void;
	isLoaded: boolean;
}>({
	member: null,
	setMember: () => {},
	isLoaded: false,
});

export function MemberProvider({ children }: { children: React.ReactNode }) {
	const [member, setMember] = useState<Member|null>(null);
	const [isLoaded, setLoaded] = useState<boolean>(false);
	const {isLoading, isAuthenticated } = useAuthContext();

	// 로그인된 회원 정보 조회
	useEffect(() => {
		if (isLoading) {
			return;
		}

		const storedMember = localStorage.getItem("member");

        if (isAuthenticated && storedMember) {
            setMember(JSON.parse(storedMember));
        } else {
			setMember(null);
		}

		setLoaded(true);

	}, [isLoading, isAuthenticated]);

	return (
		<MemberContext.Provider value={{ member, setMember, isLoaded }}>
			{children}
		</MemberContext.Provider>
	);
}

export function useMemberContext() {
	return useContext(MemberContext);
}