// Auth context: provides user state + login/register/logout/refresh via /api/auth/* endpoints

const AuthCtx = React.createContext({
  user: null,
  loading: true,
  login: () => {},
  register: () => {},
  logout: () => {},
  refresh: () => {},
});

const AuthProvider = ({ children }) => {
  const [state, setState] = React.useState({ user: null, loading: true });

  const refresh = React.useCallback(async () => {
    try {
      const r = await fetch('/api/auth/me', { credentials: 'same-origin', cache: 'no-store' });
      if (r.ok) {
        const data = await r.json();
        setState({ user: data.user, loading: false });
      } else {
        setState({ user: null, loading: false });
      }
    } catch (e) {
      setState({ user: null, loading: false });
    }
  }, []);

  React.useEffect(() => { refresh(); }, [refresh]);

  const login = async ({ email, password, rememberMe }) => {
    const r = await fetch('/api/auth/login', {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password, rememberMe: !!rememberMe }),
    });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) throw { status: r.status, ...data };
    setState({ user: data.user, loading: false });
    return data.user;
  };

  const register = async (input) => {
    const r = await fetch('/api/auth/register', {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(input),
    });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) throw { status: r.status, ...data };
    setState({ user: data.user, loading: false });
    return data.user;
  };

  const logout = async () => {
    try { await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' }); } catch (e) {}
    setState({ user: null, loading: false });
  };

  return (
    <AuthCtx.Provider value={{ ...state, login, register, logout, refresh }}>
      {children}
    </AuthCtx.Provider>
  );
};

const useAuth = () => React.useContext(AuthCtx);

Object.assign(window, { AuthCtx, AuthProvider, useAuth });
