import { useState, useEffect } from "react";
import { useRoute, useLocation } from "wouter";
import { useTranslation } from "react-i18next";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { User, Task } from "@shared/schema";
import { apiRequest } from "@/lib/queryClient";
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Sun, Moon, CheckCircle2, ArrowRight, ListTodo, Calendar as CalendarIcon, NotebookPen, BrainCircuit } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { useToast } from "@/hooks/use-toast";
import { triggerConfetti } from "@/lib/confetti";
import { Input } from "@/components/ui/input";
// Steps Configuration
const MORNING_STEPS = [
{ key: "review_yesterday", title: "Review Yesterday", description: "Did you complete everything?", icon: ListTodo },
{ key: "plan_today", title: "Plan Today", description: "What are your top 3 priorities?", icon: CalendarIcon },
{ key: "check_schedule", title: "Visualize Success", description: "Take a moment to visualize your day.", icon: BrainCircuit },
];
const EVENING_STEPS = [
{ key: "review_today", title: "Review Today", description: "Celebrate your wins!", icon: CheckCircle2 },
{ key: "plan_tomorrow", title: "Plan Tomorrow", description: "Set yourself up for success.", icon: CalendarIcon },
{ key: "clear_mind", title: "Clear Mind", description: "Jot down any lingering thoughts.", icon: NotebookPen },
];
export default function FocusRoutinePage() {
const { t } = useTranslation();
const [, setLocation] = useLocation();
const [match, params] = useRoute("/focus/routine/:type");
const type = params?.type as "morning" | "evening";
const [stepIndex, setStepIndex] = useState(0);
const queryClient = useQueryClient();
const { toast } = useToast();
// Prevent hydration mismatch or early render
if (!match || !['morning', 'evening'].includes(type)) {
return
Invalid routine type
;
}
const steps = type === "morning" ? MORNING_STEPS : EVENING_STEPS;
const currentStep = steps[stepIndex];
const { data: user } = useQuery({ queryKey: ["/api/user"] });
const { data: tasks } = useQuery({ queryKey: ["/api/tasks"] });
// Task Context
const overdueTasks = tasks?.filter(t => t.status !== 'done' && t.dueDate && new Date(t.dueDate) < new Date()) || [];
const todayTasks = tasks?.filter(t => t.status !== 'done' && ((t.dueDate && new Date(t.dueDate) <= new Date()) || !t.dueDate)) || [];
const completedToday = tasks?.filter(t => {
if (t.status !== 'done') return false;
// Check if completed today (approximate based on status update or we need 'completedAt' field which we don't strictly preserve in schema except via AuditLog, but let's assume 'done' tasks are relevant)
// Ideally we filter by 'last updated' or audit log, but for now just showing 'Done' tasks is okay as visual reinforcement.
return true;
}) || [];
const completeRoutineMutation = useMutation({
mutationFn: async () => {
await apiRequest("POST", `/api/user/routine/${type}/complete`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["/api/user"] });
if (type === 'evening') {
triggerConfetti(0.5, 0.5);
toast({ title: t('routine.dayComplete', "Day Complete! Sleep well.") });
setLocation('/achievements'); // Or dashboard
} else {
toast({ title: t('routine.dayStarted', "Have a great day!") });
setLocation('/');
}
},
onError: () => {
toast({ title: "Failed to complete routine", variant: "destructive" });
}
});
const handleNext = () => {
if (stepIndex < steps.length - 1) {
setStepIndex(stepIndex + 1);
} else {
completeRoutineMutation.mutate();
}
};
if (!user) return null;
const Icon = currentStep.icon;
return (
{type === "morning" ? : }
Step {stepIndex + 1} of {steps.length}
{currentStep.title}
{currentStep.description}
{/* DYNAMIC CONTENT BASED ON STEP */}
{currentStep.key === "review_yesterday" && (
{overdueTasks.length > 0 ? (
Overdue Tasks
{overdueTasks.map(t => (
-
{t.title}
))}
) : (
No overdue tasks from yesterday!
Great job staying on track.
)}
)}
{currentStep.key === "plan_today" && (
Your schedule for specific tasks:
{todayTasks.length > 0 ? (
{todayTasks.slice(0, 5).map(task => (
{task.title}
{task.estimatedDuration &&
{task.estimatedDuration}m}
))}
{todayTasks.length > 5 &&
and {todayTasks.length - 5} more...
}
) : (
No tasks specifically scheduled for today.
)}
💡 Tip: Pick just 3 absolute "Must Do" tasks for today.
)}
{currentStep.key === "review_today" && (
{completedToday.length}
Tasks Completed
"Small progress is still progress."
)}
{/* Default / Text Input Steps */}
{["clear_mind", "check_schedule", "plan_tomorrow"].includes(currentStep.key) && (
{currentStep.key === "clear_mind" && (
)}
{currentStep.key !== "clear_mind" && (
Take 2 minutes to {currentStep.title.toLowerCase()}.
)}
)}
);
}