<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="flex items-center p-4 mb-4 bg-gray-100 rounded-lg shadow-md">
		<p class="font-medium text-gray-700">
			AuthSig Address: <span class="text-orange-500">{authSig.address}</span>
		</p>
	</div>
	<!-- Error Message -->
{:else if error}
	<div class="flex items-center p-4 mb-4 bg-red-100 rounded-lg shadow-md">
		<p class="font-medium text-red-700">{error}</p>
	</div>
	<!-- Login Button -->
{:else}
	<div class="flex justify-center">
		<button
			class="flex items-center px-4 py-2 m-2 font-bold text-white bg-orange-500 rounded-lg shadow-lg hover:bg-orange-600"
			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}
