<template>
  <view class="page">
    <view class="header-hero" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="top-bar">
        <view class="top-left" @click="goBack">
          <AppIcon name="chevronLeft" size="sm" color="white" />
        </view>
        <view class="top-center">
          <text class="app-name">Labeling</text>
          <LocationPicker />
        </view>
        <view class="top-right" @click="isMenuOpen = true">
          <AppIcon name="menu" size="sm" color="white" />
        </view>
      </view>

      <view class="bt-bar" @click="goBluetoothPage">
        <view class="bt-left">
          <AppIcon name="bluetooth" size="sm" color="white" />
          <text class="bt-text">{{ btConnected ? btDeviceName : 'No printer connected' }}</text>
        </view>
        <view class="bt-status" :class="{ connected: btConnected }">
          <text class="bt-dot" />
          <text class="bt-label">{{ btConnected ? 'Connected' : 'Disconnected' }}</text>
        </view>
        <AppIcon name="chevronRight" size="sm" color="white" />
      </view>
    </view>

    <view class="body">
      <view class="sidebar">
        <view
          v-for="cat in labelCategories"
          :key="cat.id"
          class="cat-item"
          :class="{ active: selectedCategory === cat.id }"
          @click="selectedCategory = cat.id"
        >
          <view v-if="selectedCategory === cat.id" class="active-bar" />
          <view class="cat-icon" :class="cat.bgClass">
            <AppIcon :name="cat.icon" size="sm" :color="selectedCategory === cat.id ? 'white' : cat.iconColor" />
          </view>
          <text class="cat-name">{{ cat.name }}</text>
        </view>
      </view>

      <scroll-view class="main-panel" scroll-y>
        <view class="panel-inner">
          <view class="search-box">
            <view class="search-icon-wrap">
              <AppIcon name="search" size="sm" color="gray" />
            </view>
            <input
              v-model="searchTerm"
              class="search-input"
              placeholder="Search products..."
              placeholder-class="placeholder"
            />
          </view>

          <view v-if="filteredProductCategories.length === 0" class="empty">
            <AppIcon name="search" size="lg" color="gray" />
            <text class="empty-text">No products found</text>
          </view>

          <view v-else class="category-list">
            <view
              v-for="pCat in filteredProductCategories"
              :key="pCat.id"
              class="cat-section"
            >
              <view class="cat-header" @click="toggleCategory(pCat.id)">
                <view class="cat-header-left">
                  <view class="cat-header-icon" :class="pCat.colorClass">
                    <AppIcon :name="pCat.icon" size="sm" :color="pCat.iconColor" />
                  </view>
                  <view class="cat-header-info">
                    <text class="cat-header-name">{{ pCat.name }}</text>
                    <text class="cat-header-count">{{ pCat.products.length }} items</text>
                  </view>
                </view>
                <AppIcon
                  :name="expandedCategories.indexOf(pCat.id) >= 0 ? 'chevronUp' : 'chevronDown'"
                  size="sm"
                  color="gray"
                />
              </view>

              <view v-if="expandedCategories.indexOf(pCat.id) >= 0" class="cat-foods">
                <view class="food-grid">
                  <view
                    v-for="product in pCat.products"
                    :key="product.id"
                    class="food-card"
                    @click="handleProductClick(product)"
                  >
                    <view class="food-img-wrap">
                      <image :src="product.image" class="food-img" mode="aspectFill" />
                      <view class="size-badge">
                        <text class="size-badge-text">{{ product.templateSize }}</text>
                      </view>
                      <view v-if="product.labelTypes.length > 0" class="type-badge">
                        <text class="type-badge-text">{{ product.labelTypes.length }} Types</text>
                      </view>
                    </view>
                    <text class="food-name">{{ getDisplayName(product) }}</text>
                    <text class="food-desc">{{ product.templateName }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <view v-if="showSubTypeModal" class="modal-mask" @click="showSubTypeModal = false">
      <view class="modal-body" @click.stop>
        <text class="modal-title">Select Label Type</text>
        <text class="modal-desc">{{ selectedProduct ? getDisplayName(selectedProduct) : '' }}</text>
        <view class="subtype-list">
          <view
            v-for="lt in currentLabelTypes"
            :key="lt.id"
            class="subtype-item"
            @click="selectLabelType(lt)"
          >
            <text class="subtype-name">{{ lt.name }}</text>
            <AppIcon name="chevronRight" size="sm" color="gray" />
          </view>
        </view>
        <view class="modal-cancel" @click="showSubTypeModal = false">
          <text class="modal-cancel-text">Cancel</text>
        </view>
      </view>
    </view>

    <SideMenu v-model="isMenuOpen" />
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import AppIcon from '../../components/AppIcon.vue'
import SideMenu from '../../components/SideMenu.vue'
import LocationPicker from '../../components/LocationPicker.vue'
import { getStatusBarHeight } from '../../utils/statusBar'

const statusBarHeight = getStatusBarHeight()
const isMenuOpen = ref(false)
const selectedCategory = ref('prep')
const searchTerm = ref('')
const expandedCategories = ref<string[]>([])
const showSubTypeModal = ref(false)
const selectedProduct = ref<any>(null)
const currentLabelTypes = ref<any[]>([])

const btConnected = ref(false)
const btDeviceName = ref('')

onShow(() => {
  const name = uni.getStorageSync('btDeviceName')
  btConnected.value = !!name
  btDeviceName.value = name || ''
})

const labelCategories = [
  { id: 'prep', name: 'Prep', icon: 'chef', iconColor: 'green' as const, bgClass: 'green' },
  { id: 'grabngo', name: "Grab'n'Go", icon: 'package', iconColor: 'orange' as const, bgClass: 'orange' },
]

interface LabelType {
  id: string
  name: string
  desc: string
}

interface Product {
  id: string
  name: string
  image: string
  templateSize: string
  templateName: string
  lastEdited: string
  labelTypes: LabelType[]
}

interface ProductCategory {
  id: string
  name: string
  icon: string
  iconColor: 'blue' | 'orange' | 'green' | 'purple' | 'red' | 'gray'
  colorClass: string
  products: Product[]
}

const productCategoriesByLabel: Record<string, ProductCategory[]> = {
  prep: [
    {
      id: 'meat',
      name: 'Meat',
      icon: 'food',
      iconColor: 'red',
      colorClass: 'bg-red',
      products: [
        {
          id: 'chicken',
          name: 'Chicken',
          image: 'https://images.unsplash.com/photo-1532550907401-a500c9a57435?w=400',
          templateSize: '2"x2"',
          templateName: 'Basic',
          lastEdited: '2025.12.03 11:45',
          labelTypes: [
            { id: 'defrost', name: 'Defrost', desc: 'For defrosted items, tracks thaw date' },
            { id: 'opened', name: 'Opened/Preped', desc: 'For opened or prepared items' },
            { id: 'heated', name: 'Heated', desc: 'For heated/cooked items' },
          ],
        },
      ],
    },
  ],
  grabngo: [
    {
      id: 'sandwich',
      name: 'Sandwich',
      icon: 'food',
      iconColor: 'orange',
      colorClass: 'bg-orange',
      products: [
        {
          id: 'chicken-sandwich',
          name: 'Chicken Sandwich',
          image: 'https://images.unsplash.com/photo-1553909489-cd47e0907980?w=400',
          templateSize: '2"x6"',
          templateName: "G'n'G",
          lastEdited: '2025.12.03 11:45',
          labelTypes: [],
        },
      ],
    },
  ],
}

// 按详情页规则：chicken→Chicken，2"x6"/2"x4"→Cheese Burger Deluxe，其余→Syrup（图片仍用产品图）
function getDisplayName(product: Product): string {
  if (product.id === 'chicken') return 'Chicken'
  const size = product.templateSize || ''
  if (size.indexOf('2"x6"') >= 0 || size.indexOf('2"x4"') >= 0) return 'Cheese Burger Deluxe'
  return 'Syrup'
}

const filteredProductCategories = computed(() => {
  const cats = productCategoriesByLabel[selectedCategory.value] || []
  const s = searchTerm.value.toLowerCase()
  if (!s) return cats
  return cats
    .map(function (cat) {
      return {
        ...cat,
        products: cat.products.filter(function (p) {
          const displayName = getDisplayName(p)
          return p.name.toLowerCase().indexOf(s) >= 0 || displayName.toLowerCase().indexOf(s) >= 0
        }),
      }
    })
    .filter(function (cat) { return cat.products.length > 0 })
})

const toggleCategory = (catId: string) => {
  if (expandedCategories.value.indexOf(catId) >= 0) {
    expandedCategories.value = []
  } else {
    expandedCategories.value = [catId]
  }
}

const handleProductClick = (product: Product) => {
  if (product.labelTypes.length > 0) {
    selectedProduct.value = product
    currentLabelTypes.value = product.labelTypes
    showSubTypeModal.value = true
  } else {
    goPreview(product.id, '')
  }
}

const selectLabelType = (lt: LabelType) => {
  const product = selectedProduct.value
  if (product) {
    showSubTypeModal.value = false
    goPreview(product.id, lt.id)
  }
}

const goBack = () => {
  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack()
  } else {
    uni.redirectTo({ url: '/pages/index/index' })
  }
}

const goBluetoothPage = () => {
  uni.navigateTo({ url: '/pages/labels/bluetooth' })
}

const goPreview = (productId: string, subType: string) => {
  let url = '/pages/labels/preview?productId=' + productId
  if (subType) {
    url += '&subType=' + subType
  }
  uni.navigateTo({ url })
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f9fafb;
  display: flex;
  flex-direction: column;
}

.header-hero {
  background: linear-gradient(135deg, var(--theme-primary), var(--theme-primary-dark));
  padding-left: 32rpx;
  padding-right: 32rpx;
  padding-bottom: 0;
}

.top-bar {
  height: 96rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.top-left,
.top-right {
  width: 64rpx;
  height: 64rpx;
  border-radius: 999rpx;
  background: rgba(255, 255, 255, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
}

.top-center {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.app-name {
  font-size: 34rpx;
  font-weight: 600;
  color: #ffffff;
}

.bt-bar {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 16rpx 20rpx;
  margin-top: 16rpx;
  margin-bottom: 16rpx;
  background: rgba(255, 255, 255, 0.12);
  border-radius: 16rpx;
}

.bt-left {
  display: flex;
  align-items: center;
  gap: 12rpx;
  flex: 1;
  min-width: 0;
}

.bt-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.bt-status {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 6rpx 16rpx;
  background: rgba(255, 255, 255, 0.12);
  border-radius: 999rpx;
  flex-shrink: 0;
}

.bt-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: #fbbf24;
}

.bt-status.connected .bt-dot {
  background: #4ade80;
}

.bt-label {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.85);
}

.body {
  flex: 1;
  display: flex;
  min-height: 0;
}

.sidebar {
  width: 200rpx;
  background: #ffffff;
  border-right: 1rpx solid #e5e7eb;
  padding: 16rpx 0;
  overflow-y: auto;
}

.cat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 8rpx;
  position: relative;
}

.cat-item.active {
  background: var(--theme-primary-light);
}

.active-bar {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 6rpx;
  background: var(--theme-primary);
  border-radius: 0 6rpx 6rpx 0;
}

.cat-icon {
  width: 64rpx;
  height: 64rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8rpx;
}

.cat-icon.green {
  background: #f0fdf4;
}

.cat-icon.orange {
  background: #fff7ed;
}

.cat-icon.red {
  background: #fef2f2;
}

.cat-icon.blue {
  background: #eff6ff;
}

.cat-icon.cyan {
  background: #ecfeff;
}

.cat-item.active .cat-icon.green,
.cat-item.active .cat-icon.orange,
.cat-item.active .cat-icon.red,
.cat-item.active .cat-icon.blue,
.cat-item.active .cat-icon.cyan {
  background: var(--theme-primary);
}

.cat-name {
  font-size: 20rpx;
  color: #4b5563;
  text-align: center;
  word-break: break-word;
}

.cat-item.active .cat-name {
  color: var(--theme-primary);
  font-weight: 600;
}

.main-panel {
  flex: 1;
  min-width: 0;
  height: 100%;
}

.panel-inner {
  padding: 24rpx;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
}

.search-icon-wrap {
  position: absolute;
  left: 20rpx;
  z-index: 1;
}

.search-input {
  flex: 1;
  height: 72rpx;
  padding-left: 64rpx;
  padding-right: 20rpx;
  background: #f3f4f6;
  border-radius: 16rpx;
  font-size: 26rpx;
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 24rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #9ca3af;
  margin-top: 24rpx;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.cat-section {
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

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

.cat-header-left {
  display: flex;
  align-items: center;
  gap: 16rpx;
  flex: 1;
  min-width: 0;
}

.cat-header-icon {
  width: 56rpx;
  height: 56rpx;
  border-radius: 14rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.cat-header-icon.bg-red {
  background: #fef2f2;
}

.cat-header-icon.bg-blue {
  background: #eff6ff;
}

.cat-header-icon.bg-green {
  background: #f0fdf4;
}

.cat-header-icon.bg-orange {
  background: #fff7ed;
}

.cat-header-icon.bg-purple {
  background: #faf5ff;
}

.cat-header-info {
  flex: 1;
  min-width: 0;
}

.cat-header-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #111827;
  display: block;
}

.cat-header-count {
  font-size: 22rpx;
  color: #9ca3af;
  display: block;
  margin-top: 2rpx;
}

.cat-foods {
  padding: 0 16rpx 16rpx;
  border-top: 1rpx solid #f3f4f6;
}

.food-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  column-gap: 12rpx;
  row-gap: 12rpx;
  padding-top: 16rpx;
}

.food-card {
  background: #f9fafb;
  padding: 10rpx;
  border-radius: 14rpx;
}

.food-card:active {
  background: #f3f4f6;
}

.food-img-wrap {
  width: 100%;
  position: relative;
  padding-top: 75%;
  border-radius: 10rpx;
  background: #e5e7eb;
  margin-bottom: 10rpx;
  overflow: hidden;
}

.food-img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

.size-badge {
  position: absolute;
  left: 8rpx;
  top: 8rpx;
  background: rgba(0, 0, 0, 0.25);
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.size-badge-text {
  font-size: 18rpx;
  color: #fff;
  font-weight: 500;
}

.type-badge {
  position: absolute;
  right: 8rpx;
  bottom: 8rpx;
  background: rgba(0, 0, 0, 0.25);
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.type-badge-text {
  font-size: 18rpx;
  color: #fff;
  font-weight: 500;
}

.food-name {
  font-size: 24rpx;
  font-weight: 600;
  color: #111827;
  display: block;
  margin-bottom: 2rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.food-desc {
  font-size: 20rpx;
  color: #6b7280;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.modal-mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.modal-body {
  width: 100%;
  background: #fff;
  border-radius: 32rpx 32rpx 0 0;
  padding: 40rpx 32rpx;
  max-height: 70vh;
  overflow-y: auto;
}

.modal-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #111827;
  display: block;
  margin-bottom: 8rpx;
}

.modal-desc {
  font-size: 28rpx;
  color: #6b7280;
  display: block;
  margin-bottom: 32rpx;
}

.subtype-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.subtype-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 28rpx 24rpx;
  background: #f9fafb;
  border-radius: 16rpx;
  border: 2rpx solid #e5e7eb;
}

.subtype-item:active {
  background: var(--theme-primary-light);
  border-color: var(--theme-primary);
}

.subtype-name {
  flex: 1;
  min-width: 0;
  font-size: 30rpx;
  font-weight: 600;
  color: #111827;
}

.modal-cancel {
  width: 100%;
  height: 88rpx;
  background: #f3f4f6;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-cancel-text {
  font-size: 30rpx;
  font-weight: 500;
  color: #374151;
  line-height: 1;
}

@media (min-width: 768px) {
  .sidebar {
    width: 260rpx;
  }

  .food-grid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
    column-gap: 16rpx;
    row-gap: 16rpx;
  }
}
</style>
