<script setup>
const props = defineProps({
  row: {
    type: Object,
    required: true,
    default: {}
  }
})

const accounts = ref([])
const showFullIban = ref(false)

const formatIban = (iban) => {
  const cleaned = String(iban || "").replace(/\s+/g, "").toUpperCase()
  if (!cleaned) return ""
  return cleaned.match(/.{1,4}/g)?.join(" ") || cleaned
}

const maskIban = (iban) => {
  const cleaned = String(iban || "").replace(/\s+/g, "").toUpperCase()
  if (!cleaned) return ""
  if (cleaned.length <= 8) return cleaned
  return `${cleaned.slice(0, 4)} **** **** ${cleaned.slice(-4)}`
}

const bankAccounts = computed(() => {
  const ids = Array.isArray(props.row?.infoData?.bankAccountIds) ? props.row.infoData.bankAccountIds : []
  if (!ids.length) return []
  return accounts.value
      .filter((a) => ids.includes(a.id))
      .map((a) => {
        const iban = formatIban(a.iban)
        const ibanDisplay = showFullIban.value ? iban : maskIban(a.iban)
        const parts = [ibanDisplay]
        if (a.bankName) parts.push(a.bankName)
        if (a.description) parts.push(`(${a.description})`)
        return {
          id: a.id,
          label: parts.filter(Boolean).join(" | ")
        }
      })
})

const setup = async () => {
  accounts.value = await useEntities("entitybankaccounts").select()
}

setup()
</script>

<template>
  <div class="flex flex-col gap-1">
    <div v-if="bankAccounts.length > 0" class="flex">
      <UButton
          color="gray"
          variant="ghost"
          size="2xs"
          :icon="showFullIban ? 'i-heroicons-eye-slash' : 'i-heroicons-eye'"
          @click="showFullIban = !showFullIban"
      />
    </div>
    <span v-for="account in bankAccounts" :key="account.id">{{ account.label }}</span>
    <span v-if="bankAccounts.length === 0">-</span>
  </div>
</template>
