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

	import { PKPClient } from '@lit-protocol/pkp-client';
	import { PKPWalletConnect } from '@lit-protocol/pkp-walletconnect';

	const CONTROLLER_AUTHSIG = {
		sig: '0xace8d4a052d437cb834393e6a41c2ff0f2a3c877b0961fad94cca74cb9adb1be192a869b7f41bbeb2b073cef29bf2aa8f0aa8f0796c5b9bf3a4ad6a44b3997b21b',
		derivedVia: 'web3.eth.personal.sign',
		signedMessage:
			'localhost:5173 wants you to sign in with your Ethereum account:\n0x1A5cfC9EA11afb50011F847fb7dC07bA1e18b05A\n\n\nURI: http://localhost:5173/\nVersion: 1\nChain ID: 100\nNonce: s5u4vZcvFgQHN17ns\nIssued At: 2023-07-20T13:30:44.566Z\nExpiration Time: 2023-07-27T13:30:43.591Z',
		address: '0x1a5cfc9ea11afb50011f847fb7dc07ba1e18b05a'
	};
	let uri = '';
	const PKP_PUBKEY =
		'046da3ba67065fd1e2726242ca01cd4601524893f4aa4b0042578fa6cbec28fa8c9a28eb9f7893932fc09717edc9e1db57e157a21eed346247c1db5a722a01f571';

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

	// Set up PKP WalletConnect
	const pkpWalletConnect = new PKPWalletConnect();

	// Initialize PKPClient
	async function initializePKPClient() {
		await pkpClient.connect();
		pkpWalletConnect.addPKPClient(pkpClient);
	}

	// Initialize WalletConnect
	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);
	}

	// Get initialized SignClient
	function getSignClient() {
		return pkpWalletConnect.getSignClient();
	}

	// Event listeners
	function onSessionProposal(proposal) {
		console.log('Received session proposal: ', proposal);

		// Accept session proposal
		pkpWalletConnect.approveSessionProposal(proposal).then(() => {
			// Print active sessions
			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;

		// Accept session request
		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) {
		// React to session delete event
		console.log(`Session deleted ${JSON.stringify(event)}`);
		console.log('\n' + '*'.repeat(50) + '\n');
	}

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

	onMount(async () => {
		await initializePKPClient();
		await initializeWalletConnect();

		// Set up event listeners
		pkpWalletConnect.on('session_proposal', onSessionProposal);
		pkpWalletConnect.on('session_request', onSessionRequest);
		getSignClient().on('session_delete', onSessionDelete);

		const uri = ''; // Set the initial URI value here
		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>
