<template>
	<view class="category-page">
		<!-- 自定义导航栏 -->
		<view class="navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar__content" :style="{ height: navBarHeight + 'px' }">
				<view class="navbar__back" @click="goBack">
					<image src="/static/ic_back.png" class="navbar__back-icon" mode="aspectFit" />
				</view>
				<text class="navbar__title">{{ categoryName }}</text>
				<view class="navbar__placeholder"></view>
			</view>
		</view>
		<view :style="{ height: (statusBarHeight + navBarHeight) + 'px' }"></view>

		<!-- 筛选区域 -->
		<view class="filter-section" v-if="filters.length">
			<view v-for="filter in filters" :key="filter.filterKey" class="filter-group">
				<text class="filter-group__label">{{ filter.filterName }}</text>
				<view class="filter-group__options">
					<view v-for="opt in filter.options" :key="opt" class="filter-option"
						:class="{ 'filter-option--active': selectedFilters[filter.filterKey] === opt }"
						@click="selectFilter(filter.filterKey, opt)">{{ opt }}</view>
				</view>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="product-grid" v-if="products.length">
			<view v-for="p in products" :key="p.id" class="product-card" @click="goDetail(p.id)">
				<image class="product-card__img" :src="fullUrl(p.thumb || p.bannerImages?.[0] || '')"
					mode="aspectFill" />
				<view class="product-card__info">
					<text class="product-card__name">{{ p.name }}</text>
					<view class="product-card__bottom">
						<text class="product-card__price">¥{{ p.basePrice }}</text>
						<text class="product-card__stock">库存{{ p.stock }}</text>
					</view>
				</view>
			</view>
		</view>
		<view v-else-if="!loading" class="empty-state">
			<image class="empty-state__icon" src="/static/ic_none.png" mode="aspectFit" />
			<text class="empty-state__text">暂无商品</text>
		</view>
		<view v-if="loading" class="loading-text">加载中...</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted } from 'vue'
	import { get } from '../../utils/request'
	import { BASE_URL } from '../../utils/request'

	const statusBarHeight = ref(0)
	const navBarHeight = ref(44)
	const categoryName = ref('')
	const categoryId = ref(0)
	const filters = ref<any[]>([])
	const selectedFilters = reactive<Record<string, string>>({})
	const products = ref<any[]>([])
	const loading = ref(false)

	function fullUrl(path : string) : string {
		if (!path) return ''
		if (path.startsWith('http')) return path
		return BASE_URL + path
	}

	function goBack() {
		uni.navigateBack()
	}

	function goDetail(id : number) {
		uni.navigateTo({ url: `/pages/product/detail?id=${id}` })
	}

	function selectFilter(key : string, value : string) {
		if (selectedFilters[key] === value) {
			delete selectedFilters[key]
		} else {
			selectedFilters[key] = value
		}
		loadProducts()
	}

	async function loadFilters() {
		try {
			const res = await get<any[]>(`/api/categories/${categoryId.value}/filters`)
			filters.value = res || []
		} catch { filters.value = [] }
	}

	async function loadProducts() {
		loading.value = true
		try {
			const params : Record<string, any> = {
				categoryId: categoryId.value,
				pageSize: 50,
			}
			// Add selected filters as query params
			Object.keys(selectedFilters).forEach(key => {
				if (selectedFilters[key]) params[key] = selectedFilters[key]
			})
			const res = await get<{ list : any[]; total : number }>('/api/products', params)
			products.value = res?.list || []
		} catch { products.value = [] }
		finally { loading.value = false }
	}

	onMounted(() => {
		const sysInfo = uni.getSystemInfoSync()
		statusBarHeight.value = sysInfo.statusBarHeight || 0
		const menuBtn = uni.getMenuButtonBoundingClientRect()
		navBarHeight.value = menuBtn.height + (menuBtn.top - (sysInfo.statusBarHeight || 0)) * 2

		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1] as any
		categoryId.value = Number(currentPage.options?.id || 0)
		categoryName.value = decodeURIComponent(currentPage.options?.name || '')

		loadFilters()
		loadProducts()
	})
</script>

<style scoped>
	.category-page {
		min-height: 100vh;
		background: #f5f5f5;
	}

	/* 导航栏 */
	.navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		background: linear-gradient(135deg, #FFCFDE 0%, #FFA6C4 100%);
	}

	.navbar__content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 24rpx;
	}

	.navbar__back {
		padding: 10rpx;
	}

	.navbar__back-icon {
		width: 40rpx;
		height: 40rpx;
	}

	.navbar__title {
		font-size: 34rpx;
		font-weight: 600;
		color: #000;
	}

	.navbar__placeholder {
		width: 60rpx;
	}

	/* 筛选区域 */
	.filter-section {
		background: #fff;
		padding: 20rpx 24rpx 8rpx;
	}

	.filter-group {
		display: flex;
		margin-bottom: 16rpx;
	}

	.filter-group__label {
		font-size: 26rpx;
		color: #666;
		font-weight: 500;
		width: 80rpx;
		flex-shrink: 0;
		padding-top: 10rpx;
		letter-spacing: 4rpx;
	}

	.filter-group__options {
		display: flex;
		flex-wrap: wrap;
		gap: 12rpx;
		flex: 1;
	}

	.filter-option {
		padding: 10rpx 24rpx;
		font-size: 24rpx;
		color: #333;
		background: #f5f5f5;
		border-radius: 8rpx;
		border: 2rpx solid transparent;
	}

	.filter-option--active {
		color: #e91e63;
		background: #fce4ec;
		border-color: #e91e63;
	}

	/* 商品网格 */
	.product-grid {
		display: flex;
		flex-wrap: wrap;
		padding: 16rpx 16rpx;
		gap: 16rpx;
	}

	.product-card {
		width: calc(50% - 8rpx);
		background: #fff;
		border-radius: 16rpx;
		overflow: hidden;
	}

	.product-card__img {
		width: 100%;
		height: 340rpx;
	}

	.product-card__info {
		padding: 16rpx 20rpx 20rpx;
	}

	.product-card__name {
		font-size: 26rpx;
		color: #333;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
		overflow: hidden;
		margin-bottom: 10rpx;
	}

	.product-card__bottom {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.product-card__price {
		font-size: 30rpx;
		color: #e91e63;
		font-weight: bold;
		background: linear-gradient(to right, #FFB6C8, #FF6D9B);
		-webkit-background-clip: text;
		color: transparent;
		padding: 4rpx 16rpx;
		background: linear-gradient(to right, #fce4ec, #f8bbd0);
		color: #e91e63;
		border-radius: 6rpx;
		font-size: 26rpx;
	}

	.product-card__stock {
		font-size: 22rpx;
		color: #999;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 200rpx;
	}

	.empty-state__icon {
		width: 300rpx;
		height: 300rpx;
		margin-bottom: 20rpx;
	}

	.empty-state__text {
		font-size: 28rpx;
		color: #bbb;
	}

	.loading-text {
		text-align: center;
		padding: 40rpx;
		color: #999;
		font-size: 26rpx;
	}
</style>