<script setup>
import { computed, onMounted, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import LinkCard from './LinkCard.vue'
import { useLinksStore } from '@/stores/links'
import { useSettingsStore } from '@/stores/settings'
import { tagService } from '@/services/tagService'
import styles from './LinkList.module.scss'

const props = defineProps({
  links: {
    type: Array,
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
  columns: {
    type: Number,
    default: null,
  },
  columnWidth: {
    type: Number,
    default: 240,
  },
})

const emit = defineEmits(['open', 'edit', 'remove', 'view'])

const linksStore = useLinksStore()
const settingsStore = useSettingsStore()
const { state } = storeToRefs(settingsStore)

// 当前视图模式
const libraryView = computed(() => state.value?.libraryView || 'tag')

// 使用标签顺序获取分组书签
const linksByTag = computed(() => {
  const tagOrder = state.value?.tagOrder || null
  return linksStore.getLinksByTagWithOrder(tagOrder)
})

const gridStyle = computed(() => {
  const width = Math.max(props.columnWidth ?? 240, 200)
  if (props.columns && props.columns > 0) {
    return {
      gridTemplateColumns: `repeat(${props.columns}, ${width}px)`,
      gridAutoColumns: `${width}px`,
    }
  }
  // 使用 auto-fill 自适应列数，根据容器宽度自动计算
  return {
    gridTemplateColumns: `repeat(auto-fill, ${width}px)`,
    gridAutoColumns: `${width}px`,
    justifyContent: 'start',
  }
})

// 获取按标签分组的书签列表（转换为数组，便于排序）
const groupedLinks = computed(() => {
  const map = linksByTag.value
  if (!map || map.size === 0) return []
  
  const result = []
  const tagOrder = state.value?.tagOrder || []
  
  map.forEach((links, tag) => {
    // 对每个标签下的书签按 order 排序
    const sortedLinks = [...links].sort((a, b) => {
      const orderA = a.order ?? 0
      const orderB = b.order ?? 0
      return orderA - orderB
    })
    
    result.push({
      tag,
      links: sortedLinks,
      count: sortedLinks.length,
      order: tagOrder.includes(tag) ? tagOrder.indexOf(tag) : 9999, // 有顺序的标签使用顺序，没有的排在最后
    })
  })
  
  // 排序：未分类放在最后，其他按自定义顺序或标签名排序
  result.sort((a, b) => {
    if (a.tag === tagService.UNCATEGORIZED_TAG) return 1
    if (b.tag === tagService.UNCATEGORIZED_TAG) return -1
    if (a.order !== b.order) {
      return a.order - b.order
    }
    return a.tag.localeCompare(b.tag, 'zh-CN')
  })
  
  return result
})

// 默认展开所有标签
const defaultActiveNames = computed(() => {
  return groupedLinks.value.map(group => group.tag)
})

// 是否有标签分组数据
const hasGroupedData = computed(() => {
  const map = linksByTag.value
  return map && map.size > 0
})

// #region agent log
const measureCardWidths = () => {
  nextTick(() => {
    const gridEl = document.querySelector(`.${styles.grid}`)
    if (!gridEl) return
    
    const computedStyle = window.getComputedStyle(gridEl)
    const gridTemplateColumns = computedStyle.gridTemplateColumns
    const columnWidth = props.columnWidth ?? 240
    const columns = props.columns
    
    fetch('http://127.0.0.1:7242/ingest/f96150ac-89c4-4b8b-bead-0078442f7ecb', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        location: 'LinkList.vue:measureCardWidths',
        message: 'Grid style computed',
        data: { gridTemplateColumns, columnWidth, columns, libraryView: libraryView.value },
        timestamp: Date.now(),
        sessionId: 'debug-session',
        runId: 'run2',
        hypothesisId: 'F'
      })
    }).catch(() => {})
    
    const cardItems = gridEl.querySelectorAll(`.${styles.linkCardItem}`)
    cardItems.forEach((item, index) => {
      const rect = item.getBoundingClientRect()
      const computedItemStyle = window.getComputedStyle(item)
      const card = item.querySelector('article')
      const cardRect = card ? card.getBoundingClientRect() : null
      const computedCardStyle = card ? window.getComputedStyle(card) : null
      
      const linkId = item.closest('[data-link-id]')?.getAttribute('data-link-id') || `item-${index}`
      
      fetch('http://127.0.0.1:7242/ingest/f96150ac-89c4-4b8b-bead-0078442f7ecb', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          location: 'LinkList.vue:measureCardWidths',
          message: 'Card width measurement',
          data: {
            index,
            linkId,
            itemWidth: rect.width,
            itemMaxWidth: computedItemStyle.maxWidth,
            itemMinWidth: computedItemStyle.minWidth,
            itemWidthStyle: computedItemStyle.width,
            itemDisplay: computedItemStyle.display,
            itemFlexDirection: computedItemStyle.flexDirection,
            itemBoxSizing: computedItemStyle.boxSizing,
            cardWidth: cardRect?.width || null,
            cardMaxWidth: computedCardStyle?.maxWidth || null,
            cardWidthStyle: computedCardStyle?.width || null,
            cardDisplay: computedCardStyle?.display || null,
            cardFlexShrink: computedCardStyle?.flexShrink || null,
            cardFlexGrow: computedCardStyle?.flexGrow || null,
            cardBoxSizing: computedCardStyle?.boxSizing || null,
            cardPadding: computedCardStyle?.padding || null,
            cardBorder: computedCardStyle?.borderWidth || null
          },
          timestamp: Date.now(),
          sessionId: 'debug-session',
          runId: 'run2',
          hypothesisId: 'B,E'
        })
      }).catch(() => {})
    })
  })
}

onMounted(() => {
  setTimeout(measureCardWidths, 500)
})
// #endregion
</script>

<template>
  <div>
    <el-skeleton v-if="loading" animated :rows="3" />
    <div v-else-if="links.length">
      <!-- 标签视图：按标签分类展示 -->
      <el-collapse v-if="libraryView === 'tag' && hasGroupedData" :model-value="defaultActiveNames">
        <el-collapse-item
          v-for="group in groupedLinks"
          :key="group.tag"
          :name="group.tag"
        >
          <template #title>
            <span class="collapse-title">
              {{ group.tag }}
              <span class="tag-count">({{ group.count }})</span>
            </span>
          </template>
          <div :class="[styles.grid]" :style="gridStyle">
            <div v-for="link in group.links" :key="link.id" :class="styles.linkCardItem">
              <LinkCard
                :link="link"
                @open="emit('open', $event)"
                @edit="emit('edit', $event)"
                @remove="emit('remove', $event)"
                @view="emit('view', $event)"
              />
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
      <!-- 全部书签视图：按排序显示所有书签 -->
      <div v-else :class="[styles.grid]" :style="gridStyle">
        <div v-for="(link, index) in links" :key="link.id" :class="styles.linkCardItem" :data-link-id="link.id">
          <LinkCard
            :link="link"
            @open="emit('open', $event)"
            @edit="emit('edit', $event)"
            @remove="emit('remove', $event)"
            @view="emit('view', $event)"
          />
        </div>
      </div>
    </div>
    <div v-else :class="styles.empty">暂无书签，可通过新增或导入来开始使用。</div>
  </div>
</template>

<style scoped>
:deep(.el-collapse) {
  border: none;
  background: transparent;
}

:deep(.el-collapse-item) {
  margin-bottom: 16px;
  border: none;
  background: transparent;
}

:deep(.el-collapse-item__header) {
  padding: 12px 0;
  border: none;
  border-bottom: 1px solid rgba(148, 163, 184, 0.15);
  font-weight: 500;
  font-size: 14px;
  color: #475569;
  background: transparent;
}

:deep(.el-collapse-item__header:hover) {
  color: #1e293b;
}

:deep(.el-collapse-item__wrap) {
  border: none;
  background: transparent;
}

:deep(.el-collapse-item__content) {
  padding: 16px 0;
  padding-top: 16px;
}

.collapse-title {
  font-weight: 500;
  font-size: 14px;
  color: inherit;
  display: flex;
  align-items: center;
}

.tag-count {
  color: #94a3b8;
  font-size: 12px;
  margin-left: 6px;
  font-weight: normal;
}
</style>

