<template>
  <view class="class-bullet-container">
    <view class="category-grid">
      <view
        v-for="item in topCategories"
        :key="item.id"
        class="category-item"
        @click="handleItemClick(item)"
      >
        <image
          v-if="item.categoryImage || item.logoUrl"
          :src="item.categoryImage || item.logoUrl"
          class="category-icon"
          mode="aspectFit"
        />
        <text class="category-text">{{ item.categoryName || item.name }}</text>
      </view>
      <view class="category-item" @click="handleMoreClick">
        <image src="@/static/app/images/more.png" class="category-icon" mode="aspectFit" />
        <text class="category-text">更多</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useCategoryNavStore } from '@/store'

// 定义分类项接口（与模板字段一致）
interface CategoryItem {
  id: number
  categoryImage?: string
  logoUrl?: string
  name?: string
  categoryName?: string
}

// 定义组件属性
interface Props {
  /** 分类数据数组 */
  categories?: CategoryItem[]
}

const props = withDefaults(defineProps<Props>(), {
  categories: () => []
})

const categoryNavStore = useCategoryNavStore()

// 定义事件
const emit = defineEmits<{
  /** 点击分类项事件 */
  'itemClick': [item: CategoryItem]
}>()

// 模拟数据
const mockCategories: CategoryItem[] = [
  { id: 1, logoUrl: '/src/static/images/ls/6.png', name: '外卖点餐' },
  { id: 2, logoUrl: '/src/static/images/ls/7.png', name: '净菜商城' },
  { id: 3, logoUrl: '/src/static/images/ls/8.png', name: '生鲜冷链' },
  { id: 4, logoUrl: '/src/static/images/ls/9.png', name: '肉类' },
  { id: 5, logoUrl: '/src/static/images/ls/10.png', name: '调料' },
  { id: 6, logoUrl: '/src/static/images/ls/11.png', name: '零食' },
  { id: 7, logoUrl: '/src/static/images/ls/12.png', name: '海鲜' }
]

// 使用传入的数据或默认数据
const categories = computed(() => {
  return props.categories.length > 0 ? props.categories : mockCategories
})
const topCategories = computed(() => categories.value.slice(0, 4))

// 点击处理（列表页菜谱 id 来自 store，不放在 URL query）
const handleItemClick = (item: CategoryItem) => {
  emit('itemClick', item)
  categoryNavStore.setPendingRecipeCategoryId(item.id)
  navigateTo('/pages-store/pages/list/index')
}

function navigateTo(url: string) {
  uni.navigateTo({ url })
}

function handleMoreClick() {
  navigateTo('/pages-store/pages/list/index')
}
</script>

<style lang="scss" scoped>
.class-bullet-container {
  width: 100%;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  gap: 12rpx;
}

.category-item {
  min-width: 0;
  min-height: 108rpx;
  padding: 8rpx 4rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
}

.category-icon {
  width: 54rpx;
  height: 54rpx;
  flex-shrink: 0;
}

.category-text {
  font-size: 22rpx;
  color: #333;
  line-height: 1.2;
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
