import Web3 from 'web3';
import LeumasTokenABI from "../../assets/LeumasToken.json";

const TOKEN_ADDRESS = `${import.meta.env.VITE_REACT_APP_LEUMAS_TOKEN_ADDRESS}`;

const connectMetaMask = async (setWeb3, setAccount, setTokenContract) => {
  if (typeof window.ethereum !== 'undefined') {
    try {
      const web3Instance = new Web3(window.ethereum);
      setWeb3(web3Instance);

      const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
      setAccount(accounts[0]);

      const contractInstance = new web3Instance.eth.Contract(LeumasTokenABI, TOKEN_ADDRESS);
      setTokenContract(contractInstance);
    } catch (error) {
      console.error('User denied account access...');
    }
  } else {
    alert('Please install MetaMask to use this feature!');
  }
};

export default connectMetaMask;
