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

const AuthContext = createContext(null);

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

  useEffect(() => {
    const token = localStorage.getItem('scms_token');
    const username = localStorage.getItem('scms_username');
    if (token && username) {
      setUser({ username, token });
    }
    setLoading(false);
  }, []);

  const login = (token, username) => {
    localStorage.setItem('scms_token', token);
    localStorage.setItem('scms_username', username);
    setUser({ username, token });
  };

  const logout = () => {
    localStorage.removeItem('scms_token');
    localStorage.removeItem('scms_username');
    setUser(null);
  };

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

export const useAuth = () => useContext(AuthContext);
