<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, shallowRef } from 'vue';
import type { Tag, TagGroup } from '~/composables/useProductCenter';

const props = defineProps<{ tags: Tag[]; tagGroups: TagGroup[]; selectedTagIds: string[] }>();
const emit = defineEmits<{ 'toggle-tag': [id: string] }>();
const openGroup = shallowRef<string | null>(null);
const rootElement = shallowRef<HTMLElement | null>(null);
const groupedTags = computed(() => {
  return props.tagGroups
    .filter((group) => group.name.includes('物流') || group.name.includes('工艺'))
    .sort((a, b) => a.sortOrder - b.sortOrder)
    .map((group) => ({
      id: group.id,
      label: group.name.includes('物流') ? '物流' : '工艺',
      tags: props.tags.filter((tag) => tag.group?.id === group.id),
    }))
    .filter((group) => group.tags.length > 0);
});
const selectedTagByGroup = computed(() => {
  const selectedIds = new Set(props.selectedTagIds);
  return new Map(
    props.tags
      .filter((tag) => selectedIds.has(tag.id) && tag.group)
      .map((tag) => [tag.group!.id, tag]),
  );
});
const selectedGroups = computed(() => groupedTags.value
  .map((group) => ({ ...group, selectedTag: selectedTagByGroup.value.get(group.id) }))
  .filter((group) => group.selectedTag));

function selectTag(id: string): void {
  emit('toggle-tag', id);
  openGroup.value = null;
}

function closeOnOutsideClick(event: MouseEvent): void {
  if (!rootElement.value?.contains(event.target as Node)) openGroup.value = null;
}

onMounted(() => document.addEventListener('click', closeOnOutsideClick));
onBeforeUnmount(() => document.removeEventListener('click', closeOnOutsideClick));
</script>

<template>
  <div ref="rootElement" class="tag-filters">
    <div class="filter-controls">
      <div v-for="group in groupedTags" :key="group.id" class="filter-group">
        <div class="dropdown">
        <button type="button" class="filter-button" :class="{ open: openGroup === group.id }" @click="openGroup = openGroup === group.id ? null : group.id">{{ group.label }}<i class="fa-solid fa-chevron-down"></i></button>
        <div v-if="openGroup === group.id" class="menu">
          <button v-for="tag in group.tags" :key="tag.id" type="button" :class="{ selected: selectedTagIds.includes(tag.id) }" @click="selectTag(tag.id)"><span>{{ tag.name }}</span><span class="checkbox"><i v-if="selectedTagIds.includes(tag.id)" class="fa-solid fa-check"></i></span></button>
        </div>
        </div>
      </div>
    </div>
    <div v-if="selectedGroups.length" class="selected-tags" :class="{ 'craft-only': selectedGroups.length === 1 && selectedGroups[0]?.label === '工艺' }">
      <div v-for="group in selectedGroups" :key="group.id" class="selected-tag">
        <span>{{ group.selectedTag?.name }}</span>
        <button type="button" class="selected-tag-remove" :aria-label="`取消${group.selectedTag?.name}筛选`" @click="emit('toggle-tag', group.selectedTag!.id)">
          <i class="fa-solid fa-xmark"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.tag-filters { display: flex; flex-direction: column; align-items: flex-start; gap: 12px; }.filter-controls, .selected-tags { display: flex; align-items: flex-start; gap: 12px; }.filter-group { display: flex; align-items: flex-start; }.dropdown { position: relative; }
.filter-button { display: flex; align-items: center; gap: 6px; height: 38px; padding: 0 16px; border: 1px solid #c7c7c7; border-radius: 60px; background: #fff; color: #000; font-size: 16px; cursor: pointer; }.filter-button i { color: #777; font-size: 11px; transition: transform .2s; }.filter-button.open i { transform: rotate(180deg); }
.menu { position: absolute; z-index: 40; top: 50px; left: -2px; width: 141px; padding: 6px; border-radius: 6px; background: #fff; box-shadow: 0 1px 5px rgba(0,0,0,.25); }
.menu button { display: flex; align-items: center; justify-content: space-between; width: 129px; height: 36px; padding: 6px; border: 0; background: #fff; color: #000; text-align: left; font-size: 16px; cursor: pointer; }.menu button:hover { background: #fafafa; }
.checkbox { display: grid; place-items: center; width: 18px; height: 18px; border: 1px solid #c7c7c7; border-radius: 4px; color: #fff; font-size: 11px; }.menu button.selected .checkbox { border-color: #ff6800; background: #ff6800; }
.selected-tag { display: flex; align-items: center; justify-content: center; gap: 6px; height: 30px; padding: 0 16px; border-radius: 60px; background: #f2f2f2; color: #000; font-size: 16px; line-height: normal; white-space: nowrap; }.selected-tag-remove { display: grid; place-items: center; width: 20px; height: 20px; padding: 0; border: 0; background: transparent; color: #000; font-size: 16px; cursor: pointer; }
</style>
