import { useState, useEffect, useRef } from 'react' import { Pencil, Trash2, Check, X } from 'lucide-react' import { api } from '../utils/api' import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, ReferenceLine } from 'recharts' import dayjs from 'dayjs' import 'dayjs/locale/de' dayjs.locale('de') function rollingAvg(arr, window=7) { return arr.map((d,i)=>{ const s=arr.slice(Math.max(0,i-window+1),i+1).map(x=>x.weight).filter(v=>v!=null) return s.length ? {...d, avg: Math.round(s.reduce((a,b)=>a+b,0)/s.length*10)/10} : d }) } export default function WeightScreen() { const [entries, setEntries] = useState([]) const [editing, setEditing] = useState(null) // {id, date, weight, note} const [newDate, setNewDate] = useState(dayjs().format('YYYY-MM-DD')) const [newWeight,setNewWeight]= useState('') const [newNote, setNewNote] = useState('') const [saving, setSaving] = useState(false) const [saved, setSaved] = useState(false) const load = () => api.listWeight(365).then(data => setEntries(data)) useEffect(()=>{ load() },[]) const handleSave = async () => { if (!newWeight) return setSaving(true) try { await api.upsertWeight(newDate, parseFloat(newWeight), newNote) setSaved(true); await load() setTimeout(()=>setSaved(false), 2000) setNewWeight(''); setNewNote('') } finally { setSaving(false) } } const handleUpdate = async () => { if (!editing) return await api.updateWeight(editing.id, editing.date, parseFloat(editing.weight), editing.note||'') setEditing(null); await load() } const handleDelete = async (id) => { if (!confirm('Eintrag löschen?')) return await api.deleteWeight(id); await load() } const sorted = [...entries].sort((a,b)=>a.date.localeCompare(b.date)) const withAvg = rollingAvg(sorted) const chartData = withAvg.map(d=>({date:dayjs(d.date).format('DD.MM'), weight:d.weight, avg:d.avg})) const weights = entries.map(e=>e.weight) const avgAll = weights.length ? Math.round(weights.reduce((a,b)=>a+b,0)/weights.length*10)/10 : null return (