<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) {
		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');
		});
	}

	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>
	<h1>Connect to dapp:</h1>
	<input type="text" bind:value={uri} placeholder="Enter the URI" />
	<button on:click={handleConnect}>Connect</button>
</main>

<style>
	main {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	input {
		padding: 8px;
		margin-bottom: 16px;
		font-size: 16px;
		width: 300px;
	}
</style>
