<script>
	import { onMount } from 'svelte';
	import { PKPClient } from '@lit-protocol/pkp-client';
	import { PKPWalletConnect } from '@lit-protocol/pkp-walletconnect';
	import { checkAndSignAuthMessage } from '@lit-protocol/lit-node-client';

	let authSig;
	let uri = '';
	const PKP_PUBKEY =
		'046da3ba67065fd1e2726242ca01cd4601524893f4aa4b0042578fa6cbec28fa8c9a28eb9f7893932fc09717edc9e1db57e157a21eed346247c1db5a722a01f571';

	async function generateAuthSig() {
		authSig = await checkAndSignAuthMessage({ chain: 'xdai' });
		console.log('Generated authSig:', authSig);
	}

	// Set up PKP client
	const pkpClient = new PKPClient({
		controllerAuthSig: authSig,
		pkpPubKey: PKP_PUBKEY
	});

	const pkpWalletConnect = new PKPWalletConnect();

	async function initializePKPClient(authSig) {
		// Set up PKP client using the provided authSig
		const pkpClient = new PKPClient({
			controllerAuthSig: authSig,
			pkpPubKey: PKP_PUBKEY
		});

		await pkpClient.connect();
		pkpWalletConnect.addPKPClient(pkpClient);
	}

	async function initializeWalletConnect() {
		const config = {
			projectId: '7db8ca514b865088d90cebec1bf28318',
			metadata: {
				name: 'Test Wallet',
				description: 'Test Wallet',
				url: '#',
				icons: ['https://walletconnect.com/walletconnect-logo.png']
			}
		};
		await pkpWalletConnect.initWalletConnect(config);
	}

	function getSignClient() {
		return pkpWalletConnect.getSignClient();
	}

	function onSessionProposal(proposal) {
		console.log('Received session proposal: ', proposal);
		pkpWalletConnect.approveSessionProposal(proposal).then(() => {
			const sessions = Object.values(pkpWalletConnect.getActiveSessions());
			for (const session of sessions) {
				const { name, url } = session.peer.metadata;
				console.log(`Active Session: ${name} (${url})`);
			}
			console.log('\n' + '*'.repeat(50) + '\n');
		});
	}

	function onSessionRequest(requestEvent) {
		const isConfirmed = confirm(
			`The dApp ${requestEvent.params.request.method} is requesting an action. Do you want to proceed?`
		);

		if (isConfirmed) {
			console.log('Received session request: ', requestEvent);
			const { topic, params } = requestEvent;
			const { request } = params;
			const requestSession = getSignClient().session.get(topic);
			const { name, url } = requestSession.peer.metadata;
			console.log(`\nApproving ${request.method} request for session ${name} (${url})...\n`);
			pkpWalletConnect.approveSessionRequest(requestEvent).then(() => {
				console.log(`Check the ${name} dapp to confirm whether the request was approved`);
				console.log('\n' + '*'.repeat(50) + '\n');
			});
		} else {
			console.log(`User declined the ${requestEvent.params.request.method} request.`);
		}
	}

	function onSessionDelete(event) {
		console.log(`Session deleted ${JSON.stringify(event)}`);
		console.log('\n' + '*'.repeat(50) + '\n');
	}

	function connectToDapp(uri) {
		console.log(`Received URI: ${uri}`);
		pkpWalletConnect.pair({ uri: uri }).then(() => {
			console.log(`Number of pairings: ${getSignClient().core.pairing.pairings.values.length}`);
			console.log('\n' + '*'.repeat(50) + '\n');
		});
	}

	onMount(async () => {
		// Generate authSig first
		await generateAuthSig();

		// Now pass it to initializePKPClient
		await initializePKPClient(authSig);
		await initializeWalletConnect();

		pkpWalletConnect.on('session_proposal', onSessionProposal);
		pkpWalletConnect.on('session_request', onSessionRequest);
		getSignClient().on('session_delete', onSessionDelete);
		const uri = '';
		connectToDapp(uri);
	});

	function handleConnect() {
		connectToDapp(uri);
	}
</script>

<main class="flex flex-col items-center justify-center">
	<h1 class="text-2xl font-bold mb-4">Connect to dapp:</h1>
	<input type="text" bind:value={uri} placeholder="Enter the URI" class="p-2 mb-4 text-lg w-72" />
	<button
		on:click={handleConnect}
		class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Connect</button
	>
</main>
