<template>
  <span class="fc-tag-chip">
    <v-chip
      size="small" closable
      :color="store.colorFor(tag.kind)" variant="tonal"
      class="fc-tag-chip__nav"
      role="link"
      :title="`Browse images tagged “${tag.name}”`"
      @click="$emit('navigate', tag)"
      @click:close="$emit('remove', tag.id)"
    >
      <v-icon start size="x-small">{{ iconFor(tag.kind) }}</v-icon>
      {{ tag.name }}<span
        v-if="tag.fandom_id" class="fc-tag-chip__fandom"
        :title="tag.fandom_name ? `Fandom: ${tag.fandom_name}` : 'Has a fandom'"
      >→<template v-if="fandomLabel">&nbsp;{{ fandomLabel }}</template></span>
    </v-chip>
    <!-- Modal-safe kebab is baked into KebabMenu (this chip lives in the
         teleported image modal — #711). -->
    <KebabMenu class="fc-tag-chip__kebab" :label="`More actions for ${tag.name}`">
      <v-list-item @click="$emit('rename', tag)">
        <v-list-item-title>Rename…</v-list-item-title>
      </v-list-item>
      <v-list-item v-if="tag.kind === 'character'" @click="$emit('set-fandom', tag)">
        <v-list-item-title>Set fandom…</v-list-item-title>
      </v-list-item>
    </KebabMenu>
  </span>
</template>

<script setup>
import { computed } from 'vue'
import { useTagStore } from '../../stores/tags.js'
import KebabMenu from '../common/KebabMenu.vue'

const props = defineProps({ tag: { type: Object, required: true } })
defineEmits(['remove', 'rename', 'set-fandom', 'navigate'])

const store = useTagStore()

// Show a character's fandom inline (truncated). Falls back to a bare arrow when
// only fandom_id is known but the name wasn't resolved (older payloads).
const FANDOM_MAX = 15
const fandomLabel = computed(() => {
  const n = props.tag.fandom_name
  if (!n) return ''
  return n.length > FANDOM_MAX ? `${n.slice(0, FANDOM_MAX)}…` : n
})

const KIND_ICONS = {
  general: 'mdi-tag', character: 'mdi-account-circle',
  fandom: 'mdi-book-open-page-variant', series: 'mdi-bookshelf',
  meta: 'mdi-cog-outline', rating: 'mdi-shield-check-outline',
}
function iconFor (k) { return KIND_ICONS[k] || 'mdi-tag' }
</script>

<style scoped>
.fc-tag-chip { display: inline-flex; align-items: center; gap: 1px; }
/* The chip body navigates to the filtered gallery (#5); signal it's clickable.
   The close ✕ (remove) and the sibling kebab stay as the explicit controls. */
.fc-tag-chip__nav { cursor: pointer; }
.fc-tag-chip__nav:focus-visible {
  outline: 2px solid rgb(var(--v-theme-accent));
  outline-offset: 1px;
}
.fc-tag-chip__kebab { opacity: 0.7; }
.fc-tag-chip:hover .fc-tag-chip__kebab { opacity: 1; }
.fc-tag-chip__fandom { opacity: 0.7; font-size: 0.85em; }
</style>
