<template>
  <div class="page home">
    <!-- 顶部蓝色品牌区 -->
    <header class="home-hd">
      <div class="home-hd__top">
        <div class="loc" @click="toast('切换校区')">
          <span class="loc__icon">📍</span>
          <span class="loc__text">阳光大学 · 东校区</span>
          <span class="loc__arrow">▾</span>
        </div>
        <div class="bell" @click="go('/messages')">
          <span>🔔</span>
          <i class="dot"></i>
        </div>
      </div>

      <div class="home-hd__brand">
        <h1 class="brand">校跑侠</h1>
        <p class="slogan">校园跑腿 · 代拿代买 · 最快 15 分钟送达</p>
      </div>

      <div class="home-hd__search" @click="toast('搜索服务')">
        <span class="s-icon">🔍</span>
        <span class="s-ph">搜索：代拿快递、代取外卖、帮我买…</span>
        <span class="s-btn">搜索</span>
      </div>
    </header>

    <div class="page__inner home-bd">
      <!-- 服务九宫格 -->
      <section class="card grid-card">
        <div
          v-for="s in services"
          :key="s.key"
          class="grid-item"
          @click="onService(s)"
        >
          <span class="grid-item__icon" :style="iconBoxStyle(s)">
            <AppIcon v-if="s.svg" :name="s.key" :size="30" />
            <span v-else>{{ s.emoji }}</span>
          </span>
          <span class="grid-item__name">{{ s.name }}</span>
        </div>
      </section>

      <!-- 公告 -->
      <van-notice-bar
        class="notice"
        left-icon="volume-o"
        :scrollable="false"
        :text="notices[0]"
        color="#0958d9"
        background="#e8f1ff"
      />

      <!-- 极速下单 CTA -->
      <section class="card cta" @click="go('/order/create')">
        <div class="cta__left">
          <div class="cta__title">极速下单</div>
          <div class="cta__sub">填地址 · 定悬赏 · 骑手秒接</div>
        </div>
        <div class="cta__badge">立即发单 →</div>
      </section>

      <!-- 进行中的订单 -->
      <section class="section" v-if="runningOrder">
        <div class="section__head">
          <div class="section__title">进行中的订单</div>
          <div class="section__more" @click="go('/orders')">全部订单 ›</div>
        </div>
        <div class="card order-mini" @click="go('/orders')">
          <div class="order-mini__hd">
            <van-tag :color="statusColor(runningOrder.status)" round type="primary">
              {{ statusText(runningOrder.status) }}
            </van-tag>
            <span class="order-mini__type">{{ runningOrder.type }}</span>
            <span class="order-mini__time muted">{{ runningOrder.time }}</span>
          </div>
          <div class="route">
            <div class="route__row"><i class="dotf"></i>{{ runningOrder.from }}</div>
            <div class="route__row"><i class="dott"></i>{{ runningOrder.to }}</div>
          </div>
        </div>
      </section>

      <!-- 平台数据 -->
      <section class="section">
        <div class="stat card">
          <div class="stat__item"><b>2.6万+</b><span class="muted">在读用户</span></div>
          <div class="stat__sep"></div>
          <div class="stat__item"><b>15分钟</b><span class="muted">平均送达</span></div>
          <div class="stat__sep"></div>
          <div class="stat__item"><b>99.2%</b><span class="muted">准时率</span></div>
        </div>
      </section>

      <!-- 为什么选择我们 -->
      <section class="section">
        <div class="section__head"><div class="section__title">为什么选择校跑侠</div></div>
        <div class="feat">
          <div class="feat__item card" v-for="f in feats" :key="f.t">
            <div class="feat__t">{{ f.t }}</div>
            <div class="feat__d muted">{{ f.d }}</div>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { services as MOCK_SERVICES, orderStatusMap } from '../data/mock.js'
import { api } from '../api/index.js'
import { ensureLogin } from '../store/session.js'
import { formatOrderTime } from '../utils/time.js'
import { icons } from '../components/icons/index.js'

const router = useRouter()
const go = (p) => router.push(p)
const toast = (m) => showToast(m)

const notices = ref(['新学期上线：跨校区配送，最快 15 分钟送达'])
const runningOrder = ref(null)
// 从后端读取的服务列表（带 svg 或 emoji）
const services = ref([])

const statusText = (s) => orderStatusMap[s]?.text || ''
const statusColor = (s) => orderStatusMap[s]?.color || '#1677ff'

async function loadHome() {
  try {
    notices.value = await api.getNotices()
  } catch (e) {
    /* 保留默认公告 */
  }
  
  try {
    // 🎯 从后端获取服务列表
    const res = await api.getServices()
    const svcList = Array.isArray(res) ? res : []
    
    // 为每个服务生成对应的 icon（svg 或 emoji）
    const enriched = svcList.map(svc => {
      // 检查是否有自定义 SVG 图标
      if (iconsByName[svc.key]) {
        return { ...svc, svg: iconsByName[svc.key], emoji: null }
      } else if (iconsByEmoji[svc.key]) {
        return { ...svc, svg: null, emoji: iconsByEmoji[svc.key] }
      } else {
        // 使用默认 emoji
        return { ...svc, svg: null, emoji: '📦' }
      }
    })
    services.value = enriched
  } catch (e) {
    console.error('[Home] 加载服务失败:', e)
    // 降级到 mock
    services.value = MOCK_SERVICES.slice(0, -2) // 去掉"全部服务"
  }
  
  try {
    const profile = await ensureLogin()
    const res = await api.getMyOrders(profile.id, 'running')
    const o = res.list[0]
    runningOrder.value = o ? { ...o, time: formatOrderTime(o.createdAt) } : null
  } catch (e) {
    /* 忽略 */
  }
}
onMounted(loadHome)
onActivated(loadHome)

const feats = [
  { t: '极速接单', d: '骑手实时抢单' },
  { t: '安全保障', d: '全程可追踪' },
  { t: '价格透明', d: '明码标价无套路' },
  { t: '校园专属', d: '懂校园更贴心' }
]

function onService(s) {
  if (s.key === 'more' || s.key === 'queue') {
    showToast('功能开发中')
    return
  }
  router.push('/order/create')
}

// 🔧 内置映射表（作为 fallback，如果后端返回的 serviceKey 不存在则使用）
const iconsByName = {
  'express': () => icons.express,
  'food': () => icons.food,
  'help': () => icons.help,
  'coupon': () => icons.coupon,
  'member': () => icons.member,
  'queue': () => icons.queue,
  'print': () => icons.print,
  'send': () => icons.send,
  'favorite': () => icons.favorite,
  'points': () => icons.points,
  'wallet': () => icons.wallet,
  'address': () => icons.address,
  'invite': () => icons.invite,
  'order': () => icons.order,
  'setting': () => icons.setting,
  'feedback': () => icons.feedback,
  'service': () => icons.service
}

const iconsByEmoji = {
  'buy': '🛒',
  'sale': '💸',
  'money': '💰',
  'delivery': '🚀',
  'study': '📚'
}

// 把品牌色转成浅色底
function fade(hex) {
  return hex + '1a'
}

// 图标底框样式：SVG 彩色图标用中性底，emoji 用品牌色浅底
function iconBoxStyle(s) {
  if (s.svg) return { background: '#f2f4f8' }
  // s.emoji 可能是字符串（如 '🛒'）或 false/null
  const emoji = typeof s.emoji === 'string' ? s.emoji : null
  if (emoji) {
    // 尝试从映射表取颜色，否则用默认灰色
    const colorMap = {
      '🛒': '#ff976a',
      '💸': '#faad14',
      '💰': '#f5c300',
      '🚀': '#ff8800',
      '📚': '#722ed1'
    }
    const hex = colorMap[emoji] || '#ccc'
    return { background: fade(hex), color: hex }
  }
  return { background: '#f2f4f8', color: '#999' }
}
</script>

<style scoped>
.home {
  background: var(--brand-bg);
}
.home-hd {
  background: linear-gradient(160deg, #2f7bff 0%, #1677ff 45%, #0958d9 100%);
  padding: calc(env(safe-area-inset-top) + 14px) 16px 46px;
  color: #fff;
  border-radius: 0 0 22px 22px;
}
.home-hd__top {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.loc {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  font-weight: 600;
}
.loc__arrow {
  opacity: 0.8;
}
.bell {
  position: relative;
  font-size: 18px;
}
.bell .dot {
  position: absolute;
  top: -2px;
  right: -2px;
  width: 7px;
  height: 7px;
  background: #ff4d4f;
  border-radius: 50%;
  border: 1px solid #fff;
}
.home-hd__brand {
  margin: 16px 2px 14px;
}
.brand {
  margin: 0;
  font-size: 26px;
  font-weight: 800;
  letter-spacing: 1px;
}
.slogan {
  margin: 6px 0 0;
  font-size: 13px;
  opacity: 0.92;
}
.home-hd__search {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 22px;
  padding: 8px 8px 8px 14px;
  box-shadow: 0 6px 16px rgba(9, 88, 217, 0.25);
}
.s-icon {
  font-size: 15px;
}
.s-ph {
  flex: 1;
  margin-left: 8px;
  font-size: 13px;
  color: var(--brand-text-tertiary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.s-btn {
  background: linear-gradient(135deg, var(--brand-primary), var(--brand-primary-dark));
  color: #fff;
  font-size: 13px;
  font-weight: 600;
  padding: 6px 16px;
  border-radius: 18px;
}
.home-bd {
  margin-top: -32px;
  position: relative;
}

/* 九宫格 */
.grid-card {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 6px 0;
  padding: 16px 6px;
}
.grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 7px;
  padding: 6px 0;
}
.grid-item__icon {
  width: 46px;
  height: 46px;
  border-radius: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}
.grid-item__name {
  font-size: 12px;
  color: var(--brand-text-secondary);
}

.notice {
  margin-top: 12px;
  border-radius: 10px;
  overflow: hidden;
}

/* CTA */
.cta {
  margin-top: 12px;
  padding: 16px 18px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(120deg, #eef4ff, #ffffff);
  border: 1px solid #e3edff;
}
.cta__title {
  font-size: 17px;
  font-weight: 800;
  color: var(--brand-text);
}
.cta__sub {
  margin-top: 4px;
  font-size: 12px;
  color: var(--brand-text-tertiary);
}
.cta__badge {
  background: linear-gradient(135deg, var(--brand-primary), var(--brand-primary-dark));
  color: #fff;
  font-size: 13px;
  font-weight: 700;
  padding: 9px 16px;
  border-radius: 20px;
  box-shadow: 0 4px 12px rgba(22, 119, 255, 0.35);
}

/* 进行中订单 mini */
.order-mini {
  padding: 14px;
}
.order-mini__hd {
  display: flex;
  align-items: center;
  gap: 8px;
}
.order-mini__type {
  font-weight: 700;
  font-size: 14px;
}
.order-mini__time {
  margin-left: auto;
  font-size: 12px;
}
.route {
  margin-top: 10px;
}
.route__row {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: var(--brand-text-secondary);
  padding: 3px 0;
}
.dotf,
.dott {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex: 0 0 8px;
}
.dotf {
  background: #00b42a;
}
.dott {
  background: var(--brand-primary);
}

/* 平台数据 */
.stat {
  display: flex;
  align-items: center;
  padding: 16px 0;
}
.stat__item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}
.stat__item b {
  font-size: 18px;
  color: var(--brand-primary);
}
.stat__item span {
  font-size: 12px;
}
.stat__sep {
  width: 1px;
  height: 26px;
  background: var(--brand-border);
}

/* 特色 */
.feat {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}
.feat__item {
  padding: 14px;
}
.feat__t {
  font-weight: 700;
  font-size: 14px;
}
.feat__d {
  margin-top: 2px;
  font-size: 12px;
}
</style>
