<template>
  <div class="dashboard">
    <!-- ═══ Header ═══ -->
    <header class="dash-header">
      <div class="dash-header-left">
        <h1 class="dash-title">{{ $t('dashboard.title') }}</h1>
        <span class="dash-subtitle">{{ $t('dashboard.subtitle') }}</span>
      </div>
      <div class="dash-header-right">
        <button class="df-btn df-btn--ghost" @click="refresh">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 11-2.12-9.36L23 10"/></svg>
        </button>
        <button class="df-btn df-btn--primary" @click="quickCapture">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          {{ $t('dashboard.captureIdea') }}
        </button>
      </div>
    </header>

    <!-- ═══ Stat Cards ═══ -->
    <div class="stat-row">
      <div
        v-for="(stat, i) in stats" :key="stat.key"
        class="stat-card"
        :style="{ animationDelay: `${i * 60}ms` }"
      >
        <div class="stat-card-bg" :class="'stat-bg--' + stat.key"></div>
        <div class="stat-card-inner">
          <div class="stat-top">
            <div class="stat-icon-wrap" :style="{ background: stat.iconBg }">
              <span class="stat-icon">{{ stat.icon }}</span>
            </div>
            <span class="stat-trend" :class="stat.trend > 0 ? 'up' : stat.trend < 0 ? 'down' : 'flat'">
              <template v-if="stat.trend > 0">↑</template><template v-else-if="stat.trend < 0">↓</template>
              <template v-else>—</template>
              {{ stat.trend > 0 ? '+' : '' }}{{ stat.trend }}
            </span>
          </div>
          <div class="stat-value">{{ stat.value }}</div>
          <div class="stat-label">{{ stat.label }}</div>
        </div>
      </div>
    </div>

    <!-- ═══ Main Grid ═══ -->
    <div class="dash-grid">
      <!-- Left: Active Projects -->
      <section class="df-panel" style="animation-delay: 240ms">
        <div class="df-panel-head">
          <h2 class="df-panel-title">{{ $t('dashboard.activeProjects') }}</h2>
          <router-link to="/projects" class="df-link">{{ $t('dashboard.viewAll') }}</router-link>
        </div>
        <div class="project-list">
          <div v-for="(p, i) in displayProjects" :key="p.id" class="project-row" :style="{ animationDelay: `${300 + i * 50}ms` }">
            <div class="project-row-top">
              <div class="project-identity">
                <span class="project-dot" :class="'dot-' + p.stage"></span>
                <span class="project-name">{{ p.name }}</span>
              </div>
              <span class="project-stage-chip" :class="'chip-' + p.stage">{{ $t('dashboard.stage.' + p.stageLabelKey) }}</span>
            </div>
            <div class="project-bar-wrap">
              <div class="project-bar">
                <div class="project-bar-fill" :class="'fill-' + p.stage" :style="{ width: p.progress + '%' }"></div>
              </div>
              <span class="project-pct">{{ p.progress }}%</span>
            </div>
            <div class="project-meta-row">
              <span class="project-meta-item">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 3v12"/><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M18 9a9 9 0 01-9 9"/></svg>
                {{ $t('dashboard.taskUnit', { n: p.activeTasks }) }}
              </span>
              <span class="project-meta-time">{{ p.lastActivity }}</span>
            </div>
          </div>
          <div v-if="displayProjects.length === 0" class="empty-hint">暂无项目，去 <router-link to="/projects" class="df-link">创建一个</router-link></div>
        </div>
      </section>

      <!-- Right Column -->
      <div class="dash-right">
        <!-- Ideas -->
        <section class="df-panel" style="animation-delay: 280ms">
          <div class="df-panel-head">
            <h2 class="df-panel-title">{{ $t('dashboard.ideaPool') }}</h2>
            <router-link to="/ideas" class="df-link">{{ $t('dashboard.viewAll') }}</router-link>
          </div>
          <div class="idea-rows">
            <div v-for="idea in displayIdeas" :key="idea.id" class="idea-row">
              <div class="idea-score-ring" :class="'ring-' + idea.tier">
                <span class="idea-score-num">{{ idea.score }}</span>
              </div>
              <div class="idea-body">
                <span class="idea-name">{{ idea.title }}</span>
                <span class="idea-status">{{ ideaStatusLabel(idea.statusLabel) }}</span>
              </div>
            </div>
            <div v-if="displayIdeas.length === 0" class="empty-hint">{{ $t('dashboard.empty.noIdeas') }}</div>
          </div>
        </section>

        <!-- Decisions -->
        <section class="df-panel" style="animation-delay: 320ms">
          <div class="df-panel-head">
            <h2 class="df-panel-title">{{ $t('dashboard.recentDecisions') }}</h2>
          </div>
          <div class="empty-hint" style="padding:12px 0;text-align:center;color:var(--df-text-dim);font-size:12px">
            {{ $t('dashboard.empty.noData') }}
          </div>
        </section>

        <!-- Annotations -->
        <section class="df-panel" style="animation-delay: 360ms">
          <div class="df-panel-head">
            <h2 class="df-panel-title">{{ $t('dashboard.openAnnotations') }}</h2>
          </div>
          <div class="empty-hint" style="padding:12px 0;text-align:center;color:var(--df-text-dim);font-size:12px">
            {{ $t('dashboard.empty.noData') }}
          </div>
        </section>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useProjectStore } from '../stores/project'
import { parseTs } from '../utils/time'

const router = useRouter()
const store = useProjectStore()
const { t } = useI18n()

const stats = computed(() => [
  { key: 'ideas', icon: '\u{1F4A1}', label: t('dashboard.stats.ideas'), value: store.stats.ideas, trend: 0,
    iconBg: 'rgba(123,111,240,0.12)' },
  { key: 'projects', icon: '\u{1F4C2}', label: t('dashboard.stats.projects'), value: store.stats.projects, trend: 0,
    iconBg: 'rgba(94,175,240,0.10)' },
  { key: 'tasks', icon: '⚡', label: t('dashboard.stats.activeTasks'), value: store.stats.activeTasks, trend: 0,
    iconBg: 'rgba(61,219,160,0.10)' },
  { key: 'drafts', icon: '\u{1F4DD}', label: t('dashboard.stats.drafts'), value: store.stats.drafts, trend: 0,
    iconBg: 'rgba(240,199,94,0.10)' },
])

function getProjectStage(status: string): { stage: string; stageLabelKey: string; progress: number } {
  switch (status) {
    case 'planning': return { stage: 'coding', stageLabelKey: 'planning', progress: 20 }
    case 'in_progress': return { stage: 'coding', stageLabelKey: 'coding', progress: 55 }
    case 'paused': return { stage: 'testing', stageLabelKey: 'paused', progress: 40 }
    case 'completed': return { stage: 'release', stageLabelKey: 'done', progress: 100 }
    case 'cancelled': return { stage: 'testing', stageLabelKey: 'cancelled', progress: 0 }
    default: return { stage: 'coding', stageLabelKey: 'coding', progress: 30 }
  }
}

function getProjectTaskCount(projectId: string): number {
  return store.tasks.filter(t => t.project_id === projectId && t.status === 'in_progress').length
}

function formatLastActivity(iso: string): string {
  const ms = parseTs(iso)
  if (ms == null) return '—'
  const diffMin = Math.floor((Date.now() - ms) / 60000)
  if (diffMin < 1) return t('common.justNow')
  if (diffMin < 60) return t('common.minutesAgo', { n: diffMin })
  const diffH = Math.floor(diffMin / 60)
  if (diffH < 24) return t('common.hoursAgo', { n: diffH })
  const diffD = Math.floor(diffH / 24)
  return t('common.dayAgo', { n: diffD })
}

const displayProjects = computed(() =>
  store.projects.map(p => {
    const stageInfo = getProjectStage(p.status)
    return {
      id: p.id,
      name: p.name,
      ...stageInfo,
      activeTasks: getProjectTaskCount(p.id),
      lastActivity: formatLastActivity(p.updated_at),
    }
  })
)

const displayIdeas = computed(() =>
  store.ideas.slice(0, 4).map(i => ({
    id: i.id,
    title: i.title,
    score: i.score ?? 0,
    tier: (i.score ?? 0) >= 80 ? 'high' : (i.score ?? 0) >= 60 ? 'mid' : 'low',
    statusLabel: i.status,
  }))
)

function ideaStatusLabel(status: string): string {
  return t('dashboard.ideaStatus.' + status)
}

async function refresh() {
  await Promise.all([store.loadProjects(), store.loadTasks(), store.loadIdeas()])
}

function quickCapture() {
  router.push('/ideas')
}

onMounted(async () => {
  try {
    await Promise.all([store.loadProjects(), store.loadTasks(), store.loadIdeas()])
  } catch (e) {
    console.error('Dashboard load failed:', e)
  }
})
</script>

<style scoped>
.dashboard { padding: 16px 20px 20px; }

/* ═══ Header ═══ */
.dash-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14px;
}
.dash-title {
  font-size: 18px;
  font-weight: 500;
  letter-spacing: -0.4px;
  color: var(--df-text);
  line-height: 1.2;
}
.dash-subtitle {
  font-size: 11px;
  color: var(--df-text-dim);
  margin-top: 2px;
  display: flex;
  align-items: center;
  gap: 5px;
}
.dash-subtitle::before {
  content: '';
  width: 5px; height: 5px;
  border-radius: 50%;
  background: var(--df-success);
  display: inline-block;
}
.dash-header-right { display: flex; gap: 6px; align-items: center; }

/* — Buttons — */
.df-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 9px 14px;
  line-height: 1;
  border: none;
  border-radius: var(--df-radius-sm);
  font-family: var(--df-font-sans);
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s var(--df-ease);
  white-space: nowrap;
}
.df-btn--primary {
  background: var(--df-accent);
  color: #fff;
  
}
.df-btn--primary:hover {
  background: var(--df-accent);
  filter: brightness(1.1);
  
}
.df-btn--ghost {
  background: rgba(255,255,255,0.03);
  color: var(--df-text-secondary);
  border: 0.5px solid var(--df-border);
}
.df-btn--ghost:hover {
  background: rgba(255,255,255,0.06);
  color: var(--df-text);
  border-color: var(--df-border-strong);
}
.df-btn--xs { padding: 4px 10px; font-size: 11px; }

/* ═══ Stat Cards ═══ */
.stat-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin-bottom: 14px;
}
.stat-card {
  position: relative;
  border-radius: var(--df-radius-md);
  overflow: hidden;
  border: 0.5px solid var(--df-border);
  animation: fadeInUp 0.5s var(--df-ease) both;
}
.stat-card-bg {
  position: absolute;
  inset: 0;
  pointer-events: none;
}
.stat-bg--ideas { background: var(--df-accent-bg); }
.stat-bg--projects { background: var(--df-info-bg); }
.stat-bg--tasks { background: var(--df-success-bg); }
.stat-bg--drafts { background: var(--df-warning-bg); }
.stat-card-inner {
  position: relative;
  padding: 12px 14px 10px;
}
.stat-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.stat-icon-wrap {
  width: 28px; height: 28px;
  display: flex; align-items: center; justify-content: center;
  border-radius: var(--df-radius-sm);
}
.stat-icon { font-size: 14px; }

.stat-trend {
  font-family: var(--df-font-mono);
  font-size: 10px;
  font-weight: 500;
  padding: 1px 6px;
  border-radius: var(--df-radius-sm);
}
.stat-trend.up { color: var(--df-success); background: rgba(61,219,160,0.10); }
.stat-trend.down { color: var(--df-danger); background: rgba(240,101,101,0.10); }
.stat-trend.flat { color: var(--df-text-dim); background: rgba(255,255,255,0.04); }

.stat-value {
  font-size: 24px;
  font-weight: 500;
  letter-spacing: -0.8px;
  color: var(--df-text);
  line-height: 1;
  margin-bottom: 2px;
}
.stat-label {
  font-size: 11px;
  color: var(--df-text-dim);
  font-weight: 450;
}

/* ═══ Grid Layout ═══ */
.dash-grid {
  display: grid;
  grid-template-columns: 1fr 320px;
  gap: 12px;
}
.dash-right { display: flex; flex-direction: column; gap: 12px; }

/* ═══ Panel ═══ */
.df-panel {
  background: var(--df-bg-card);
  border: 0.5px solid var(--df-border);
  border-radius: var(--df-radius-md);
  padding: 14px 16px;
  animation: fadeInUp 0.5s var(--df-ease) both;
}
.df-panel-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.df-panel-title {
  font-size: 12px;
  font-weight: 500;
  color: var(--df-text);
  letter-spacing: -0.1px;
}
.df-link {
  font-size: 11px;
  color: var(--df-accent);
  text-decoration: none;
  font-weight: 500;
  opacity: 0.8;
  transition: opacity 0.15s;
}
.df-link:hover { opacity: 1; text-decoration: underline; }

/* ═══ Project Rows ═══ */
.project-list { display: flex; flex-direction: column; }
.project-row {
  padding: 10px 0;
  border-bottom: 0.5px solid var(--df-border);
  animation: fadeInUp 0.4s var(--df-ease) both;
}
.project-row:last-child { border-bottom: none; }

.project-row-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
.project-identity { display: flex; align-items: center; gap: 8px; }
.project-dot {
  width: 6px; height: 6px; border-radius: 50%;
}
.dot-coding { background: var(--df-accent);  }
.dot-testing { background: var(--df-warning);  }
.dot-release { background: var(--df-success);  }

.project-name {
  font-size: 12px;
  font-weight: 500;
  font-family: var(--df-font-mono);
  color: var(--df-text);
}

.project-stage-chip {
  font-size: 9px;
  font-weight: 500;
  padding: 1px 6px;
  border-radius: var(--df-radius-sm);
  letter-spacing: 0.3px;
  text-transform: uppercase;
}
.chip-coding { background: rgba(123,111,240,0.12); color: var(--df-accent); }
.chip-testing { background: rgba(240,199,94,0.12); color: var(--df-warning); }
.chip-release { background: rgba(61,219,160,0.12); color: var(--df-success); }

.project-bar-wrap { display: flex; align-items: center; gap: 8px; margin-bottom: 5px; }
.project-bar {
  flex: 1;
  height: 3px;
  background: rgba(255,255,255,0.06);
  border-radius: var(--df-radius-sm);
  overflow: hidden;
}
.project-bar-fill {
  height: 100%;
  border-radius: var(--df-radius-sm);
  transition: width 0.6s var(--df-ease);
}
.fill-coding { background: var(--df-accent); }
.fill-testing { background: var(--df-warning); }
.fill-release { background: var(--df-success); }

.project-pct {
  font-family: var(--df-font-mono);
  font-size: 11px;
  color: var(--df-text-dim);
  min-width: 32px;
  text-align: right;
}

.project-meta-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.project-meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: var(--df-text-dim);
}
.project-meta-time {
  font-size: 11px;
  color: var(--df-text-dim);
  font-family: var(--df-font-mono);
}

/* ═══ Idea Rows ═══ */
.idea-rows { display: flex; flex-direction: column; }
.idea-row {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 7px 0;
  border-bottom: 0.5px solid var(--df-border);
}
.idea-row:last-child { border-bottom: none; }

.idea-score-ring {
  width: 32px; height: 32px;
  border-radius: var(--df-radius);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.ring-high { background: rgba(61,219,160,0.10); border: 0.5px solid rgba(61,219,160,0.15); }
.ring-mid  { background: rgba(240,199,94,0.08); border: 0.5px solid rgba(240,199,94,0.12); }
.ring-low  { background: rgba(240,101,101,0.08); border: 0.5px solid rgba(240,101,101,0.12); }

.idea-score-num {
  font-family: var(--df-font-mono);
  font-size: 13px;
  font-weight: 500;
}
.ring-high .idea-score-num { color: var(--df-success); }
.ring-mid  .idea-score-num { color: var(--df-warning); }
.ring-low  .idea-score-num { color: var(--df-danger); }

.idea-name { font-size: 12px; font-weight: 500; color: var(--df-text); display: block; }
.idea-status { font-size: 10px; color: var(--df-text-dim); margin-top: 1px; display: block; }

/* ═══ Decision Rows ═══ */
.decision-rows { display: flex; flex-direction: column; }
.decision-row {
  display: flex;
  gap: 10px;
  padding: 7px 0;
  border-bottom: 0.5px solid var(--df-border);
}
.decision-row:last-child { border-bottom: none; }

.decision-marker {
  width: 20px; height: 20px;
  display: flex; align-items: center; justify-content: center;
  font-size: 9px;
  flex-shrink: 0;
  border-radius: var(--df-radius-sm);
}
.marker-ai { background: rgba(94,175,240,0.12); color: var(--df-info); }
.marker-human { background: rgba(123,111,240,0.12); color: var(--df-accent); }

.decision-q { font-size: 11px; color: var(--df-text-secondary); display: block; margin-bottom: 2px; }
.decision-a {
  font-size: 11px;
  font-weight: 500;
  color: var(--df-accent);
  display: block;
  line-height: 1.3;
}
.decision-time {
  font-family: var(--df-font-mono);
  font-size: 9px;
  color: var(--df-text-dim);
  margin-top: 3px;
  display: block;
}

/* ═══ Annotation Rows ═══ */
.anno-rows { display: flex; flex-direction: column; }
.anno-row {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 5px 0;
  border-bottom: 0.5px solid var(--df-border);
}
.anno-row:last-child { border-bottom: none; }

.anno-tag {
  font-family: var(--df-font-mono);
  font-size: 9px;
  font-weight: 500;
  padding: 2px 7px;
  border-radius: var(--df-radius-sm);
  min-width: 54px;
  text-align: center;
  letter-spacing: 0.5px;
  flex-shrink: 0;
}
.tag-fixme   { background: rgba(240,101,101,0.14); color: var(--df-danger); }
.tag-todo    { background: rgba(94,175,240,0.12); color: var(--df-info); }
.tag-risk    { background: rgba(240,199,94,0.12); color: #f0a830; }
.tag-question { background: rgba(94,175,240,0.10); color: var(--df-info); }

.anno-text {
  font-family: var(--df-font-mono);
  font-size: 10px;
  color: var(--df-text-secondary);
  line-height: 1.3;
}

/* ═══ Responsive ═══ */

/* 窄窗口：单栏 */
@media (max-width: 900px) {
  .dashboard { padding: 12px 14px 16px; }
  .dash-grid { grid-template-columns: 1fr; }
  .dash-right { flex-direction: row; flex-wrap: wrap; gap: 10px; }
  .dash-right > .df-panel { flex: 1 1 280px; min-width: 0; }
}

/* 中等窗口：两栏但右栏缩窄 */
@media (min-width: 901px) and (max-width: 1200px) {
  .dash-grid { grid-template-columns: 1fr 280px; }
  .stat-row { grid-template-columns: repeat(4, 1fr); gap: 8px; }
  .stat-card-inner { padding: 10px 12px 8px; }
  .stat-value { font-size: 22px; }
  .stat-icon-wrap { width: 24px; height: 24px; }
  .stat-icon { font-size: 12px; }
}

/* 宽窗口：右栏展开 */
@media (min-width: 1201px) {
  .dash-grid { grid-template-columns: 1fr 340px; }
}

/* 超宽窗口：充分利用 */
@media (min-width: 1600px) {
  .dashboard { padding: 20px 28px 24px; }
  .dash-grid { grid-template-columns: 1fr 400px; gap: 16px; }
  .stat-row { gap: 14px; }
  .stat-card-inner { padding: 14px 18px 12px; }
  .stat-value { font-size: 28px; }
  .stat-icon-wrap { width: 30px; height: 30px; }
  .df-panel { padding: 16px 18px; }
}
</style>
