'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, initialMember }: { children: React.ReactNode; initialMember?: Member|null }) {
	const [member, setMember] = useState<Member|null>(initialMember ?? null);
	const [isLoaded, setLoaded] = useState<boolean>(initialMember !== undefined);
	const {isLoading, isAuthenticated } = useAuthContext();

	// 서버에서 내려온 initialMember를 localStorage에 동기화 (source of truth = 서버)
	useEffect(() => {
		if (initialMember) {
			localStorage.setItem('member', JSON.stringify(initialMember));
		}
	}, [initialMember]);

	// 로그인된 회원 정보 조회
	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);
}