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 UsageBadge from '../components/UsageBadge' 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 [error, setError] = useState(null) const [weightUsage, setWeightUsage] = useState(null) // Phase 3: Usage badge const load = () => api.listWeight(365).then(data => setEntries(data)) const loadUsage = () => { // Load feature usage for badge api.getFeatureUsage().then(features => { const weightFeature = features.find(f => f.feature_id === 'weight_entries') setWeightUsage(weightFeature) }).catch(err => console.error('Failed to load usage:', err)) } useEffect(()=>{ load() loadUsage() },[]) const handleSave = async () => { if (!newWeight) return setSaving(true) setError(null) try { await api.upsertWeight(newDate, parseFloat(newWeight), newNote) setSaved(true) await load() await loadUsage() // Reload usage after save setTimeout(()=>setSaved(false), 2000) setNewWeight(''); setNewNote('') } catch (err) { console.error('Save failed:', err) setError(err.message || 'Fehler beim Speichern') setTimeout(()=>setError(null), 5000) } 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 (
Noch keine Einträge.
} {entries.map((e,i)=>{ const prev = entries[i+1] const delta = prev ? Math.round((e.weight-prev.weight)*10)/10 : null const isEditing = editing?.id===e.id return (