<script>
	import { onMount } from 'svelte';
	import { checkAndSignAuthMessage } from '@lit-protocol/lit-node-client';
	import { LOCAL_STORAGE_KEYS } from '@lit-protocol/constants';

	let authSig = null;
	let error = null;

	async function generateAuthSig() {
		authSig = null;
		error = null;
		try {
			authSig = await checkAndSignAuthMessage({
				chain: 'xdai'
			});
		} catch (err) {
			console.error(err);
			error = `Failed to sign auth message: ${err.message}`;
		}
	}
	onMount(() => {
		const storedAuthSig = localStorage.getItem(LOCAL_STORAGE_KEYS.AUTH_SIGNATURE);
		if (storedAuthSig) {
			authSig = JSON.parse(storedAuthSig);
		}
	});
</script>

<!-- AuthSig Address Displayed -->
{#if authSig}
	<div class="bg-gray-100 p-4 rounded-lg shadow-md mb-4 flex items-center">
		<p class="text-gray-700 font-medium">
			AuthSig Address: <span class="text-orange-500">{authSig.address}</span>
		</p>
	</div>
	<!-- Error Message -->
{:else if error}
	<div class="bg-red-100 p-4 rounded-lg shadow-md mb-4 flex items-center">
		<p class="text-red-700 font-medium">{error}</p>
	</div>
	<!-- Login Button -->
{:else}
	<div class="flex justify-center">
		<button
			class="bg-orange-500 hover:bg-orange-600 text-white font-bold py-2 px-4 rounded-lg shadow-lg flex items-center m-2"
			on:click={generateAuthSig}
		>
			<img
				src="https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg"
				alt="MetaMask"
				class="w-6 h-6 mr-2"
			/>
			<span class="text-lg">Login</span>
		</button>
	</div>
{/if}
