<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="page-title">Label Preview</text>
          <LocationPicker />
        </view>
        <view class="top-right" @click="isMenuOpen = true">
          <AppIcon name="menu" size="sm" color="white" />
        </view>
      </view>
    </view>

    <view class="content">
      <view class="food-card">
        <view class="food-info">
          <text class="food-name">{{ displayProductName }}</text>
          <text class="food-cat">{{ productCategory }}</text>
          <view v-if="labelTypeName" class="food-label-type">
            <AppIcon name="tag" size="sm" color="primary" />
            <text class="food-label-type-text">{{ labelTypeName }}</text>
          </view>
        </view>
        <view class="food-template">
          <text class="template-size">{{ templateSize }}</text>
          <text class="template-name">{{ templateName }}</text>
        </view>
      </view>

      <view class="qty-card">
        <text class="qty-label">Print Quantity</text>
        <view class="qty-control">
          <view class="qty-btn" :class="{ disabled: printQty <= 1 }" @click="decrement">
            <AppIcon name="minus" size="sm" color="gray" />
          </view>
          <text class="qty-value">{{ printQty }}</text>
          <view class="qty-btn" @click="increment">
            <AppIcon name="plus" size="sm" color="gray" />
          </view>
        </view>
      </view>

      <text class="section-title">Label Preview</text>

      <view class="label-card">
        <view class="label-img-wrap">
          <image :src="labelImage" class="label-img" mode="widthFix" />
        </view>
      </view>

      <view class="info-row">
        <view class="info-item">
          <text class="info-label">Last Edited</text>
          <text class="info-value">{{ lastEdited }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">Location</text>
          <text class="info-value">{{ locationName }}</text>
        </view>
      </view>

      <view class="note-card">
        <AppIcon name="alert" size="sm" color="blue" />
        <text class="note-text">This is a preview of the label. Actual printed labels may vary slightly in appearance.</text>
      </view>
    </view>

    <view class="bottom-bar">
      <view class="bottom-info">
        <text class="bottom-qty">{{ printQty }} label{{ printQty > 1 ? 's' : '' }}</text>
        <view class="bt-indicator" :class="{ connected: btConnected }">
          <text class="bt-dot" />
          <text class="bt-name">{{ btConnected ? btDeviceName : 'No printer' }}</text>
        </view>
      </view>
      <view class="bottom-actions">
        <view class="btn-preview-sq" @click="showPreviewModal = true">
          <AppIcon name="eye" size="md" color="primary" />
        </view>
        <view class="print-btn" :class="{ disabled: isPrinting }" @click="handlePrint">
          <AppIcon name="printer" size="sm" color="white" />
          <text class="print-btn-text">{{ isPrinting ? 'Printing...' : 'Print' }}</text>
        </view>
      </view>
    </view>

    <view v-if="showPreviewModal" class="modal-mask" @click="showPreviewModal = false">
      <view class="modal-body modal-body-label-only" @click.stop>
        <view class="modal-label-wrap">
          <view class="modal-label-inner">
            <image :src="labelImage" class="modal-label-img" mode="widthFix" />
          </view>
        </view>
      </view>
    </view>

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

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad, 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 isPrinting = ref(false)
const isMenuOpen = ref(false)
const printQty = ref(1)
const showPreviewModal = ref(false)

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

const productName = ref('Chicken')
const productCategory = ref('Meat')
const labelTypeName = ref('')
const templateSize = ref('2"x2"')
const templateName = ref('Basic')
const lastEdited = ref('2025.12.03 11:45')
const locationName = ref('Location A')

const labelImage = computed(() => {
  const size = templateSize.value
  if (size.indexOf('2"x6"') >= 0 || size.indexOf('2"x4"') >= 0) {
    return '/static/lable2.png'
  }
  return '/static/lable1.png'
})

// 产品名称按标签模板固定：lable1 → Syrup，lable2 → Cheese Burger Deluxe
const displayProductName = computed(() =>
  labelImage.value.includes('lable1') ? 'Syrup' : 'Cheese Burger Deluxe'
)

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

interface ProductData {
  name: string
  category: string
  templateSize: string
  templateName: string
  lastEdited: string
  labelTypes: { id: string; name: string }[]
}

const productMap: Record<string, ProductData> = {
  'chicken': { name: 'Chicken', category: 'Meat', templateSize: '2"x2"', templateName: 'Basic', lastEdited: '2025.12.03 11:45', labelTypes: [{ id: 'defrost', name: 'Defrost' }, { id: 'opened', name: 'Opened/Preped' }, { id: 'heated', name: 'Heated' }] },
  'beef': { name: 'Beef', category: 'Meat', templateSize: '2"x2"', templateName: 'Basic', lastEdited: '2025.12.04 09:20', labelTypes: [{ id: 'defrost', name: 'Defrost' }, { id: 'opened', name: 'Opened/Preped' }, { id: 'heated', name: 'Heated' }] },
  'bacon': { name: 'Bacon', category: 'Meat', templateSize: '2"x2"', templateName: 'Basic', lastEdited: '2025.12.03 14:30', labelTypes: [{ id: 'raw', name: 'Raw Bacon' }, { id: 'cooked', name: 'Cooked Bacon' }] },
  'chicken-sandwich': { name: 'Chicken Sandwich', category: 'Sandwich', templateSize: '2"x6"', templateName: "G'n'G", lastEdited: '2025.12.03 11:45', labelTypes: [] },
  'turkey-club': { name: 'Turkey Club', category: 'Sandwich', templateSize: '2"x6"', templateName: "G'n'G", lastEdited: '2025.12.04 09:30', labelTypes: [] },
  'cheese-burger': { name: 'Cheese Burger', category: 'Sandwich', templateSize: '2"x6"', templateName: "G'n'G", lastEdited: '2025.12.03 15:20', labelTypes: [] },
  'caesar-salad': { name: 'Caesar Salad', category: 'Salads', templateSize: '2"x4"', templateName: "G'n'G", lastEdited: '2025.12.04 09:00', labelTypes: [] },
  'greek-salad': { name: 'Greek Salad', category: 'Salads', templateSize: '2"x4"', templateName: "G'n'G", lastEdited: '2025.12.03 12:30', labelTypes: [] },
  'fresh-juice': { name: 'Fresh Juice', category: 'Beverages', templateSize: '2"x2"', templateName: "G'n'G", lastEdited: '2025.12.04 07:45', labelTypes: [] },
  'smoothie': { name: 'Smoothie', category: 'Beverages', templateSize: '2"x2"', templateName: "G'n'G", lastEdited: '2025.12.03 11:00', labelTypes: [] },
  'milk': { name: 'Milk', category: 'Dairy', templateSize: '2"x2"', templateName: 'Basic', lastEdited: '2025.12.04 08:30', labelTypes: [] },
  'cheese': { name: 'Cheese', category: 'Dairy', templateSize: '2"x2"', templateName: 'Basic', lastEdited: '2025.12.03 11:15', labelTypes: [] },
  'sliced-ham': { name: 'Sliced Ham', category: 'Deli', templateSize: '2"x2"', templateName: 'Basic', lastEdited: '2025.12.04 10:00', labelTypes: [] },
  'turkey-deli': { name: 'Turkey Deli', category: 'Deli', templateSize: '2"x2"', templateName: 'Basic', lastEdited: '2025.12.03 14:20', labelTypes: [] },
}

onLoad((opts: any) => {
  const pid = (opts && opts.productId) || 'chicken'
  const subType = (opts && opts.subType) || ''

  const product = productMap[pid]
  if (product) {
    productName.value = product.name
    productCategory.value = product.category
    templateSize.value = product.templateSize
    templateName.value = product.templateName
    lastEdited.value = product.lastEdited

    if (subType) {
      const found = product.labelTypes.filter(function (lt) { return lt.id === subType })
      if (found.length > 0) {
        labelTypeName.value = found[0].name
      }
    }
  }

  const storeId = uni.getStorageSync('storeId') || '001'
  locationName.value = 'Location A'
})

const increment = () => { if (printQty.value < 99) printQty.value++ }
const decrement = () => { if (printQty.value > 1) printQty.value-- }
const goBack = () => uni.navigateBack()

const handlePrint = () => {
  if (isPrinting.value) return
  if (!btConnected.value) {
    uni.showModal({
      title: 'No Printer Connected',
      content: 'Please connect a Bluetooth printer first.',
      confirmText: 'Connect',
      cancelText: 'Cancel',
      success: (res) => {
        if (res.confirm) uni.navigateTo({ url: '/pages/labels/bluetooth' })
      },
    })
    return
  }
  isPrinting.value = true
  setTimeout(() => {
    isPrinting.value = false
    uni.showToast({ title: printQty.value + ' label' + (printQty.value > 1 ? 's' : '') + ' printed!', icon: 'success' })
  }, 2000)
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f9fafb;
  overflow-x: hidden;
  overflow-x: clip;
  width: 100%;
  max-width: 100vw;
  box-sizing: border-box;
}

.header-hero {
  background: linear-gradient(135deg, var(--theme-primary), var(--theme-primary-dark));
  padding: 16rpx 32rpx 24rpx;
}

.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;
}

.page-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #fff;
  display: block;
}

.content {
  padding: 32rpx;
  padding-bottom: 300rpx;
  box-sizing: border-box;
  overflow-x: hidden;
  overflow-x: clip;
  width: 100%;
  max-width: 100%;
  min-width: 0;
}

.food-card {
  background: #fff;
  padding: 28rpx;
  border-radius: 20rpx;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

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

.food-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #111827;
  display: block;
  margin-bottom: 4rpx;
}

.food-cat {
  font-size: 26rpx;
  color: #6b7280;
  display: block;
}

.food-label-type {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-top: 12rpx;
}

.food-label-type-text {
  font-size: 24rpx;
  color: var(--theme-primary);
  font-weight: 500;
}

.food-template {
  flex-shrink: 0;
  text-align: center;
  background: #f3f4f6;
  padding: 16rpx 20rpx;
  border-radius: 14rpx;
}

.template-size {
  font-size: 28rpx;
  font-weight: 700;
  color: #111827;
  display: block;
}

.template-name {
  font-size: 22rpx;
  color: #6b7280;
  display: block;
  margin-top: 4rpx;
}

.qty-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  padding: 24rpx 28rpx;
  border-radius: 20rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.qty-label {
  font-size: 30rpx;
  font-weight: 600;
  color: #111827;
}

.qty-control {
  display: flex;
  align-items: center;
}

.qty-btn {
  width: 64rpx;
  height: 64rpx;
  border-radius: 14rpx;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qty-btn:active {
  background: #e5e7eb;
}

.qty-btn.disabled {
  opacity: 0.35;
}

.qty-value {
  width: 88rpx;
  text-align: center;
  font-size: 36rpx;
  font-weight: 700;
  color: #111827;
}

.section-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #111827;
  display: block;
  margin-bottom: 20rpx;
}

/* 使用 block 布局避免移动端 Safari flex+图片溢出问题 */
.label-card {
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  overflow-x: clip;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
  padding: 24rpx 0;
  display: block;
  width: 100%;
  max-width: 100%;
  position: relative;
  contain: layout;
}

.label-img-wrap {
  width: 100%;
  max-width: 100%;
  overflow: hidden;
  overflow-x: clip;
  box-sizing: border-box;
  position: relative;
}

/* 移动端：width:auto + max-width:100% 比 width:100% 更可靠 */
.label-img {
  width: 100%;
  max-width: 100%;
  height: auto;
  display: block;
  vertical-align: top;
  object-fit: contain;
  border-radius: 12rpx;
  box-sizing: border-box;
}

.info-row {
  display: flex;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.info-item {
  flex: 1;
  background: #fff;
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.info-label {
  font-size: 22rpx;
  color: #9ca3af;
  display: block;
  margin-bottom: 6rpx;
}

.info-value {
  font-size: 26rpx;
  font-weight: 600;
  color: #111827;
  display: block;
}

.note-card {
  display: flex;
  align-items: flex-start;
  gap: 16rpx;
  padding: 24rpx 28rpx;
  background: #eff6ff;
  border: 1rpx solid #bfdbfe;
  border-radius: 16rpx;
}

.note-text {
  flex: 1;
  font-size: 26rpx;
  color: #1e40af;
  line-height: 1.5;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 32rpx;
  /* 兼容浏览器：env(safe-area-inset-bottom) + 最小 36px，避免打印按钮偏上/遮挡 */
  padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 36px);
  background: #fff;
  border-top: 1rpx solid #e5e7eb;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.04);
}

.bottom-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.bottom-qty {
  font-size: 26rpx;
  font-weight: 600;
  color: #111827;
}

.bt-indicator {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

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

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

.bt-name {
  font-size: 24rpx;
  color: #9ca3af;
}

.bt-indicator.connected .bt-name {
  color: #16a34a;
}

.bottom-actions {
  display: flex;
  align-items: stretch;
  gap: 24rpx;
}

.btn-preview-sq {
  width: 100rpx;
  height: 100rpx;
  flex-shrink: 0;
  background: #fff;
  border: 2rpx solid #d1d5db;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-preview-sq:active {
  background: #f3f4f6;
}

.print-btn {
  flex: 1;
  min-width: 0;
  height: 100rpx;
  background: var(--theme-primary);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.print-btn.disabled {
  opacity: 0.6;
}

.print-btn-text {
  font-size: 30rpx;
  font-weight: 600;
  color: #fff;
  line-height: 1;
}

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

.modal-body {
  width: 100%;
  max-width: 700rpx;
  max-height: 85vh;
  background: #fff;
  border-radius: 24rpx;
  overflow-x: hidden;
  overflow-y: hidden;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.modal-body-label-only .modal-label-wrap {
  margin-bottom: 0;
  padding: 24rpx;
}

.modal-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 32rpx;
  border-bottom: 1rpx solid #e5e7eb;
  flex-shrink: 0;
}

.modal-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #111827;
}

.modal-close {
  width: 52rpx;
  height: 52rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f3f4f6;
  transform: rotate(45deg);
}

.modal-scroll {
  flex: 1;
  min-width: 0;
  padding: 28rpx 40rpx;
  overflow-y: auto;
  overflow-x: hidden;
  overflow-x: clip;
  box-sizing: border-box;
}

.modal-label-wrap {
  width: 100%;
  max-width: 100%;
  margin-bottom: 24rpx;
  padding: 0;
  box-sizing: border-box;
  overflow: hidden;
  overflow-x: clip;
}

.modal-label-inner {
  width: 100%;
  max-width: 100%;
  min-width: 0;
  overflow: hidden;
  overflow-x: clip;
  box-sizing: border-box;
}

.modal-label-img {
  width: 100%;
  max-width: 100%;
  height: auto;
  display: block;
  vertical-align: top;
  object-fit: contain;
  border-radius: 12rpx;
  box-sizing: border-box;
}

.modal-info {
  text-align: center;
}

.modal-info-text {
  font-size: 30rpx;
  font-weight: 600;
  color: #111827;
  display: block;
  margin-bottom: 8rpx;
}

.modal-info-sub {
  font-size: 24rpx;
  color: #6b7280;
  display: block;
  margin-bottom: 4rpx;
}

/* 移动端额外约束，防止部分浏览器仍出现溢出 */
@media screen and (max-width: 768px) {
  .page,
  .content,
  .label-card,
  .label-img-wrap {
    max-width: 100vw;
  }
  .label-img,
  .modal-label-img {
    max-width: 100% !important;
  }
}
</style>
