import { useState, useEffect } from 'react' import { api } from '../utils/api' import { Target, TrendingUp, Calendar, CheckCircle2, AlertCircle } from 'lucide-react' import dayjs from 'dayjs' export default function CustomGoalsPage() { const [customGoals, setCustomGoals] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [selectedGoal, setSelectedGoal] = useState(null) const [formData, setFormData] = useState({ date: new Date().toISOString().split('T')[0], value: '', note: '' }) const [recentProgress, setRecentProgress] = useState([]) useEffect(() => { loadCustomGoals() }, []) const loadCustomGoals = async () => { try { setLoading(true) const grouped = await api.listGoalsGrouped() // Extract all goals and filter for custom only (no source_table) const allGoals = Object.values(grouped).flat() const custom = allGoals.filter(g => !g.source_table) setCustomGoals(custom) setError(null) } catch (err) { console.error('Failed to load custom goals:', err) setError(err.message || 'Fehler beim Laden') } finally { setLoading(false) } } const loadRecentProgress = async (goalId) => { try { const entries = await api.listGoalProgress(goalId) setRecentProgress(entries.slice(0, 5)) // Last 5 entries } catch (err) { console.error('Failed to load progress:', err) setRecentProgress([]) } } const handleSelectGoal = async (goal) => { setSelectedGoal(goal) setFormData({ date: new Date().toISOString().split('T')[0], value: goal.current_value || '', note: '' }) await loadRecentProgress(goal.id) } const handleSaveProgress = async () => { if (!formData.value || !formData.date) { setError('Bitte Datum und Wert eingeben') return } try { const data = { date: formData.date, value: parseFloat(formData.value), note: formData.note || null } await api.createGoalProgress(selectedGoal.id, data) // Reset form and reload setFormData({ date: new Date().toISOString().split('T')[0], value: '', note: '' }) await loadCustomGoals() await loadRecentProgress(selectedGoal.id) // Update selected goal with new current_value const updated = customGoals.find(g => g.id === selectedGoal.id) if (updated) setSelectedGoal(updated) setError(null) } catch (err) { console.error('Failed to save progress:', err) setError(err.message || 'Fehler beim Speichern') } } const getProgressPercentage = (goal) => { if (!goal.current_value || !goal.target_value) return 0 const current = parseFloat(goal.current_value) const target = parseFloat(goal.target_value) const start = parseFloat(goal.start_value) || 0 if (goal.direction === 'decrease') { return Math.min(100, Math.max(0, ((start - current) / (start - target)) * 100)) } else { return Math.min(100, Math.max(0, ((current - start) / (target - start)) * 100)) } } if (loading) { return (