<template>
  <section class="page-card" v-if="!loggedIn">
    <div class="auth-prompt">
      <h2>请先登录</h2>
      <p class="tag">登录萌芽账号后即可查看你的历史订单记录。</p>
      <a class="login-btn" :href="loginUrl">使用萌芽账号登录</a>
    </div>
  </section>

  <section class="page-card" v-else>
    <div class="orders-header">
      <div class="header-info">
        <h2>我的订单</h2>
        <p class="tag">
          {{ authState.username || authState.account }}
          <span v-if="orders.length" class="order-count">共 {{ orders.length }} 笔</span>
        </p>
      </div>
      <div class="orders-actions">
        <button class="ghost small-act" @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 small-act" @click="goHome">← 返回商店</button>
      </div>
    </div>

    <div v-if="loading" class="status">加载中…</div>

    <div v-else-if="orders.length === 0" class="empty-state">
      <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="opacity:0.3"><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="orders-list">
      <div v-for="order in orders" :key="order.id" class="order-card">
        <!-- Card header -->
        <div class="order-card-header">
          <div class="order-product-name">{{ order.productName }}</div>
          <div class="order-status-badge" :class="order.deliveryMode === 'manual' && !order.deliveredCodes?.length ? 'badge-pending' : 'badge-done'">
            {{ order.deliveryMode === 'manual' && !order.deliveredCodes?.length ? '等待发货' : '已完成' }}
          </div>
        </div>

        <!-- Meta row -->
        <div class="order-meta-row">
          <span class="meta-item">
            <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="meta-item">
            <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="order-id-tag">{{ order.id.slice(0, 8) }}…</span>
        </div>

        <!-- Delivered codes -->
        <div class="order-codes" v-if="order.deliveredCodes?.length">
          <div class="codes-label">
            <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="codes-list">
            <div v-for="(code, i) in order.deliveredCodes" :key="i" class="code-item">
              <span class="code-index">{{ i + 1 }}</span>
              <span class="code-text">{{ code }}</span>
            </div>
          </div>
        </div>

        <!-- Manual delivery pending -->
        <div class="pending-notice" v-else-if="order.deliveryMode === 'manual'">
          <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>

<style scoped>
/* ── Auth prompt ── */
.auth-prompt {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 48px 0;
  text-align: center;
}

/* ── Header ── */
.orders-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 14px;
  margin-bottom: 22px;
  flex-wrap: wrap;
}

.header-info h2 {
  margin: 0 0 4px;
  font-size: 22px;
}

.order-count {
  margin-left: 6px;
  font-size: 13px;
  color: var(--muted);
  background: rgba(180, 154, 203, 0.12);
  padding: 2px 8px;
  border-radius: 999px;
}

.orders-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.small-act {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-size: 13px;
  padding: 6px 12px;
}

/* ── Empty & loading ── */
.status {
  padding: 24px 0;
  color: var(--muted);
  font-size: 14px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  padding: 48px 0;
  color: var(--muted);
  font-size: 14px;
}

/* ── Order list ── */
.orders-list {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

/* ── Order card ── */
.order-card {
  padding: 0;
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.72);
  border: 1px solid var(--line);
  overflow: hidden;
  transition: box-shadow 0.2s;
}

.order-card:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
}

.order-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 14px 16px 10px;
}

.order-product-name {
  font-size: 16px;
  font-weight: 700;
  color: var(--text);
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.order-status-badge {
  padding: 3px 10px;
  border-radius: 999px;
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}

.badge-done {
  background: rgba(100, 185, 140, 0.15);
  color: #3a9a68;
}

.badge-pending {
  background: rgba(145, 168, 208, 0.15);
  color: #5a7db0;
}

/* Meta row */
.order-meta-row {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 0 16px 12px;
  flex-wrap: wrap;
  border-bottom: 1px solid var(--line);
}

.meta-item {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: var(--muted);
}

.order-id-tag {
  font-size: 11px;
  color: var(--muted);
  font-family: monospace;
  background: rgba(0,0,0,0.04);
  padding: 2px 7px;
  border-radius: 4px;
}

/* Codes */
.order-codes {
  padding: 12px 16px;
}

.codes-label {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 12px;
  font-weight: 600;
  color: var(--muted);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 8px;
}

.codes-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.code-item {
  display: flex;
  align-items: baseline;
  gap: 10px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid var(--line);
  border-radius: 6px;
}

.code-index {
  font-size: 11px;
  color: var(--muted);
  font-weight: 700;
  min-width: 16px;
  flex-shrink: 0;
}

.code-text {
  font-size: 14px;
  color: var(--text);
  word-break: break-all;
  font-family: monospace;
  line-height: 1.5;
}

/* Pending notice */
.pending-notice {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 12px 16px;
  padding: 10px 14px;
  background: rgba(145, 168, 208, 0.1);
  border-radius: 6px;
  border-left: 3px solid var(--accent-2);
  font-size: 13px;
  color: #5a7db0;
}

@media (max-width: 900px) {
  .orders-header {
    gap: 10px;
  }

  .header-info h2 {
    font-size: 18px;
  }

  .order-product-name {
    font-size: 15px;
  }

  .order-meta-row {
    gap: 10px;
  }
}
</style>
