<template>
  <BaseModal :show="show" :title="t('web5.sendBitcoinTitle')" max-width="max-w-2xl" content-class="max-h-[90vh] overflow-y-auto" @close="close">
        <!-- Method tabs -->
        <div class="flex gap-1 mb-4 p-1 bg-white/5 rounded-lg">
          <button
            v-for="m in (['auto', 'lightning', 'onchain', 'ecash', 'ark'] as const)"
            :key="m"
            @click="sendMethod = m"
            class="flex-1 px-2 py-1.5 rounded text-xs font-medium capitalize transition-colors"
            :class="sendMethod === m ? 'bg-white/15 text-white' : 'text-white/50 hover:text-white/80'"
          >{{ m === 'onchain' ? t('sendBitcoin.onChain') : m === 'lightning' ? t('sendBitcoin.lightning') : m === 'ecash' ? t('sendBitcoin.ecash') : m === 'ark' ? 'Ark' : t('sendBitcoin.auto') }}</button>
        </div>

        <div v-if="sendMethod === 'auto'" class="mb-3 p-2 bg-white/5 rounded-lg">
          <p class="text-xs text-white/50">{{ t('sendBitcoin.autoMethodDesc') }}</p>
        </div>

        <div class="mb-3">
          <div class="flex items-center justify-between mb-1">
            <label class="text-white/60 text-sm">{{ t('sendBitcoin.amountSats') }}</label>
            <button
              v-if="sendMethod === 'onchain'"
              @click="toggleSendAll"
              class="text-xs px-2 py-0.5 rounded border transition-colors"
              :class="sendAll
                ? 'bg-orange-500/20 border-orange-500/40 text-orange-300'
                : 'bg-white/5 border-white/15 text-white/60 hover:text-white/90'"
            >
              Send all funds
            </button>
          </div>
          <input
            v-model.number="amount"
            type="number"
            min="1"
            :placeholder="sendAll ? '' : '1000'"
            :disabled="sendAll"
            class="w-full input-glass disabled:opacity-50"
          />
          <p v-if="sendAll" class="text-xs text-white/50 mt-1">
            Sweeps your entire on-chain balance{{ onchainBalance !== null ? ` (~${onchainBalance.toLocaleString()} sats)` : '' }} minus network fees.
          </p>
        </div>

        <div v-if="effectiveMethod !== 'ecash'" class="mb-3">
          <label class="text-white/60 text-sm block mb-1">
            {{ effectiveMethod === 'lightning' ? t('sendBitcoin.lightningInvoice') : effectiveMethod === 'ark' ? 'Ark address, invoice or lightning address' : t('sendBitcoin.bitcoinAddress') }}
          </label>
          <textarea v-model="dest" rows="2" :placeholder="effectiveMethod === 'lightning' ? 'lnbc...' : effectiveMethod === 'ark' ? 'tark1… / lnbc… / user@lnaddress' : 'bc1...'" class="w-full input-glass font-mono"></textarea>
        </div>

        <div v-if="ecashToken && effectiveMethod === 'ecash'" class="mb-3 p-2 bg-white/5 rounded-lg">
          <p class="text-white/50 text-xs mb-1">{{ t('sendBitcoin.tokenShareLabel') }}</p>
          <p class="text-xs font-mono text-white/80 break-all">{{ ecashToken }}</p>
          <button @click="copyText(ecashToken)" class="mt-2 text-xs text-orange-400 hover:text-orange-300">{{ t('common.copy') }}</button>
        </div>

        <div v-if="resultTxid" class="mb-3 alert-success">
          <p class="text-xs">{{ t('sendBitcoin.sentTx', { txid: resultTxid }) }}</p>
        </div>
        <div v-if="resultHash" class="mb-3 alert-success">
          <p class="text-xs">{{ t('sendBitcoin.paidHash', { hash: resultHash }) }}</p>
        </div>
        <div v-if="resultArk" class="mb-3 alert-success">
          <p class="text-xs">{{ resultArk }}</p>
        </div>

        <div v-if="error" class="mb-3 alert-error">{{ error }}</div>

        <div class="flex gap-3">
          <button @click="close" class="flex-1 glass-button px-4 py-2 rounded-lg text-sm">{{ t('common.close') }}</button>
          <button @click="send" :disabled="processing || (!amount && !isSweep)" class="flex-1 glass-button glass-button-warning px-4 py-2 rounded-lg text-sm font-medium disabled:opacity-50">
            {{ processing ? t('common.sending') : t('common.send') }}
          </button>
        </div>
  </BaseModal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { rpcClient } from '@/api/rpc-client'
import BaseModal from '@/components/BaseModal.vue'

const { t } = useI18n()

const props = defineProps<{ show: boolean }>()
const emit = defineEmits<{ close: []; sent: [] }>()

const sendMethod = ref<'auto' | 'lightning' | 'onchain' | 'ecash' | 'ark'>('auto')
const amount = ref<number>(0)
const dest = ref('')
const processing = ref(false)
const error = ref('')
const resultTxid = ref('')
const resultHash = ref('')
const resultArk = ref('')
const ecashToken = ref('')

// "Send all funds" — sweeps the whole on-chain balance (explicit on-chain tab only)
const sendAll = ref(false)
const onchainBalance = ref<number | null>(null)
const isSweep = computed(() => sendMethod.value === 'onchain' && sendAll.value)

function toggleSendAll() {
  sendAll.value = !sendAll.value
  if (sendAll.value && onchainBalance.value === null) {
    rpcClient.call<{ balance_sats: number }>({ method: 'lnd.getinfo', timeout: 5000 })
      .then((res) => { onchainBalance.value = res.balance_sats || 0 })
      .catch(() => { /* balance hint is best-effort */ })
  }
}

// Leaving the on-chain tab disarms the sweep so it can never apply elsewhere
watch(sendMethod, (m) => { if (m !== 'onchain') sendAll.value = false })

const effectiveMethod = computed(() => {
  if (sendMethod.value !== 'auto') return sendMethod.value
  const amt = amount.value || 0
  if (amt <= 0) return 'lightning'
  if (amt < 1000) return 'ecash'
  if (amt > 500000) return 'onchain'
  return 'lightning'
})

function close() {
  error.value = ''
  resultTxid.value = ''
  resultHash.value = ''
  resultArk.value = ''
  ecashToken.value = ''
  emit('close')
}

function copyText(text: string) {
  navigator.clipboard.writeText(text).catch(() => {})
}

async function send() {
  if (processing.value) return
  if (!amount.value && !isSweep.value) return
  processing.value = true
  error.value = ''
  ecashToken.value = ''
  resultTxid.value = ''
  resultHash.value = ''
  resultArk.value = ''

  const method = effectiveMethod.value
  try {
    if (method === 'ark') {
      if (!dest.value.trim()) { error.value = 'Enter an Ark address, invoice or lightning address'; return }
      await rpcClient.call<{ sent: boolean }>({
        method: 'wallet.ark-send',
        params: { destination: dest.value.trim(), amount_sats: amount.value },
        // Ark sends can wait on round participation.
        timeout: 130000,
      })
      resultArk.value = `Sent ${amount.value.toLocaleString()} sats via Ark`
    } else if (method === 'ecash') {
      const res = await rpcClient.call<{ token: string }>({
        method: 'wallet.ecash-send',
        params: { amount_sats: amount.value },
      })
      ecashToken.value = res.token
    } else if (method === 'lightning') {
      if (!dest.value.trim()) { error.value = t('web5.pasteInvoice'); return }
      const res = await rpcClient.call<{ payment_hash: string }>({
        method: 'lnd.payinvoice',
        params: { payment_request: dest.value.trim() },
      })
      resultHash.value = res.payment_hash
    } else {
      if (!dest.value.trim()) { error.value = t('web5.enterBitcoinAddress'); return }
      const res = await rpcClient.call<{ txid: string }>({
        method: 'lnd.sendcoins',
        params: isSweep.value
          ? { addr: dest.value.trim(), send_all: true }
          : { addr: dest.value.trim(), amount: amount.value },
      })
      resultTxid.value = res.txid
    }
    emit('sent')
  } catch (err: unknown) {
    error.value = err instanceof Error ? err.message : t('web5.sendFailed')
  } finally {
    processing.value = false
  }
}
</script>
