<script>
	import { onMount } from 'svelte';

	import { PKPEthersWallet } from '@lit-protocol/pkp-ethers';
	import { LOCAL_STORAGE_KEYS } from '@lit-protocol/constants';

	let pkpWallet;
	let authSig = null;

	// Load wallet on component mount
	onMount(async () => {
		const storedAuthSig = localStorage.getItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE);

		if (storedAuthSig) {
			authSig = JSON.parse(storedAuthSig);
			pkpWallet = new PKPEthersWallet({
				controllerAuthSig: authSig,
				pkpPubKey:
					'046da3ba67065fd1e2726242ca01cd4601524893f4aa4b0042578fa6cbec28fa8c9a28eb9f7893932fc09717edc9e1db57e157a21eed346247c1db5a722a01f571',
				rpc: 'https://rpc.gnosischain.com/'
			});
			await pkpWallet.init();
			console.log(pkpWallet);
		} else {
			alert('no authsig');
		}
	});

	const sendTransaction = async () => {
		if (!authSig) {
			alert('no authsig');
		} else {
			console.log('transaction initiated');
			const from = pkpWallet.address;
			const to = '0x1A5cfC9EA11afb50011F847fb7dC07bA1e18b05A';
			const value = BigInt(10000000000000000);
			const gasLimit = 21000;

			// @lit-protocol/pkp-ethers will automatically add missing fields (nonce, chainId, gasPrice, gasLimit)
			const transactionRequest = {
				from,
				to,
				value,
				gasLimit
			};
			console.log('transaction request created');

			const signedTransactionRequest = await pkpWallet.signTransaction(transactionRequest);
			await pkpWallet.sendTransaction(signedTransactionRequest);
			console.log('transaction sent');
		}
	};
</script>

<div class="p-4 bg-gray-200 flex justify-center items-center flex-col">
	{#if pkpWallet}
		<div class="mb-4 text-lg font-medium">
			PKP Wallet: <span class="text-blue-600">{pkpWallet.address}</span>
		</div>
	{/if}
	<button
		class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full shadow-lg focus:outline-none focus:shadow-outline-blue active:bg-blue-800 transition duration-150 ease-in-out"
		on:click={sendTransaction}
	>
		send 0.01 xdai
	</button>
</div>
