<template>
  <!-- Only render the card when there is at least one field with a value to show -->
  <div class="section-card" v-if="visibleFields.length">
    <h3 class="section-title">{{ title }}</h3>
    <div class="info-list">
      <div class="info-row" v-for="f in visibleFields" :key="f.fieldid">
        <span class="info-label">{{ f.label }}</span>
        <span class="info-value">{{ displayValue(f) }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { customFieldsApi } from '../api'

const props = defineProps({
  assetid: { type: [Number, String], default: null },
  title: { type: String, default: 'Additional Details' },
})

const fields = ref([])

const visibleFields = computed(() =>
  fields.value.filter(f => f.showondetail && f.value != null && String(f.value).trim() !== ''))

function displayValue(f) {
  if (f.datatype === 'boolean') {
    return ['true', '1', 'yes'].includes(String(f.value).toLowerCase()) ? 'Yes' : 'No'
  }
  return f.value
}

async function load() {
  if (!props.assetid) { fields.value = []; return }
  try {
    const response = await customFieldsApi.forAsset(props.assetid)
    fields.value = response.data.data || []
  } catch (err) {
    console.error('Error loading custom fields:', err)
    fields.value = []
  }
}

onMounted(load)
watch(() => props.assetid, load)
</script>
