<template>
  <section class="page-card" v-if="!loading && product">
    <!-- Header -->
    <div class="flex items-center justify-between gap-4 mb-5">
      <div>
        <h2>立即下单 · {{ product.name }}</h2>
        <p class="tag">一个扫码流程即可完成订单</p>
      </div>
      <button class="ghost" @click="goBack">返回商品</button>
    </div>

    <!-- Grid: summary + form -->
    <div class="grid gap-6 mb-5 max-md:grid-cols-1" style="grid-template-columns: minmax(280px, 1fr) 320px;">
      <!-- Summary -->
      <div class="flex gap-[18px] bg-white/80 rounded-[var(--radius-default)] border border-white/35 p-[18px] max-md:flex-col max-md:items-center">
        <img
          :src="product.coverUrl"
          :alt="product.name"
          class="w-[140px] h-[140px] object-cover rounded-lg max-md:w-full max-md:h-[200px]"
        />
        <div class="flex-1 flex flex-col gap-2">
          <h3>{{ product.name }}</h3>
          <p class="tag">库存：{{ product.quantity }}</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" 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" @submit.prevent="submitOrder">
        <div class="form-field">
          <label>下单数量</label>
          <input
            v-model.number="form.quantity"
            min="1"
            :max="product.maxPerAccount > 0 ? product.maxPerAccount : undefined"
            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" 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-center">
      <h4 class="text-lg font-bold mb-2">订单 {{ orderResult.orderId }} 已创建</h4>

      <template v-if="!confirmed">
        <p class="tag mb-2">请扫描下方二维码完成付款</p>
        <img :src="orderResult.qrCodeUrl" alt="下单二维码" class="max-w-[320px] mx-auto w-full rounded-lg border border-white/35 my-3" />
        <div class="flex flex-col items-center gap-2.5 my-4">
          <button class="primary" :disabled="confirming" @click="doConfirm">
            {{ confirming ? '确认中...' : '我已完成扫码付款' }}
          </button>
          <p class="tag">扫码完成后点击上方按钮获取购买内容</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, 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'

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 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 goBack = () => router.push('/')

const submitOrder = async () => {
  if (!product.value) return
  error.value = ''
  submitting.value = true
  orderResult.value = null
  confirmed.value = false
  deliveredCodes.value = []
  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
  }
}

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