<template>
  <view>
    <button @click="createWallet" :disabled="!!wallet">Create Wallet</button>
    <view v-if="wallet">
      <p>Public Key: {{ wallet.publicKey.toString() }}</p>
      <p>Balance: {{ balance }} SOL</p>
      <input v-model="recipientPublicKey" placeholder="Recipient Public Key" />
      <input v-model.number="amount" type="number" placeholder="Amount in SOL" />
      <button @click="sendSol">Send SOL</button>
    </view>
  </view>
</template>
<script lang="ts" setup>
import { solanaService } from '@/utils/solana'
const wallet = solanaService.wallet
const balance = ref(0)
const recipientPublicKey = ref('')
const amount = ref(0)

const createWallet = async () => {
  await solanaService.createWallet()
  await updateBalance()
}

const updateBalance = async () => {
  if (wallet.value) {
    balance.value = await solanaService.getBalance(wallet.value.publicKey.toString())
  }
}

const sendSol = async () => {
  if (wallet.value && recipientPublicKey.value && amount.value > 0) {
    try {
      const signature = await solanaService.sendTransaction(recipientPublicKey.value, amount.value)
      console.log('Transaction sent:', signature)
      await updateBalance()
    } catch (error) {
      console.error('Failed to send transaction:', error)
    }
  }
}

onMounted(updateBalance)
</script>
