"use client"; import { useEffect, useState } from "react"; import { Card, CardContent } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"; import { MoreHorizontal, Pencil, Trash2, Flame } from "lucide-react"; import { toast } from "sonner"; interface Habit { id: string; name: string; description?: string; domain: string; frequency?: string; difficulty?: string; streak?: number; } export function HabitCard() { const [habits, setHabits] = useState([]); const [domainMap, setDomainMap] = useState>(new Map()); const [loading, setLoading] = useState(true); const [deleteId, setDeleteId] = useState(null); const [deleting, setDeleting] = useState(false); const [editing, setEditing] = useState(null); useEffect(() => { fetchHabits(); fetchDomains(); }, []); async function fetchHabits() { try { const res = await fetch("/api/habits?sort=-created"); const data = await res.json(); setHabits(data.items || []); } catch { toast.error("Unable to load habits"); } finally { setLoading(false); } } async function fetchDomains() { try { const res = await fetch("/api/domains?sort=sort_order"); const data = await res.json(); const map = new Map(); for (const d of data.items || []) map.set(d.id, d.name); setDomainMap(map); } catch {} } async function handleDelete(id: string) { setDeleting(true); try { const res = await fetch(`/api/habits/${id}`, { method: "DELETE" }); if (!res.ok) throw new Error(); toast.success("Habit deleted"); setHabits((h) => h.filter((x) => x.id !== id)); } catch { toast.error("Unable to delete habit"); } finally { setDeleting(false); setDeleteId(null); } } if (loading) return

Loading habits...

; return ( <>
{habits.map((habit) => (
{habit.name} {habit.streak && habit.streak > 0 && ( {habit.streak} )}
{domainMap.get(habit.domain) || habit.domain} {habit.frequency && {habit.frequency}} {habit.difficulty && {habit.difficulty}}
setEditing(habit)}> Edit setDeleteId(habit.id)}> Delete
))}
!o && setDeleteId(null)}> Delete habit? This cannot be undone. Cancel deleteId && handleDelete(deleteId)} disabled={deleting}>{deleting ? "Deleting..." : "Delete"} ); }