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

const AuthContext = createContext();

export const AuthProvider = ({ children }) => { // ONE declaration of AuthProvider
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [user, setUser] = useState(null);

  const login = async (credentials) => {
    // Mock authentication logic
    if (credentials.username === 'user' && credentials.password === 'password') {
      setIsLoggedIn(true);
      setUser({ username: credentials.username });
      return Promise.resolve(); // Resolve promise on successful login
    } else {
      setIsLoggedIn(false);
      setUser(null);
      return Promise.reject(new Error('Invalid credentials')); // Reject promise on invalid credentials
    }
  };

  const register = async (credentials) => {
    // Mock registration logic
    if (credentials.username && credentials.password) {
      setIsLoggedIn(true);
      setUser({ username: credentials.username });
      return Promise.resolve(); // Resolve promise on successful registration
    } else {
      setIsLoggedIn(false);
      setUser(null);
      return Promise.reject(new Error('Registration failed')); // Reject promise on failed registration
    }
  };

  const logout = () => {
    setIsLoggedIn(false);
    setUser(null);
  };

  const value = {
    isLoggedIn,
    user,
    login,
    register,
    logout
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  return useContext(AuthContext);
};