'use client' import { useState, useEffect, useCallback, useMemo } from 'react' import { useRouter } from 'next/navigation' import { History, Scale } from 'lucide-react' import { useLiveQuery } from 'dexie-react-hooks' import { db } from '@/lib/sync' import { Card, LoadingState } from '@/components/ui' import { Header, PageContainer } from '@/components/layout/header' import { WeightQuickLog } from '@/components/weight/WeightQuickLog' import { WeightCard } from '@/components/weight/WeightCard' import { WeightChart } from '@/components/weight/WeightChart' import { WeightAlert } from '@/components/weight/WeightAlert' import { useApp } from '../provider' export default function WeightPage() { const router = useRouter() const { currentWorkspace, refreshData } = useApp() const [serverData, setServerData] = useState([]) const [loading, setLoading] = useState(true) const localData = useLiveQuery( () => db.weightLogs .where('workspaceId') .equals(currentWorkspace.id) .and((w) => !w.deletedAt) .reverse() .limit(100) .toArray(), [currentWorkspace.id] ) const fetchData = useCallback(async () => { try { const response = await fetch(`/api/workspaces/${currentWorkspace.id}/weight?limit=100`) if (response.ok) { const data = await response.json() setServerData(data.weightLogs) } } catch (err) { console.error('Failed to fetch weight logs:', err) } finally { setLoading(false) } }, [currentWorkspace.id]) useEffect(() => { fetchData() }, [fetchData]) const handleLogged = () => { fetchData() refreshData() } const readings = useMemo( () => (serverData.length > 0 ? serverData : localData || []), [serverData, localData] ) // Check for rapid weight change const rapidChange = useMemo(() => { if (readings.length < 2) return null const latest = readings[0] const previous = readings[1] const hoursDiff = (new Date(latest.recordedAt).getTime() - new Date(previous.recordedAt).getTime()) / (1000 * 60 * 60) if (hoursDiff <= 48 && Math.abs(latest.weightKg - previous.weightKg) >= 2) { return { currentKg: latest.weightKg, previousKg: previous.weightKg, timeframeHours: Math.round(hoursDiff) } } return null }, [readings]) if (loading && !localData) { return ( <>
) } return ( <>
, label: 'History', onClick: () => router.push('/weight/history'), }} /> {/* Rapid Change Alert */} {rapidChange && ( )} {/* Quick Log */}

Log Weight

{/* 30-Day Trend */} {readings.length >= 2 && (

30-Day Trend

({ weightKg: r.weightKg, recordedAt: r.recordedAt }))} />
)} {/* Recent Readings */}

Recent

{readings.length === 0 ? (

No weight readings yet

Use the form above to track your weight

) : (
{readings.slice(0, 5).map((reading: any, i: number) => ( ))}
)}
) }