<template>
  <v-container fluid class="pt-2 pb-6">

    <!-- Search lives in BrowseView's sticky bar (shared across tabs); this view
         reacts to route.query.q. The kind filter stays here. -->
    <div class="fc-tags__controls">
      <v-chip-group
        v-model="kind" selected-class="text-accent" :mandatory="false"
      >
        <v-chip v-for="k in KINDS" :key="k" :value="k" filter size="small">
          {{ k }}
        </v-chip>
      </v-chip-group>
    </div>

    <v-alert v-if="store.error" type="error" variant="tonal" closable class="my-4">
      Failed to load: {{ store.error }}
    </v-alert>
    <v-alert v-else-if="store.isEmpty" type="info" variant="tonal" class="my-4">
      No tags match.
    </v-alert>

    <div class="fc-tags__grid">
      <TagCard
        v-for="c in store.cards" :key="c.id" :card="c"
        @open="openTag" @rename="onRename" @manage="onManage" @read="onRead"
        @merge-with="onMergeWith" @delete="onDeleteTag"
        @set-fandom="onSetFandom" @aliases="onAliases"
      />
    </div>

    <div v-if="store.loading" class="fc-tags__sentinel">
      <v-progress-circular indeterminate color="accent" size="28" />
    </div>
    <div v-else-if="store.hasMore" ref="sentinelEl" class="fc-tags__sentinel" />

    <MergeConfirmDialog
      :model-value="pendingMerge !== null"
      :collision="pendingMerge"
      @confirm="confirmMerge"
      @cancel="pendingMerge = null"
    />

    <v-dialog v-model="mergePickerOpen" max-width="520">
      <v-card>
        <v-card-title>Merge “{{ mergeSource?.name }}” into…</v-card-title>
        <v-card-text>
          <p class="text-body-2 mb-3" style="opacity: 0.7;">
            Pick the target tag. Source tag will be deleted; all its
            image associations will move to the target. Must be same
            kind ({{ mergeSource?.kind }}).
          </p>
          <v-autocomplete
            v-model="mergeTargetId"
            v-model:menu="mergeMenuOpen"
            :items="mergeHits" item-title="name" item-value="id"
            :loading="mergeLoading"
            density="compact" variant="outlined" hide-details
            placeholder="Search target tag…" no-filter
            @update:search="onMergeSearch"
            @keydown.enter.capture="onMergeEnter"
          />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn variant="text" @click="mergePickerOpen = false">Cancel</v-btn>
          <v-btn
            color="warning" variant="flat" rounded="pill"
            :disabled="!mergeTargetId"
            @click="onMergeConfirm"
          >Merge</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <DestructiveConfirmModal
      v-model="deleteTagModalOpen"
      action="delete"
      kind="tag"
      :run-id="deleteTagTarget?.id || 0"
      tier="B"
      :projected-counts="{ associations: deleteTagUsage }"
      :description="deleteTagTarget
        ? `Delete tag “${deleteTagTarget.name}” and remove all image associations.`
        : ''"
      @confirm="onDeleteTagConfirm"
    />

    <v-dialog
      v-model="fandomDialogOpen" max-width="460"
      @after-enter="fandomSetRef?.focusSearch?.()"
    >
      <FandomSetDialog
        ref="fandomSetRef"
        v-if="fandomTarget" :tag="fandomTarget"
        @updated="onFandomUpdated" @cancel="fandomDialogOpen = false"
      />
    </v-dialog>

    <v-dialog v-model="aliasesDialogOpen" max-width="480">
      <TagAliasesDialog
        v-if="aliasesTarget" :tag="aliasesTarget"
        @close="aliasesDialogOpen = false"
      />
    </v-dialog>
  </v-container>
</template>

<script setup>
import { computed, ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTagDirectoryStore } from '../stores/tagDirectory.js'
import { useAdminStore } from '../stores/admin.js'
import { useApi } from '../composables/useApi.js'
import { useInfiniteScroll } from '../composables/useInfiniteScroll.js'
import { useAcceptOnEnter } from '../composables/useAcceptOnEnter.js'
import TagCard from '../components/discovery/TagCard.vue'
import MergeConfirmDialog from '../components/discovery/MergeConfirmDialog.vue'
import DestructiveConfirmModal from '../components/modal/DestructiveConfirmModal.vue'
import FandomSetDialog from '../components/modal/FandomSetDialog.vue'
import TagAliasesDialog from '../components/discovery/TagAliasesDialog.vue'

// Must stay a subset of the backend TagKind enum (character, fandom,
// general, series, archive, post). 'fandom' is this model's
// copyright/franchise concept (characters link via fandom_id).
// 'artist' retired in FC-2d-vii-c — artists are the Artist row, not
// a tag. 'meta' + 'rating' retired by operator 2026-05-26 (alembic 0023).
const KINDS = ['character', 'fandom', 'general', 'series']
const store = useTagDirectoryStore()
const route = useRoute()
const router = useRouter()

const kind = ref(null)
const sentinelEl = ref(null)
const pendingMerge = ref(null)

async function onRename({ id, name }) {
  const res = await store.rename(id, name)
  if (res.collision) pendingMerge.value = res.collision
}

async function confirmMerge() {
  const c = pendingMerge.value
  pendingMerge.value = null
  if (c) await store.merge(c.sourceId, c.target.id)
}

// Search term comes from BrowseView's shared sticky bar via route.query.q.
const searchTerm = computed(() => (typeof route.query.q === 'string' ? route.query.q : ''))
watch(searchTerm, (v) => store.setQuery(v || ''))
watch(kind, (v) => store.setKind(v || null))

useInfiniteScroll(sentinelEl, () => {
  if (store.hasMore && !store.loading) store.loadMore()
})
// Apply any deep-linked q (and load). setQuery resets + fetches.
onMounted(() => store.setQuery(searchTerm.value || ''))

function openTag(tagId) {
  router.push({ name: 'gallery', query: { tag_id: tagId } })
}

// Character fandom editing (dots-menu → FandomSetDialog).
const fandomDialogOpen = ref(false)
const fandomTarget = ref(null)
const fandomSetRef = ref(null)
function onSetFandom(card) {
  fandomTarget.value = card
  fandomDialogOpen.value = true
}
function onFandomUpdated() {
  fandomDialogOpen.value = false
  store.reset()  // reload so the card reflects the new fandom (or its removal)
}

// Tag-side alias view (TagCard ⋮ → Aliases…): see/remove the model keys that
// fold into this tag. Creation lives in the image modal's suggestion flow.
const aliasesDialogOpen = ref(false)
const aliasesTarget = ref(null)
function onAliases(card) {
  aliasesTarget.value = card
  aliasesDialogOpen.value = true
}

function onManage(id) {
  router.push({ name: 'series-manage', params: { tagId: id } })
}

function onRead(id) {
  router.push({ name: 'series-read', params: { tagId: id } })
}

// --- FC-3k tag merge + delete ----------------------------------------

const adminStore = useAdminStore()
const api = useApi()

// Tag merge via dots-menu (separate from inline-rename collision flow above)
const mergePickerOpen = ref(false)
// Enter on the closed dropdown accepts the target instead of re-opening it.
const { menuOpen: mergeMenuOpen, onEnter: onMergeEnter } = useAcceptOnEnter(
  () => onMergeConfirm()
)
const mergeSource = ref(null)
const mergeTargetId = ref(null)
const mergeHits = ref([])
const mergeLoading = ref(false)
let mergeDebounce = null

function onMergeWith(card) {
  mergeSource.value = card
  mergeTargetId.value = null
  mergeHits.value = []
  mergePickerOpen.value = true
}

function onMergeSearch(q) {
  if (mergeDebounce) clearTimeout(mergeDebounce)
  if (!q) { mergeHits.value = []; return }
  mergeDebounce = setTimeout(async () => {
    mergeLoading.value = true
    try {
      const hits = await api.get('/api/tags/autocomplete', {
        params: { q, kind: mergeSource.value?.kind, limit: 20 },
      })
      mergeHits.value = (hits || []).filter(
        (h) => h.id !== mergeSource.value?.id,
      )
    } finally {
      mergeLoading.value = false
    }
  }, 250)
}

async function onMergeConfirm() {
  if (!mergeSource.value || !mergeTargetId.value) return
  try {
    await adminStore.mergeTags(mergeTargetId.value, mergeSource.value.id)
    mergePickerOpen.value = false
    store.reset()
  } catch {
    // adminStore.lastError already set; UI surfaces it elsewhere.
  }
}

// Tag delete via dots-menu (Tier B)
const deleteTagModalOpen = ref(false)
const deleteTagTarget = ref(null)
const deleteTagUsage = ref(0)

async function onDeleteTag(card) {
  deleteTagTarget.value = card
  try {
    deleteTagUsage.value = await adminStore.tagUsageCount(card.id)
  } catch {
    deleteTagUsage.value = 0
  }
  deleteTagModalOpen.value = true
}

async function onDeleteTagConfirm() {
  if (!deleteTagTarget.value) return
  try {
    await adminStore.deleteTag(deleteTagTarget.value.id)
    store.reset()
  } catch {
    // adminStore.lastError already set.
  }
}
</script>

<style scoped>
.fc-tags__controls {
  display: flex; align-items: center; gap: 16px;
  flex-wrap: wrap; margin-bottom: 16px;
}
.fc-tags__grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(440px, 1fr));
  gap: 12px;
}
.fc-tags__sentinel {
  display: flex; justify-content: center; padding: 32px 0; min-height: 60px;
}
</style>
