import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import type { ReactNode } from 'react'; import type { ChecklistItem, UserChecklistProgress } from '@cra-compliance/types'; import { wpApiFetch, errorMessage } from '../hooks/useApi'; import { CHECKLIST, CHECKLIST_TOTAL } from '../content/checklist'; interface ComplianceContextType { progress: Record; loading: boolean; loadError: string | null; reload: () => void; toggleItem: (item: ChecklistItem) => Promise; saveNotes: (itemId: string, notes: string) => Promise; savingItemId: string | null; savingNotesId: string | null; totalItems: number; completedItems: number; compliancePercent: number; } const ComplianceContext = createContext(null); const KNOWN_IDS = new Set(CHECKLIST.flatMap((category) => category.items.map((item) => item.id))); export function ComplianceProvider({ children }: { children: ReactNode }) { const [progress, setProgress] = useState>({}); const [loading, setLoading] = useState(true); const [loadError, setLoadError] = useState(null); const [savingItemId, setSavingItemId] = useState(null); const [savingNotesId, setSavingNotesId] = useState(null); const progressRef = useRef(progress); progressRef.current = progress; const load = useCallback(() => { setLoading(true); setLoadError(null); wpApiFetch<{ data: Record | [] }>('checklist') .then((res) => setProgress(Array.isArray(res.data) ? {} : res.data || {})) .catch((error: unknown) => setLoadError(errorMessage(error, 'Checklist progress could not be loaded.'))) .finally(() => setLoading(false)); }, []); useEffect(load, [load]); const toggleItem = useCallback(async (item: ChecklistItem) => { const current = progressRef.current[item.id]; const completed = !(current?.completed ?? false); setSavingItemId(item.id); try { await wpApiFetch(`checklist/${item.id}`, { method: 'POST', body: JSON.stringify({ completed, notes: current?.notes || '' }), }); setProgress((prev) => ({ ...prev, [item.id]: { item_id: item.id, completed, completed_at: completed ? new Date().toISOString() : null, notes: prev[item.id]?.notes || '', }, })); } finally { setSavingItemId(null); } }, []); const saveNotes = useCallback(async (itemId: string, notes: string) => { setSavingNotesId(itemId); try { const completed = progressRef.current[itemId]?.completed || false; await wpApiFetch(`checklist/${itemId}`, { method: 'POST', body: JSON.stringify({ completed, notes }), }); setProgress((prev) => ({ ...prev, [itemId]: { item_id: itemId, completed, completed_at: prev[itemId]?.completed_at ?? null, notes, }, })); } finally { setSavingNotesId(null); } }, []); const completedItems = useMemo( () => Object.values(progress).filter((entry) => entry.completed && KNOWN_IDS.has(entry.item_id)).length, [progress], ); const compliancePercent = CHECKLIST_TOTAL > 0 ? Math.round((completedItems / CHECKLIST_TOTAL) * 100) : 0; const value = useMemo(() => ({ progress, loading, loadError, reload: load, toggleItem, saveNotes, savingItemId, savingNotesId, totalItems: CHECKLIST_TOTAL, completedItems, compliancePercent, }), [progress, loading, loadError, load, toggleItem, saveNotes, savingItemId, savingNotesId, completedItems, compliancePercent]); return {children}; } export function useCompliance() { const context = useContext(ComplianceContext); if (!context) throw new Error('useCompliance must be used within a ComplianceProvider'); return context; }