<script setup lang="ts">
/**
 * 确认订单页
 *
 * 结算购物车中已选中的商品：选择收货地址、优惠券、填写备注，提交订单后支持模拟支付。
 */
import { ElMessage } from 'element-plus'
import {
  ArrowRight,
  Check,
  CircleCheck,
  Goods,
  Location,
  Plus,
  Ticket
} from '@element-plus/icons-vue'
import AppHeader from '@/components/layout/AppHeader.vue'
import AppFooter from '@/components/layout/AppFooter.vue'
import EmptyState from '@/components/common/EmptyState.vue'
import { getCartApi } from '@/api/cart'
import { getAddressListApi, createAddressApi } from '@/api/address'
import { getMyCouponsApi } from '@/api/coupon'
import { submitOrderApi, payOrderApi } from '@/api/order'
import type { CartItem } from '@/types/cart'
import type { Address, AddressSaveReq } from '@/types/address'
import type { UserCoupon } from '@/types/coupon'
import type { OrderSubmitResult } from '@/types/order'

/** 与后端 OrderConstant 保持一致：满 99 免运费，默认运费 0 */
const FREIGHT_THRESHOLD = 99
const DEFAULT_FREIGHT = 0

const router = useRouter()

const loading = ref(true)
const items = ref<CartItem[]>([])
const addressList = ref<Address[]>([])
const addressLoading = ref(false)
const selectedAddressId = ref<number | null>(null)
const couponList = ref<UserCoupon[]>([])
const selectedCouponId = ref<number | null>(null)
const couponDialog = ref(false)
const remark = ref('')
const submitting = ref(false)
const submitted = ref<OrderSubmitResult | null>(null)
const paying = ref(false)

const selectedItems = computed(() => {
  return items.value.filter(item => item.selected === 1 && item.productStatus === 1)
})

const totalQuantity = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + item.quantity, 0)
})

const totalAmount = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + Number(item.subtotal || 0), 0)
})

const freightAmount = computed(() => {
  return totalAmount.value >= FREIGHT_THRESHOLD ? 0 : DEFAULT_FREIGHT
})

interface CouponOption {
  coupon: UserCoupon
  discount: number
  usable: boolean
  shortage: number
  amountText: string
  ruleText: string
}

const couponOptions = computed<CouponOption[]>(() => {
  const total = totalAmount.value
  return couponList.value.map(coupon => {
    const amount = Number(coupon.amount || 0)
    const minAmount = Number(coupon.minAmount || 0)
    const maxDiscount = Number(coupon.maxDiscount || 0)

    let discount = 0
    if (coupon.couponType === 1) {
      discount = total * (1 - amount)
      if (maxDiscount > 0 && discount > maxDiscount) {
        discount = maxDiscount
      }
    } else {
      discount = amount
    }
    discount = Math.max(0, Math.min(discount, Math.max(0, total - 0.01)))

    const shortage = Math.max(0, minAmount - total)
    return {
      coupon,
      discount: round2(discount),
      usable: total > 0 && shortage === 0,
      shortage: round2(shortage),
      amountText: couponAmountText(coupon),
      ruleText: couponRuleText(coupon)
    }
  })
})

const selectedCoupon = computed(() => {
  return couponOptions.value.find(option => option.coupon.id === selectedCouponId.value) || null
})

const discountAmount = computed(() => selectedCoupon.value?.discount || 0)

const payAmount = computed(() => {
  return round2(Math.max(0.01, totalAmount.value + freightAmount.value - discountAmount.value))
})

async function loadCheckout() {
  loading.value = true
  try {
    const [cart, addresses, coupons] = await Promise.all([
      getCartApi(),
      getAddressListApi(),
      getMyCouponsApi(0)
    ])
    items.value = cart?.items || []
    addressList.value = addresses || []
    couponList.value = coupons || []

    const defaultAddress = addressList.value.find(address => address.isDefault === 1) || addressList.value[0]
    if (defaultAddress) {
      selectedAddressId.value = defaultAddress.id
    }
  } catch {
    /* 拦截器已提示 */
  } finally {
    loading.value = false
  }
}

function openCouponDialog() {
  couponDialog.value = true
}

function chooseCoupon(option: CouponOption | null) {
  if (option && !option.usable) return
  selectedCouponId.value = option ? option.coupon.id : null
  couponDialog.value = false
}

async function handleSubmit() {
  if (!selectedAddressId.value) {
    ElMessage.warning('请先选择收货地址')
    return
  }
  if (!selectedItems.value.length) {
    ElMessage.warning('没有可结算的商品')
    return
  }

  submitting.value = true
  try {
    const result = await submitOrderApi({
      items: selectedItems.value.map(item => ({
        skuId: item.skuId,
        quantity: item.quantity
      })),
      addressId: selectedAddressId.value,
      couponId: selectedCouponId.value ?? undefined,
      remark: remark.value.trim() || undefined
    })
    submitted.value = result
    window.scrollTo({ top: 0, behavior: 'smooth' })
  } catch {
    /* 拦截器已提示 */
  } finally {
    submitting.value = false
  }
}

async function handlePay() {
  if (!submitted.value) return
  paying.value = true
  try {
    await payOrderApi(submitted.value.orderId)
    ElMessage.success('支付成功')
    router.push('/user')
  } catch {
    /* 拦截器已提示 */
  } finally {
    paying.value = false
  }
}

// ==================== 新增地址 ====================
const addressDialog = ref(false)
const addressFormRef = ref()
const addressSaving = ref(false)
const addressForm = reactive<AddressSaveReq>({
  id: undefined,
  receiver: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  tag: '',
  isDefault: 0
})

const addressRules = {
  receiver: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  detail: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

function openAddressDialog() {
  Object.assign(addressForm, {
    id: undefined,
    receiver: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    tag: '',
    isDefault: 0
  })
  addressDialog.value = true
}

async function submitAddress() {
  if (!addressFormRef.value) return
  await addressFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    addressSaving.value = true
    try {
      const id = await createAddressApi(addressForm)
      ElMessage.success('地址已添加')
      addressDialog.value = false
      addressList.value = await getAddressListApi()
      selectedAddressId.value = id
    } catch {
      /* 拦截器已提示 */
    } finally {
      addressSaving.value = false
    }
  })
}

// ==================== 工具方法 ====================
function formatPrice(value: number | string | null | undefined) {
  return Number(value || 0).toFixed(2)
}

function round2(value: number) {
  return Math.round(value * 100) / 100
}

function couponAmountText(coupon: UserCoupon) {
  const amount = Number(coupon.amount || 0)
  if (coupon.couponType === 1) {
    const rate = Math.round(amount * 100)
    return `${rate / 10} 折`
  }
  return `¥${formatPrice(amount)}`
}

function couponRuleText(coupon: UserCoupon) {
  const min = Number(coupon.minAmount || 0)
  if (coupon.couponType === 0 && min > 0) {
    return `满 ¥${formatPrice(min)} 可用`
  }
  if (coupon.couponType === 1) {
    const max = Number(coupon.maxDiscount || 0)
    return max > 0 ? `最高抵扣 ¥${formatPrice(max)}` : '不限最高抵扣'
  }
  return '无门槛'
}

onMounted(loadCheckout)
</script>

<template>
  <div class="checkout-page">
    <AppHeader />

    <main class="checkout-main">
      <div class="container">
        <div class="page-head">
          <h1 class="page-title">
            <span class="title-badge">
              <el-icon :size="18"><Location /></el-icon>
            </span>
            确认订单
          </h1>
          <span v-if="selectedItems.length" class="count-badge">共 {{ totalQuantity }} 件</span>
        </div>

        <el-skeleton v-if="loading" :rows="6" animated class="checkout-skeleton" />

        <template v-else-if="!selectedItems.length && !submitted">
          <EmptyState description="购物车中还没有待结算的商品" />
          <div class="empty-actions">
            <button type="button" class="go-shopping-btn" @click="router.push('/cart')">
              返回购物车
            </button>
          </div>
        </template>

        <template v-else-if="submitted">
          <section class="success-panel">
            <div class="success-icon">
              <el-icon :size="44"><CircleCheck /></el-icon>
            </div>
            <h2>订单提交成功</h2>
            <p class="success-no">订单号：{{ submitted.orderNo }}</p>
            <p class="success-amount">
              应付金额 <b>¥{{ formatPrice(payAmount) }}</b>
            </p>
            <div class="success-actions">
              <button type="button" class="pay-btn" :disabled="paying" @click="handlePay">
                {{ paying ? '支付中...' : '立即支付' }}
              </button>
              <button type="button" class="ghost-btn" @click="router.push('/user')">
                查看订单
              </button>
              <button type="button" class="text-btn" @click="router.push('/')">
                返回首页
              </button>
            </div>
          </section>
        </template>

        <template v-else>
          <div class="checkout-grid">
            <div class="checkout-col">
              <!-- 收货地址 -->
              <section class="ck-section">
                <div class="section-head">
                  <span class="section-badge">
                    <el-icon :size="16"><Location /></el-icon>
                  </span>
                  <h2>收货地址</h2>
                  <div class="section-actions">
                    <button type="button" class="section-link" @click="router.push('/user')">
                      管理地址
                    </button>
                    <button type="button" class="section-btn" @click="openAddressDialog">
                      <el-icon :size="14"><Plus /></el-icon>
                      新增地址
                    </button>
                  </div>
                </div>

                <div v-loading="addressLoading" class="address-list">
                  <template v-if="addressList.length">
                    <div
                      v-for="address in addressList"
                      :key="address.id"
                      class="address-card"
                      :class="{ active: selectedAddressId === address.id }"
                      @click="selectedAddressId = address.id"
                    >
                      <div class="address-top">
                        <span class="address-receiver">{{ address.receiver }}</span>
                        <span class="address-phone">{{ address.phone }}</span>
                        <span v-if="address.isDefault === 1" class="default-tag">默认</span>
                        <span v-if="address.tag" class="address-tag">{{ address.tag }}</span>
                      </div>
                      <p class="address-detail">{{ address.fullAddress || address.detail }}</p>
                      <div class="address-check">
                        <el-radio :model-value="selectedAddressId ?? undefined" :value="address.id" />
                      </div>
                    </div>
                  </template>
                  <div v-else class="no-address">
                    <p>还没有收货地址</p>
                    <button type="button" class="section-btn" @click="openAddressDialog">
                      <el-icon :size="14"><Plus /></el-icon>
                      新增地址
                    </button>
                  </div>
                </div>
              </section>

              <!-- 商品清单 + 备注 -->
              <section class="ck-section">
                <div class="section-head">
                  <span class="section-badge">
                    <el-icon :size="16"><Goods /></el-icon>
                  </span>
                  <h2>商品清单</h2>
                  <span class="section-count">{{ selectedItems.length }} 种商品</span>
                </div>

                <div class="goods-list">
                  <div v-for="item in selectedItems" :key="item.skuId" class="goods-item">
                    <el-image
                      :src="item.productImage || item.skuImage"
                      fit="cover"
                      class="goods-image"
                      lazy
                    >
                      <template #error>
                        <div class="goods-placeholder">🍪</div>
                      </template>
                    </el-image>
                    <div class="goods-info">
                      <p class="goods-name" @click="router.push(`/product/${item.productId}`)">
                        {{ item.productName }}
                      </p>
                      <p class="goods-sku">{{ item.skuName }}</p>
                    </div>
                    <div class="goods-price">
                      <span class="goods-unit">¥{{ formatPrice(item.price) }}</span>
                      <span class="goods-qty">× {{ item.quantity }}</span>
                    </div>
                    <div class="goods-subtotal">¥{{ formatPrice(item.subtotal) }}</div>
                  </div>
                </div>

                <div class="remark-box">
                  <label class="remark-label" for="order-remark">订单备注</label>
                  <el-input
                    id="order-remark"
                    v-model="remark"
                    type="textarea"
                    :rows="2"
                    maxlength="200"
                    show-word-limit
                    placeholder="选填，200 字以内"
                  />
                </div>
              </section>
            </div>

            <!-- 结算栏 -->
            <aside class="checkout-aside">
              <div class="summary-card">
                <h3>金额明细</h3>

                <div class="sum-row">
                  <span>商品金额</span>
                  <b>¥{{ formatPrice(totalAmount) }}</b>
                </div>
                <div class="sum-row">
                  <span>运费</span>
                  <b class="free-text">包邮</b>
                </div>

                <button type="button" class="coupon-row" @click="openCouponDialog">
                  <span class="coupon-label">
                    <el-icon :size="16"><Ticket /></el-icon>
                    优惠券
                  </span>
                  <span v-if="selectedCoupon" class="coupon-value has-value">
                    -¥{{ formatPrice(discountAmount) }}
                  </span>
                  <span v-else class="coupon-value" :class="{ empty: !couponOptions.length }">
                    {{ couponOptions.length ? '选择优惠券' : '暂无可用' }}
                  </span>
                  <el-icon :size="14" class="coupon-arrow"><ArrowRight /></el-icon>
                </button>

                <div v-if="selectedCoupon" class="sum-row discount-row">
                  <span>优惠券抵扣</span>
                  <b>-¥{{ formatPrice(discountAmount) }}</b>
                </div>

                <div class="sum-row total-row">
                  <span>实付金额</span>
                  <b class="pay-amount">¥{{ formatPrice(payAmount) }}</b>
                </div>

                <button
                  type="button"
                  class="submit-btn"
                  :disabled="submitting"
                  @click="handleSubmit"
                >
                  <span>{{ submitting ? '提交中...' : '提交订单' }}</span>
                  <el-icon :size="16"><ArrowRight /></el-icon>
                </button>
                <p class="submit-tip">待付款订单超时后将自动取消</p>
              </div>
            </aside>
          </div>
        </template>
      </div>
    </main>

    <AppFooter />

    <!-- 新增地址 -->
    <el-dialog v-model="addressDialog" title="新增收货地址" width="520px">
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressRules"
        label-width="80px"
      >
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="addressForm.receiver" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="省">
          <el-input v-model="addressForm.province" placeholder="如：广东省" />
        </el-form-item>
        <el-form-item label="城市">
          <el-input v-model="addressForm.city" placeholder="如：深圳市" />
        </el-form-item>
        <el-form-item label="区/县">
          <el-input v-model="addressForm.district" placeholder="如：南山区" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input
            v-model="addressForm.detail"
            type="textarea"
            :rows="2"
            placeholder="街道、楼栋、门牌号等"
          />
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="addressForm.tag" placeholder="请选择标签" clearable>
            <el-option label="家" value="家" />
            <el-option label="公司" value="公司" />
            <el-option label="学校" value="学校" />
          </el-select>
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch v-model="addressForm.isDefault" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addressDialog = false">取消</el-button>
        <el-button type="primary" :loading="addressSaving" @click="submitAddress">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 选择优惠券 -->
    <el-dialog v-model="couponDialog" title="选择优惠券" width="520px">
      <div class="coupon-picker">
        <div
          class="coupon-option no-coupon"
          :class="{ active: !selectedCouponId }"
          @click="chooseCoupon(null)"
        >
          <span class="co-name">不使用优惠券</span>
          <el-icon v-if="!selectedCouponId" :size="16" class="co-check"><Check /></el-icon>
        </div>

        <template v-if="couponOptions.length">
          <div
            v-for="option in couponOptions"
            :key="option.coupon.id"
            class="coupon-option"
            :class="{
              active: selectedCouponId === option.coupon.id,
              disabled: !option.usable
            }"
            @click="chooseCoupon(option)"
          >
            <div class="co-left">
              <span class="co-amount">{{ option.amountText }}</span>
              <span class="co-name">{{ option.coupon.couponName }}</span>
            </div>
            <div class="co-right">
              <span v-if="option.usable" class="co-rule">{{ option.ruleText }}</span>
              <span v-else class="co-rule warn">差 ¥{{ formatPrice(option.shortage) }} 可用</span>
              <el-icon v-if="selectedCouponId === option.coupon.id" :size="16" class="co-check">
                <Check />
              </el-icon>
            </div>
          </div>
        </template>
        <div v-else class="coupon-empty">暂无可用优惠券</div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.checkout-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $bg-page;
}

.checkout-main {
  flex: 1;
  padding: 28px 0 48px;
}

.container {
  max-width: $container-max;
  margin: 0 auto;
  padding: 0 24px;
}

// ==================== 页头 ====================
.page-head {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-family: 'Fredoka', 'PingFang SC', sans-serif;
  font-size: $font-size-xxl;
  font-weight: 700;
  color: $color-text-primary;
  display: flex;
  align-items: center;
  gap: 10px;

  .title-badge {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    border-radius: 12px;
    background: $color-primary-light;
    color: $color-primary;
  }
}

.count-badge {
  padding: 5px 12px;
  border: 2px solid $color-border;
  border-radius: $radius-full;
  background: $bg-surface;
  color: $color-text-secondary;
  font-size: $font-size-sm;
  font-weight: 600;
}

.checkout-skeleton {
  padding: 20px;
  border: 2px solid $color-border;
  border-radius: $radius-lg;
  background: $bg-surface;
  box-shadow: $clay-shadow-sm;
}

.empty-actions {
  display: flex;
  justify-content: center;
  margin-top: -12px;
}

.go-shopping-btn {
  min-height: 44px;
  padding: 0 28px;
  border: 2px solid $color-border-dark;
  border-radius: $radius-full;
  background: linear-gradient(135deg, $color-primary, $color-cta);
  color: #fff;
  font-size: $font-size-md;
  font-weight: 600;
  box-shadow: 0 4px 0 0 $color-primary-dark;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s, filter 0.2s;

  &:hover {
    filter: brightness(1.04);
    transform: translateY(-1px);
  }

  &:active {
    box-shadow: 0 1px 0 0 $color-primary-dark;
    transform: translateY(3px);
  }
}

// ==================== 主体布局 ====================
.checkout-grid {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 360px;
  gap: 24px;
  align-items: start;
}

.checkout-col {
  display: flex;
  flex-direction: column;
  gap: 24px;
  min-width: 0;
}

.ck-section {
  padding: 22px;
  background: $bg-surface;
  border: 2px solid $color-border;
  border-radius: $radius-lg;
  box-shadow: $clay-shadow-sm;
}

.section-head {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 18px;
  flex-wrap: wrap;

  h2 {
    margin: 0;
    font-size: $font-size-lg;
    font-weight: 700;
    color: $color-text-primary;
  }
}

.section-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 10px;
  background: $color-primary-light;
  color: $color-primary;
  flex-shrink: 0;
}

.section-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 14px;
}

.section-link {
  padding: 0;
  border: none;
  background: transparent;
  color: $color-text-secondary;
  font-size: $font-size-sm;
  font-weight: 600;
  cursor: pointer;
  transition: color 0.2s;

  &:hover {
    color: $color-primary;
  }
}

.section-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  min-height: 34px;
  padding: 0 14px;
  border: 2px solid $color-border-dark;
  border-radius: $radius-full;
  background: linear-gradient(135deg, $color-primary, $color-cta);
  color: #fff;
  font-size: $font-size-sm;
  font-weight: 600;
  box-shadow: 0 3px 0 0 $color-primary-dark;
  cursor: pointer;
  transition: filter 0.2s, transform 0.2s, box-shadow 0.2s;

  &:hover {
    filter: brightness(1.04);
    transform: translateY(-1px);
  }

  &:active {
    box-shadow: 0 1px 0 0 $color-primary-dark;
    transform: translateY(2px);
  }
}

.section-count {
  margin-left: auto;
  color: $color-text-secondary;
  font-size: $font-size-sm;
  font-weight: 600;
}

// ==================== 收货地址 ====================
.address-list {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 14px;
  min-height: 110px;
}

.address-card {
  position: relative;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 14px 44px 14px 16px;
  border: 2px solid $color-border;
  border-radius: $radius-md;
  background: $bg-card;
  cursor: pointer;
  transition: border-color 0.2s, box-shadow 0.2s, transform 0.2s;

  &:hover {
    border-color: $color-primary;
    transform: translateY(-1px);
  }

  &.active {
    border-color: $color-primary;
    background: $color-primary-light;
    box-shadow: 0 0 0 3px rgba(240, 78, 62, 0.12);
  }
}

.address-top {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  padding-right: 24px;
}

.address-receiver {
  font-size: $font-size-md;
  font-weight: 700;
  color: $color-text-primary;
}

.address-phone {
  font-size: $font-size-sm;
  color: $color-text-secondary;
}

.default-tag {
  padding: 2px 8px;
  border-radius: $radius-full;
  background: $color-primary;
  color: #fff;
  font-size: $font-size-xs;
  font-weight: 600;
}

.address-tag {
  padding: 2px 8px;
  border: 1px solid $color-border-dark;
  border-radius: $radius-full;
  color: $color-text-secondary;
  font-size: $font-size-xs;
  font-weight: 600;
}

.address-detail {
  margin: 0;
  font-size: $font-size-sm;
  line-height: 1.55;
  color: $color-text-regular;
  word-break: break-all;
}

.address-check {
  position: absolute;
  top: 14px;
  right: 12px;
}

.no-address {
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  min-height: 110px;
  border: 2px dashed $color-border-dark;
  border-radius: $radius-md;
  color: $color-text-secondary;
  font-size: $font-size-md;
}

// ==================== 商品清单 ====================
.goods-list {
  display: flex;
  flex-direction: column;
}

.goods-item {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 14px 0;
  border-bottom: 2px solid $color-border;

  &:last-child {
    border-bottom: none;
  }
}

.goods-image {
  width: 68px;
  height: 68px;
  border-radius: $radius-sm;
  border: 2px solid $color-border;
  background: $bg-page;
  flex-shrink: 0;
  overflow: hidden;
}

.goods-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26px;
}

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

.goods-name {
  margin: 0 0 6px;
  font-size: $font-size-md;
  font-weight: 600;
  color: $color-text-primary;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  &:hover {
    color: $color-primary;
  }
}

.goods-sku {
  margin: 0;
  font-size: $font-size-sm;
  color: $color-text-secondary;
}

.goods-price {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  flex-shrink: 0;
}

.goods-unit {
  font-size: $font-size-sm;
  color: $color-text-regular;
  font-weight: 600;
}

.goods-qty {
  font-size: $font-size-xs;
  color: $color-text-placeholder;
}

.goods-subtotal {
  width: 92px;
  text-align: right;
  font-size: $font-size-md;
  font-weight: 700;
  color: $color-primary;
  flex-shrink: 0;
}

.remark-box {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 2px dashed $color-border;
}

.remark-label {
  display: block;
  margin-bottom: 10px;
  font-size: $font-size-sm;
  font-weight: 700;
  color: $color-text-primary;
}

// ==================== 结算栏 ====================
.checkout-aside {
  position: sticky;
  top: calc(#{$header-height} + 24px);
}

.summary-card {
  padding: 22px;
  background: $bg-surface;
  border: 2px solid $color-border;
  border-radius: $radius-lg;
  box-shadow: $clay-shadow-md;

  h3 {
    margin: 0 0 16px;
    font-size: $font-size-lg;
    font-weight: 700;
    color: $color-text-primary;
  }
}

.sum-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 9px 0;
  font-size: $font-size-md;
  color: $color-text-regular;

  b {
    color: $color-text-primary;
    font-weight: 700;
  }

  .free-text {
    color: $color-success;
    font-weight: 600;
  }

  &.discount-row b {
    color: $color-primary;
  }

  &.total-row {
    margin-top: 6px;
    padding-top: 16px;
    border-top: 2px solid $color-border;
    font-size: $font-size-md;
    font-weight: 700;
    color: $color-text-primary;
  }
}

.pay-amount {
  color: $color-primary;
  font-size: $font-size-xl;
  font-weight: 800;
}

.coupon-row {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  margin: 8px 0 12px;
  padding: 12px 14px;
  border: 2px solid $color-border;
  border-radius: $radius-md;
  background: $bg-card;
  cursor: pointer;
  transition: border-color 0.2s, background 0.2s;

  &:hover {
    border-color: $color-primary;
    background: $color-primary-light;
  }
}

.coupon-label {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: $font-size-sm;
  font-weight: 700;
  color: $color-text-primary;
  white-space: nowrap;
}

.coupon-value {
  margin-left: auto;
  font-size: $font-size-sm;
  color: $color-text-primary;
  font-weight: 600;
  white-space: nowrap;

  &.has-value {
    color: $color-primary;
    font-weight: 700;
  }

  &.empty {
    color: $color-text-placeholder;
  }
}

.coupon-arrow {
  color: $color-text-placeholder;
  flex-shrink: 0;
}

.submit-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  min-height: 48px;
  margin-top: 14px;
  border: 2px solid $color-border-dark;
  border-radius: $radius-full;
  background: linear-gradient(135deg, $color-primary, $color-cta);
  color: #fff;
  font-size: $font-size-lg;
  font-weight: 700;
  box-shadow: 0 5px 0 0 $color-primary-dark;
  cursor: pointer;
  transition: filter 0.2s, transform 0.2s, box-shadow 0.2s;

  &:hover:not(:disabled) {
    filter: brightness(1.05);
    transform: translateY(-1px);
  }

  &:active:not(:disabled) {
    box-shadow: 0 1px 0 0 $color-primary-dark;
    transform: translateY(4px);
  }

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
}

.submit-tip {
  margin: 12px 0 0;
  text-align: center;
  font-size: $font-size-xs;
  color: $color-text-placeholder;
}

// ==================== 提交成功 ====================
.success-panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 56px 24px;
  background: $bg-surface;
  border: 2px solid $color-border;
  border-radius: $radius-lg;
  box-shadow: $clay-shadow-md;
  text-align: center;
}

.success-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 84px;
  height: 84px;
  margin-bottom: 18px;
  border-radius: $radius-full;
  background: rgba(46, 196, 182, 0.14);
  color: $color-success;
}

.success-panel h2 {
  margin: 0 0 12px;
  font-size: $font-size-xxl;
  font-weight: 700;
  color: $color-text-primary;
}

.success-no {
  margin: 0 0 8px;
  font-size: $font-size-md;
  color: $color-text-secondary;
}

.success-amount {
  margin: 0 0 28px;
  font-size: $font-size-md;
  color: $color-text-regular;

  b {
    margin-left: 6px;
    font-size: $font-size-xxl;
    color: $color-primary;
  }
}

.success-actions {
  display: flex;
  align-items: center;
  gap: 14px;
  flex-wrap: wrap;
  justify-content: center;
}

.pay-btn,
.ghost-btn {
  min-height: 44px;
  padding: 0 26px;
  border-radius: $radius-full;
  font-size: $font-size-md;
  font-weight: 700;
  cursor: pointer;
  transition: filter 0.2s, transform 0.2s, box-shadow 0.2s;
}

.pay-btn {
  border: 2px solid $color-border-dark;
  background: linear-gradient(135deg, $color-primary, $color-cta);
  color: #fff;
  box-shadow: 0 4px 0 0 $color-primary-dark;

  &:hover:not(:disabled) {
    filter: brightness(1.05);
    transform: translateY(-1px);
  }

  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
}

.ghost-btn {
  border: 2px solid $color-border-dark;
  background: $bg-card;
  color: $color-text-primary;
  box-shadow: 0 4px 0 0 $color-border;

  &:hover {
    transform: translateY(-1px);
  }
}

.text-btn {
  padding: 0;
  border: none;
  background: transparent;
  color: $color-text-secondary;
  font-size: $font-size-md;
  font-weight: 600;
  cursor: pointer;

  &:hover {
    color: $color-primary;
  }
}

// ==================== 优惠券选择 ====================
.coupon-picker {
  max-height: 52vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding-right: 4px;
}

.coupon-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 14px 16px;
  border: 2px solid $color-border;
  border-radius: $radius-md;
  background: $bg-card;
  cursor: pointer;
  transition: border-color 0.2s, background 0.2s, box-shadow 0.2s;

  &:hover:not(.disabled) {
    border-color: $color-primary;
    background: $color-primary-light;
  }

  &.active {
    border-color: $color-primary;
    background: $color-primary-light;
    box-shadow: 0 0 0 3px rgba(240, 78, 62, 0.12);
  }

  &.disabled {
    opacity: 0.55;
    cursor: not-allowed;
  }
}

.co-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 0;
}

.co-amount {
  font-size: $font-size-xl;
  font-weight: 800;
  color: $color-primary;
  line-height: 1.2;
}

.co-name {
  font-size: $font-size-md;
  font-weight: 600;
  color: $color-text-primary;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.co-right {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-shrink: 0;
}

.co-rule {
  font-size: $font-size-xs;
  color: $color-text-secondary;
  font-weight: 600;
  white-space: nowrap;

  &.warn {
    color: $color-warning;
  }
}

.co-check {
  color: $color-primary;
}

.coupon-empty {
  padding: 40px 20px;
  text-align: center;
  color: $color-text-secondary;
  font-size: $font-size-md;
}

// ==================== 响应式 ====================
@media (max-width: 960px) {
  .checkout-grid {
    grid-template-columns: 1fr;
  }

  .checkout-aside {
    position: static;
  }
}

@media (max-width: 640px) {
  .container {
    padding: 0 14px;
  }

  .address-list {
    grid-template-columns: 1fr;
  }

  .section-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .goods-item {
    align-items: flex-start;
    flex-wrap: wrap;
  }

  .goods-price {
    margin-left: auto;
  }

  .goods-subtotal {
    width: 100%;
    text-align: right;
    padding-top: 8px;
  }
}
</style>
