jQuery(document).ready(function() {
var Hash_String = window.location.search;
	const Hash_Param = new URLSearchParams(Hash_String);
	if(Hash_Param.has('hash')){
		console.log('In setting hash');
		document.cookie = "storefront_digest=" + Hash_Param.get('hash') +"; path=/";
		var shop_name = window.location.hostname;
		window.location.href="https://"+shop_name;
	}

    var current_url = window.location + " ";
	$('main').append(
		'<div id="updateModal" class="modal" style="display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 999; /* Sit on top */ padding-top: 5%; /* Location of the box */ left: 0;	top: 0;	width: 100%; /* Full width */ height: 100%; /* Full height */	overflow: auto; /* Enable scroll if needed */ background-color: rgb(0,0,0); /* Fallback color */ background-color: rgba(0,0,0,0.4); /* Black w/ opacity */	opacity:1;">' +

		'<div class="mo-modal-content">' +

		'<p><span id = "MOclosebuttonprofile" onclick="closeUpdateModal();" class="close" style="float: right;font-size: 21px;font-weight: 700;line-height: 1;color: #000;text-shadow: 0 1px 0 #fff;filter: alpha(opacity=20);opacity: .2; cursor: pointer">x</span></p>' +
		'<p id="MOupdateheading" style="color:#0d0d0d; text-align: center; font-weight: 600; font-size: 22px; display:inline-block; font-family:sans-serif ; border-bottom: 3px solid #d47303;" >UPDATE PROFILE</p><br><br>' +
		'<p style="text-align: center; color: #131212; font-weight: 600; font-family:sans-serif; font-size: 18px;" id="userEmailText">Email</p>' +
		'<input type="text" style="display:inline-block; background-color: #f5f4f4; color:#0d0d0d; padding:18px 36px; text-align: center; font-size:14px; margin:5px; width:100%; border: 2px solid #f6f6f6;"  id="userEmail" >' +
		'<hr style="margin: 0.5rem 0;">' +
		'<p style="text-align: center; color: #131212; font-weight: 600; font-family:sans-serif; font-size: 18px;" id="firstName">Enter First Name</p>' +
		'<input type="text" style="display:inline-block; background-color: #f5f4f4; color:#0d0d0d; padding:18px 36px; text-align: center; font-size:14px; margin:5px; width:100%; border: 2px solid #f6f6f6;"  id="updateFirstName" >' +
		'<label id="mobileError" style="color:#de621b;"></label><br>' +
		'<hr style="margin: 0.5rem 0;">' +
		'<p style="text-align: center; color: #131212; font-weight: 600; font-family:sans-serif; font-size: 18px;" id="lastName">Enter Last Name</p>' +
		'<input type="text" style="display:inline-block; background-color: #f5f4f4; color:#0d0d0d; padding:18px 36px; text-align: center; font-size:14px; margin:5px; width:100%; border: 2px solid #f6f6f6;"  id="updateLastName" >' +
		'<label id="mobileError" style="color:#de621b;"></label><br>' +
		'<hr style="margin: 0.5rem 0;">' +
		'<button id="mo_button" onclick="return updateWeb3CustomerProfile();" class="btn" style="cursor: pointer; border: 1px solid transparent; background-color:#f16c13; text-align=center; box-shadow: 0 10px 30px 0 rgba(233, 189, 95, 0.4); border-radius: 5px 5px 5px 5px; color:white; font-size:17px; padding:13px 60px;">UPDATE</button><br>' +
		'</div>' +

		'</div>');


	var styles = '.mo-modal-content {' +
		'box-shadow: 1px 1px 6px 1px;' +
		'background-color: #fefefe; margin: auto; padding: 20px; border: 1px solid #888; width: 30%; text-align:center;}' +
		'html {-ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%}' +
		'body {line-height: 1.1; color: #333; background-color: #fff;}' +
		'div[class^="iti__flag"] { display: inline-block ;}' +
		'#MOLoginModal{' +
		' padding-top: 8%; background-color: rgba(0,0,0,0.4); opacity:1}' +
		'@media (max-width : 420px){ #MOLoginModal .mo-modal-content {' +
		'background-color: rgba(0,0,0,0.4) box-shadow: 2px 2px 6px 2px; margin: auto; padding: 20px; border: 1px solid #888; width: 92%; text-align:center;' +
		'}' +
		'#updateModal{' +
		' padding-top: 8%; background-color: rgba(0,0,0,0.4); opacity:1}' +
		'@media (max-width : 420px){ #updateModal .mo-modal-content {' +
		'background-color: rgba(0,0,0,0.4) box-shadow: 2px 2px 6px 2px; margin: auto; padding: 20px; border: 1px solid #888; width: 92%; text-align:center;' +
		'}' +

		'.close {color: #aaaaaa; float: right; position: relative; top: -16px; font-size: 28px; font-weight: bold;}' +

		'.close:hover,' +
		'.close:focus { color: #000; text-decoration: none; cursor: pointer; }' +
		'.modal { display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 999; /* Sit on top */ padding-top: 5%; /* Location of the box */ left: 0;	top: 0;	width: 100%; /* Full width */ height: 100%; /* Full height */	overflow: auto; /* Enable scroll if needed */ background-color: rgb(0,0,0); /* Fallback color */ background-color: rgba(0,0,0,0.4); /* Black w/ opacity */	opacity:1; }';

	var styleSheet = document.createElement("style");
	styleSheet.type = "text/css";
	styleSheet.innerText = styles;
	document.head.appendChild(styleSheet);

	if (current_url.indexOf("account") > 0 && current_url.indexOf("account/login") < 0 && current_url.indexOf("account/register") < 0) {
		var anchors = document.querySelectorAll('a[href*="/account/addresses"]');
		var els1 = anchors[0];
		var el = document.createElement("div");
		el.innerHTML = '<a href="#" id="profile_update" onclick="return openUpdateModal();">Update Profile</a><br><br>';
		els1.parentNode.insertBefore(el, els1);
		$.ajax({
			url: "/apps/blockchain/web3/getweb3customer",
			type: "GET",
			success: function(data, text) {
				if (data.error == undefined) {

					document.getElementById("userEmail").value = data.email;
					document.getElementById("updateFirstName").value = data.firstName;
					document.getElementById("updateLastName").value = data.lastName;

				}
			},
			error: function(request, status, error) {
				alert('Error error');
			}
		});
	}

	$('a[href^="/account/logout"]').on("click", function() {
		$.ajax($(this).attr('href'))
			.done(function() {
				deleteCookie('storefront_digest');
				deleteCookie('walletAddress');
				window.location.reload();
			});
		return false;
	});
	$("#my_button").on("click", async function() {
connectWallet('login')
;return false;
});
	var cartValue = getCookie("cart");
	if(typeof cartValue !== 'undefined'){
    createCookie("cart", cartValue, 15);
  }
});async function updateWeb3CustomerProfile(){
    $.ajax({
      url: '/apps/cryptowallet/web3/updateweb3customer?first_name=' + document.getElementById("updateFirstName").value + '&last_name=' + document.getElementById("updateLastName").value + '&email=' + document.getElementById("userEmail").value + '&walletAddress=' + publicAddress,
      type: "GET",
      success: function(data, text) {
        if (data.status == 'success') {
          showSuccessMessage('updateprofile');
          window.alert("Profile Updated Successfully!");
        }else{
          console.log(JSON.stringify(data));
          window.alert("Error error!");
          showMessage("Error Updating Profile", "msg");
        }
      },
      error: function(request, status, error) {
        alert("Error error");
        showMessage("Error Connecting Wallet", "msg");
      }
    });
  }

function openUpdateModal() {
	document.getElementById('updateModal').style.display = 'block';
}

function closeUpdateModal() {
  document.getElementById('updateModal').style.display = 'none';
}

function getCheckoutUrl() {
	var checkout_url;
	var queryString = window.location.search;
	const urlParams = new URLSearchParams(queryString);
	if (urlParams.has('checkout_url')) {
		checkout_url = "/checkout";
	} else {
		checkout_url = "/account";
	}
	return checkout_url;
}

function getCookie(cookieName) {
	let cookie = {};
	document.cookie.split(";").forEach(function(el) {
		let [key, value] = el.split("=");
		cookie[key.trim()] = value;
	})
	return cookie[cookieName];
}

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	} else {
		expires = "";
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}

function deleteCookie(name){
  document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}function showMessage(msg, msgType = "error") {
	let para;
	if (elementExist()) {
		para = createElement();
	} else {
		para = document.getElementById("customErrorMsg");
	}
	if (msgType == "msg") {
		para.style.borderLeftColor = "#72aee6";
	} else if (msgType == "success") {
		para.style.borderLeftColor = "#198754";
	} else {
		para.style.borderLeftColor = "#d63638";
	}
	para.innerHTML = msg;
}


function elementExist(id = "customErrorMsg") {
	return document.getElementById(id) == null;
}

function createElement() {

	const para = document.createElement('p');
	para.setAttribute("id", "customErrorMsg");
	const h1 = document.getElementById("mo_button");
	insertAfter(para, h1);
	return para;

}

function insertAfter(newNode, referenceNode) {
	referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

"use strict";
const Web3Modal = window.Web3Modal.default;
let web3Modal;
let provider;
let selectedAccount;
let web3ModalProv;
async function intiateWe3Login() {
	await web3ModalInit();
}

function web3ModalInit() {
	const CHAIN_ID = 1;
	const providerOptions = {
	};

	web3Modal = new Web3Modal({
		cacheProvider: false,
		providerOptions,
		disableInjectedProvider: false,
	});
}

async function fetchAccountData() {
	web3ModalProv = new Web3(provider);
	provider.on("accountsChanged", (accounts) => {
   if(typeof accounts != 'undefined' && accounts.length == 0) web3ModalProv = undefined;
		console.log(accounts);
	});

	provider.on("chainChanged", (chainId) => {
		console.log(chainId);
	});

	provider.on("disconnect", (code, reason) => {
		console.log(code, reason);
	});
}

async function refreshAccountData() {
	await fetchAccountData(provider);
}

async function onConnectLoadWeb3Modal() {

	try {
		// await web3Modal.clearCachedProvider();
		provider = await web3Modal.connect();
	} catch (e) {
		console.log(e);
		return {
			err: e
		};
	}

	await refreshAccountData();
	return {
		err: null
	};
}

window.addEventListener('load', async () => {
	web3ModalInit();
});

async function intiateWeb3Object(){
	await web3ModalInit();
	let msg = "";
	msg = await onConnectLoadWeb3Modal();
	if (msg.err) {
		console.log("fetchAddress ", msg.err);
		return;
	}

	if (web3ModalProv) {
		window.web3 = web3ModalProv;
	}
}

async function checkMetamask(){
	if (typeof window.ethereum !== 'undefined') {
		return true;
	}
	return false;
}

async function fetchAddress() {
let metamaskInstalled = await checkMetamask();
	if(metamaskInstalled == false){
		alert("Please Install Metamask on your browser");
		return;
	}
	let accountsOnEnable;
	if(typeof web3ModalProv == 'undefined'){
		var current_url = window.location + " ";
		await intiateWeb3Object();
	}
	try {
		if(typeof provider != 'undefined') accountsOnEnable = await web3.eth.getAccounts();
		else return null;
	} catch (error) {
		console.error("error ", error.message);
	}
	let address = accountsOnEnable[0];
	if(typeof address != 'undefined') address = address.toLowerCase();
		else return null;
	console.log(address);
	return address;
}

async function getPostSignatureUrl(type, publicAddress, signature, checkoutUrl){
	let url = '';
	if(type == 'connectwallet' || type == 'thankyoupage' || type == 'adminmint'){
		url = '/apps/blockchain/web3/connectwallet/' + publicAddress + '/' + signature;
	}else if(type == 'updateprofile'){
		url = "/apps/blockchain/web3/updateweb3customer?first_name=" + document.getElementById("updateFirstName").value + "&last_name=" + document.getElementById("updateLastName").value + "&email=" + document.getElementById("userEmail").value + "&walletAddress=" + publicAddress +"&web3Signature=" + signature;
	}else if(type == 'login'){
		var shopName = window.location.host;
		url = '/apps/blockchain/web3/authorize/' + shopName + '/' + publicAddress + '/' + signature + checkoutUrl;
	}else if(type == 'checkout'){
		var shopifyCustomerId = '';
		var cartValue = getCookie("cart");
		if(ShopifyAnalytics.meta.page.customerId !== undefined) shopifyCustomerId = ShopifyAnalytics.meta.page.customerId;
		url = '/apps/blockchain/web3/digest/' + publicAddress + '/' + signature + '/' + cartValue + '?shopifyCustomerId='+shopifyCustomerId;
	}
	return url;
}
function disableMOButton(){
	$('#mo_button').attr('disabled','disabled');
	$('#mo_button').text('Wallet Connected');
}

async function showSuccessMessage(type){
	let successMessage = '';
	if(type == 'updateprofile'){
		successMessage = 'Updated Profile successfully';
	}else if(type == 'connectwallet'){
		disableMOButton();
	}else if(type == 'adminmint'){
		 disableMOButton();
	   document.getElementById('walletNote').textContent = "Your wallet is connected successfully! You will get notification once NFT is transferred to your wallet. Thank you!"; 
}
else if(type == 'thankyoupage'){
		disableMOButton();
		document.getElementById('connectWalletDiv').style.display = 'none';
  var element = document.getElementsByClassName('section')[1];
  element.style.filter='blur(0px)';
	}
	showMessage(successMessage, "msg");
	return;
}

var publicAddress;

async function connectWallet(type) {
	let address = await fetchAddress();
	if (address == null) {
		showMessage("<strong>Error:</strong> Please complete the authentication from wallet ");
		return;
	}
	console.log("address: " + address);

	let ajaxurl = '/apps/blockchain/web3/message/' + address;
	jQuery.get(ajaxurl, function(response) {
		if (response['status'] != 'error') {
			let message = response['message'];
			publicAddress = address;

			handleSignMessage(message, publicAddress)
				.then(handleAuthenticate)
				.catch((error) => {
					console.log("error", error);
		showMessage("<strong>Error:</strong> Please complete the authentication from wallet ");
					return;
				})

			function handleSignMessage(message, publicAddress) {
				return new Promise((resolve, reject) => {
					web3.eth.personal.sign(web3.utils.utf8ToHex(message), publicAddress,
						(err, signature) => {
							if (err) {
								console.log("", err);
		showMessage("<strong>Error:</strong> Please complete the authentication from wallet ");
								return reject({
									msg: err.message
								});
							}
							return resolve({
								publicAddress,
								signature
							});
							s
						}
					)

				});

			}

			async function handleAuthenticate({
				publicAddress,
				signature
			}) {
				
				if(type == 'login' || type == 'checkout'){
					showMessage("Verifying your signature", "msg");
					var checkoutUrl = getCheckoutUrl();
					let url = await getPostSignatureUrl(type, publicAddress, signature, checkoutUrl);
					location.href = url;
				}else if(type == 'connectwallet' || type == 'adminmint' || type == 'updateprofile' || type == 'thankyoupage'){
					showMessage("Connecting Wallet", "msg");
					$.ajax({
						url: await getPostSignatureUrl(type, publicAddress, signature, ''),
						type: "GET",
						success: function(data, text) {
							if (data.status == 'success') {
								console.log(type);
								showSuccessMessage(type);
							}else{
								console.log(JSON.stringify(data));
								window.alert("Error error!");
								showMessage("Error Connecting Wallet", "msg");
							}
						},
						error: function(request, status, error) {
							alert("Error error");
							showMessage("Error Connecting Wallet", "msg");
						}
					});
				}
			}

		}
	});

}