'use client'; import { useState, useEffect } from 'react'; import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, LineChart, Line, CartesianGrid } from 'recharts'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { BarChart3, TrendingUp } from 'lucide-react'; interface HabitAnalyticsProps { domainId: string; habits: { id: string; name: string }[]; } interface StreakItem { habitId: string; habitName: string; currentStreak: number; bestStreak: number; } interface CompletionDay { date: string; count: number; } export function HabitAnalytics({ domainId, habits }: HabitAnalyticsProps) { const [open, setOpen] = useState(false); const [streaks, setStreaks] = useState([]); const [completions, setCompletions] = useState([]); const [loading, setLoading] = useState(false); useEffect(() => { if (!open) return; setLoading(true); Promise.all([ fetch('/api/habits/streaks').then((r) => r.json()), ...habits.map((h) => fetch( '/api/domains/' + domainId + '/habits/' + h.id + '/completions?from=' + daysAgo(30) + '&order=asc&limit=365' ).then((r) => r.json()) ), ]) .then(([streaksData, ...completionsData]) => { setStreaks((streaksData.streaks || []).slice(0, 5)); const dateMap = new Map(); for (const data of completionsData) { for (const item of data.items || []) { const d = item.date?.split('T')[0]; if (d) dateMap.set(d, (dateMap.get(d) || 0) + 1); } } const sorted = Array.from(dateMap.entries()) .sort(([a], [b]) => a.localeCompare(b)) .map(([date, count]) => ({ date, count })); setCompletions(sorted); }) .catch(() => {}) .finally(() => setLoading(false)); }, [open, domainId, habits]); if (!open) { return ( ); } return (

Analytics (30 days)

{loading ? (

Loading analytics...

) : (
Daily Completions {completions.length === 0 ? (

No data yet

) : ( v.slice(5)} /> )}
Top Streaks {streaks.length === 0 ? (

No streaks yet

) : ( )}
)}
); } function daysAgo(n: number): string { const d = new Date(); d.setDate(d.getDate() - n); return d.toISOString().split('T')[0]; }