<template>
  <div class="wizard-page">
    <div class="wz-orb wz-orb-a" aria-hidden="true" />
    <div class="wz-orb wz-orb-b" aria-hidden="true" />

    <div class="wz-card">
      <header class="wz-head">
        <div class="wz-brand">
          <div class="wz-mark">
            <img src="/FRLD-logo-white-no_title.png" alt="迷毂" class="wz-mark-img" />
          </div>
          <div class="wz-titles">
            <div class="wz-title">平台配置向导</div>
            <div class="wz-sub">按需选择导航方式与功能模块，系统据此裁剪界面并按需加载内核能力</div>
          </div>
        </div>
        <div class="wz-user">{{ auth.user?.displayName ?? auth.user?.username ?? '' }}</div>
      </header>

      <div v-if="loading" class="wz-loading">正在加载配置选项…</div>

      <div v-else class="wz-grid">
        <div class="wz-main">
          <section class="wz-section">
            <div class="wz-section-head">
              <el-icon><Compass /></el-icon><h3>导航方式</h3><span class="req">至少选 1 项</span>
            </div>
            <div class="chip-grid">
              <button
                v-for="o in options?.navigationKinds ?? []" :key="o.id" type="button"
                class="chip" :class="{ on: sel.navigationKinds.includes(o.id) }"
                @click="toggle(sel.navigationKinds, o.id)">
                <div class="chip-name">{{ o.name }}</div>
                <div class="chip-desc">{{ o.description }}</div>
              </button>
            </div>
          </section>

          <section class="wz-section">
            <div class="wz-section-head"><el-icon><Box /></el-icon><h3>功能模块</h3></div>
            <div class="chip-grid">
              <button
                v-for="o in options?.modules ?? []" :key="o.id" type="button"
                class="chip" :class="{ on: sel.modules.includes(o.id) }"
                @click="toggle(sel.modules, o.id)">
                <div class="chip-name">{{ o.name }}</div>
                <div class="chip-desc">{{ o.description }}</div>
              </button>
            </div>
          </section>

          <section v-if="scenarioTemplates.length" class="wz-section">
            <div class="wz-section-head"><el-icon><Histogram /></el-icon><h3>业务场景</h3></div>
            <div class="chip-grid">
              <button
                v-for="t in scenarioTemplates" :key="t.id" type="button"
                class="chip" :class="{ on: sel.scenarios.includes(t.id) }"
                @click="toggle(sel.scenarios, t.id)">
                <div class="chip-name">{{ t.name }}</div>
                <div class="chip-desc">{{ t.category }}</div>
              </button>
            </div>
          </section>
        </div>

        <aside class="wz-summary">
          <div class="sum-title">已选概览</div>
          <div class="sum-row"><span>导航方式</span><b>{{ sel.navigationKinds.length }}</b></div>
          <div class="sum-row"><span>功能模块</span><b>{{ sel.modules.length }}</b></div>
          <div class="sum-row"><span>业务场景</span><b>{{ sel.scenarios.length }}</b></div>
          <div class="sum-divider" />
          <div class="sum-label">将激活的内核场景插件</div>
          <div class="sum-scenes">
            <el-tag v-for="s in activeScenes" :key="s" size="small" effect="dark" class="sum-tag">{{ s }}</el-tag>
            <span v-if="!activeScenes.length" class="sum-empty">（请先选择导航方式）</span>
          </div>
        </aside>
      </div>

      <footer class="wz-foot">
        <el-button text class="logout-btn" @click="onLogout">退出登录</el-button>
        <div class="foot-right">
          <span class="foot-hint">保存后写入部署画像并联动 SimpleLite 选择性加载导航场景</span>
          <el-button type="primary" :loading="saving" :disabled="!canSave" @click="save">
            <el-icon v-if="!saving" class="btn-ic"><Check /></el-icon>完成并进入平台
          </el-button>
        </div>
      </footer>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Compass, Box, Histogram, Check } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { getWizardOptions, getWizardProfile, saveWizardProfile } from '@/api/wizard'
import type { WizardOptions, ScenarioTemplateLite } from '@/types/wizard'

const router = useRouter()
const auth = useAuthStore()

const loading = ref(true)
const saving = ref(false)
const options = ref<WizardOptions | null>(null)

const sel = reactive({
  platformType: 'standard',
  navigationKinds: [] as string[],
  modules: [] as string[],
  scenarios: [] as string[]
})

const scenarioTemplates = computed<ScenarioTemplateLite[]>(() => options.value?.scenarios?.templates ?? [])

// 导航方式 → 内核场景 id 预览（与后端 DeploymentProfile.NavKindToSceneId 对齐）。
const NAV_SCENE: Record<string, string> = {
  magnetic: 'scene.magnetic',
  qrcode: 'scene.qrcode',
  laser: 'scene.laser'
}
const activeScenes = computed(() => sel.navigationKinds.map((k) => NAV_SCENE[k] ?? `scene.${k}`))

const canSave = computed(() => sel.navigationKinds.length > 0)

function toggle(list: string[], id: string) {
  const i = list.indexOf(id)
  if (i >= 0) list.splice(i, 1)
  else list.push(id)
}

onMounted(async () => {
  try {
    const [opt, profile] = await Promise.all([getWizardOptions(), getWizardProfile()])
    options.value = opt
    sel.platformType = profile.platformType || 'standard'
    sel.navigationKinds = [...(profile.navigationKinds ?? [])]
    // WMS 为暂定保留的核心仓储模块，首次进入默认勾选，避免用户误漏。
    sel.modules = profile.modules?.length ? [...profile.modules] : ['wms']
    sel.scenarios = [...(profile.scenarios ?? [])]
  } catch (e) {
    ElMessage.error(`加载向导失败：${e instanceof Error ? e.message : String(e)}`)
  } finally {
    loading.value = false
  }
})

async function save() {
  if (!canSave.value) {
    ElMessage.warning('请至少选择一种导航方式')
    return
  }
  saving.value = true
  try {
    await saveWizardProfile({
      platformType: sel.platformType,
      modules: sel.modules,
      navigationKinds: sel.navigationKinds,
      scenarios: sel.scenarios
    })
    auth.markWizardDone()
    ElMessage.success('部署配置已保存')
    router.push(auth.scope === 'RCSMonitor' ? '/monitor/map' : '/admin/dashboard')
  } catch (e) {
    ElMessage.error(`保存失败：${e instanceof Error ? e.message : String(e)}`)
  } finally {
    saving.value = false
  }
}

function onLogout() {
  auth.logout()
  router.push('/login')
}
</script>

<style scoped>
.wizard-page {
  position: relative;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  padding: 24px;
  background:
    radial-gradient(ellipse 75% 55% at 16% 14%, #dcbef7 0%, transparent 55%),
    radial-gradient(ellipse 80% 65% at 86% 90%, #abc9f5 0%, transparent 58%),
    linear-gradient(135deg, #cbb2f0 0%, #b7adec 46%, #a7c6f2 100%);
}
.wz-orb {
  position: absolute; border-radius: 50%; filter: blur(110px); pointer-events: none; opacity: 0.28;
}
.wz-orb-a {
  width: 480px; height: 480px; top: -180px; left: -140px;
  background: radial-gradient(circle, var(--lg-accent) 0%, var(--lg-primary) 55%, transparent 85%);
}
.wz-orb-b {
  width: 560px; height: 560px; bottom: -220px; right: -180px;
  background: radial-gradient(circle, var(--lg-primary-hover) 0%, var(--lg-primary-deep) 55%, transparent 88%);
}

.wz-card {
  position: relative;
  z-index: 2;
  width: 1040px;
  max-width: calc(100vw - 32px);
  max-height: calc(100vh - 48px);
  display: flex;
  flex-direction: column;
  border-radius: 18px;
  overflow: hidden;
  /* 固定深紫玻璃底（与登录页一致，不随主题切换） */
  border: 1px solid rgba(255, 255, 255, 0.08);
  background:
    linear-gradient(135deg, rgba(var(--lg-card-rgb), 0.92) 0%, rgba(20, 12, 38, 0.95) 100%);
  backdrop-filter: blur(26px) saturate(150%);
  -webkit-backdrop-filter: blur(26px) saturate(150%);
  box-shadow:
    0 40px 100px rgba(0, 0, 0, 0.6),
    0 0 80px rgba(var(--lg-primary-rgb), 0.4),
    0 0 0 1px rgba(var(--lg-accent-rgb), 0.28) inset;
}

.wz-head {
  display: flex; align-items: center; justify-content: space-between;
  padding: 22px 28px;
  border-bottom: 1px solid rgba(var(--lg-accent-rgb), 0.18);
  background: linear-gradient(180deg, rgba(var(--lg-primary-rgb), 0.18) 0%, transparent 100%);
}
.wz-brand { display: flex; align-items: center; gap: 14px; }
.wz-mark {
  height: 46px; min-width: 46px;
  padding: 0 12px;
  border-radius: 12px;
  background: linear-gradient(135deg, rgba(var(--lg-primary-rgb), 0.55) 0%, rgba(var(--lg-accent-rgb), 0.30) 100%);
  border: 1px solid rgba(255, 255, 255, 0.20);
  display: inline-flex; align-items: center; justify-content: center;
  box-shadow:
    0 10px 26px rgba(var(--lg-primary-rgb), 0.5),
    0 0 24px rgba(var(--lg-accent-rgb), 0.28),
    0 0 0 1px rgba(255, 255, 255, 0.16) inset;
}
.wz-mark-img {
  display: block;
  height: 28px;
  width: auto;
  filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.35));
}
.wz-titles { display: flex; flex-direction: column; gap: 4px; }
.wz-title {
  font-size: 20px; font-weight: 700; letter-spacing: 2px; color: #fff;
}
.wz-sub { font-size: 12.5px; color: rgba(232, 215, 245, 0.65); }
.wz-user {
  font-size: 13px; color: rgba(255, 255, 255, 0.8);
  padding: 5px 12px; border-radius: 999px;
  background: rgba(255, 255, 255, 0.06); border: 1px solid rgba(255, 255, 255, 0.14);
}

.wz-loading {
  padding: 80px; text-align: center; color: rgba(255, 255, 255, 0.7); font-size: 14px;
}

.wz-grid {
  flex: 1; min-height: 0;
  display: grid; grid-template-columns: 1fr 280px;
  gap: 0;
}
.wz-main {
  overflow-y: auto;
  padding: 22px 26px;
  display: flex; flex-direction: column; gap: 22px;
}
.wz-section-head {
  display: flex; align-items: center; gap: 8px; margin-bottom: 12px;
  color: #fff;
}
.wz-section-head .el-icon { font-size: 18px; color: var(--lg-accent); }
.wz-section-head h3 { margin: 0; font-size: 15px; font-weight: 600; }
.wz-section-head .req {
  font-size: 11px; color: var(--lg-accent);
  padding: 1px 8px; border-radius: 8px;
  border: 1px solid rgba(var(--lg-accent-rgb), 0.4);
}

.chip-grid {
  display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px;
}
.chip {
  appearance: none; cursor: pointer; text-align: left;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.16);
  border-radius: 12px;
  padding: 12px 14px;
  color: rgba(255, 255, 255, 0.78);
  transition: all .18s ease;
}
.chip:hover {
  background: rgba(255, 255, 255, 0.1); color: #fff; transform: translateY(-1px);
}
.chip.on {
  background: linear-gradient(135deg, rgba(var(--lg-primary-rgb), 0.6) 0%, rgba(var(--lg-primary-hover-rgb), 0.4) 100%);
  border-color: rgba(var(--lg-accent-rgb), 0.85);
  color: #fff;
  box-shadow: 0 0 20px rgba(var(--lg-primary-hover-rgb), 0.5), 0 0 0 1px rgba(var(--lg-accent-rgb), 0.5) inset;
}
.chip-name { font-size: 14px; font-weight: 600; }
.chip-desc { font-size: 11.5px; opacity: 0.75; margin-top: 4px; line-height: 1.5; }

.wz-summary {
  border-left: 1px solid rgba(var(--lg-accent-rgb), 0.16);
  background: rgba(0, 0, 0, 0.18);
  padding: 22px 20px;
  overflow-y: auto;
}
.sum-title { font-size: 13px; font-weight: 600; color: #fff; margin-bottom: 14px; letter-spacing: 1px; }
.sum-row {
  display: flex; align-items: center; justify-content: space-between;
  font-size: 13px; color: rgba(255, 255, 255, 0.75); padding: 7px 0;
}
.sum-row b { color: var(--lg-accent); font-size: 15px; font-variant-numeric: tabular-nums; }
.sum-divider { height: 1px; background: rgba(255, 255, 255, 0.12); margin: 14px 0; }
.sum-label { font-size: 12px; color: rgba(232, 215, 245, 0.65); margin-bottom: 10px; }
.sum-scenes { display: flex; flex-wrap: wrap; gap: 6px; }
.sum-tag {
  font-family: var(--mg-font-mono);
  /* 锁定固定紫，不随 Element Plus 主题色变化 */
  background: rgba(var(--lg-primary-rgb), 0.30) !important;
  border-color: rgba(var(--lg-accent-rgb), 0.5) !important;
  color: #fff !important;
}
.sum-empty { font-size: 12px; color: rgba(255, 255, 255, 0.4); }

.wz-foot {
  display: flex; align-items: center; justify-content: space-between;
  padding: 16px 26px;
  border-top: 1px solid rgba(var(--lg-accent-rgb), 0.18);
  background: rgba(var(--lg-aside-rgb), 0.4);
}
.logout-btn { color: rgba(255, 255, 255, 0.6) !important; }
.foot-right { display: flex; align-items: center; gap: 16px; }
.foot-hint { font-size: 12px; color: rgba(232, 215, 245, 0.55); }
.btn-ic { margin-right: 4px; }

/* 「完成并进入平台」主按钮锁定固定紫色（与登录按钮同款，不随主题切换） */
.wz-foot :deep(.el-button--primary) {
  --el-button-bg-color: var(--lg-primary);
  --el-button-border-color: var(--lg-primary);
  --el-button-hover-bg-color: var(--lg-primary-hover);
  --el-button-hover-border-color: var(--lg-primary-hover);
  --el-button-active-bg-color: var(--lg-primary-deep);
  --el-button-active-border-color: var(--lg-primary-deep);
  color: #fff;
  box-shadow: 0 8px 20px rgba(var(--lg-primary-rgb), 0.45);
}

@media (max-width: 880px) {
  .wz-grid { grid-template-columns: 1fr; }
  .wz-summary { border-left: none; border-top: 1px solid rgba(var(--lg-accent-rgb), 0.16); }
}
</style>
