<script setup lang="ts" generic="T extends object">
withDefaults(
  defineProps<{
    items: T[];
    itemKey: (item: T) => string;
    selectedId?: string | null;
    label: string;
    emptyText?: string;
  }>(),
  {
    selectedId: null,
    emptyText: "暂无对象。",
  },
);
const emit = defineEmits<{ select: [item: T] }>();
</script>

<template>
  <section class="entity-index" :aria-label="label">
    <header class="entity-index-toolbar"><slot name="toolbar" /></header>
    <ul v-if="items.length" class="entity-index-list" :aria-label="label">
      <li v-for="item in items" :key="itemKey(item)">
        <button
          class="entity-index-row"
          type="button"
          :aria-current="itemKey(item) === selectedId ? 'true' : undefined"
          :data-selected="itemKey(item) === selectedId ? 'true' : 'false'"
          @click="emit('select', item)"
        >
          <slot
            name="item"
            :item="item"
            :selected="itemKey(item) === selectedId"
          />
        </button>
      </li>
    </ul>
    <p v-else class="muted-box">{{ emptyText }}</p>
    <footer v-if="$slots.footer" class="entity-index-footer">
      <slot name="footer" />
    </footer>
  </section>
</template>
