<template>
  <AdminPageShell
    eyebrow="平台總覽"
    title="行銷平台儀表板"
    description="管理銷售實驗、視覺編輯器與行銷模組的統一入口。"
  >
    <template #actions>
      <div class="company-badge">{{ currentCorporateCustomerName }}</div>
    </template>

    <template #summary>
      <div class="metrics-grid">
        <AdminMetricCard label="實驗總數" :value="experimentSummary.total" hint="目前已建立的實驗數量" />
        <AdminMetricCard label="進行中" :value="experimentSummary.running" tone="success" hint="目前正在運行中的實驗" />
        <AdminMetricCard label="草稿中" :value="experimentSummary.draft" tone="warning" hint="尚未上線、待整理的草稿" />
        <AdminMetricCard label="已結束 / 暫停" :value="experimentSummary.ended" tone="danger" hint="已結束或暫停中的實驗" />
      </div>
    </template>

    <div class="content-grid">
      <!-- 主線 -->
      <div class="card" v-loading="loadingExperiments">
        <p class="card__eyebrow">目前主線</p>
        <h3 class="card__title">銷售實驗主線</h3>
        <p class="card__desc">建立並管理 A/B 實驗、設定各版本變體、用視覺編輯器調整頁面內容，再發佈版本上線。</p>

        <div class="exp-list">
          <div
            v-for="exp in recentExperiments"
            :key="exp.id"
            class="exp-item"
            @click="goToExperiment(exp.id)"
          >
            <span class="exp-item__name">{{ exp.name }}</span>
            <el-tag :type="statusTypeMap[exp.status] || 'info'" effect="light" size="small">
              {{ statusLabelMap[exp.status] || exp.status }}
            </el-tag>
          </div>
          <div v-if="recentExperiments.length === 0 && !loadingExperiments" class="exp-empty">
            尚未建立實驗
          </div>
        </div>

        <div class="card__actions">
          <el-button type="primary" @click="goToExperiments">前往銷售實驗</el-button>
          <el-button @click="openEditorDemo">預覽示範頁</el-button>
        </div>
      </div>

      <!-- 舊版模組 -->
      <div class="card card--legacy">
        <p class="card__eyebrow">舊版模組</p>
        <h3 class="card__title">既有行銷模組</h3>
        <p class="card__desc">行銷圖卡與倒數計時器目前持續可用，與新實驗主線並行運作。</p>
        <div class="tag-group">
          <el-tag type="warning" effect="light">ose-card</el-tag>
          <el-tag type="warning" effect="light">conutdown-timer</el-tag>
        </div>
        <div class="card__actions">
          <el-button @click="goToOseCard">前往行銷圖卡</el-button>
          <el-button @click="goToCountdownTimer">前往倒數計時器</el-button>
        </div>
      </div>

      <!-- 完成度 -->
      <div class="card">
        <p class="card__eyebrow">主線進度</p>
        <h3 class="card__title">目前完成度</h3>
        <div class="progress-list">
          <div v-for="item in progressItems" :key="item.label" class="progress-item">
            <div class="progress-item__dot" :class="{ 'progress-item__dot--done': item.done }">
              {{ item.done ? '✓' : '○' }}
            </div>
            <span class="progress-item__label">{{ item.label }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="bottom-grid">
      <div class="card">
        <p class="card__section-title">平台資訊架構</p>
        <el-steps :active="4" finish-status="success" align-center>
          <el-step title="Dashboard" description="登入後首頁與主線總覽" />
          <el-step title="銷售實驗" description="新主線管理入口" />
          <el-step title="變體 / 版本" description="管理變體與版本節點" />
          <el-step title="編輯器" description="Visual Editor 全頁編輯" />
        </el-steps>
      </div>

      <div class="card">
        <p class="card__section-title">目前使用者上下文</p>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="登入帳號">{{ currentUserEmail }}</el-descriptions-item>
          <el-descriptions-item label="目前公司">{{ currentCorporateCustomerName }}</el-descriptions-item>
          <el-descriptions-item label="模式">新舊並行</el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
  </AdminPageShell>
</template>

<script setup>
import AdminMetricCard from "@/components/AdminMetricCard.vue"
import AdminPageShell from "@/components/AdminPageShell.vue"
import { computed, onMounted, ref } from "vue"
import { useRouter } from "vue-router"
import { useStore } from "vuex"
import experimentApi from "@/module/experiment/service/experiment-api"
import { mapExperimentListItem, statusLabelMap, statusTypeMap, summarizeExperiments } from "@/module/experiment/model/experiment-view-model"

const router = useRouter()
const store = useStore()

const experiments = ref([])
const loadingExperiments = ref(false)

const experimentSummary = computed(() => summarizeExperiments(experiments.value))
const recentExperiments = computed(() => experiments.value.slice(0, 4))

const currentUserEmail = computed(
  () => store.state.user.user_info?.email || "未載入"
)

const currentCorporateCustomerName = computed(
  () => store.state.user.current_corporate_customer_name || "請選擇公司"
)

const progressItems = [
  { label: "視覺編輯器", done: true },
  { label: "實驗 / 變體建立與編輯", done: true },
  { label: "版本建立、發佈、回退", done: true },
  { label: "Runtime API", done: true },
  { label: "Staging 真實環境驗證", done: true },
  { label: "SDK / GTM 實裝", done: false },
]

const goToExperiments = () => {
  router.push({ name: "experiments" })
}

const goToExperiment = (id) => {
  router.push({ name: "experiment-detail", params: { experimentId: id } })
}

const openEditorDemo = () => {
  if (typeof window === "undefined") return
  window.open(`${window.location.origin}/editor-demo.html`, "_blank")
}

const goToOseCard = () => {
  router.push({ name: "ose-card" })
}

const goToCountdownTimer = () => {
  router.push({ name: "conutdown-timer-list" })
}

onMounted(async () => {
  loadingExperiments.value = true
  try {
    const items = await experimentApi.listExperiments()
    experiments.value = items.map(mapExperimentListItem)
  } catch {
    experiments.value = []
  } finally {
    loadingExperiments.value = false
  }
})
</script>

<style scoped>
.company-badge {
  padding: 6px 14px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background: #f8fafc;
  color: #374151;
  font-size: 13px;
  font-weight: 500;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

/* Card */
.card {
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  padding: 22px 24px;
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.card--legacy {
  background: #f8fafc;
  border-color: #e2e8f0;
  opacity: 0.88;
}

.card__eyebrow {
  margin: 0;
  color: #94a3b8;
  font-size: 10px;
  font-weight: 700;
  letter-spacing: 0.2em;
  text-transform: uppercase;
}

.card__title {
  margin: 0;
  color: #0f172a;
  font-size: 17px;
  font-weight: 700;
}

.card__desc {
  margin: 0;
  color: #64748b;
  font-size: 13.5px;
  line-height: 1.7;
}

.card__actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-top: auto;
  padding-top: 4px;
}

.card__section-title {
  margin: 0 0 16px;
  color: #0f172a;
  font-size: 14px;
  font-weight: 600;
}

/* Grid layouts */
.content-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.bottom-grid {
  display: grid;
  grid-template-columns: 3fr 2fr;
  gap: 16px;
}

/* Experiment list */
.exp-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
}

.exp-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 9px 12px;
  border: 1px solid #f1f5f9;
  border-radius: 10px;
  background: #f8fafc;
  cursor: pointer;
  transition: background 0.12s, border-color 0.12s;
}

.exp-item:hover {
  background: #f1f5f9;
  border-color: #e2e8f0;
}

.exp-item__name {
  font-size: 13.5px;
  font-weight: 500;
  color: #1e293b;
}

.exp-empty {
  font-size: 13px;
  color: #94a3b8;
  padding: 8px 0;
}

/* Tag group */
.tag-group {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* Progress list */
.progress-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.progress-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-item__dot {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  flex-shrink: 0;
  background: #f1f5f9;
  color: #94a3b8;
}

.progress-item__dot--done {
  background: #d1fae5;
  color: #059669;
}

.progress-item__label {
  font-size: 13px;
  color: #475569;
}
</style>
