'use client'; import React, { useState, useMemo } from 'react'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { QuitPlan, UsageEntry, UserPreferences } from '@/lib/storage'; import { Target, TrendingDown, ChevronDown, ChevronUp, Cigarette, Leaf } from 'lucide-react'; import { useTheme } from '@/lib/theme-context'; import { getTodayString } from '@/lib/date-utils'; import { cn } from '@/lib/utils'; interface SubstancePlanSectionProps { substance: 'nicotine' | 'weed'; plan: QuitPlan | null; usageData: UsageEntry[]; trackingStartDate: string | null; onGeneratePlan: () => void; isExpanded: boolean; onToggle: () => void; } function SubstancePlanSection({ substance, plan, usageData, trackingStartDate, onGeneratePlan, isExpanded, onToggle }: SubstancePlanSectionProps) { const { theme } = useTheme(); // 1. Data Processing const substanceUsage = useMemo(() => usageData.filter(e => e.substance === substance), [usageData, substance]); const uniqueDaysWithData = useMemo(() => new Set(substanceUsage.map(e => e.date)).size, [substanceUsage]); const daysRemaining = Math.max(0, 7 - uniqueDaysWithData); const totalUsage = substanceUsage.reduce((sum, e) => sum + e.count, 0); const currentAverage = uniqueDaysWithData > 0 ? Math.round(totalUsage / uniqueDaysWithData) : 0; // 2. Unlock Logic const isUnlocked = useMemo(() => { if (!trackingStartDate || uniqueDaysWithData < 7) return false; const [y, m, d] = trackingStartDate.split('-').map(Number); const startObj = new Date(y, m - 1, d); const now = new Date(); const todayObj = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const daysPassed = Math.floor((todayObj.getTime() - startObj.getTime()) / (1000 * 60 * 60 * 24)); return daysPassed >= 7 || uniqueDaysWithData > 7; }, [uniqueDaysWithData, trackingStartDate]); // 3. Plan Validation & Calculations const isValidPlan = plan && plan.startDate && plan.weeklyTargets && Array.isArray(plan.weeklyTargets); const activePlan = isValidPlan ? plan : null; const todayStr = getTodayString(); const todayUsage = substanceUsage .filter(e => e.date === todayStr) .reduce((sum, e) => sum + e.count, 0); let weekNumber = 0; let currentTarget = 0; let totalWeeks = 0; let usagePercent = 0; if (activePlan) { const startDate = new Date(activePlan.startDate); const today = new Date(); weekNumber = Math.floor((today.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24 * 7)) + 1; totalWeeks = activePlan.weeklyTargets.length; currentTarget = weekNumber <= totalWeeks ? activePlan.weeklyTargets[weekNumber - 1] : 0; usagePercent = currentTarget > 0 ? (todayUsage / currentTarget) * 100 : 0; } // 4. Styling const isNicotine = substance === 'nicotine'; const Icon = isNicotine ? Cigarette : Leaf; const label = isNicotine ? 'Nicotine' : 'Weed'; // Base Colors const bgColor = isNicotine ? (theme === 'light' ? 'bg-yellow-500/10' : 'bg-yellow-500/5') : (theme === 'light' ? 'bg-emerald-500/10' : 'bg-emerald-500/5'); const borderColor = isNicotine ? (theme === 'light' ? 'border-yellow-500/20' : 'border-yellow-500/10') : (theme === 'light' ? 'border-emerald-500/20' : 'border-emerald-500/10'); const accentColor = isNicotine ? 'text-yellow-500' : 'text-emerald-500'; const progressFill = isNicotine ? 'bg-yellow-500' : 'bg-emerald-500'; // Specific plan color for the progress bar alert states let progressColor = progressFill; if (activePlan) { if (usagePercent >= 100) progressColor = 'bg-red-500'; else if (usagePercent >= 80) progressColor = isNicotine ? 'bg-orange-400' : 'bg-yellow-400'; } return (
{/* HEADER / SUMMARY ROW */}

{label} Plan

{activePlan ? `Week ${Math.min(weekNumber, totalWeeks)} of ${totalWeeks}` : `Tracking: Day ${uniqueDaysWithData}/7`}

Today = 100 ? "text-red-500" : accentColor)}> {todayUsage}{activePlan ? ` / ${currentTarget}` : ''}
{isExpanded ? : }
{/* EXPANDED CONTENT */} {isExpanded && (
{!activePlan ? (
Weekly Baseline Progress {daysRemaining > 0 ? `${daysRemaining} days left` : 'Ready!'}
{isUnlocked ? (

Baseline established: {currentAverage} puffs/day

) : (

Keep logging for {daysRemaining} more days to calculate your personalized reduction plan.

)}
) : (
{/* Active Plan Detail */}

Current Daily Limit

{currentTarget}

puffs allowed today

{/* Progress Bar Detail */}
Usage Progress {Math.round(usagePercent)}%
{/* Weekly Matrix */}
{activePlan.weeklyTargets.map((target, idx) => { const wNum = idx + 1; const isFuture = wNum > weekNumber; const isCurrent = wNum === weekNumber; return (

Wk {wNum}

{isFuture ? '?' : target}

); })}
Start: {activePlan.baselineAverage}/day End: {new Date(activePlan.endDate).toLocaleDateString()}
)}
)}
); } interface UnifiedQuitPlanCardProps { preferences: UserPreferences | null; usageData: UsageEntry[]; onGeneratePlan: (substance: 'nicotine' | 'weed') => void; refreshKey: number; } export function UnifiedQuitPlanCard({ preferences, usageData, onGeneratePlan, refreshKey }: UnifiedQuitPlanCardProps) { const [expandedSubstance, setExpandedSubstance] = useState<'nicotine' | 'weed' | 'none'>('nicotine'); if (!preferences) return null; // Determine which substances to show const showNicotine = preferences.substance === 'nicotine' || usageData.some(e => e.substance === 'nicotine'); const showWeed = preferences.substance === 'weed' || usageData.some(e => e.substance === 'weed'); if (!showNicotine && !showWeed) return null; return ( Quit Journey Plan {showNicotine && ( setExpandedSubstance(expandedSubstance === 'nicotine' ? 'none' : 'nicotine')} plan={preferences.quitState?.nicotine?.plan || (preferences.substance === 'nicotine' ? preferences.quitPlan : null)} usageData={usageData} trackingStartDate={ preferences.quitState?.nicotine?.startDate || (preferences.substance === 'nicotine' ? preferences.trackingStartDate : null) || usageData.filter(e => e.substance === 'nicotine').sort((a, b) => a.date.localeCompare(b.date))[0]?.date || null } onGeneratePlan={() => onGeneratePlan('nicotine')} /> )} {showWeed && ( setExpandedSubstance(expandedSubstance === 'weed' ? 'none' : 'weed')} plan={preferences.quitState?.weed?.plan || (preferences.substance === 'weed' ? preferences.quitPlan : null)} usageData={usageData} trackingStartDate={ preferences.quitState?.weed?.startDate || (preferences.substance === 'weed' ? preferences.trackingStartDate : null) || usageData.filter(e => e.substance === 'weed').sort((a, b) => a.date.localeCompare(b.date))[0]?.date || null } onGeneratePlan={() => onGeneratePlan('weed')} /> )} ); }