import React, { createContext, useContext, useEffect, useState } from 'react';

const AuthContext = createContext();

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null); // { user_id, email }
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    try {
      const saved = JSON.parse(localStorage.getItem('auth_user') || 'null');
      if (saved && saved.user_id) setUser(saved);
    } catch {}
    setLoading(false);
  }, []);

  const login = async (email, password) => {
    const res = await fetch('http://localhost:8010/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ email, password }),
    });
    if (!res.ok) {
      // 서버가 에러 메시지를 JSON 으로 보낼 수도 있으므로 파싱 시도
      let msg = '로그인 실패';
      try { msg = (await res.json())?.detail || msg; } catch { /* ignore */ }
      throw new Error(msg);
    }
    const data = await res.json(); // { user_id, email }
    setUser(data);
    try { localStorage.setItem('auth_user', JSON.stringify(data)); } catch {}
    return data;
  };

  const logout = async () => {
    try {
      await fetch('http://localhost:8010/auth/logout', { method: 'POST', credentials: 'include' });
    } catch {}
    setUser(null);
    try { localStorage.removeItem('auth_user'); } catch {}
  };

  const value = { user, loading, login, logout };
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export function useAuth() {
  return useContext(AuthContext);
}


