let signClient: any;

const projectId = "";

 async function initSignClient(url: string) {
    signClient = await SignClient.init({
      projectId,
      metadata: {
        name: "",
        description:
          "",
        url: "",
        icons: [
          "",
        ],
      },
    });

    try {
      const pairResult = await signClient.pair({ uri: url });
      console.log("✅ Paired with dApp:", pairResult);
    } catch (err) {
      console.error("❌ Pairing failed:", err);
    }

    // Listen for session proposals
    subscribeToEvents();
  }

  // 📡 Listen for session proposals
  function subscribeToEvents() {
    signClient.on("session_proposal", async (proposal) => {
      console.log("📨 Received session proposal:", proposal);

      // Accept the session proposal manually
      const { id, params } = proposal;
      const { requiredNamespaces, relays, proposer } = params;
      console.log("wallet?.address=>", wallet?.address)
      const responseNamespaces = {
        eip155: {
          accounts: [`eip155:137:${wallet?.address}`], // Your wallet address
          methods: ["eth_sendTransaction"],
          events: []
        }
      };

      const session = await signClient.approve({
        id,
        relayProtocol: relays[0].protocol,
        namespaces: responseNamespaces
      });

      console.log("✅ Session approved:", session);
    });

    signClient.on("session_request", (requestEvent) => {
      console.log("💬 Received session request:", JSON.stringify(requestEvent))
      // Handle dApp requests like `eth_sendTransaction`, `personal_sign` here
      handleSessionRequest(requestEvent);
    });
    signClient.on("session_delete", ({ topic }) => {
      console.log("Session deleted:", topic);
    });
    signClient.on("session_event", ({ event }) => {
      console.log("Session event:", event);
    });
  }


  async function handleSessionRequest(event) {
    const { topic, params, id } = event;
    const { request } = params;

    if (request.method === "eth_sendTransaction") {
      const txParams = request.params[0]; // Transaction object from dApp

      try {
        // Build transaction
        const tx = {
          to: txParams.to,
          value: ethers.BigNumber.from(txParams.value || "0"),
          gasPrice: 250000000000,
          gasLimit: 236740,
          data: txParams.data || "0x",
          nonce: await provider?.getTransactionCount(wallet.address),
        };

        // Sign & send
        const txResponse = await wallet?.sendTransaction(tx);
        await provider?.waitForTransaction(txResponse.hash, 1);
        console.log("🚀 Transaction sent:", txResponse?.hash);

        // Respond back to dApp
        await signClient.respond({
          topic,
          response: {
            id,
            jsonrpc: "2.0",
            result: txResponse?.hash,
          },
        });
      } catch (error) {
        console.error("❌ Transaction failed:", error);

        await signClient.respond({
          topic,
          response: {
            id,
            jsonrpc: "2.0",
            error: {
              code: -32000,
              message: error?.message
            },
          },
        });
      }
    }
  }