<script setup lang="ts">
import { onMounted, computed, ref } from 'vue'
import { useAuthStore } from '../stores/auth'
import { useActivitiesStore } from '../stores/activities'
import { useCoachingStore } from '../stores/coaching'
import type { FitnessEntry, WeeklyStats, PersonalRecord, TodayWorkout, CalendarDay, MonthlyTrend, WeeklyDigest, ProgressSummary } from '../types/models'
import Card from 'primevue/card'
import Tag from 'primevue/tag'
import Button from 'primevue/button'
import { useRouter } from 'vue-router'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, HeatmapChart, GaugeChart } from 'echarts/charts'
import {
  TooltipComponent, LegendComponent, GridComponent, VisualMapComponent, CalendarComponent,
} from 'echarts/components'
import VChart from 'vue-echarts'

use([CanvasRenderer, LineChart, BarChart, HeatmapChart, GaugeChart, TooltipComponent, LegendComponent, GridComponent, VisualMapComponent, CalendarComponent])

const auth = useAuthStore()
const store = useActivitiesStore()
const coaching = useCoachingStore()
const router = useRouter()

const recentActivities = computed(() => store.activities.slice(0, 5))
const fitness = ref<FitnessEntry[]>([])
const weeklyStats = ref<WeeklyStats[]>([])
const records = ref<PersonalRecord[]>([])
const todayWorkout = ref<TodayWorkout | null>(null)
const calendarDays = ref<CalendarDay[]>([])
const monthlyTrends = ref<MonthlyTrend[]>([])
const weeklyDigest = ref<WeeklyDigest | null>(null)
const digestLoading = ref(false)
const progress = ref<ProgressSummary | null>(null)
const aiProgress = ref('')
const aiProgressLoading = ref(false)

// Delta helpers
function delta(current: number | null | undefined, previous: number | null | undefined): number | null {
  if (current == null || previous == null) return null
  return current - previous
}

function deltaPercent(current: number | null | undefined, previous: number | null | undefined): number | null {
  if (current == null || previous == null || previous === 0) return null
  return Math.round(((current - previous) / previous) * 100)
}

function trendClass(d: number | null, inverted = false): string {
  if (d == null || d === 0) return 'text-surface-400'
  const positive = inverted ? d < 0 : d > 0
  return positive ? 'text-green-600' : 'text-red-500'
}

function trendIcon(d: number | null): string {
  if (d == null || d === 0) return ''
  return d > 0 ? 'pi pi-arrow-up' : 'pi pi-arrow-down'
}

function fitnessZoneLabel(tsb: number | null): { label: string; color: string; description: string } {
  if (tsb == null) return { label: '—', color: 'text-surface-400', description: '' }
  if (tsb > 25) return { label: 'Восстановлен', color: 'text-emerald-600', description: 'Высокая свежесть, готовность к интенсивной работе' }
  if (tsb > 5) return { label: 'Свежий', color: 'text-green-600', description: 'Хорошая форма для качественных тренировок' }
  if (tsb > -10) return { label: 'Оптимально', color: 'text-blue-600', description: 'Баланс нагрузки и восстановления' }
  if (tsb > -25) return { label: 'Устал', color: 'text-amber-600', description: 'Накопленная усталость, следите за восстановлением' }
  return { label: 'Перегрузка', color: 'text-red-600', description: 'Высокий риск перетренированности' }
}

function formatDurationLabel(seconds: number): string {
  if (seconds < 60) return `${seconds}s`
  if (seconds < 3600) return `${seconds / 60}m`
  return `${seconds / 3600}h`
}

function formatDuration(seconds: number): string {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  return h > 0 ? `${h}h ${m}m` : `${m}m`
}

function formatDistance(meters: number | null): string {
  if (!meters) return '—'
  return `${(meters / 1000).toFixed(1)} km`
}

function formatDate(iso: string): string {
  return new Date(iso).toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' })
}

// Charts

function buildFitnessChart() {
  if (fitness.value.length === 0) return null

  const dates = fitness.value.map(e => e.date)
  const ctlData = fitness.value.map(e => e.ctl)
  const atlData = fitness.value.map(e => e.atl)
  const tsbData = fitness.value.map(e => e.tsb)

  return {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const date = params[0].name
        return `<b>${date}</b><br/>` +
          params.map((p: any) => `${p.marker} ${p.seriesName}: <b>${p.value.toFixed(1)}</b>`).join('<br/>')
      },
    },
    legend: { data: ['Фитнес (CTL)', 'Усталость (ATL)', 'Форма (TSB)'], top: 0, textStyle: { color: '#6b7280', fontSize: 11 } },
    grid: { left: 40, right: 20, top: 40, bottom: 30 },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: { color: '#6b7280', fontSize: 10, formatter: (v: string) => { const d = new Date(v); return `${d.getDate()}/${d.getMonth() + 1}` } },
      splitLine: { show: false },
    },
    yAxis: { type: 'value', axisLabel: { color: '#6b7280' }, splitLine: { lineStyle: { color: '#e5e7eb' } } },
    series: [
      { name: 'Фитнес (CTL)', type: 'line', data: ctlData, showSymbol: false, lineStyle: { width: 2 }, itemStyle: { color: '#3b82f6' } },
      { name: 'Усталость (ATL)', type: 'line', data: atlData, showSymbol: false, lineStyle: { width: 2 }, itemStyle: { color: '#ef4444' } },
      {
        name: 'Форма (TSB)', type: 'line', data: tsbData, showSymbol: false, lineStyle: { width: 2 }, itemStyle: { color: '#10b981' },
        areaStyle: {
          color: {
            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(16,185,129,0.15)' },
              { offset: 0.5, color: 'rgba(16,185,129,0)' },
              { offset: 0.5, color: 'rgba(239,68,68,0)' },
              { offset: 1, color: 'rgba(239,68,68,0.1)' },
            ],
          },
        },
      },
    ],
  }
}

function buildWeeklyChart() {
  if (weeklyStats.value.length === 0) return null

  const weeks = weeklyStats.value.map(w => {
    const d = new Date(w.week)
    return `${d.getDate()}/${d.getMonth() + 1}`
  })

  return {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const week = params[0].name
        return `<b>Неделя ${week}</b><br/>` +
          params.map((p: any) => `${p.marker} ${p.seriesName}: <b>${p.value}</b>`).join('<br/>')
      },
    },
    legend: { data: ['Дистанция (км)', 'TSS', 'Часы'], top: 0, textStyle: { color: '#6b7280', fontSize: 11 } },
    grid: { left: 40, right: 40, top: 40, bottom: 30 },
    xAxis: { type: 'category', data: weeks, axisLabel: { color: '#6b7280', fontSize: 10 } },
    yAxis: [
      { type: 'value', axisLabel: { color: '#6b7280' }, splitLine: { lineStyle: { color: '#e5e7eb' } } },
      { type: 'value', axisLabel: { color: '#6b7280' }, splitLine: { show: false } },
    ],
    series: [
      {
        name: 'Дистанция (км)', type: 'bar', data: weeklyStats.value.map(w => w.distance),
        itemStyle: { color: '#3b82f6', borderRadius: [4, 4, 0, 0] }, barMaxWidth: 30,
      },
      {
        name: 'TSS', type: 'bar', data: weeklyStats.value.map(w => w.tss),
        itemStyle: { color: '#a855f7', borderRadius: [4, 4, 0, 0] }, barMaxWidth: 30,
      },
      {
        name: 'Часы', type: 'line', yAxisIndex: 1,
        data: weeklyStats.value.map(w => +(w.duration / 3600).toFixed(1)),
        showSymbol: true, symbolSize: 6, itemStyle: { color: '#10b981' }, lineStyle: { width: 2 },
      },
    ],
  }
}

function buildCalendarChart() {
  if (calendarDays.value.length === 0) return null

  const now = new Date()
  const yearAgo = new Date(now)
  yearAgo.setFullYear(yearAgo.getFullYear() - 1)
  const rangeStart = yearAgo.toISOString().slice(0, 10)
  const rangeEnd = now.toISOString().slice(0, 10)

  const data = calendarDays.value.map(d => [d.date, d.tss || d.count])
  const maxVal = Math.max(...data.map(d => d[1] as number), 1)

  return {
    backgroundColor: 'transparent',
    tooltip: {
      formatter: (params: any) => {
        const d = calendarDays.value.find(c => c.date === params.data[0])
        if (!d) return params.data[0]
        return `<b>${params.data[0]}</b><br/>Тренировок: ${d.count}<br/>Время: ${Math.round(d.duration / 60)} мин<br/>TSS: ${d.tss}`
      },
    },
    visualMap: {
      min: 0,
      max: maxVal,
      show: false,
      inRange: { color: ['#ebedf0', '#9be9a8', '#40c463', '#30a14e', '#216e39'] },
    },
    calendar: {
      range: [rangeStart, rangeEnd],
      cellSize: [13, 13],
      top: 30,
      left: 40,
      right: 10,
      itemStyle: { borderWidth: 2, borderColor: '#fff', borderRadius: 2 },
      yearLabel: { show: false },
      monthLabel: { color: '#6b7280', fontSize: 10 },
      dayLabel: { color: '#6b7280', fontSize: 9, firstDay: 1, nameMap: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'] },
      splitLine: { show: false },
    },
    series: [{
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data,
    }],
  }
}

function buildMonthlyTrendsChart() {
  if (monthlyTrends.value.length === 0) return null

  const months = monthlyTrends.value.map(m => m.month)

  return {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const month = params[0].name
        return `<b>${month}</b><br/>` +
          params.map((p: any) => `${p.marker} ${p.seriesName}: <b>${p.value ?? '—'}</b>`).join('<br/>')
      },
    },
    legend: { data: ['Средняя мощность (W)', 'Средний пульс', 'W/kg', 'Часы'], top: 0, textStyle: { color: '#6b7280', fontSize: 11 } },
    grid: { left: 50, right: 50, top: 40, bottom: 30 },
    xAxis: { type: 'category', data: months, axisLabel: { color: '#6b7280', fontSize: 10 } },
    yAxis: [
      { type: 'value', name: 'W / bpm', axisLabel: { color: '#6b7280' }, splitLine: { lineStyle: { color: '#e5e7eb' } } },
      { type: 'value', name: 'W/kg / ч', axisLabel: { color: '#6b7280' }, splitLine: { show: false } },
    ],
    series: [
      {
        name: 'Средняя мощность (W)', type: 'line', data: monthlyTrends.value.map(m => m.avg_power),
        showSymbol: true, symbolSize: 6, itemStyle: { color: '#3b82f6' }, lineStyle: { width: 2 },
        connectNulls: true,
      },
      {
        name: 'Средний пульс', type: 'line', data: monthlyTrends.value.map(m => m.avg_hr),
        showSymbol: true, symbolSize: 6, itemStyle: { color: '#ef4444' }, lineStyle: { width: 2 },
        connectNulls: true,
      },
      {
        name: 'W/kg', type: 'line', yAxisIndex: 1, data: monthlyTrends.value.map(m => m.w_per_kg),
        showSymbol: true, symbolSize: 6, itemStyle: { color: '#10b981' }, lineStyle: { width: 2 },
        connectNulls: true,
      },
      {
        name: 'Часы', type: 'bar', yAxisIndex: 1, data: monthlyTrends.value.map(m => m.hours),
        itemStyle: { color: 'rgba(168,85,247,0.3)', borderRadius: [4, 4, 0, 0] }, barMaxWidth: 25,
      },
    ],
  }
}

async function loadDigest() {
  digestLoading.value = true
  try {
    weeklyDigest.value = await store.fetchWeeklyDigest()
  } catch {
    // digest not available
  } finally {
    digestLoading.value = false
  }
}

async function loadAiProgress() {
  aiProgressLoading.value = true
  try {
    aiProgress.value = await store.fetchAiProgress()
  } catch {
    aiProgress.value = ''
  } finally {
    aiProgressLoading.value = false
  }
}

const fitnessZone = computed(() => fitnessZoneLabel(progress.value?.fitness?.tsb ?? null))

const weekVsWeekTss = computed(() => deltaPercent(progress.value?.this_week?.tss, progress.value?.last_week?.tss))
const weekVsWeekHours = computed(() => deltaPercent(progress.value?.this_week?.hours, progress.value?.last_week?.hours))
const monthVsMonthTss = computed(() => deltaPercent(progress.value?.this_month?.tss, progress.value?.last_month?.tss))
const monthVsMonthPower = computed(() => delta(progress.value?.this_month?.avg_power, progress.value?.last_month?.avg_power))
const ctlDelta = computed(() => delta(progress.value?.fitness?.ctl, progress.value?.fitness_7d_ago?.ctl))

onMounted(async () => {
  // Load everything in parallel
  const promises: Promise<any>[] = [
    store.fetchActivities(5),
  ]

  promises.push(
    store.fetchProgressSummary().then(p => { progress.value = p }).catch(() => {}),
    store.fetchFitness(90).then(f => { fitness.value = f }).catch(() => {}),
    store.fetchWeeklyStats(8).then(w => { weeklyStats.value = w }).catch(() => {}),
    store.fetchPersonalRecords().then(r => { records.value = r }).catch(() => {}),
    coaching.fetchTodayWorkout().then(t => { todayWorkout.value = t }).catch(() => {}),
    store.fetchActivityCalendar(12).then(c => { calendarDays.value = c }).catch(() => {}),
    store.fetchMonthlyTrends(12).then(m => { monthlyTrends.value = m }).catch(() => {}),
  )

  await Promise.all(promises)
})
</script>

<template>
  <div>
    <h1 class="text-2xl font-semibold mb-6">Dashboard</h1>

    <!-- ===== FITNESS STATUS BAR ===== -->
    <div v-if="progress" class="grid grid-cols-2 md:grid-cols-5 gap-3 mb-6">
      <!-- Current Form -->
      <Card class="col-span-2 md:col-span-1">
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">Состояние</p>
          <p class="text-lg font-bold" :class="fitnessZone.color">{{ fitnessZone.label }}</p>
          <p v-if="progress.fitness?.tsb != null" class="text-xs text-surface-400 mt-1">TSB {{ progress.fitness.tsb }}</p>
        </template>
      </Card>

      <!-- CTL -->
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">Фитнес (CTL)</p>
          <div class="flex items-baseline gap-2">
            <p class="text-2xl font-bold">{{ progress.fitness?.ctl ?? '—' }}</p>
            <span v-if="ctlDelta != null" class="text-xs font-medium" :class="trendClass(ctlDelta)">
              <i :class="trendIcon(ctlDelta)" class="text-[10px]"></i>
              {{ ctlDelta > 0 ? '+' : '' }}{{ ctlDelta.toFixed(1) }}
            </span>
          </div>
          <p class="text-xs text-surface-400">за 7 дней</p>
        </template>
      </Card>

      <!-- This week volume -->
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">Эта неделя</p>
          <p class="text-2xl font-bold">{{ progress.this_week.hours }}<span class="text-sm font-normal text-surface-500">ч</span></p>
          <div class="flex items-center gap-1 mt-1">
            <span v-if="weekVsWeekHours != null" class="text-xs font-medium" :class="trendClass(weekVsWeekHours)">
              <i :class="trendIcon(weekVsWeekHours)" class="text-[10px]"></i>
              {{ weekVsWeekHours > 0 ? '+' : '' }}{{ weekVsWeekHours }}%
            </span>
            <span class="text-xs text-surface-400">vs прошлая</span>
          </div>
        </template>
      </Card>

      <!-- This week TSS -->
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">TSS неделя</p>
          <p class="text-2xl font-bold">{{ progress.this_week.tss }}</p>
          <div class="flex items-center gap-1 mt-1">
            <span v-if="weekVsWeekTss != null" class="text-xs font-medium" :class="trendClass(weekVsWeekTss)">
              <i :class="trendIcon(weekVsWeekTss)" class="text-[10px]"></i>
              {{ weekVsWeekTss > 0 ? '+' : '' }}{{ weekVsWeekTss }}%
            </span>
            <span class="text-xs text-surface-400">vs прошлая</span>
          </div>
        </template>
      </Card>

      <!-- Monthly power change -->
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">Мощность (месяц)</p>
          <p class="text-2xl font-bold">{{ progress.this_month.avg_power ?? '—' }}<span class="text-sm font-normal text-surface-500">W</span></p>
          <div class="flex items-center gap-1 mt-1">
            <span v-if="monthVsMonthPower != null" class="text-xs font-medium" :class="trendClass(monthVsMonthPower)">
              <i :class="trendIcon(monthVsMonthPower)" class="text-[10px]"></i>
              {{ monthVsMonthPower > 0 ? '+' : '' }}{{ monthVsMonthPower }}W
            </span>
            <span class="text-xs text-surface-400">vs прошлый</span>
          </div>
        </template>
      </Card>
    </div>

    <!-- Static fallback cards when no progress data -->
    <div v-else class="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 mb-6">
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">FTP</p>
          <p class="text-2xl font-bold">{{ auth.rider?.ftp ?? '—' }} <span class="text-sm text-surface-500 font-normal">W</span></p>
        </template>
      </Card>
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">Вес</p>
          <p class="text-2xl font-bold">{{ auth.rider?.weight ?? '—' }} <span class="text-sm text-surface-500 font-normal">кг</span></p>
        </template>
      </Card>
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">W/кг</p>
          <p class="text-2xl font-bold">
            {{ auth.rider?.ftp && auth.rider?.weight ? (auth.rider.ftp / auth.rider.weight).toFixed(2) : '—' }}
          </p>
        </template>
      </Card>
      <Card>
        <template #content>
          <p class="text-surface-500 text-xs uppercase mb-1">Тренировок</p>
          <p class="text-2xl font-bold">{{ store.total }}</p>
        </template>
      </Card>
    </div>

    <!-- ===== TODAY'S WORKOUT ===== -->
    <Card v-if="todayWorkout" class="mb-6 border-l-4 border-l-primary cursor-pointer hover:shadow-md transition-shadow" @click="router.push({ name: 'coach' })">
      <template #content>
        <div class="flex items-center justify-between">
          <div>
            <div class="flex items-center gap-2 mb-1">
              <i class="pi pi-bolt text-primary"></i>
              <p class="text-surface-500 text-xs uppercase">Тренировка на сегодня</p>
            </div>
            <p class="text-lg font-bold">{{ todayWorkout.title }}</p>
            <p v-if="todayWorkout.description" class="text-surface-500 text-sm mt-1 line-clamp-2">{{ todayWorkout.description }}</p>
          </div>
          <div class="flex items-center gap-3">
            <Tag :value="todayWorkout.workout_type" severity="info" />
            <div v-if="todayWorkout.duration_minutes" class="text-right">
              <p class="text-sm font-semibold">{{ todayWorkout.duration_minutes }} мин</p>
              <p v-if="todayWorkout.target_tss" class="text-xs text-surface-400">TSS {{ todayWorkout.target_tss }}</p>
            </div>
            <i class="pi pi-chevron-right text-surface-300"></i>
          </div>
        </div>
      </template>
    </Card>

    <!-- ===== WEEK VS WEEK COMPARISON (detailed) ===== -->
    <div v-if="progress && (progress.this_week.rides > 0 || progress.last_week.rides > 0)" class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
      <Card>
        <template #title>
          <span class="text-sm">Эта неделя</span>
        </template>
        <template #content>
          <div class="grid grid-cols-3 gap-3 text-center">
            <div>
              <p class="text-surface-500 text-xs">Тренировок</p>
              <p class="text-lg font-bold">{{ progress.this_week.rides }}</p>
            </div>
            <div>
              <p class="text-surface-500 text-xs">Часы</p>
              <p class="text-lg font-bold">{{ progress.this_week.hours }}</p>
            </div>
            <div>
              <p class="text-surface-500 text-xs">TSS</p>
              <p class="text-lg font-bold">{{ progress.this_week.tss }}</p>
            </div>
            <div>
              <p class="text-surface-500 text-xs">Дистанция</p>
              <p class="text-lg font-bold">{{ progress.this_week.distance_km }} <span class="text-xs font-normal">км</span></p>
            </div>
            <div>
              <p class="text-surface-500 text-xs">Ср. мощность</p>
              <p class="text-lg font-bold">{{ progress.this_week.avg_power ?? '—' }} <span class="text-xs font-normal">W</span></p>
            </div>
            <div>
              <p class="text-surface-500 text-xs">Ср. пульс</p>
              <p class="text-lg font-bold">{{ progress.this_week.avg_hr ?? '—' }}</p>
            </div>
          </div>
        </template>
      </Card>
      <Card>
        <template #title>
          <span class="text-sm">Прошлая неделя</span>
        </template>
        <template #content>
          <div class="grid grid-cols-3 gap-3 text-center">
            <div>
              <p class="text-surface-500 text-xs">Тренировок</p>
              <p class="text-lg font-bold">{{ progress.last_week.rides }}</p>
            </div>
            <div>
              <p class="text-surface-500 text-xs">Часы</p>
              <p class="text-lg font-bold">{{ progress.last_week.hours }}</p>
            </div>
            <div>
              <p class="text-surface-500 text-xs">TSS</p>
              <p class="text-lg font-bold">{{ progress.last_week.tss }}</p>
            </div>
            <div>
              <p class="text-surface-500 text-xs">Дистанция</p>
              <p class="text-lg font-bold">{{ progress.last_week.distance_km }} <span class="text-xs font-normal">км</span></p>
            </div>
            <div>
              <p class="text-surface-500 text-xs">Ср. мощность</p>
              <p class="text-lg font-bold">{{ progress.last_week.avg_power ?? '—' }} <span class="text-xs font-normal">W</span></p>
            </div>
            <div>
              <p class="text-surface-500 text-xs">Ср. пульс</p>
              <p class="text-lg font-bold">{{ progress.last_week.avg_hr ?? '—' }}</p>
            </div>
          </div>
        </template>
      </Card>
    </div>

    <!-- ===== FITNESS TREND ===== -->
    <Card v-if="fitness.length > 0" class="mb-6">
      <template #title>
        <div class="flex items-center gap-2">
          <i class="pi pi-chart-line text-blue-500"></i>
          Тренд фитнеса
        </div>
      </template>
      <template #content>
        <VChart :option="buildFitnessChart() ?? undefined" style="height: 280px" autoresize />
        <div class="flex items-center justify-center gap-6 mt-2 text-xs text-surface-500">
          <span>CTL — хронич. нагрузка (фитнес)</span>
          <span>ATL — острая нагрузка (усталость)</span>
          <span>TSB — баланс формы</span>
        </div>
      </template>
    </Card>

    <!-- ===== AI PROGRESS ANALYSIS ===== -->
    <Card class="mb-6">
      <template #title>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <i class="pi pi-sparkles text-violet-500"></i>
            AI Анализ прогресса
          </div>
          <Button
            v-if="!aiProgress"
            label="Анализировать"
            icon="pi pi-sparkles"
            severity="secondary"
            size="small"
            :loading="aiProgressLoading"
            @click="loadAiProgress"
          />
          <Button
            v-else
            icon="pi pi-refresh"
            severity="secondary"
            text
            rounded
            size="small"
            :loading="aiProgressLoading"
            @click="loadAiProgress"
            title="Обновить анализ"
          />
        </div>
      </template>
      <template #content>
        <div v-if="aiProgressLoading" class="flex items-center justify-center py-8 text-surface-400">
          <i class="pi pi-spin pi-spinner text-2xl mr-2"></i>
          Анализирую данные...
        </div>
        <div v-else-if="aiProgress" class="prose prose-sm max-w-none" v-html="aiProgress"></div>
        <p v-else class="text-surface-400 text-sm">
          AI проанализирует ваши тренировки за последние месяцы, оценит динамику прогресса и даст рекомендации по развитию.
        </p>
      </template>
    </Card>

    <!-- ===== PERSONAL RECORDS ===== -->
    <Card v-if="records.length > 0" class="mb-6">
      <template #title>
        <div class="flex items-center gap-2">
          <i class="pi pi-trophy text-amber-500"></i>
          Личные рекорды
        </div>
      </template>
      <template #content>
        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
          <div
            v-for="pr in records"
            :key="pr.duration"
            class="bg-surface-50 rounded-lg p-3 text-center border border-surface-200 cursor-pointer hover:border-primary transition-colors"
            @click="router.push({ name: 'activity-detail', params: { id: pr.activity_id } })"
          >
            <p class="text-surface-500 text-xs uppercase mb-1">{{ formatDurationLabel(pr.duration) }}</p>
            <p class="text-xl font-bold">{{ pr.power }}<span class="text-sm font-normal text-surface-500">W</span></p>
            <p v-if="auth.rider?.weight" class="text-xs text-surface-400">{{ (pr.power / auth.rider.weight).toFixed(1) }} W/кг</p>
          </div>
        </div>
      </template>
    </Card>

    <!-- ===== WEEKLY VOLUME ===== -->
    <Card v-if="weeklyStats.length > 0" class="mb-6">
      <template #title>
        <div class="flex items-center gap-2">
          <i class="pi pi-chart-bar text-indigo-500"></i>
          Нагрузка по неделям
        </div>
      </template>
      <template #content>
        <VChart :option="buildWeeklyChart() ?? undefined" style="height: 280px" autoresize />
      </template>
    </Card>

    <!-- ===== MONTHLY TRENDS ===== -->
    <Card v-if="monthlyTrends.length > 0" class="mb-6">
      <template #title>
        <div class="flex items-center gap-2">
          <i class="pi pi-chart-line text-blue-500"></i>
          Тренды по месяцам
        </div>
      </template>
      <template #content>
        <VChart :option="buildMonthlyTrendsChart() ?? undefined" style="height: 300px" autoresize />
      </template>
    </Card>

    <!-- ===== ACTIVITY HEATMAP ===== -->
    <Card v-if="calendarDays.length > 0" class="mb-6">
      <template #title>
        <div class="flex items-center gap-2">
          <i class="pi pi-calendar text-green-600"></i>
          Календарь активности
        </div>
      </template>
      <template #content>
        <VChart :option="buildCalendarChart() ?? undefined" style="height: 180px" autoresize />
        <div class="flex items-center justify-end gap-1 mt-2 text-xs text-surface-400">
          <span>Меньше</span>
          <span class="inline-block w-3 h-3 rounded-sm" style="background: #ebedf0"></span>
          <span class="inline-block w-3 h-3 rounded-sm" style="background: #9be9a8"></span>
          <span class="inline-block w-3 h-3 rounded-sm" style="background: #40c463"></span>
          <span class="inline-block w-3 h-3 rounded-sm" style="background: #30a14e"></span>
          <span class="inline-block w-3 h-3 rounded-sm" style="background: #216e39"></span>
          <span>Больше</span>
        </div>
      </template>
    </Card>

    <!-- ===== WEEKLY AI DIGEST ===== -->
    <Card class="mb-6">
      <template #title>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <i class="pi pi-sparkles text-purple-500"></i>
            Еженедельный дайджест
          </div>
          <Button
            v-if="!weeklyDigest"
            label="Сгенерировать"
            icon="pi pi-sparkles"
            severity="secondary"
            size="small"
            :loading="digestLoading"
            @click="loadDigest"
          />
        </div>
      </template>
      <template #content>
        <div v-if="digestLoading" class="flex items-center justify-center py-8 text-surface-400">
          <i class="pi pi-spin pi-spinner text-2xl mr-2"></i>
          Генерирую дайджест...
        </div>
        <div v-else-if="weeklyDigest?.digest">
          <div class="flex items-center gap-4 text-sm text-surface-500 mb-4 flex-wrap">
            <span>{{ weeklyDigest.week_start }} — {{ weeklyDigest.week_end }}</span>
            <span>{{ weeklyDigest.total_activities }} трен.</span>
            <span>{{ weeklyDigest.total_hours }}ч</span>
            <span>TSS {{ weeklyDigest.total_tss }}</span>
            <span>{{ weeklyDigest.total_distance_km }} км</span>
          </div>
          <div class="prose prose-sm max-w-none" v-html="weeklyDigest.digest"></div>
        </div>
        <div v-else-if="weeklyDigest && !weeklyDigest.digest" class="text-surface-400 text-center py-4">
          {{ weeklyDigest.message || 'Нет тренировок за прошлую неделю' }}
        </div>
        <p v-else class="text-surface-400 text-sm">Итоги прошлой недели: объём, ключевые метрики, рекомендации AI-тренера.</p>
      </template>
    </Card>

    <!-- ===== RECENT ACTIVITIES ===== -->
    <h2 class="text-lg font-semibold mb-4">Последние тренировки</h2>
    <div v-if="recentActivities.length === 0" class="text-surface-500">
      Нет тренировок. Загрузите первый .FIT файл!
    </div>
    <div v-else class="flex flex-col gap-3">
      <Card
        v-for="a in recentActivities"
        :key="a.id"
        class="cursor-pointer hover:border-primary transition-colors"
        @click="router.push({ name: 'activity-detail', params: { id: a.id } })"
      >
        <template #content>
          <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-2">
            <div class="flex items-center gap-3">
              <div>
                <p class="font-semibold">{{ a.name || 'Тренировка' }}</p>
                <p class="text-surface-500 text-sm">{{ formatDate(a.date) }}</p>
              </div>
              <Tag :value="a.activity_type" severity="info" class="text-xs" />
            </div>
            <div class="flex items-center gap-4 md:gap-6 text-sm flex-wrap">
              <div class="text-center">
                <p class="text-surface-500 text-xs">Время</p>
                <p class="font-semibold">{{ formatDuration(a.duration) }}</p>
              </div>
              <div v-if="a.distance" class="text-center">
                <p class="text-surface-500 text-xs">Дистанция</p>
                <p class="font-semibold">{{ formatDistance(a.distance) }}</p>
              </div>
              <div v-if="a.metrics?.avg_power" class="text-center">
                <p class="text-surface-500 text-xs">Мощность</p>
                <p class="font-semibold">{{ a.metrics.avg_power }}W</p>
              </div>
              <div v-if="a.metrics?.tss" class="text-center">
                <p class="text-surface-500 text-xs">TSS</p>
                <p class="font-semibold">{{ a.metrics.tss }}</p>
              </div>
              <div v-if="a.metrics?.normalized_power" class="text-center hidden md:block">
                <p class="text-surface-500 text-xs">NP</p>
                <p class="font-semibold">{{ a.metrics.normalized_power }}W</p>
              </div>
            </div>
          </div>
        </template>
      </Card>
    </div>
  </div>
</template>
