<script setup lang="ts">
import { toRefs, ref, watch, onBeforeUnmount } from 'vue'
import { getCachedImageUrl, revokeAllImageUrls } from '../../common/imageCache'

interface Child {
  id: string | number
  name: string
  age: number
  points?: number
  image_id: string | null
}

const props = defineProps<{
  child: Child | null
}>()

const { child } = toRefs(props)
const imageUrl = ref<string | null>(null)

const imageCacheName = 'images-v1'

const fetchImage = async (imageId: string) => {
  try {
    const url = await getCachedImageUrl(imageId, imageCacheName)
    imageUrl.value = url
  } catch (err) {
    console.error('Error fetching child image:', err)
  }
}

watch(
  () => child.value?.image_id,
  (newImageId) => {
    if (newImageId) {
      fetchImage(newImageId)
    }
  },
  { immediate: true },
)

// Revoke created object URLs when component unmounts to avoid memory leaks
onBeforeUnmount(() => {
  revokeAllImageUrls()
})
</script>

<template>
  <div v-if="child" class="detail-card-horizontal">
    <img v-if="imageUrl" :src="imageUrl" alt="Child Image" class="child-image" />
    <div class="main-info">
      <div class="child-name">{{ child.name }}</div>
      <div class="child-age">Age: {{ child.age }}</div>
    </div>
    <div class="points">
      <span class="label">Points</span>
      <span class="value">{{ child.points ?? '—' }}</span>
    </div>
  </div>
</template>

<style scoped>
.detail-card-horizontal {
  display: flex;
  align-items: center;
  background: var(--detail-card-bg);
  border-radius: 12px;
  box-shadow: var(--detail-card-shadow);
  padding: 0.7rem 1rem;
  max-width: 420px;
  width: 100%;
  min-height: 64px;
  box-sizing: border-box;
  gap: 1rem;
}

.child-image {
  width: 48px;
  height: 48px;
  object-fit: cover;
  border-radius: 50%;
  flex-shrink: 0;
}

.main-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex: 1 1 auto;
  min-width: 0;
}

.child-name {
  font-size: 1.08rem;
  font-weight: 600;
  color: var(--child-name-color);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.child-age {
  font-size: 0.97rem;
  color: var(--child-age-color);
  margin-top: 2px;
}

.points {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  min-width: 54px;
  margin-left: 0.7rem;
}

.points .label {
  font-size: 0.85rem;
  color: var(--points-label-color);
  margin-bottom: 1px;
}

.points .value {
  font-size: 1.6rem;
  font-weight: 900;
  color: var(--points-value-color);
}

@media (max-width: 480px) {
  .detail-card-horizontal {
    padding: 0.5rem 0.4rem;
    max-width: 98vw;
    gap: 0.6rem;
  }
  .child-image {
    width: 38px;
    height: 38px;
  }
  .points {
    min-width: 38px;
    margin-left: 0.3rem;
  }
}
</style>
