<template>
  <section class="page-card checkout-wrap max-w-full overflow-x-hidden min-w-0" v-if="!loading && product">
    <!-- Header：窄屏纵向排列，避免与标题抢宽度 -->
    <div class="flex flex-col gap-3 mb-5 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
      <button type="button" class="ghost shrink-0 self-start w-full sm:w-auto text-center" @click="goBack">返回商品</button>
    </div>

    <!-- Grid：禁止内联 columns（会盖掉 max-md 单列）；小屏单列，lg 起双列 -->
    <div class="grid grid-cols-1 gap-6 mb-5 min-w-0 lg:grid-cols-[minmax(0,1fr)_320px] lg:items-start">
      <!-- Summary -->
      <div class="flex flex-col gap-[18px] bg-white/80 rounded-[var(--radius-default)] border border-white/35 p-4 min-w-0 sm:flex-row sm:p-[18px] sm:items-start">
        <img
          :src="product.coverUrl"
          :alt="product.name"
          class="w-full max-w-[200px] h-[160px] sm:h-[140px] object-cover rounded-lg mx-auto sm:mx-0 sm:w-[140px] sm:max-w-none sm:shrink-0"
        />
        <div class="flex-1 flex flex-col gap-2 min-w-0 w-full">
          <h3>{{ product.name }}</h3>
          <p class="tag">库存：{{ stockLabel(product) }}</p>
          <p class="tag">浏览量：{{ product.viewCount || 0 }}</p>
          <p class="font-semibold text-accent2">
            <span v-if="isFree" class="text-[#3a9a68] font-black">免费</span>
            <span v-else-if="product.discountPrice > 0 && product.discountPrice < product.price">
              <span class="line-through text-muted mr-1.5 text-[15px]">¥ {{ product.price.toFixed(2) }}</span>
              ¥ {{ product.discountPrice.toFixed(2) }}
            </span>
            <span v-else>¥ {{ product.price.toFixed(2) }}</span>
          </p>
          <p class="markdown break-words overflow-x-auto max-w-full" v-html="renderMarkdown(product.description)"></p>
        </div>
      </div>

      <!-- Require-login gate -->
      <div v-if="!orderResult && product.requireLogin && !loggedIn" class="flex flex-col gap-4 items-center p-8 text-center border border-white/35 rounded-lg bg-white/60">
        <p class="text-[18px] font-semibold text-apptext">该商品需要登录后才能购买</p>
        <a class="primary inline-block no-underline px-7 py-2.5 rounded-lg text-base font-bold cursor-pointer" :href="loginUrl">立即登录</a>
      </div>

      <!-- Order form -->
      <form v-else-if="!orderResult" class="flex flex-col gap-3 min-w-0 w-full" @submit.prevent="submitOrder">
        <div class="form-field">
          <label>下单数量</label>
          <input
            v-model.number="form.quantity"
            min="1"
            :max="maxOrderQty"
            type="number"
          />
        </div>
        <p class="tag">预计总价：¥ {{ totalPrice.toFixed(2) }}</p>
        <p class="tag text-accent" v-if="product.maxPerAccount > 0">
          该商品每个账户最多可购买 {{ product.maxPerAccount }} 个
        </p>

        <div class="form-field">
          <label>备注（选填）</label>
          <textarea v-model="form.note" placeholder="填写您的备注信息…" rows="3"></textarea>
        </div>

        <div class="grid grid-cols-2 gap-3 max-md:grid-cols-1">
          <div class="form-field">
            <label>手机号（选填）</label>
            <input v-model="form.contactPhone" type="tel" placeholder="138xxxx0000" />
          </div>
          <div class="form-field">
            <label>邮箱（选填）</label>
            <input v-model="form.contactEmail" type="email" placeholder="you@example.com" />
          </div>
        </div>

        <p class="tag" v-if="!loggedIn">
          <a class="text-accent2 no-underline font-semibold hover:underline" :href="loginUrl">登录萌芽账号</a> 后购买可享受：历史订单记录、专属优惠商品及更多购买权益
        </p>

        <button class="primary w-full" type="submit" :disabled="submitting">
          {{ submitting ? '生成中...' : '生成二维码下单' }}
        </button>
        <p class="text-[#d64848] text-[15px]" v-if="error">{{ error }}</p>
      </form>
    </div>

    <!-- Order result -->
    <section v-if="orderResult" class="mt-4 text-left sm:text-center max-w-full min-w-0 px-0">
      <h4 class="text-base sm:text-lg font-bold mb-2 break-words leading-snug">
        订单已创建
        <span class="mt-2 flex flex-wrap items-center gap-2 justify-start sm:justify-center">
          <span class="font-mono text-[12px] sm:text-[13px] font-normal text-muted break-all text-left max-w-full">{{ orderResult.orderId }}</span>
          <button
            type="button"
            class="checkout-copy-id shrink-0 text-[13px] font-semibold px-3 py-1.5 rounded-lg border border-white/50 bg-white/70 text-apptext hover:bg-white/90 active:scale-[0.98] transition-colors"
            @click="copyOrderId"
          >{{ orderIdCopyHint || '复制订单号' }}</button>
        </span>
      </h4>

      <template v-if="!confirmed">
        <!-- 付费：真实收款码模拟（资产见 src/assets/payment） -->
        <template v-if="needPayChannel">
          <p class="text-apptext text-base sm:text-lg font-bold mb-2">
            应付金额
            <span class="text-accent2 text-[#4a6fa8]">¥ {{ paidAmountSnapshot.toFixed(2) }}</span>
          </p>
          <p class="tag mb-3 leading-relaxed text-[14px] sm:text-[15px] text-apptext/90 max-w-[40rem] mx-auto sm:mx-auto">
            请使用下方<strong>支付宝</strong>或<strong>微信</strong>扫码支付；<strong>转账备注请务必填写订单号</strong>，便于核对。
          </p>
          <div class="tag mb-3 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3 rounded-lg bg-white/40 border border-white/30 px-3 py-2.5 text-left">
            <p class="font-mono text-[12px] sm:text-[13px] break-all m-0 flex-1 min-w-0 text-apptext">
              <span class="font-sans font-semibold text-muted">订单号：</span>{{ orderResult.orderId }}
            </p>
            <button
              type="button"
              class="checkout-copy-id shrink-0 w-full sm:w-auto text-[13px] font-semibold px-3 py-2 sm:py-1.5 rounded-lg border border-accent2/40 bg-white/80 text-accent2 hover:bg-white active:scale-[0.98] transition-colors"
              @click="copyOrderId"
            >{{ orderIdCopyHint || '一键复制' }}</button>
          </div>

          <div
            class="flex flex-col gap-2 w-full max-w-md mx-auto mb-4 sm:max-w-none sm:flex-row sm:flex-wrap sm:justify-center sm:gap-2"
            role="tablist"
            aria-label="收款渠道"
          >
            <button
              v-for="ch in payChannels"
              :key="ch.id"
              type="button"
              role="tab"
              class="w-full sm:w-auto sm:min-w-[7.5rem] px-4 py-3 sm:py-2 rounded-xl border text-[15px] font-semibold transition-colors text-left sm:text-center touch-manipulation"
              :class="payChannel === ch.id
                ? 'border-accent2 bg-white/90 text-accent2 shadow-sm ring-2 ring-accent2/25'
                : 'border-white/45 bg-white/55 text-apptext active:bg-white/80'"
              :aria-selected="payChannel === ch.id"
              @click="payChannel = ch.id"
            >
              <span class="block">{{ ch.label }}</span>
              <span class="block text-[12px] font-normal text-muted mt-0.5">{{ ch.hint }}</span>
            </button>
          </div>

          <div class="flex justify-center my-3">
            <img
              :src="currentPayQrSrc"
              :alt="currentPayQrAlt"
              class="max-w-[min(300px,88vw)] w-full rounded-xl border border-white/40 shadow-[0_8px_28px_rgba(33,33,40,0.12)] bg-white/50"
            />
          </div>

          <p v-if="orderResult.qrCodeUrl" class="tag mb-3 opacity-80">
            <span class="sr-only">系统订单凭证</span>
            <button
              type="button"
              class="text-accent2 underline-offset-2 hover:underline bg-transparent border-none cursor-pointer p-0 font-inherit text-[13px]"
              @click="showOrderTokenQr = !showOrderTokenQr"
            >{{ showOrderTokenQr ? '收起' : '展开' }}订单系统二维码（可选）</button>
          </p>
          <div v-show="showOrderTokenQr" class="flex justify-center mb-2">
            <img
              :src="orderResult.qrCodeUrl"
              alt="订单凭证二维码"
              class="max-w-[160px] w-full rounded-lg border border-white/35 opacity-90"
            />
          </div>
        </template>

        <!-- 免费：仅展示系统下发的凭证码 -->
        <template v-else>
          <p class="tag mb-2">免费订单已生成，可保存下方凭证</p>
          <img
            v-if="orderResult.qrCodeUrl"
            :src="orderResult.qrCodeUrl"
            alt="订单凭证"
            class="max-w-[320px] mx-auto w-full rounded-lg border border-white/35 my-3"
          />
        </template>

        <div class="flex flex-col items-stretch sm:items-center gap-2.5 my-4 max-w-md mx-auto sm:max-w-none">
          <button type="button" class="primary w-full sm:w-auto px-6" :disabled="confirming" @click="doConfirm">
            {{ confirming ? '确认中...' : (needPayChannel ? '我已完成扫码付款' : '确认领取') }}
          </button>
          <p class="tag text-center text-[13px] sm:text-[15px]">{{ needPayChannel ? '完成支付后点击上方按钮获取购买内容' : '点击确认以查看购买内容' }}</p>
        </div>
        <p class="text-[#d64848] text-[15px]" v-if="confirmError">{{ confirmError }}</p>
      </template>

      <template v-else>
        <span class="inline-block px-4 py-1.5 rounded-full bg-gradient-to-br from-accent to-accent2 text-white text-[15px] font-semibold mb-3">订单已完成</span>
        <div v-if="deliveredCodes.length" class="my-3 flex flex-col items-center gap-2">
          <p class="tag">购买后内容</p>
          <textarea
            class="w-[min(520px,100%)] min-h-[120px] px-4 py-3.5 rounded-lg border border-white/35 bg-white/90 text-apptext text-base leading-[1.7] resize-none"
            style="font-family: var(--font-serif);"
            readonly
            :value="deliveredCodes.join('\n')"
          ></textarea>
        </div>
        <div v-else-if="isManualDelivery" class="flex items-start gap-3 p-4 bg-[rgba(90,180,120,0.08)] border border-[rgba(90,180,120,0.25)] rounded-lg text-apptext max-w-lg mx-auto text-left">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
          <div>
            <p class="text-base font-semibold text-[#3a9a68] mb-1">等待发货中</p>
            <p class="tag">管理员将尽快处理您的订单并进行发货，请关注您的邮箱或联系方式。</p>
          </div>
        </div>
        <p class="tag mt-3">感谢购买！如有问题请联系售后邮箱。</p>
      </template>
    </section>
  </section>

  <section class="page-card" v-else-if="!loading">
    <h2>未找到该商品</h2>
    <p class="tag mt-2">该商品无法下单，请返回商店页。</p>
    <div class="flex gap-3 mt-[18px]">
      <button class="ghost" @click="goBack">返回商品</button>
    </div>
  </section>

  <section class="page-card" v-else>
    <div class="py-6 text-muted">加载中...</div>
  </section>
</template>

<script setup>
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import MarkdownIt from 'markdown-it'
import { fetchProducts, createOrder, confirmOrder } from '../shared/api'
import { authState, isLoggedIn, getLoginUrl } from '../shared/auth'
import { isFixedFulfillment, stockLabel } from '../shared/fulfillment'
import qrAlipay from '../../assets/payment/支付宝个人收款码.png'
import qrWechatPay from '../../assets/payment/微信个人收款码.png'
import qrWechatReward from '../../assets/payment/微信赞赏码.png'

const route = useRoute()
const router = useRouter()
const md = new MarkdownIt()
const product = ref(null)
const loading = ref(true)
const submitting = ref(false)
const error = ref('')
const orderResult = ref(null)
const confirmed = ref(false)
const confirming = ref(false)
const confirmError = ref('')
const deliveredCodes = ref([])
const paidAmountSnapshot = ref(0)
const payChannel = ref('alipay')
const showOrderTokenQr = ref(false)
/** 复制订单号反馈：空串表示显示默认按钮文案 */
const orderIdCopyHint = ref('')
let orderIdCopyTimer = null

const copyOrderId = async () => {
  const id = orderResult.value?.orderId
  if (!id) return
  try {
    if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(id)
    } else {
      const ta = document.createElement('textarea')
      ta.value = id
      ta.setAttribute('readonly', '')
      ta.style.position = 'fixed'
      ta.style.left = '-9999px'
      document.body.appendChild(ta)
      ta.select()
      document.execCommand('copy')
      document.body.removeChild(ta)
    }
    orderIdCopyHint.value = '已复制'
  } catch {
    orderIdCopyHint.value = '复制失败'
  }
  clearTimeout(orderIdCopyTimer)
  orderIdCopyTimer = setTimeout(() => {
    orderIdCopyHint.value = ''
  }, 2000)
}

/** 真实收款码：与 src/assets/payment 内图片一致 */
const payChannels = [
  { id: 'alipay', label: '支付宝', hint: '个人收款', img: qrAlipay },
  { id: 'wechat', label: '微信支付', hint: '个人收款', img: qrWechatPay },
  { id: 'reward', label: '微信赞赏', hint: '可选 · 谢谢支持', img: qrWechatReward }
]

const loggedIn = computed(() => isLoggedIn())
const loginUrl = computed(() => getLoginUrl())

const form = reactive({ quantity: 1, note: '', contactPhone: '', contactEmail: '' })
const isManualDelivery = ref(false)

const renderMarkdown = (content) => md.render(content || '')

const getPayPrice = (p) => {
  if (!p) return 0
  if (p.price === 0) return 0
  if (p.discountPrice > 0 && p.discountPrice < p.price) return p.discountPrice
  return p.price
}

const unitPrice = computed(() => getPayPrice(product.value))
const isFree = computed(() => unitPrice.value === 0)
const totalPrice = computed(() => {
  if (!product.value) return 0
  const qty = form.quantity && form.quantity > 0 ? form.quantity : 1
  return unitPrice.value * qty
})

/** 数量上限：固定内容只受每账户限购；卡密还受库存限制 */
const maxOrderQty = computed(() => {
  const p = product.value
  if (!p) return undefined
  const per = p.maxPerAccount > 0 ? p.maxPerAccount : null
  if (isFixedFulfillment(p)) {
    return per ?? undefined
  }
  const stock = (p.quantity ?? 0) > 0 ? p.quantity : null
  if (per != null && stock != null) return Math.min(per, stock)
  if (per != null) return per
  if (stock != null) return stock
  return undefined
})

const needPayChannel = computed(() => paidAmountSnapshot.value > 0.0001)

const currentPayQrSrc = computed(() => {
  const ch = payChannels.find((c) => c.id === payChannel.value)
  return ch?.img || qrAlipay
})

const currentPayQrAlt = computed(() => {
  const ch = payChannels.find((c) => c.id === payChannel.value)
  return ch ? `${ch.label}收款码` : '收款码'
})

const goBack = () => router.push('/')

const submitOrder = async () => {
  if (!product.value) return
  error.value = ''
  submitting.value = true
  orderResult.value = null
  confirmed.value = false
  deliveredCodes.value = []
  paidAmountSnapshot.value = totalPrice.value
  payChannel.value = 'alipay'
  showOrderTokenQr.value = false
  orderIdCopyHint.value = ''
  clearTimeout(orderIdCopyTimer)
  try {
    const payload = {
      productId: product.value.id,
      quantity: form.quantity,
      note: form.note || '',
      contactPhone: form.contactPhone || '',
      contactEmail: form.contactEmail || '',
      notifyEmail: authState.email || ''
    }
    const token = isLoggedIn() ? authState.token : null
    const response = await createOrder(payload, token)
    orderResult.value = response
  } catch (err) {
    error.value = err?.response?.data?.error || '下单失败，请稍候再试'
  } finally {
    submitting.value = false
  }
}

const doConfirm = async () => {
  if (!orderResult.value?.orderId) return
  confirmError.value = ''
  confirming.value = true
  try {
    const result = await confirmOrder(orderResult.value.orderId)
    deliveredCodes.value = result.deliveredCodes || []
    isManualDelivery.value = result.isManual || result.deliveryMode === 'manual'
    confirmed.value = true
  } catch (err) {
    confirmError.value = err?.response?.data?.error || '确认失败，请重试'
  } finally {
    confirming.value = false
  }
}

onUnmounted(() => {
  clearTimeout(orderIdCopyTimer)
})

onMounted(async () => {
  try {
    const list = await fetchProducts()
    product.value = list.find((item) => item.id === route.params.id) || null
  } finally {
    loading.value = false
  }
})
</script>
