<template>
  <section v-if="!loggedIn">
    <div class="flex flex-col items-center gap-4 py-12 text-center">
      <h2>请先登录</h2>
      <p class="tag">登录萌芽账号后即可查看你的历史订单记录。</p>
      <a
        class="inline-flex items-center px-[18px] py-[10px] rounded-lg bg-gradient-to-br from-accent to-accent2 text-white no-underline text-[17px] shadow-[0_10px_30px_rgba(184,109,92,0.32)] hover:-translate-y-px transition-transform"
        :href="loginUrl"
      >使用萌芽账号登录</a>
    </div>
  </section>

  <section v-else>
    <!-- Header -->
    <div class="flex items-center justify-between gap-3.5 mb-[22px] flex-wrap max-md:gap-2.5">
      <div>
        <h2 class="text-[22px] mb-1 max-md:text-lg">我的订单</h2>
        <p class="tag">
          {{ authState.username || authState.account }}
          <span
            v-if="orders.length"
            class="ml-1.5 text-[13px] text-muted bg-[rgba(217,168,120,0.14)] px-2 py-0.5 rounded-full"
          >共 {{ orders.length }} 笔</span>
        </p>
      </div>
      <div class="flex gap-2 flex-shrink-0">
        <button
          class="ghost inline-flex items-center gap-1.5 text-[13px] px-3 py-1.5"
          @click="refresh"
        >
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>
          刷新
        </button>
        <button class="ghost inline-flex items-center gap-1.5 text-[13px] px-3 py-1.5" @click="goHome">← 返回商店</button>
      </div>
    </div>

    <div v-if="loading" class="py-6 text-muted text-sm">加载中…</div>

    <div v-else-if="orders.length === 0" class="flex flex-col items-center gap-2.5 py-12 text-muted text-sm">
      <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="opacity-30"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
      <p>暂无订单记录</p>
    </div>

    <div v-else class="flex flex-col gap-3.5">
      <div
        v-for="order in orders"
        :key="order.id"
        class="rounded-[10px] bg-white/72 border border-white/35 overflow-hidden transition-shadow hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)]"
      >
        <!-- Card header -->
        <div class="flex items-center justify-between gap-3 px-4 pt-3.5 pb-2.5">
          <div class="text-base font-bold text-apptext flex-1 min-w-0 overflow-hidden text-ellipsis whitespace-nowrap max-md:text-[15px]">
            {{ order.productName }}
          </div>
          <div
            class="px-2.5 py-0.5 rounded-full text-xs font-semibold flex-shrink-0"
            :class="order.deliveryMode === 'manual' && !order.deliveredCodes?.length
              ? 'bg-[rgba(217,168,120,0.16)] text-[#8b5038]'
              : 'bg-[rgba(100,185,140,0.15)] text-[#3a9a68]'"
          >
            {{ order.deliveryMode === 'manual' && !order.deliveredCodes?.length ? '等待发货' : '已完成' }}
          </div>
        </div>

        <!-- Meta row -->
        <div class="flex items-center gap-3.5 px-4 pb-3 flex-wrap border-b border-white/35 max-md:gap-2.5">
          <span class="inline-flex items-center gap-1 text-[13px] text-muted">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
            {{ formatTime(order.createdAt) }}
          </span>
          <span class="inline-flex items-center gap-1 text-[13px] text-muted">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12V22H4V12"/><path d="M22 7H2v5h20V7z"/><path d="M12 22V7"/><path d="M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z"/><path d="M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z"/></svg>
            × {{ order.quantity }} 件
          </span>
          <span class="text-[11px] text-muted font-mono bg-black/[0.04] px-1.5 py-0.5 rounded">{{ order.id.slice(0, 8) }}…</span>
        </div>

        <!-- Delivered codes -->
        <div v-if="order.deliveredCodes?.length" class="px-4 py-3">
          <div class="flex items-center gap-1.5 text-xs font-semibold text-muted uppercase tracking-[0.5px] mb-2">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
            发货内容
          </div>
          <div class="flex flex-col gap-1.5">
            <div
              v-for="(code, i) in order.deliveredCodes"
              :key="i"
              class="flex items-baseline gap-2.5 px-3 py-2 bg-white/90 border border-white/35 rounded-md"
            >
              <span class="text-[11px] text-muted font-bold min-w-[16px] flex-shrink-0">{{ i + 1 }}</span>
              <span class="text-sm text-apptext break-all font-mono leading-relaxed">{{ code }}</span>
            </div>
          </div>
        </div>

        <!-- Manual delivery pending -->
        <div
          v-else-if="order.deliveryMode === 'manual'"
          class="flex items-center gap-2 mx-4 my-3 px-3.5 py-2.5 bg-[rgba(217,168,120,0.1)] rounded-md border-l-[3px] border-accent2 text-[13px] text-[#8b5038]"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
          订单已提交，等待人工发货，请耐心等候
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { fetchMyOrders } from '../shared/api'
import { authState, isLoggedIn, getLoginUrl } from '../shared/auth'

const router = useRouter()
const orders = ref([])
const loading = ref(true)

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

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

const formatTime = (isoStr) => {
  if (!isoStr) return ''
  try {
    const d = new Date(isoStr)
    return d.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
  } catch { return isoStr }
}

const refresh = async () => {
  if (!isLoggedIn()) return
  loading.value = true
  try {
    orders.value = await fetchMyOrders(authState.token)
  } catch {
    orders.value = []
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  if (isLoggedIn()) { refresh() } else { loading.value = false }
})
</script>
