<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>
        <h2>我的订单</h2>
        <p class="tag">
          已登录：{{ authState.username || authState.account }}
          <span v-if="orders.length">· 共 {{ orders.length }} 笔订单</span>
        </p>
      </div>
      <div class="orders-actions">
        <button class="ghost" @click="refresh">刷新</button>
        <button class="ghost" @click="goHome">返回商店</button>
      </div>
    </div>

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

    <div v-else-if="orders.length === 0" class="status">暂无订单记录</div>

    <div v-else class="orders-list">
      <div v-for="order in orders" :key="order.id" class="order-card">
        <div class="order-head">
          <div>
            <h4>{{ order.productName }}</h4>
            <span class="tag">订单号：{{ order.id }}</span>
          </div>
          <div class="order-meta">
            <span class="badge">数量 {{ order.quantity }}</span>
            <span class="tag">{{ formatTime(order.createdAt) }}</span>
          </div>
        </div>
        <div class="order-codes" v-if="order.deliveredCodes?.length">
          <p class="tag">购买内容</p>
          <textarea
            class="codes-box"
            readonly
            :value="order.deliveredCodes.join('\n')"
            :rows="Math.min(order.deliveredCodes.length, 5)"
          ></textarea>
        </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 {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 48px 0;
  text-align: center;
}

.orders-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 20px;
}

.orders-actions {
  display: flex;
  gap: 10px;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.order-card {
  padding: 18px;
  border-radius: var(--radius);
  background: rgba(255, 255, 255, 0.7);
  border: 1px solid var(--line);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

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

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

.codes-box {
  width: 100%;
  padding: 10px 12px;
  border-radius: 10px;
  border: 1px solid var(--line);
  background: rgba(255, 255, 255, 0.9);
  color: var(--text);
  font-size: 13px;
  line-height: 1.7;
  resize: none;
}

.status {
  padding: 24px 0;
  color: var(--muted);
}

@media (max-width: 900px) {
  .orders-header {
    flex-direction: column;
    align-items: stretch;
  }

  .order-head {
    flex-direction: column;
  }

  .order-meta {
    align-items: flex-start;
    flex-direction: row;
    gap: 10px;
  }
}
</style>
