<template>
  <div>
    <Text size="lg" weight="semibold" class="mb-4">{{ t('catalog.headers.selectSupplier') }}</Text>

    <div v-if="isLoading" class="flex justify-center py-12">
      <span class="loading loading-spinner loading-lg"></span>
    </div>

    <div v-else-if="filteredItems.length === 0" class="text-center py-12">
      <Text tone="muted">{{ t('catalog.empty.noSuppliers') }}</Text>
    </div>

    <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
      <SupplierCard
        v-for="supplier in filteredItems"
        :key="supplier.uuid || supplier.teamUuid"
        :supplier="supplier"
        selectable
        @select="$emit('select', { uuid: supplier.uuid || supplier.teamUuid, name: supplier.name })"
      />
    </div>

    <PaginationLoadMore
      v-if="filteredItems.length > 0 && canLoadMore"
      :shown="filteredItems.length"
      :total="total"
      :can-load-more="canLoadMore"
      :loading="isLoadingMore"
      hide-counter
      @load-more="loadMore"
      class="mt-4"
    />
  </div>
</template>

<script setup lang="ts">
const props = defineProps<{
  searchQuery: string
}>()

const emit = defineEmits<{
  (e: 'select', supplier: { uuid: string; name: string }): void
}>()

const { t } = useI18n()
const { items, total, isLoading, isLoadingMore, canLoadMore, loadMore, init } = useCatalogSuppliers()

await init()

const filteredItems = computed(() => {
  if (!props.searchQuery.trim()) return items.value
  const q = props.searchQuery.toLowerCase()
  return items.value.filter((item: any) =>
    item.name?.toLowerCase().includes(q)
  )
})
</script>
