import { Link, useNavigate } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useMemo, useState, useEffect, useRef } from 'react'
import {
BarChart, Bar, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from 'recharts'
import GridLayout, { WidthProvider } from 'react-grid-layout'
import 'react-grid-layout/css/styles.css'
import 'react-resizable/css/styles.css'
import { startOfWeek, format, subWeeks, eachWeekOfInterval, subDays, addDays } from 'date-fns'
import api from '../utils/api'
import { useIsMobile } from '../hooks/useMediaQuery'
import StatCard from '../components/ui/StatCard'
import HrvBadge from '../components/ui/HrvBadge'
import SleepHypnogram from '../components/health/SleepHypnogram'
import BodyBatteryChart from '../components/health/BodyBatteryChart'
import ActivityMap from '../components/activity/ActivityMap'
import {
formatDuration, formatDistance, formatHeartRate, formatElevation,
formatDate, sportColor, formatSleep, convertKm, distanceUnitLabel,
} from '../utils/format'
import { useUnit } from '../hooks/useUnits'
import SportIcon from '../components/ui/SportIcon'
import { vo2Color } from '../utils/vo2'
const Grid = WidthProvider(GridLayout)
const MEDALS = { 1: '🥇', 2: '🥈', 3: '🥉' }
const tooltipStyle = { background: '#111827', border: '1px solid #374151', borderRadius: 8, fontSize: 12, color: '#fff' }
// Compact single-stat widgets. val(health, ytdStats) → display string.
const STAT_DEFS = {
stat_steps: { label: 'Steps today', accent: 'green', sub: 'goal 10,000', val: h => h.steps != null ? h.steps.toLocaleString() : '--' },
stat_resting_hr: { label: 'Resting HR', accent: 'red', val: h => formatHeartRate(h.resting_hr) },
stat_sleep: { label: 'Sleep', accent: 'violet', val: h => formatSleep(h.sleep_duration_s) },
stat_vo2max: { label: 'VO₂ max', accent: 'blue', val: h => h.vo2max != null ? h.vo2max.toFixed(1) : '--', sub: h => h.fitness_age != null ? `fitness age ${h.fitness_age}` : undefined },
stat_hrv: { label: 'HRV status', accent: 'purple', val: h => (h.hrv_weekly_avg ?? h.hrv_nightly_avg) != null ? `${Math.round(h.hrv_weekly_avg ?? h.hrv_nightly_avg)} ms` : '--', sub: h => h.hrv_status ? : undefined },
stat_running: { label: 'Running this year', accent: 'green', val: (h, y, u) => y ? `${convertKm(y.running_km, u).toFixed(0)} ${distanceUnitLabel(u)}` : '--' },
stat_cycling: { label: 'Cycling this year', accent: 'orange', val: (h, y, u) => y ? `${convertKm(y.cycling_km, u).toFixed(0)} ${distanceUnitLabel(u)}` : '--' },
stat_stress: { label: 'Stress', accent: 'orange', val: h => h.avg_stress != null ? Math.round(h.avg_stress) : '--' },
stat_calories: { label: 'Active calories', accent: 'orange', val: h => h.active_calories != null ? Math.round(h.active_calories).toLocaleString() : '--' },
stat_floors: { label: 'Floors climbed', accent: 'green', val: h => h.floors_climbed != null ? h.floors_climbed : '--' },
}
// Full widget registry: size defaults + palette label. Stats inherit from STAT_DEFS.
const WIDGETS = {
...Object.fromEntries(Object.entries(STAT_DEFS).map(([id, d]) => [id, { label: d.label, w: 2, h: 1, minW: 1, minH: 1 }])),
weekly: { label: 'Weekly distance', w: 6, h: 3, minW: 4, minH: 2 },
bodyBattery: { label: 'Body Battery', w: 4, h: 3, minW: 3, minH: 2 },
vo2maxTrend: { label: 'VO₂ max trend', w: 3, h: 3, minW: 2, minH: 2 },
sleepDetail: { label: 'Sleep stages', w: 5, h: 3, minW: 3, minH: 2 },
weight: { label: 'Weight trend', w: 3, h: 3, minW: 2, minH: 2 },
featured: { label: 'Latest activity', w: 8, h: 5, minW: 4, minH: 3 },
recent: { label: 'Recent activities', w: 4, h: 5, minW: 3, minH: 3 },
prs: { label: 'Running PRs', w: 12, h: 2, minW: 4, minH: 2 },
}
// Default arrangement (used for new users and to migrate pre-redesign layouts).
const DEFAULT_LAYOUT = [
{ i: 'stat_steps', x: 0, y: 0, w: 2, h: 1 },
{ i: 'stat_resting_hr', x: 2, y: 0, w: 2, h: 1 },
{ i: 'stat_sleep', x: 4, y: 0, w: 2, h: 1 },
{ i: 'stat_vo2max', x: 6, y: 0, w: 2, h: 1 },
{ i: 'stat_hrv', x: 8, y: 0, w: 2, h: 1 },
{ i: 'stat_running', x: 10, y: 0, w: 2, h: 1 },
{ i: 'weekly', x: 0, y: 1, w: 6, h: 3 },
{ i: 'bodyBattery', x: 6, y: 1, w: 4, h: 3 },
{ i: 'featured', x: 0, y: 4, w: 8, h: 5 },
{ i: 'recent', x: 8, y: 4, w: 4, h: 5 },
{ i: 'prs', x: 0, y: 9, w: 12, h: 2 },
]
const attachMins = (lay) =>
lay.filter(l => WIDGETS[l.i]).map(l => ({ ...l, minW: WIDGETS[l.i].minW, minH: WIDGETS[l.i].minH }))
function buildLayout(saved) {
const known = (saved || []).filter(l => WIDGETS[l.i])
// Migrate old layouts (no stat_* widgets) or empty/missing to the new default.
const hasStats = known.some(l => l.i.startsWith('stat_'))
return attachMins(known.length && hasStats ? known : DEFAULT_LAYOUT)
}
// ── Reusable card shell ──────────────────────────────────────────────────────
function Card({ title, viewHref, children, className = '' }) {
return (
{title && (
{title}
{viewHref && View →}
)}
{children}
)
}
function Stat({ label, value }) {
return (
)
}
// ── Chart widgets ────────────────────────────────────────────────────────────
// Body Battery widget — wraps the shared BodyBatteryChart in a dashboard Card.
// The dashboard variant fills its grid cell (fill) and uses a compact y-axis.
function BodyBatteryToday({ bb, hires, sleepStart, sleepEnd, activities }) {
return (
)
}
function Sparkline({ data, dataKey, color, gradId, fmt }) {
return (
format(new Date(d), 'MMM d')}
formatter={v => [fmt ? fmt(v) : v, '']} />
)
}
function Vo2MaxTrend({ health, recentHealth, profile }) {
const series = useMemo(
() => [...(recentHealth || [])].filter(d => d.vo2max != null)
.sort((a, b) => new Date(a.date) - new Date(b.date))
.map(d => ({ date: d.date, v: d.vo2max })),
[recentHealth],
)
const color = vo2Color(health.vo2max, profile?.birth_year, profile?.biological_sex)
return (
{health.vo2max != null ? health.vo2max.toFixed(1) : '--'}
ml/kg/min
{health.fitness_age != null &&
Fitness age {health.fitness_age}
}
{series.length >= 2
?
v.toFixed(1)} />
: Not enough history
}
)
}
function WeightMini({ recentHealth }) {
const series = useMemo(
() => [...(recentHealth || [])].filter(d => d.weight_kg != null)
.sort((a, b) => new Date(a.date) - new Date(b.date))
.map(d => ({ date: d.date, w: +d.weight_kg.toFixed(2) })),
[recentHealth],
)
const latest = series.length ? series[series.length - 1].w : null
return (
{latest != null ? latest.toFixed(1) : '--'}
kg
{series.length >= 2
?
`${v.toFixed(1)} kg`} />
: Not enough history
}
)
}
// Canonical sleep-stage palette — matches the Health page hypnogram/charts.
const SLEEP_STAGES = [
{ key: 'sleep_deep_s', label: 'Deep', color: '#6366f1' },
{ key: 'sleep_rem_s', label: 'REM', color: '#7c3aed' },
{ key: 'sleep_light_s', label: 'Light', color: '#a78bfa' },
{ key: 'sleep_awake_s', label: 'Awake', color: '#eab308' },
]
function SleepDetail({ health, sleepStages }) {
const total = SLEEP_STAGES.reduce((s, st) => s + (health[st.key] || 0), 0)
const hasHypnogram = health.sleep_start && health.sleep_end && sleepStages?.length
return (
{formatSleep(health.sleep_duration_s)}
{health.sleep_score != null && (
score {Math.round(health.sleep_score)}
)}
{total > 0 ? (
<>
{SLEEP_STAGES.map(st => {
const pct = ((health[st.key] || 0) / total) * 100
if (pct < 0.5) return null
return
})}
{SLEEP_STAGES.map(st => (health[st.key] ? (
{st.label}
{formatSleep(health[st.key])}
) : null))}
{hasHypnogram && (
)}
>
) : (
No sleep stages for last night
)}
)
}
const sportLabel = s => (s ? s.charAt(0).toUpperCase() + s.slice(1) : 'Other')
function WeeklyChart({ activities }) {
const navigate = useNavigate()
const unit = useUnit()
const distLabel = distanceUnitLabel(unit)
const { data, sports } = useMemo(() => {
if (!activities?.length) return { data: [], sports: [] }
// Sports present, ordered by total distance (largest stacks at the bottom).
const totals = {}
for (const a of activities) totals[a.sport_type] = (totals[a.sport_type] || 0) + (a.distance_m || 0)
const sports = Object.keys(totals).sort((x, y) => totals[y] - totals[x])
const now = new Date()
const weeks = eachWeekOfInterval({ start: subWeeks(startOfWeek(now), 7), end: startOfWeek(now) })
const data = weeks.map(weekStart => {
const weekEnd = addDays(weekStart, 7)
const row = { week: format(weekStart, 'MMM d'), weekStartISO: format(weekStart, 'yyyy-MM-dd'), weekEndISO: format(weekEnd, 'yyyy-MM-dd') }
for (const s of sports) row[s] = 0
for (const a of activities) {
const t = new Date(a.start_time)
if (t >= weekStart && t < weekEnd) row[a.sport_type] += (a.distance_m || 0) / 1000
}
for (const s of sports) row[s] = +convertKm(row[s], unit).toFixed(2)
return row
})
return { data, sports }
}, [activities, unit])
return (
{data.length ? (
{ const p = e?.activePayload?.[0]?.payload; if (p) navigate(`/activities?from=${p.weekStartISO}&to=${p.weekEndISO}`) }}
style={{ cursor: 'pointer' }}>
`${v.toFixed(0)}`} />
[`${(+v).toFixed(1)} ${distLabel}`, sportLabel(name)]} />
{sports.map((s, i) => (
))}
) : (
No activities yet
)}
)
}
function FeaturedActivity({ activity, segments }) {
const unit = useUnit()
if (!activity) return (
No activities yet
)
return (
{activity.name}
{formatDate(activity.start_time)}
Open →
{activity.polyline
?
:
No GPS track
}
{segments?.length > 0 && (
Segments
Details →
{segments.map(seg => {
const isPodium = seg.rank && seg.rank <= 3
const delta = seg.best_s != null ? seg.duration_s - seg.best_s : null
return (
{seg.name}
{formatDuration(seg.duration_s)}
{isPodium ? {MEDALS[seg.rank]}
: delta != null ? +{formatDuration(delta)}
: -- }
)
})}
)}
)
}
function RecentActivities({ activities }) {
const unit = useUnit()
return (
{activities?.length ? (
// Rows flex to fill the card height so the list always fits exactly —
// no scrollbars (and never a spurious horizontal one). The visible count
// adapts to the widget's height rather than a fixed slice overflowing.
{activities.slice(0, 6).map(activity => (
{activity.name}
{activity.named_route_name && (
📍 {activity.named_route_name}
)}
{formatDate(activity.start_time)}
{formatDistance(activity.distance_m, unit)}
{formatHeartRate(activity.avg_heart_rate)}
))}
) : (
No activities yet — import some data
)}
)
}
const DASH_PR_LABELS = ['1k', '1 mile', '5k', '10k']
function RunningPRs({ records }) {
const byLabel = Object.fromEntries((records || []).map(r => [r.distance_label, r]))
return (
{DASH_PR_LABELS.map(label => {
const rec = byLabel[label]
return (
{label}
{rec ? formatDuration(rec.duration_s) : '--'}
)
})}
)
}
// ── Page ───────────────────────────────────────────────────────────────────
export default function DashboardPage() {
const { data: recentActivities } = useQuery({
queryKey: ['activities-recent'],
queryFn: () => api.get('/activities/', { params: { per_page: 10 } }).then(r => r.data),
})
const { data: allActivities } = useQuery({
queryKey: ['activities-all-chart'],
queryFn: () => api.get('/activities/', { params: { per_page: 100, from_date: subDays(new Date(), 60).toISOString() } }).then(r => r.data),
})
const { data: recentHealth } = useQuery({
queryKey: ['health-metrics', 'dash'],
queryFn: () => api.get('/health-metrics/', { params: { limit: 365 } }).then(r => r.data),
})
const { data: profile } = useQuery({
queryKey: ['profile'],
queryFn: () => api.get('/profile/').then(r => r.data),
})
const health = useMemo(() => {
const rows = [...(recentHealth || [])].sort((a, b) => new Date(b.date) - new Date(a.date))
const pick = f => rows.find(d => d[f] != null)?.[f] ?? null
const latest = rows[0] || {}
return {
date: rows[0]?.date ? rows[0].date.slice(0, 10) : null,
resting_hr: pick('resting_hr'),
sleep_duration_s: pick('sleep_duration_s'),
sleep_start: latest.sleep_start ?? null,
sleep_end: latest.sleep_end ?? null,
sleep_deep_s: latest.sleep_deep_s ?? null,
sleep_rem_s: latest.sleep_rem_s ?? null,
sleep_light_s: latest.sleep_light_s ?? null,
sleep_awake_s: latest.sleep_awake_s ?? null,
sleep_score: pick('sleep_score'),
hrv_nightly_avg: pick('hrv_nightly_avg'),
hrv_weekly_avg: pick('hrv_weekly_avg'),
hrv_status: pick('hrv_status'),
steps: pick('steps'),
vo2max: pick('vo2max'),
fitness_age: pick('fitness_age'),
avg_stress: pick('avg_stress'),
active_calories: pick('active_calories'),
floors_climbed: pick('floors_climbed'),
}
}, [recentHealth])
const { data: intraday } = useQuery({
queryKey: ['health-intraday-dash', health.date],
queryFn: () => api.get('/health-metrics/intraday', { params: { date: health.date } }).then(r => r.data),
enabled: !!health.date,
})
const { data: records } = useQuery({
queryKey: ['records-running'],
queryFn: () => api.get('/records/', { params: { sport_type: 'running' } }).then(r => r.data),
})
const { data: ytdStats } = useQuery({
queryKey: ['ytd-stats'],
queryFn: () => api.get('/activities/stats/ytd').then(r => r.data),
})
const featured = recentActivities?.[0]
const { data: featuredSegments } = useQuery({
queryKey: ['activity-segments', featured?.id],
queryFn: () => api.get(`/segments/by-activity/${featured.id}`).then(r => r.data),
enabled: !!featured?.id,
})
// ── Layout state ──────────────────────────────────────────────────────────
const unit = useUnit()
const isMobile = useIsMobile()
const [editMode, setEditMode] = useState(false)
const [addOpen, setAddOpen] = useState(false)
const [layout, setLayout] = useState(() => buildLayout(null))
const saveTimer = useRef(null)
const loadedRef = useRef(false)
useEffect(() => {
if (profile && !loadedRef.current) {
loadedRef.current = true
setLayout(buildLayout(profile.dashboard_layout))
}
}, [profile])
const qc = useQueryClient()
const stripLayout = (lay) => lay.map(({ i, x, y, w, h }) => ({ i, x, y, w, h }))
const saveLayout = useMutation({
mutationFn: (lay) => api.put('/profile/dashboard-layout', { layout: stripLayout(lay) }),
// Keep the cached profile in sync so re-mounting the page doesn't revert the layout.
onSuccess: (_d, lay) => qc.setQueryData(['profile'], p => (p ? { ...p, dashboard_layout: stripLayout(lay) } : p)),
})
const persist = (lay) => { clearTimeout(saveTimer.current); saveLayout.mutate(lay) }
const handleLayoutChange = (next) => {
const withMins = attachMins(next)
setLayout(withMins)
if (editMode) {
clearTimeout(saveTimer.current)
saveTimer.current = setTimeout(() => saveLayout.mutate(withMins), 700)
}
}
const addWidget = (id) => {
if (layout.some(l => l.i === id)) { setAddOpen(false); return }
const maxY = layout.reduce((m, l) => Math.max(m, l.y + l.h), 0)
const def = WIDGETS[id]
const next = attachMins([...layout, { i: id, x: 0, y: maxY, w: def.w, h: def.h }])
setLayout(next); persist(next); setAddOpen(false)
}
const removeWidget = (id) => { const next = layout.filter(l => l.i !== id); setLayout(next); persist(next) }
// Editing is desktop-only; drop out of edit mode if the viewport shrinks mid-edit.
useEffect(() => {
if (isMobile && editMode) { setEditMode(false); setAddOpen(false) }
}, [isMobile])
const finishEditing = () => { persist(layout); setEditMode(false); setAddOpen(false) }
const resetLayout = () => { const def = attachMins(DEFAULT_LAYOUT); setLayout(def); persist(def) }
const renderWidget = (id) => {
if (STAT_DEFS[id]) {
const d = STAT_DEFS[id]
// VO2 max is coloured dynamically by its current rating category.
const color = id === 'stat_vo2max'
? vo2Color(health.vo2max, profile?.birth_year, profile?.biological_sex)
: undefined
return
}
switch (id) {
case 'weekly': return
case 'bodyBattery': return
case 'vo2maxTrend': return
case 'sleepDetail': return
case 'weight': return
case 'featured': return
case 'recent': return
case 'prs': return
default: return null
}
}
const presentIds = new Set(layout.map(l => l.i))
const available = Object.keys(WIDGETS).filter(id => !presentIds.has(id))
// Single-column stack for phones: saved desktop layout read top-to-bottom,
// left-to-right; consecutive stat cards pair up into a 2-column grid.
const renderMobileStack = () => {
const sorted = [...layout].filter(l => WIDGETS[l.i]).sort((a, b) => a.y - b.y || a.x - b.x)
const groups = []
for (const l of sorted) {
const last = groups[groups.length - 1]
if (STAT_DEFS[l.i] && last?.stats) last.items.push(l)
else groups.push({ stats: !!STAT_DEFS[l.i], items: [l] })
}
// Content-driven widgets size themselves; chart widgets need the explicit
// height the grid normally provides (rowHeight=80, margin=16) or their
// ResponsiveContainers collapse.
const autoHeight = new Set(['sleepDetail', 'prs'])
return (
{groups.map((g, idx) =>
g.stats ? (
{g.items.map(l =>
{renderWidget(l.i)}
)}
) : (
{renderWidget(g.items[0].i)}
)
)}
)
}
return (
Dashboard
{editMode && (
setAddOpen(o => !o)}
className="text-sm font-medium px-3 py-1.5 rounded-lg bg-gray-800 hover:bg-gray-700 text-gray-200 transition-colors">
+ Add widget
{addOpen && (
{available.length === 0
?
All widgets are on the dashboard
: available.map(id => (
addWidget(id)}
className="block w-full text-left text-sm text-gray-300 hover:bg-gray-800 px-3 py-1.5 transition-colors">
{WIDGETS[id].label}
))}
)}
)}
{editMode && (
Reset layout
)}
{!isMobile && (
(editMode ? finishEditing() : setEditMode(true))}
className={`text-sm font-medium px-3 py-1.5 rounded-lg transition-colors ${
editMode ? 'bg-blue-600 hover:bg-blue-500 text-white' : 'bg-gray-800 hover:bg-gray-700 text-gray-200'
}`}>
{editMode ? '✓ Done' : '✎ Edit dashboard'}
)}
+ Import data
{editMode && (
Drag to move, drag a corner to resize, or remove a widget with ✕. Add widgets from the menu. Changes save automatically.
)}
{isMobile ? renderMobileStack() : (
{layout.filter(l => WIDGETS[l.i]).map(l => (
{editMode && (
removeWidget(l.i)}
className="widget-delete absolute -top-2 -right-2 z-20 w-6 h-6 flex items-center justify-center rounded-full bg-red-600 hover:bg-red-500 text-white text-xs shadow-lg"
title="Remove widget">✕
)}
{renderWidget(l.i)}
))}
)}
)
}