diff --git a/apps/web/features/study-logs/presentation/cockpit/cockpit-task-menu.tsx b/apps/web/features/study-logs/presentation/cockpit/cockpit-task-menu.tsx index 6b5ecb3..4714727 100644 --- a/apps/web/features/study-logs/presentation/cockpit/cockpit-task-menu.tsx +++ b/apps/web/features/study-logs/presentation/cockpit/cockpit-task-menu.tsx @@ -18,10 +18,13 @@ import { } from "@/features/study-logs/domain/challenge-day"; import { isWeeklyTaskGraceExpired } from "@/features/tasks/domain/task-lock"; import type { TaskStatus } from "@/features/tasks/domain/task.types"; -import type { TaskItem, CategoryGroup } from "./cockpit-tasks-section"; +import type { + BoardCategory, + BoardTask, +} from "@/features/tasks/presentation/task-board/task-board.types"; interface TaskMenuItemsProps { - task: TaskItem; + task: BoardTask; catIdx: number; taskType: "daily" | "weekly"; effectiveTodayDate: string; @@ -339,10 +342,10 @@ export function TaskMenuItems({ } interface CategoryMenuItemsProps { - cat: CategoryGroup; + cat: BoardCategory; catType: "daily" | "weekly"; - dailyCategories: CategoryGroup[]; - weeklyCategories: CategoryGroup[]; + dailyCategories: BoardCategory[]; + weeklyCategories: BoardCategory[]; selectedDateKey: string; effectiveTodayDate: string; dayOptions: ChallengeDayOption[]; diff --git a/apps/web/features/study-logs/presentation/cockpit/cockpit-tasks-section.tsx b/apps/web/features/study-logs/presentation/cockpit/cockpit-tasks-section.tsx index 4f979d5..f693bc2 100644 --- a/apps/web/features/study-logs/presentation/cockpit/cockpit-tasks-section.tsx +++ b/apps/web/features/study-logs/presentation/cockpit/cockpit-tasks-section.tsx @@ -1,7467 +1 @@ -"use client"; - -import { useState, useEffect, useRef, useMemo, useCallback } from "react"; -import { - ChevronDown, - ChevronUp, - Check, - X, - Trash2, - MoreVertical, - Pencil, - GripVertical, - RotateCcw, - Calendar, - Lock, - ArrowRight, - Trophy, - User, - Plus, -} from "lucide-react"; -import { - getChallengeDayOptions, - getCalendarWeekDayOptions, - getAdjacentWeekAnchor, - formatWeekRange, - formatDayDate, - isChallengeDayDateLocked, - isSameCalendarWeek, - validateMoveTaskChallengeDay, - type ChallengeDayOption, -} from "@/features/study-logs/domain/challenge-day"; -import { - calculateReorderIndex, - moveCategoryBetweenColumns, - moveCategoryToDay, - moveTaskBetweenCategories, -} from "@/features/tasks/domain/task-reorder"; -import { - getCollapsedCategoriesStorageKey, - isCategoryCollapsed, - readCollapsedCategoryIds, - toggleCategoryCollapseKey, - writeCollapsedCategoryIds, - isRolloverSnoozedForDate, - setRolloverSnoozedForDate, - cleanupExpiredRolloverSnooze, - ROLLOVER_SNOOZE_COOKIE, - ROLLOVER_SNOOZE_STORAGE_PREFIX, -} from "./cockpit-tasks-storage"; -import { TaskExportButton } from "@/features/tasks/presentation/task-export-button"; -import { - formatDailyTasksExport, - formatWeeklyTasksExport, - formatFullDayDate, - type TaskExportStyle, -} from "@/features/tasks/domain/task-export"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; -import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog"; -import { - Select, - SelectContent, - SelectGroup, - SelectItem, - SelectLabel, - SelectTrigger, - SelectValue, -} from "@/components/ui/select"; -import { - DropdownMenu, - DropdownMenuTrigger, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuSeparator, - DropdownMenuLabel, -} from "@/components/ui/dropdown-menu"; -import { - ContextMenu, - ContextMenuTrigger, - ContextMenuContent, - ContextMenuItem, - ContextMenuSeparator, - ContextMenuLabel, -} from "@/components/ui/context-menu"; -import { TaskMenuItems, CategoryMenuItems } from "./cockpit-task-menu"; -import { CockpitWeekNavigator } from "./cockpit-date-picker-popover"; -import { cn } from "@/lib/utils"; -import { triggerTaskConfetti } from "@/lib/confetti"; -import { playCompletionAudio } from "@/features/preferences/presentation/audio-service"; -import { trackLogRocketEvent } from "@/core/observability/logrocket"; -import { - applyRolloverToCategories, - findRolloverCandidates, - getRolloverSummary, -} from "@/features/tasks/domain/task-rollover"; -import { - canScopeTaskToChallenge, - countScopedTasks, - getTaskScope, - type TaskScope, -} from "@/features/tasks/domain/task-scope"; -import { buildTaskEditPatch } from "@/features/tasks/domain/task-edit-patch"; -import { isWeeklyTaskGraceExpired } from "@/features/tasks/domain/task-lock"; -import type { - TaskStatus, - UserCategorizedTasks, -} from "@/features/tasks/domain/task.types"; -import { - commitCategoryMutation, - commitLocalBatch, - commitTaskBatch, - commitTaskMutation, - deleteLocalCategory, - deleteLocalTask, - getAllLocalCategories, - getAllLocalTasks, - getQueuedMutationsForUser, - logTaskSync, - putLocalCategories, - putLocalCategory, - putLocalTask, - putLocalTasks, -} from "@/features/tasks/data/local/task-idb"; -import { - initTaskSync, - scheduleSync, - TASKS_SYNCED_EVENT, -} from "@/features/tasks/data/local/task-sync.service"; -import { TaskSyncIssueBanner } from "@/features/tasks/presentation/task-sync-issue-banner"; -import type { - LocalCategoryRecord, - LocalTaskRecord, - QueuedMutation, -} from "@/features/tasks/domain/task-sync.types"; - -export interface TaskItem { - id: string; - text: string; - completed: boolean; - status?: TaskStatus; - dueDate?: string | null; - createdAt?: string; - challengeId?: string | null; -} - -/** Derives the presentation status for a task item. */ -export function getTaskStatus(task: TaskItem): TaskStatus { - if (task.status) return task.status; - return task.completed ? "COMPLETED" : "TODO"; -} - -function isWeeklyTaskVisible( - task: TaskItem, - completedChallengeIds: Set -): boolean { - return !(task.challengeId && completedChallengeIds.has(task.challengeId)); -} - -export { formatDayDate }; - -export const SAMPLE_STUDY_TASKS = [ - "Complete 2h Deep Work block", - "Link YPT account", - "Join an active Study Challenge", -] as const; - -export const LOAD_SAMPLE_TASK_EVENT = "holdmetoit:load-sample-task"; - -export interface CategoryGroup { - id?: string; - name: string; - isCollapsed: boolean; - sortOrder?: number; - createdAt?: string | Date; - updatedAt?: string | Date; - tasks: TaskItem[]; -} - -export interface CockpitTasksSectionProps { - isLoggedIn: boolean; - userId?: string | null; - userTasks?: UserCategorizedTasks | null; - completedChallengeIds?: string[]; - challengeStartDate?: string; - challengeId?: string; - challengeStatus?: "UPCOMING" | "ACTIVE" | "COMPLETED"; - todayDate?: string; - todayDayNumber?: number; - totalChallengeDays?: number; - initialSelectedDateKey?: string; - onOpenHoursModal?: (dayNumber?: number) => void; - isAdmin?: boolean; - initialCollapsedCategoryIds?: string[]; - initialIsRolloverSnoozed?: boolean; -} - -/** Renders the participant's categorized task board and task actions. */ -export function CockpitTasksSection({ - isLoggedIn, - userId, - userTasks, - completedChallengeIds, - challengeStartDate, - challengeId, - challengeStatus, - todayDate, - todayDayNumber, - totalChallengeDays = 7, - initialSelectedDateKey, - onOpenHoursModal, - isAdmin = false, - initialCollapsedCategoryIds, - initialIsRolloverSnoozed, -}: CockpitTasksSectionProps) { - const persistTask = useCallback( - ( - task: LocalTaskRecord, - mutation: Omit - ): Promise => - isLoggedIn && userId - ? commitTaskMutation(task, { ...mutation, userId }) - : putLocalTask(task), - [isLoggedIn, userId] - ); - - const persistTasks = useCallback( - ( - tasks: LocalTaskRecord[], - mutation: Omit - ): Promise => - isLoggedIn && userId - ? commitTaskBatch(tasks, { ...mutation, userId }) - : putLocalTasks(tasks), - [isLoggedIn, userId] - ); - - const persistCategory = useCallback( - ( - category: LocalCategoryRecord, - mutation: Omit - ): Promise => - isLoggedIn && userId - ? commitCategoryMutation(category, { ...mutation, userId }) - : putLocalCategory(category), - [isLoggedIn, userId] - ); - - const deleteTaskWithMutation = useCallback( - ( - taskId: string, - mutation: Omit - ): Promise => - isLoggedIn && userId - ? commitTaskMutation( - null, - { ...mutation, userId }, - { - deleteTaskId: taskId, - } - ) - : deleteLocalTask(taskId), - [isLoggedIn, userId] - ); - - const deleteCategoryWithMutation = useCallback( - ( - categoryId: string, - mutation: Omit - ): Promise => - isLoggedIn && userId - ? commitCategoryMutation( - null, - { ...mutation, userId }, - { - deleteCategoryId: categoryId, - } - ) - : deleteLocalCategory(categoryId), - [isLoggedIn, userId] - ); - - const linkableChallengeId = - challengeId && challengeStatus !== "COMPLETED" ? challengeId : null; - const isChallengeActive = challengeStatus - ? challengeStatus === "ACTIVE" - : Boolean(challengeStartDate); - const hasChallengeContext = Boolean( - (challengeStartDate || (challengeStatus === "ACTIVE" && todayDate)) && - isChallengeActive - ); - const effectiveStartDate = - challengeStartDate || (hasChallengeContext ? todayDate : undefined); - const [addModalType, setAddModalType] = useState<"daily" | "weekly" | null>( - null - ); - const [newTodoText, setNewTodoText] = useState(""); - const [selectedCategory, setSelectedCategory] = useState(""); - const [customCategory, setCustomCategory] = useState(""); - const [isCreatingCategory, setIsCreatingCategory] = useState(false); - const [newTodoStatus, setNewTodoStatus] = useState("TODO"); - const [addTodoDateKey, setAddTodoDateKey] = useState(""); - const [expandedTaskIds, setExpandedTaskIds] = useState>( - () => new Set() - ); - const [mobileActiveTab, setMobileActiveTab] = useState<"daily" | "weekly">( - "daily" - ); - - const toggleTaskExpand = (taskId: string, e?: React.MouseEvent) => { - e?.preventDefault(); - e?.stopPropagation(); - setExpandedTaskIds((prev) => { - const next = new Set(prev); - if (next.has(taskId)) { - next.delete(taskId); - } else { - next.add(taskId); - } - return next; - }); - }; - - const categoryInputRef = useRef(null); - const categorySelectRef = useRef(null); - - useEffect(() => { - if (isCreatingCategory && addModalType) { - const timer = setTimeout(() => { - categoryInputRef.current?.focus(); - categoryInputRef.current?.select(); - }, 50); - return () => clearTimeout(timer); - } - }, [isCreatingCategory, addModalType]); - - // Edit Task Modal State - const [editTaskModal, setEditTaskModal] = useState<{ - id: string; - text: string; - completed: boolean; - status: TaskStatus; - dueDate?: string | null; - createdAt?: string; - challengeId?: string | null; - catIdx: number; - taskType: "daily" | "weekly"; - } | null>(null); - const [editTaskInputText, setEditTaskInputText] = useState(""); - const [editTaskInputStatus, setEditTaskInputStatus] = - useState("TODO"); - const [editTaskInputDueDate, setEditTaskInputDueDate] = useState(""); - const [editTaskInputChallengeId, setEditTaskInputChallengeId] = useState< - string | null - >(null); - const isEditTaskGraceLocked = Boolean( - editTaskModal && - isWeeklyTaskGraceExpired({ - taskType: editTaskModal.taskType === "weekly" ? "WEEKLY" : "DAILY", - challengeId: editTaskModal.challengeId, - createdAt: editTaskModal.createdAt ?? new Date(), - }) - ); - const [addTodoChallengeScope, setAddTodoChallengeScope] = - useState("CHALLENGE"); - const [isRolloverDismissed, setIsRolloverDismissed] = useState(false); - - // Edit Category Modal State - const [editCategoryModal, setEditCategoryModal] = useState<{ - id?: string; - name: string; - taskType: "daily" | "weekly"; - } | null>(null); - const [editCategoryInputName, setEditCategoryInputName] = useState(""); - - // Delete Category Confirmation Modal State - const [deleteCategoryModal, setDeleteCategoryModal] = useState<{ - id?: string; - name: string; - taskType: "daily" | "weekly"; - } | null>(null); - - // Drag and Drop State - const [draggedItem, setDraggedItem] = useState<{ - type: "task" | "category"; - id?: string; - sourceCatIdx: number; - sourceColumn: "daily" | "weekly"; - sourceDateKey?: string; - } | null>(null); - - const [dragOverInfo, setDragOverInfo] = useState<{ - type: "task" | "category" | "column" | "day"; - targetId?: string; - targetCatIdx?: number; - targetColumn?: "daily" | "weekly"; - targetDateKey?: string; - position?: "above" | "below"; - } | null>(null); - - const [collapsedCategoryIds, setCollapsedCategoryIds] = useState< - Set - >(() => { - if (initialCollapsedCategoryIds !== undefined) { - return new Set( - initialCollapsedCategoryIds.filter( - (k) => - typeof k === "string" && - (k.startsWith("daily:") || k.startsWith("weekly:")) - ) - ); - } - return readCollapsedCategoryIds(userId); - }); - const collapsedCategoryIdsRef = useRef>(collapsedCategoryIds); - collapsedCategoryIdsRef.current = collapsedCategoryIds; - - useEffect(() => { - const stored = readCollapsedCategoryIds(userId); - if (stored.size > 0) { - setCollapsedCategoryIds(stored); - collapsedCategoryIdsRef.current = stored; - writeCollapsedCategoryIds(userId, stored); - } - }, [userId]); - - useEffect(() => { - if (typeof window === "undefined") return; - const handleStorage = (e: StorageEvent) => { - if (e.key === getCollapsedCategoriesStorageKey(userId)) { - const stored = readCollapsedCategoryIds(userId); - setCollapsedCategoryIds(stored); - collapsedCategoryIdsRef.current = stored; - } - }; - window.addEventListener("storage", handleStorage); - return () => { - window.removeEventListener("storage", handleStorage); - }; - }, [userId]); - - const [dailyCategories, setDailyCategories] = useState( - () => { - if ( - userTasks?.dailyCategories && - userTasks.dailyCategories.length > 0 - ) { - return userTasks.dailyCategories - .filter((c) => !c.isDeleted) - .map((c) => ({ - id: c.id, - name: c.name, - sortOrder: c.sortOrder ?? 0, - createdAt: c.createdAt - ? typeof c.createdAt === "string" - ? c.createdAt - : c.createdAt.toISOString() - : undefined, - updatedAt: c.updatedAt - ? typeof c.updatedAt === "string" - ? c.updatedAt - : c.updatedAt.toISOString() - : undefined, - isCollapsed: false, - tasks: c.tasks - .filter((t) => !t.isDeleted) - .map((t) => ({ - id: t.id, - text: t.title, - completed: t.isComplete, - status: - (t.status as TaskStatus) || - (t.isComplete ? "COMPLETED" : "TODO"), - dueDate: t.dueDate ?? null, - createdAt: t.createdAt - ? new Date(t.createdAt).toISOString() - : undefined, - challengeId: t.challengeId ?? null, - })), - })); - } - return []; - } - ); - - const [weeklyCategories, setWeeklyCategories] = useState( - () => { - if ( - userTasks?.weeklyCategories && - userTasks.weeklyCategories.length > 0 - ) { - return userTasks.weeklyCategories - .filter((c) => !c.isDeleted) - .map((c) => ({ - id: c.id, - name: c.name, - sortOrder: c.sortOrder ?? 0, - createdAt: c.createdAt - ? typeof c.createdAt === "string" - ? c.createdAt - : c.createdAt.toISOString() - : undefined, - updatedAt: c.updatedAt - ? typeof c.updatedAt === "string" - ? c.updatedAt - : c.updatedAt.toISOString() - : undefined, - isCollapsed: false, - tasks: c.tasks - .filter((t) => !t.isDeleted) - .map((t) => ({ - id: t.id, - text: t.title, - completed: t.isComplete, - status: - (t.status as TaskStatus) || - (t.isComplete ? "COMPLETED" : "TODO"), - dueDate: t.dueDate ?? null, - createdAt: t.createdAt - ? new Date(t.createdAt).toISOString() - : undefined, - challengeId: t.challengeId ?? null, - })), - })); - } - return []; - } - ); - - const completedChallengeIdSet = useMemo(() => { - const ids = new Set(completedChallengeIds ?? []); - if (challengeStatus === "COMPLETED" && challengeId) { - ids.add(challengeId); - } - return ids; - }, [completedChallengeIds, challengeStatus, challengeId]); - - const visibleWeeklyCategories = useMemo( - () => - weeklyCategories.map((category) => ({ - ...category, - tasks: category.tasks.filter((task) => - isWeeklyTaskVisible(task, completedChallengeIdSet) - ), - })), - [weeklyCategories, completedChallengeIdSet] - ); - - const effectiveTodayDate = useMemo(() => { - if (!hasChallengeContext && challengeStatus === "COMPLETED") { - return new Date().toISOString().slice(0, 10); - } - return todayDate || new Date().toISOString().slice(0, 10); - }, [hasChallengeContext, challengeStatus, todayDate]); - - const [activeWeekAnchorDateKey, setActiveWeekAnchorDateKey] = - useState(() => { - if (initialSelectedDateKey) return initialSelectedDateKey; - if (hasChallengeContext && effectiveStartDate) { - const startKey = effectiveStartDate.slice(0, 10); - if (isSameCalendarWeek(effectiveTodayDate, startKey)) { - return effectiveTodayDate; - } - return startKey; - } - return effectiveTodayDate; - }); - - const dayOptions: ChallengeDayOption[] = useMemo(() => { - if (hasChallengeContext && effectiveStartDate) { - const challengeOptions = getChallengeDayOptions( - effectiveStartDate, - effectiveTodayDate, - totalChallengeDays ?? 7 - ).slice(0, 7); - - const anchorKey = activeWeekAnchorDateKey.slice(0, 10); - const startKey = effectiveStartDate.slice(0, 10); - - const isViewingChallengeWeek = - challengeOptions.some((d) => d.dateKey === anchorKey) || - isSameCalendarWeek(anchorKey, startKey); - - if (isViewingChallengeWeek) { - return challengeOptions; - } - } - return getCalendarWeekDayOptions( - activeWeekAnchorDateKey, - effectiveTodayDate - ).slice(0, 7); - }, [ - hasChallengeContext, - effectiveStartDate, - effectiveTodayDate, - activeWeekAnchorDateKey, - totalChallengeDays, - ]); - - const todayDayOption = useMemo(() => { - return dayOptions.find((d) => d.isToday) || dayOptions[0]; - }, [dayOptions]); - - const initialDayOption = useMemo(() => { - if (initialSelectedDateKey) { - return dayOptions.find((d) => d.dateKey === initialSelectedDateKey); - } - return undefined; - }, [dayOptions, initialSelectedDateKey]); - - const [selectedDateKey, setSelectedDateKey] = useState( - () => - initialDayOption?.dateKey || - initialSelectedDateKey || - todayDayOption?.dateKey || - effectiveTodayDate - ); - const [selectedDayNumber, setSelectedDayNumber] = useState( - () => - initialDayOption?.dayNumber || - todayDayOption?.dayNumber || - (hasChallengeContext ? todayDayNumber : undefined) || - 1 - ); - - const activeDayOption = useMemo(() => { - return ( - dayOptions.find((d) => d.dateKey === selectedDateKey) || - todayDayOption || - dayOptions[0] - ); - }, [dayOptions, selectedDateKey, todayDayOption]); - - useEffect(() => { - if ( - dayOptions.length > 0 && - !dayOptions.some((d) => d.dateKey === selectedDateKey) - ) { - const fallback = dayOptions.find((d) => d.isToday) || dayOptions[0]; - if (fallback) { - setSelectedDateKey(fallback.dateKey); - setSelectedDayNumber(fallback.dayNumber); - } - } - }, [dayOptions, selectedDateKey]); - - const isActiveDayToday = - selectedDateKey === effectiveTodayDate || - Boolean(activeDayOption?.isToday); - const isActiveDayPast = - selectedDateKey < effectiveTodayDate || Boolean(activeDayOption?.isPast); - - const checkIsDayLocked = useCallback( - (dateKey: string): boolean => { - return isChallengeDayDateLocked(dateKey, effectiveTodayDate, { - challengeStartDate, - totalChallengeDays, - challengeStatus, - }); - }, - [ - effectiveTodayDate, - challengeStartDate, - totalChallengeDays, - challengeStatus, - ] - ); - - const isPastDayLocked = checkIsDayLocked(selectedDateKey); - - const [isRolloverSnoozed, setIsRolloverSnoozed] = useState( - Boolean(initialIsRolloverSnoozed) - ); - - useEffect(() => { - cleanupExpiredRolloverSnooze(userId, effectiveTodayDate); - const isSnoozed = isRolloverSnoozedForDate(userId, effectiveTodayDate); - if (isSnoozed) { - if (!isRolloverSnoozed) { - setIsRolloverSnoozed(true); - } - // Sync to cookie so all future reloads have the cookie on the server - setRolloverSnoozedForDate(userId, effectiveTodayDate); - } - }, [userId, effectiveTodayDate, isRolloverSnoozed]); - - const handleSnoozeRolloverToday = useCallback(() => { - setIsRolloverDismissed(true); - setIsRolloverSnoozed(true); - setRolloverSnoozedForDate(userId, effectiveTodayDate); - }, [userId, effectiveTodayDate]); - - const activeWeekDateKeys = useMemo(() => { - const calendarDays = getCalendarWeekDayOptions( - activeWeekAnchorDateKey, - effectiveTodayDate - ); - const keys = new Set(calendarDays.map((d) => d.dateKey)); - dayOptions.forEach((d) => keys.add(d.dateKey)); - return Array.from(keys); - }, [activeWeekAnchorDateKey, effectiveTodayDate, dayOptions]); - - const weekRangeLabel = useMemo(() => { - const calendarDays = getCalendarWeekDayOptions( - activeWeekAnchorDateKey, - effectiveTodayDate - ); - if (calendarDays.length >= 7) { - return formatWeekRange( - calendarDays[0].dateKey, - calendarDays[6].dateKey - ); - } - if (dayOptions.length > 0) { - return formatWeekRange( - dayOptions[0].dateKey, - dayOptions[dayOptions.length - 1].dateKey - ); - } - return ""; - }, [activeWeekAnchorDateKey, effectiveTodayDate, dayOptions]); - - const handleSelectDay = (opt: ChallengeDayOption) => { - setSelectedDateKey(opt.dateKey); - setSelectedDayNumber(opt.dayNumber); - }; - - const handleJumpToToday = () => { - setActiveWeekAnchorDateKey(effectiveTodayDate); - setSelectedDateKey(effectiveTodayDate); - try { - const parts = effectiveTodayDate.split("-").map(Number); - if (parts[0] && parts[1] && parts[2]) { - const dayOfWeek = new Date( - Date.UTC(parts[0], parts[1] - 1, parts[2]) - ).getUTCDay(); - setSelectedDayNumber(((dayOfWeek + 6) % 7) + 1); - } - } catch { - setSelectedDayNumber(1); - } - }; - - const handlePreviousWeek = () => { - const newAnchor = getAdjacentWeekAnchor(activeWeekAnchorDateKey, -1); - setActiveWeekAnchorDateKey(newAnchor); - const newSelected = getAdjacentWeekAnchor(selectedDateKey, -1); - setSelectedDateKey(newSelected); - }; - - const handleNextWeek = () => { - const newAnchor = getAdjacentWeekAnchor(activeWeekAnchorDateKey, 1); - setActiveWeekAnchorDateKey(newAnchor); - const newSelected = getAdjacentWeekAnchor(selectedDateKey, 1); - setSelectedDateKey(newSelected); - }; - - const handleSelectDateFromPicker = (targetDateKey: string) => { - setActiveWeekAnchorDateKey(targetDateKey); - setSelectedDateKey(targetDateKey); - try { - const parts = targetDateKey.split("-").map(Number); - if (parts[0] && parts[1] && parts[2]) { - const dayOfWeek = new Date( - Date.UTC(parts[0], parts[1] - 1, parts[2]) - ).getUTCDay(); - setSelectedDayNumber(((dayOfWeek + 6) % 7) + 1); - } - } catch { - setSelectedDayNumber(1); - } - }; - - // Weekly Todos Week Navigation (adapted for weekly system) - const [activeWeeklyAnchorDateKey, setActiveWeeklyAnchorDateKey] = - useState(() => { - if (initialSelectedDateKey) return initialSelectedDateKey; - if (hasChallengeContext && effectiveStartDate) { - const startKey = effectiveStartDate.slice(0, 10); - if (isSameCalendarWeek(effectiveTodayDate, startKey)) { - return effectiveTodayDate; - } - return startKey; - } - return effectiveTodayDate; - }); - - const activeWeeklyWeekDateKeys = useMemo(() => { - const calendarDays = getCalendarWeekDayOptions( - activeWeeklyAnchorDateKey, - effectiveTodayDate - ); - return calendarDays.map((d) => d.dateKey); - }, [activeWeeklyAnchorDateKey, effectiveTodayDate]); - - const weeklyRangeLabel = useMemo(() => { - const calendarDays = getCalendarWeekDayOptions( - activeWeeklyAnchorDateKey, - effectiveTodayDate - ); - if (calendarDays.length >= 7) { - return formatWeekRange( - calendarDays[0].dateKey, - calendarDays[6].dateKey - ); - } - return ""; - }, [activeWeeklyAnchorDateKey, effectiveTodayDate]); - - const isViewingCurrentWeeklyWeek = useMemo(() => { - return isSameCalendarWeek(activeWeeklyAnchorDateKey, effectiveTodayDate); - }, [activeWeeklyAnchorDateKey, effectiveTodayDate]); - - const handleWeeklyPreviousWeek = () => { - const newAnchor = getAdjacentWeekAnchor(activeWeeklyAnchorDateKey, -1); - setActiveWeeklyAnchorDateKey(newAnchor); - }; - - const handleWeeklyNextWeek = () => { - const newAnchor = getAdjacentWeekAnchor(activeWeeklyAnchorDateKey, 1); - setActiveWeeklyAnchorDateKey(newAnchor); - }; - - const handleWeeklyJumpToCurrentWeek = () => { - setActiveWeeklyAnchorDateKey(effectiveTodayDate); - }; - - const handleSelectWeeklyDateFromPicker = (targetDateKey: string) => { - setActiveWeeklyAnchorDateKey(targetDateKey); - }; - - const isTaskInWeeklyWeek = useCallback( - (task: TaskItem): boolean => { - if (task.dueDate) { - const taskDueDateKey = - typeof task.dueDate === "string" - ? task.dueDate.slice(0, 10) - : new Date(task.dueDate).toISOString().slice(0, 10); - return isSameCalendarWeek( - taskDueDateKey, - activeWeeklyAnchorDateKey - ); - } - if ( - hasChallengeContext && - task.challengeId && - task.challengeId === linkableChallengeId - ) { - const challengeAnchor = - effectiveStartDate?.slice(0, 10) ?? - (task.createdAt - ? typeof task.createdAt === "string" - ? task.createdAt.slice(0, 10) - : new Date(task.createdAt).toISOString().slice(0, 10) - : null); - if (challengeAnchor) { - return isSameCalendarWeek( - challengeAnchor, - activeWeeklyAnchorDateKey - ); - } - return isViewingCurrentWeeklyWeek; - } - if (task.createdAt) { - const taskCreatedKey = - typeof task.createdAt === "string" - ? task.createdAt.slice(0, 10) - : new Date(task.createdAt).toISOString().slice(0, 10); - return isSameCalendarWeek( - taskCreatedKey, - activeWeeklyAnchorDateKey - ); - } - return isViewingCurrentWeeklyWeek; - }, - [ - activeWeeklyAnchorDateKey, - hasChallengeContext, - linkableChallengeId, - effectiveStartDate, - isViewingCurrentWeeklyWeek, - ] - ); - - const getTaskDateKey = useCallback( - (task: TaskItem): string => { - if (task.dueDate) { - return typeof task.dueDate === "string" - ? task.dueDate.slice(0, 10) - : new Date(task.dueDate).toISOString().slice(0, 10); - } - if (task.createdAt) { - return new Date(task.createdAt).toISOString().slice(0, 10); - } - return effectiveTodayDate; - }, - [effectiveTodayDate] - ); - - const openAddDailyModal = (targetDateKey?: string) => { - const rawDateKey = targetDateKey || selectedDateKey; - const isTargetLocked = checkIsDayLocked(rawDateKey); - - // If target day is in a locked past challenge day, clamp to today or the first available non-past day - const initialDateKey = isTargetLocked - ? todayDayOption?.dateKey || - dayOptions.find((d) => !checkIsDayLocked(d.dateKey))?.dateKey || - effectiveTodayDate - : rawDateKey; - - setAddTodoDateKey(initialDateKey); - setNewTodoText(""); - if (dailyCategoryOptions.length > 0) { - setSelectedCategory(dailyCategoryOptions[0]); - setIsCreatingCategory(false); - } else { - setSelectedCategory(""); - setIsCreatingCategory(true); - } - setCustomCategory(""); - setNewTodoStatus("TODO"); - setAddModalType("daily"); - }; - - const weeklyCategoryOptions = Array.from( - new Set([ - ...(userTasks?.categories - ?.filter((c) => c.taskType === "WEEKLY") - .map((c) => c.name) ?? []), - ...weeklyCategories.map((c) => c.name), - ]) - ); - - const openAddWeeklyModal = () => { - setAddTodoChallengeScope(linkableChallengeId ? "CHALLENGE" : "PERSONAL"); - setNewTodoText(""); - setNewTodoStatus("TODO"); - setCustomCategory(""); - if (weeklyCategoryOptions.length > 0) { - setSelectedCategory(weeklyCategoryOptions[0]); - setIsCreatingCategory(false); - } else { - setSelectedCategory(""); - setIsCreatingCategory(true); - } - setAddModalType("weekly"); - }; - - // Independent categories created specifically for daily tasks (unplanned/independent) - const independentDailyCategoryOptions = Array.from( - new Set([ - ...(userTasks?.categories - ?.filter((c) => c.taskType === "DAILY") - .map((c) => c.name) ?? []), - ...dailyCategories - .map((c) => c.name) - .filter((name) => !weeklyCategoryOptions.includes(name)), - ]) - ).filter((name) => !weeklyCategoryOptions.includes(name)); - - // Daily inherits all weekly categories (parent categories) + independent daily categories - const dailyCategoryOptions = Array.from( - new Set([...weeklyCategoryOptions, ...independentDailyCategoryOptions]) - ); - - const weeklyCategoryNameToId = new Map( - userTasks?.categories - ?.filter((c) => c.taskType === "WEEKLY") - .map((c) => [c.name, c.id]) ?? [] - ); - - const dailyCategoryNameToId = new Map([ - ...(userTasks?.categories?.map( - (c) => [c.name, c.id] as [string, string] - ) ?? []), - ...weeklyCategories - .filter((c) => Boolean(c.id)) - .map((c) => [c.name, c.id!] as [string, string]), - ...dailyCategories - .filter((c) => Boolean(c.id)) - .map((c) => [c.name, c.id!] as [string, string]), - ]); - - useEffect(() => { - const cleanup = initTaskSync(userId); - let isCancelled = false; - - const handleSyncEvent = () => { - if (!isCancelled) { - logTaskSync("Live task sync event received, re-hydrating view..."); - hydrateFromIndexedDB({ isSyncEvent: true }); - } - }; - - if (typeof window !== "undefined") { - window.addEventListener(TASKS_SYNCED_EVENT, handleSyncEvent); - } - - async function hydrateFromIndexedDB(options?: { isSyncEvent?: boolean }) { - try { - const isSyncEvent = options?.isSyncEvent ?? false; - const pendingMutations = userId - ? await getQueuedMutationsForUser(userId) - : []; - const pendingTaskIds = new Set( - pendingMutations.map((m) => { - const p = m.payload as Record; - return String(p.taskId || p.id || ""); - }) - ); - pendingTaskIds.delete(""); - const hasServerTasks = Boolean( - userTasks && - (userTasks.dailyCategories?.length > 0 || - userTasks.weeklyCategories?.length > 0) - ); - - // On initial mount with no pending offline mutations and fresh server data, - // do not overwrite fresh React state with stale IndexedDB records to prevent - // a visual flash of old goals before sync finishes. - if ( - !isSyncEvent && - hasServerTasks && - pendingMutations.length === 0 - ) { - logTaskSync( - "Skipping initial IndexedDB state overwrite; seeding cache from server userTasks..." - ); - if ( - userTasks && - userTasks.categories && - userTasks.categories.length > 0 - ) { - const seedCats: LocalCategoryRecord[] = userTasks.categories - .filter((c) => !c.isDeleted) - .map((c) => ({ - id: c.id, - userId: userId || null, - name: c.name, - taskType: c.taskType, - sortOrder: c.sortOrder ?? 0, - revision: c.revision, - createdAt: new Date(c.createdAt).toISOString(), - updatedAt: new Date(c.updatedAt).toISOString(), - syncState: "synced", - })); - - const seedTasks: LocalTaskRecord[] = [ - ...userTasks.dailyCategories - .filter((c) => !c.isDeleted) - .flatMap((c) => c.tasks.filter((t) => !t.isDeleted)), - ...userTasks.weeklyCategories - .filter((c) => !c.isDeleted) - .flatMap((c) => c.tasks.filter((t) => !t.isDeleted)), - ].map((t) => ({ - id: t.id, - userId: userId || null, - categoryId: t.categoryId, - challengeId: t.challengeId ?? null, - title: t.title, - taskType: t.taskType, - sortOrder: t.sortOrder ?? 0, - isComplete: t.isComplete, - status: - (t.status as TaskStatus) || - (t.isComplete ? "COMPLETED" : "TODO"), - dueDate: t.dueDate ?? null, - createdAt: new Date(t.createdAt).toISOString(), - updatedAt: new Date(t.updatedAt).toISOString(), - completedAt: t.completedAt - ? new Date(t.completedAt).toISOString() - : null, - revision: t.revision, - syncState: "synced", - })); - - const existingCats = await getAllLocalCategories( - userId ?? null - ); - const existingTasks = await getAllLocalTasks(userId ?? null); - - const pendingCatIds = new Set( - existingCats - .filter((c) => c.syncState && c.syncState !== "synced") - .map((c) => c.id) - ); - const pendingTaskIds = new Set( - existingTasks - .filter((t) => t.syncState && t.syncState !== "synced") - .map((t) => t.id) - ); - - const catsToSeed = seedCats.filter( - (c) => !pendingCatIds.has(c.id) - ); - const tasksToSeed = seedTasks.filter( - (t) => !pendingTaskIds.has(t.id) - ); - - if (catsToSeed.length > 0) { - await putLocalCategories(catsToSeed); - } - if (tasksToSeed.length > 0) { - await putLocalTasks(tasksToSeed); - } - } - return; - } - - const localTasks = await getAllLocalTasks(userId ?? null); - const localCats = await getAllLocalCategories(userId ?? null); - - if (isCancelled) return; - - if (localCats.length > 0 || localTasks.length > 0) { - logTaskSync("Hydrated tasks from IndexedDB", { - cats: localCats.length, - tasks: localTasks.length, - }); - - const sortedCats = [...localCats] - .filter((c) => !c.isDeleted) - .sort((a, b) => { - const orderDiff = (a.sortOrder ?? 0) - (b.sortOrder ?? 0); - if (orderDiff !== 0) return orderDiff; - const aTime = a.createdAt - ? new Date(a.createdAt).getTime() - : 0; - const bTime = b.createdAt - ? new Date(b.createdAt).getTime() - : 0; - if (aTime !== bTime) return aTime - bTime; - return (a.id || "").localeCompare(b.id || ""); - }); - const sortedTasks = [...localTasks] - .filter((t) => !t.isDeleted) - .sort((a, b) => { - const orderDiff = (a.sortOrder ?? 0) - (b.sortOrder ?? 0); - if (orderDiff !== 0) return orderDiff; - const aTime = a.createdAt - ? new Date(a.createdAt).getTime() - : 0; - const bTime = b.createdAt - ? new Date(b.createdAt).getTime() - : 0; - if (aTime !== bTime) return aTime - bTime; - return (a.id || "").localeCompare(b.id || ""); - }); - - const tasksToHeal: LocalTaskRecord[] = []; - - const activeCollapsed = - collapsedCategoryIdsRef.current.size > 0 - ? collapsedCategoryIdsRef.current - : readCollapsedCategoryIds(userId); - - const dailyCats = sortedCats - .filter( - (c) => - c.taskType === "DAILY" || - sortedTasks.some( - (t) => - t.categoryId === c.id && t.taskType === "DAILY" - ) - ) - .map((c) => ({ - id: c.id, - name: c.name, - sortOrder: c.sortOrder ?? 0, - createdAt: c.createdAt, - updatedAt: c.updatedAt, - isCollapsed: isCategoryCollapsed( - "daily", - c, - activeCollapsed - ), - tasks: sortedTasks - .filter( - (t) => - t.categoryId === c.id && t.taskType === "DAILY" - ) - .map((t) => { - const effectiveDueDate = t.dueDate - ? typeof t.dueDate === "string" - ? t.dueDate.slice(0, 10) - : new Date(t.dueDate) - .toISOString() - .slice(0, 10) - : null; - const effectiveStatus = - (t.status as TaskStatus) || - (t.isComplete ? "COMPLETED" : "TODO"); - - if (!t.status) { - tasksToHeal.push({ - ...t, - dueDate: effectiveDueDate, - status: effectiveStatus, - }); - } - - return { - id: t.id, - text: t.title, - completed: t.isComplete, - status: effectiveStatus, - dueDate: effectiveDueDate, - createdAt: t.createdAt, - challengeId: t.challengeId ?? null, - }; - }), - })); - - const weeklyCats = sortedCats - .filter((c) => c.taskType === "WEEKLY") - .map((c) => ({ - id: c.id, - name: c.name, - sortOrder: c.sortOrder ?? 0, - createdAt: c.createdAt, - updatedAt: c.updatedAt, - isCollapsed: isCategoryCollapsed( - "weekly", - c, - activeCollapsed - ), - tasks: sortedTasks - .filter( - (t) => - t.categoryId === c.id && t.taskType === "WEEKLY" - ) - .map((t) => { - const effectiveDueDate = t.dueDate - ? typeof t.dueDate === "string" - ? t.dueDate.slice(0, 10) - : new Date(t.dueDate) - .toISOString() - .slice(0, 10) - : null; - const effectiveStatus = - (t.status as TaskStatus) || - (t.isComplete ? "COMPLETED" : "TODO"); - - if (!t.status) { - tasksToHeal.push({ - ...t, - dueDate: effectiveDueDate, - status: effectiveStatus, - }); - } - - return { - id: t.id, - text: t.title, - completed: t.isComplete, - status: effectiveStatus, - dueDate: effectiveDueDate, - createdAt: t.createdAt, - challengeId: t.challengeId ?? null, - }; - }), - })); - - if (tasksToHeal.length > 0) { - putLocalTasks(tasksToHeal).catch(() => {}); - } - - setDailyCategories((currentCategories) => { - if (pendingTaskIds.size === 0) return dailyCats; - return dailyCats.map((cat) => ({ - ...cat, - tasks: cat.tasks.map((task) => { - if (pendingTaskIds.has(task.id)) { - const currentCat = currentCategories.find((c) => - c.tasks.some((t) => t.id === task.id) - ); - const currentTask = currentCat?.tasks.find( - (t) => t.id === task.id - ); - if (currentTask) { - return { - ...task, - completed: currentTask.completed, - status: currentTask.status, - }; - } - } - return task; - }), - })); - }); - setWeeklyCategories((currentCategories) => { - if (pendingTaskIds.size === 0) return weeklyCats; - return weeklyCats.map((cat) => ({ - ...cat, - tasks: cat.tasks.map((task) => { - if (pendingTaskIds.has(task.id)) { - const currentCat = currentCategories.find((c) => - c.tasks.some((t) => t.id === task.id) - ); - const currentTask = currentCat?.tasks.find( - (t) => t.id === task.id - ); - if (currentTask) { - return { - ...task, - completed: currentTask.completed, - status: currentTask.status, - }; - } - } - return task; - }), - })); - }); - } else if (userTasks && userTasks.categories.length > 0) { - logTaskSync("Seeding IndexedDB from server userTasks..."); - const seedCats: LocalCategoryRecord[] = userTasks.categories - .filter((c) => !c.isDeleted) - .map((c) => ({ - id: c.id, - userId: userId || null, - name: c.name, - taskType: c.taskType, - sortOrder: c.sortOrder ?? 0, - revision: c.revision, - createdAt: new Date(c.createdAt).toISOString(), - updatedAt: new Date(c.updatedAt).toISOString(), - syncState: "synced", - })); - - const seedTasks: LocalTaskRecord[] = [ - ...userTasks.dailyCategories - .filter((c) => !c.isDeleted) - .flatMap((c) => c.tasks.filter((t) => !t.isDeleted)), - ...userTasks.weeklyCategories - .filter((c) => !c.isDeleted) - .flatMap((c) => c.tasks.filter((t) => !t.isDeleted)), - ].map((t) => ({ - id: t.id, - userId: userId || null, - categoryId: t.categoryId, - challengeId: t.challengeId ?? null, - title: t.title, - taskType: t.taskType, - sortOrder: t.sortOrder ?? 0, - isComplete: t.isComplete, - status: - (t.status as TaskStatus) || - (t.isComplete ? "COMPLETED" : "TODO"), - dueDate: t.dueDate ?? null, - createdAt: new Date(t.createdAt).toISOString(), - updatedAt: new Date(t.updatedAt).toISOString(), - completedAt: t.completedAt - ? new Date(t.completedAt).toISOString() - : null, - revision: t.revision, - syncState: "synced", - })); - - await putLocalCategories(seedCats); - await putLocalTasks(seedTasks); - } - } catch (err) { - logTaskSync("Error hydrating from IndexedDB:", err); - } - } - - hydrateFromIndexedDB({ isSyncEvent: false }); - - return () => { - isCancelled = true; - if (typeof window !== "undefined") { - window.removeEventListener(TASKS_SYNCED_EVENT, handleSyncEvent); - } - cleanup(); - }; - }, [userId, userTasks]); - - const toggleDailyCollapse = (index: number) => { - const targetCat = dailyCategories[index]; - if (!targetCat) return; - - const nextCollapsed = toggleCategoryCollapseKey( - "daily", - targetCat, - collapsedCategoryIds - ); - setCollapsedCategoryIds(nextCollapsed); - collapsedCategoryIdsRef.current = nextCollapsed; - writeCollapsedCategoryIds(userId, nextCollapsed); - }; - - const toggleWeeklyCollapse = (index: number) => { - const targetCat = weeklyCategories[index]; - if (!targetCat) return; - - const nextCollapsed = toggleCategoryCollapseKey( - "weekly", - targetCat, - collapsedCategoryIds - ); - setCollapsedCategoryIds(nextCollapsed); - collapsedCategoryIdsRef.current = nextCollapsed; - writeCollapsedCategoryIds(userId, nextCollapsed); - }; - - const setTaskStatus = ( - catIndex: number, - taskId: string, - taskType: "daily" | "weekly", - nextStatusOrCompleted: TaskStatus | boolean, - clickOrigin?: - | React.MouseEvent - | MouseEvent - | { clientX: number; clientY: number } - | Element - | null - ) => { - const nextStatus: TaskStatus = - typeof nextStatusOrCompleted === "boolean" - ? nextStatusOrCompleted - ? "COMPLETED" - : "TODO" - : nextStatusOrCompleted; - const nextCompleted = nextStatus === "COMPLETED"; - - if (taskType === "daily") { - let resolvedCatIdx = catIndex; - let targetTask = dailyCategories[catIndex]?.tasks.find( - (t) => t.id === taskId - ); - if (!targetTask) { - resolvedCatIdx = dailyCategories.findIndex((c) => - c.tasks.some((t) => t.id === taskId) - ); - if (resolvedCatIdx !== -1) { - targetTask = dailyCategories[resolvedCatIdx]?.tasks.find( - (t) => t.id === taskId - ); - } - } - if (!targetTask) return; - const currentStatus = getTaskStatus(targetTask); - if (currentStatus === nextStatus) return; - - if (nextStatus === "COMPLETED") { - const targetEl = - typeof document !== "undefined" - ? document.querySelector(`[data-task-id="${taskId}"]`) - : null; - triggerTaskConfetti(clickOrigin ?? targetEl); - void playCompletionAudio(); - } - - setDailyCategories((prev) => - prev.map((cat, i) => - i === resolvedCatIdx || cat.tasks.some((t) => t.id === taskId) - ? { - ...cat, - tasks: cat.tasks.map((t) => - t.id === taskId - ? { - ...t, - completed: nextCompleted, - status: nextStatus, - } - : t - ), - } - : cat - ) - ); - - const nowIso = new Date().toISOString(); - const cat = - dailyCategories[resolvedCatIdx] || - dailyCategories.find((c) => c.tasks.some((t) => t.id === taskId)); - if (cat?.id) { - const localTask: LocalTaskRecord = { - id: taskId, - userId: userId ?? null, - categoryId: cat.id, - challengeId: targetTask.challengeId ?? null, - title: targetTask.text, - taskType: "DAILY", - isComplete: nextCompleted, - status: nextStatus, - dueDate: targetTask.dueDate ?? null, - createdAt: targetTask.createdAt || nowIso, - updatedAt: nowIso, - completedAt: nextCompleted ? nowIso : null, - syncState: "pending", - }; - - persistTask(localTask, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "TOGGLE", - payload: { - taskId, - isComplete: nextCompleted, - status: nextStatus, - }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId, 400)) - .catch(() => {}); - } - - if (isLoggedIn && userId) { - trackLogRocketEvent("TaskStatusChanged", { - taskId, - taskType: "daily", - status: nextStatus, - isComplete: nextCompleted, - }); - } - - logTaskSync("Task status updated", { - taskId, - status: nextStatus, - isComplete: nextCompleted, - }); - } else { - let resolvedCatIdx = catIndex; - let targetTask = weeklyCategories[catIndex]?.tasks.find( - (t) => t.id === taskId - ); - if (!targetTask) { - resolvedCatIdx = weeklyCategories.findIndex((c) => - c.tasks.some((t) => t.id === taskId) - ); - if (resolvedCatIdx !== -1) { - targetTask = weeklyCategories[resolvedCatIdx]?.tasks.find( - (t) => t.id === taskId - ); - } - } - if (!targetTask) return; - const currentStatus = getTaskStatus(targetTask); - if (currentStatus === nextStatus) return; - - if (nextStatus === "COMPLETED") { - const targetEl = - typeof document !== "undefined" - ? document.querySelector(`[data-task-id="${taskId}"]`) - : null; - triggerTaskConfetti(clickOrigin ?? targetEl); - void playCompletionAudio(); - } - - setWeeklyCategories((prev) => - prev.map((cat, i) => - i === resolvedCatIdx || cat.tasks.some((t) => t.id === taskId) - ? { - ...cat, - tasks: cat.tasks.map((t) => - t.id === taskId - ? { - ...t, - completed: nextCompleted, - status: nextStatus, - } - : t - ), - } - : cat - ) - ); - - const nowIso = new Date().toISOString(); - const cat = - weeklyCategories[resolvedCatIdx] || - weeklyCategories.find((c) => c.tasks.some((t) => t.id === taskId)); - if (cat?.id) { - const localTask: LocalTaskRecord = { - id: taskId, - userId: userId ?? null, - categoryId: cat.id, - challengeId: targetTask.challengeId ?? null, - title: targetTask.text, - taskType: "WEEKLY", - isComplete: nextCompleted, - status: nextStatus, - dueDate: targetTask.dueDate ?? null, - createdAt: targetTask.createdAt || nowIso, - updatedAt: nowIso, - completedAt: nextCompleted ? nowIso : null, - syncState: "pending", - }; - - persistTask(localTask, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "TOGGLE", - payload: { - taskId, - isComplete: nextCompleted, - status: nextStatus, - }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId, 400)) - .catch(() => {}); - } - - if (isLoggedIn && userId) { - trackLogRocketEvent("TaskStatusChanged", { - taskId, - taskType: "weekly", - status: nextStatus, - isComplete: nextCompleted, - }); - } - - logTaskSync("Task status updated", { - taskId, - status: nextStatus, - isComplete: nextCompleted, - }); - } - }; - - const toggleDailyTask = ( - catIndex: number, - taskId: string, - clickOrigin?: - | React.MouseEvent - | MouseEvent - | { clientX: number; clientY: number } - | Element - | null - ) => { - let targetTask = dailyCategories[catIndex]?.tasks.find( - (t) => t.id === taskId - ); - if (!targetTask) { - targetTask = dailyCategories - .flatMap((c) => c.tasks) - .find((t) => t.id === taskId); - } - if (!targetTask) return; - const currentStatus = getTaskStatus(targetTask); - const nextStatus: TaskStatus = - currentStatus === "COMPLETED" ? "TODO" : "COMPLETED"; - setTaskStatus(catIndex, taskId, "daily", nextStatus, clickOrigin); - }; - - const toggleWeeklyTask = ( - catIndex: number, - taskId: string, - clickOrigin?: - | React.MouseEvent - | MouseEvent - | { clientX: number; clientY: number } - | Element - | null - ) => { - let targetTask = weeklyCategories[catIndex]?.tasks.find( - (t) => t.id === taskId - ); - if (!targetTask) { - targetTask = weeklyCategories - .flatMap((c) => c.tasks) - .find((t) => t.id === taskId); - } - if (!targetTask) return; - const currentStatus = getTaskStatus(targetTask); - const nextStatus: TaskStatus = - currentStatus === "COMPLETED" ? "TODO" : "COMPLETED"; - setTaskStatus(catIndex, taskId, "weekly", nextStatus, clickOrigin); - }; - - const handleDeleteTask = ( - catIndex: number, - taskId: string, - taskType: "daily" | "weekly" - ) => { - if (taskType === "daily") { - const taskToDelete = dailyCategories[catIndex]?.tasks.find( - (t) => t.id === taskId - ); - if (taskToDelete) { - const dateKey = getTaskDateKey(taskToDelete); - if (checkIsDayLocked(dateKey)) { - return; - } - } - setDailyCategories((prev) => - prev.map((cat, i) => - i === catIndex - ? { - ...cat, - tasks: cat.tasks.filter((t) => t.id !== taskId), - } - : cat - ) - ); - } else { - const weeklyTaskToDelete = weeklyCategories[catIndex]?.tasks.find( - (t) => t.id === taskId - ); - if ( - weeklyTaskToDelete && - isWeeklyTaskGraceExpired({ - taskType: "WEEKLY", - challengeId: weeklyTaskToDelete.challengeId, - createdAt: weeklyTaskToDelete.createdAt ?? new Date(), - }) - ) { - return; - } - setWeeklyCategories((prev) => - prev.map((cat, i) => - i === catIndex - ? { - ...cat, - tasks: cat.tasks.filter((t) => t.id !== taskId), - } - : cat - ) - ); - } - - deleteTaskWithMutation(taskId, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "DELETE", - payload: { taskId }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - - logTaskSync("Task deleted", { taskId }); - }; - - const handleSaveEditTask = ( - newText: string, - newStatus: TaskStatus, - newDueDate?: string | null - ) => { - if (!editTaskModal || !newText.trim()) return; - const { id, catIdx, taskType } = editTaskModal; - const trimmed = newText.trim(); - const nextCompleted = newStatus === "COMPLETED"; - const nowIso = new Date().toISOString(); - const resolvedDueDate = - taskType === "daily" - ? newDueDate !== undefined && newDueDate !== "" - ? newDueDate - : (editTaskModal.dueDate ?? selectedDateKey) - : newDueDate !== undefined && newDueDate !== "" - ? newDueDate - : (editTaskModal.dueDate ?? null); - - if (taskType === "daily" && resolvedDueDate) { - const originalDateKey = editTaskModal.dueDate - ? typeof editTaskModal.dueDate === "string" - ? editTaskModal.dueDate.slice(0, 10) - : new Date(editTaskModal.dueDate).toISOString().slice(0, 10) - : editTaskModal.createdAt - ? new Date(editTaskModal.createdAt).toISOString().slice(0, 10) - : effectiveTodayDate; - - if (checkIsDayLocked(resolvedDueDate)) { - return; - } - - const check = validateMoveTaskChallengeDay( - originalDateKey, - resolvedDueDate, - effectiveTodayDate, - { - isChallengeActive: hasChallengeContext, - isTargetDayLocked: checkIsDayLocked(resolvedDueDate), - } - ); - if (!check.ok) { - return; - } - } - - const patch = buildTaskEditPatch( - { - title: editTaskModal.text, - status: editTaskModal.status, - isComplete: editTaskModal.completed, - dueDate: editTaskModal.dueDate ?? null, - challengeId: editTaskModal.challengeId ?? null, - }, - { - title: trimmed, - status: newStatus, - isComplete: nextCompleted, - dueDate: resolvedDueDate, - challengeId: - taskType === "weekly" ? editTaskInputChallengeId : undefined, - }, - taskType === "daily" ? "DAILY" : "WEEKLY" - ); - - if ( - isEditTaskGraceLocked && - (patch.title !== undefined || patch.challengeId !== undefined) - ) { - return; - } - - if (Object.keys(patch).length === 0) { - setEditTaskModal(null); - return; - } - - if (nextCompleted) { - const prevTask = - taskType === "daily" - ? dailyCategories[catIdx]?.tasks.find((t) => t.id === id) - : weeklyCategories[catIdx]?.tasks.find((t) => t.id === id); - if (prevTask && getTaskStatus(prevTask) !== "COMPLETED") { - const targetEl = - typeof document !== "undefined" - ? document.querySelector(`[data-task-id="${id}"]`) - : null; - triggerTaskConfetti(targetEl); - void playCompletionAudio(); - } - } - - if (taskType === "daily") { - setDailyCategories((prev) => - prev.map((cat, i) => - i === catIdx - ? { - ...cat, - tasks: cat.tasks.map((t) => - t.id === id - ? { - ...t, - text: trimmed, - completed: nextCompleted, - status: newStatus, - dueDate: resolvedDueDate, - } - : t - ), - } - : cat - ) - ); - } else { - setWeeklyCategories((prev) => - prev.map((cat, i) => - i === catIdx - ? { - ...cat, - tasks: cat.tasks.map((t) => - t.id === id - ? { - ...t, - text: trimmed, - completed: nextCompleted, - status: newStatus, - dueDate: resolvedDueDate, - challengeId: editTaskInputChallengeId, - } - : t - ), - } - : cat - ) - ); - } - - const cat = - taskType === "daily" - ? dailyCategories[catIdx] - : weeklyCategories[catIdx]; - if (cat?.id) { - const localTask: LocalTaskRecord = { - id, - userId: userId ?? null, - categoryId: cat.id, - challengeId: - taskType === "weekly" - ? editTaskInputChallengeId - : (editTaskModal.challengeId ?? null), - title: trimmed, - taskType: taskType === "daily" ? "DAILY" : "WEEKLY", - isComplete: nextCompleted, - status: newStatus, - dueDate: resolvedDueDate, - createdAt: editTaskModal.createdAt || nowIso, - updatedAt: nowIso, - completedAt: nextCompleted ? nowIso : null, - syncState: "pending", - }; - - persistTask(localTask, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "UPDATE", - payload: { taskId: id, ...patch }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId, 400)) - .catch(() => {}); - } - - logTaskSync("Task updated", { - taskId: id, - title: trimmed, - status: newStatus, - isComplete: nextCompleted, - dueDate: resolvedDueDate, - }); - setEditTaskModal(null); - }; - - const moveTaskToDay = ( - taskId: string, - targetDateKey: string, - sourceCatIdx?: number, - sourceColumn: "daily" | "weekly" = "daily" - ) => { - const targetOpt = dayOptions.find((d) => d.dateKey === targetDateKey); - const isTargetPast = - targetOpt?.isPast ?? targetDateKey < effectiveTodayDate; - - // If source is weekly - if (sourceColumn === "weekly") { - if (checkIsDayLocked(targetDateKey)) return; - const foundWeeklyCatIdx = - sourceCatIdx !== undefined - ? sourceCatIdx - : weeklyCategories.findIndex((c) => - c.tasks.some((t) => t.id === taskId) - ); - if (foundWeeklyCatIdx === -1) return; - const sourceCat = weeklyCategories[foundWeeklyCatIdx]; - let targetDailyIdx = dailyCategories.findIndex( - (c) => - (sourceCat.id && c.id === sourceCat.id) || - c.name === sourceCat.name - ); - let currentDailyCats = dailyCategories; - if (targetDailyIdx === -1) { - const newCatId = crypto.randomUUID(); - const newDailyCat: CategoryGroup = { - id: newCatId, - name: sourceCat.name, - isCollapsed: false, - tasks: [], - }; - currentDailyCats = [...dailyCategories, newDailyCat]; - targetDailyIdx = currentDailyCats.length - 1; - persistCategory( - { - id: newCatId, - userId: userId ?? null, - name: sourceCat.name, - taskType: "DAILY", - sortOrder: targetDailyIdx, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - syncState: "pending", - }, - { - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "CREATE", - payload: { - id: newCatId, - name: sourceCat.name, - taskType: "DAILY", - sortOrder: targetDailyIdx, - }, - createdAt: Date.now(), - retryCount: 0, - } - ).catch(() => {}); - } - - const res = moveTaskBetweenCategories({ - taskId, - sourceCategoryIndex: foundWeeklyCatIdx, - sourceColumn: "weekly", - targetCategoryIndex: targetDailyIdx, - targetColumn: "daily", - targetTaskIndex: currentDailyCats[targetDailyIdx].tasks.length, - targetDueDate: targetDateKey, - dailyCategories: currentDailyCats, - weeklyCategories, - }); - - setDailyCategories(res.dailyCategories); - setWeeklyCategories(res.weeklyCategories); - - if (res.movedTask && res.targetCategoryId) { - const nowIso = new Date().toISOString(); - const isMovedComplete = Boolean( - res.movedTask.completed ?? res.movedTask.isComplete - ); - const movedStatus = - (res.movedTask.status as TaskStatus) || - (isMovedComplete ? "COMPLETED" : "TODO"); - const movedLocalTask: LocalTaskRecord = { - id: res.movedTask.id, - userId: userId ?? null, - categoryId: res.targetCategoryId, - title: res.movedTask.text ?? res.movedTask.title ?? "", - taskType: "DAILY", - sortOrder: currentDailyCats[targetDailyIdx].tasks.length, - isComplete: isMovedComplete, - status: movedStatus, - dueDate: targetDateKey, - createdAt: res.movedTask.createdAt - ? new Date(res.movedTask.createdAt).toISOString() - : nowIso, - updatedAt: nowIso, - completedAt: isMovedComplete ? nowIso : null, - syncState: "pending", - }; - - persistTask(movedLocalTask, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "MOVE", - payload: { - taskId: res.movedTask.id, - categoryId: res.targetCategoryId, - taskType: "DAILY", - sortOrder: currentDailyCats[targetDailyIdx].tasks.length, - dueDate: targetDateKey, - }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - } - return; - } - - // Source is daily - let foundCatIdx = sourceCatIdx; - let foundTask: TaskItem | undefined; - if (foundCatIdx !== undefined && dailyCategories[foundCatIdx]) { - foundTask = dailyCategories[foundCatIdx].tasks.find( - (t) => t.id === taskId - ); - } - if (!foundTask) { - for (let ci = 0; ci < dailyCategories.length; ci++) { - const t = dailyCategories[ci].tasks.find( - (item) => item.id === taskId - ); - if (t) { - foundCatIdx = ci; - foundTask = t; - break; - } - } - } - if (!foundTask || foundCatIdx === undefined) return; - - const sourceDateKey = getTaskDateKey(foundTask); - if (checkIsDayLocked(sourceDateKey)) return; - const validation = validateMoveTaskChallengeDay( - sourceDateKey, - targetDateKey, - effectiveTodayDate, - { - isChallengeActive: hasChallengeContext, - isTargetDayLocked: checkIsDayLocked(targetDateKey), - } - ); - if (!validation.ok) return; - - const nowIso = new Date().toISOString(); - const targetCat = dailyCategories[foundCatIdx]; - - setDailyCategories((prev) => - prev.map((cat, ci) => - ci === foundCatIdx - ? { - ...cat, - tasks: cat.tasks.map((t) => - t.id === taskId ? { ...t, dueDate: targetDateKey } : t - ), - } - : cat - ) - ); - - if (targetCat?.id) { - const isComplete = Boolean(foundTask.completed); - const localTask: LocalTaskRecord = { - id: foundTask.id, - userId: userId ?? null, - categoryId: targetCat.id, - title: foundTask.text, - taskType: "DAILY", - isComplete, - status: getTaskStatus(foundTask), - dueDate: targetDateKey, - createdAt: foundTask.createdAt - ? new Date(foundTask.createdAt).toISOString() - : nowIso, - updatedAt: nowIso, - completedAt: isComplete ? nowIso : null, - syncState: "pending", - }; - - persistTask(localTask, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "UPDATE", - payload: { - taskId: foundTask.id, - dueDate: targetDateKey, - }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId, 400)) - .catch(() => {}); - } - - logTaskSync("Task moved to day", { - taskId, - sourceDateKey, - targetDateKey, - }); - }; - - const toggleTaskChallengeScope = useCallback( - (taskId: string, newChallengeId: string | null) => { - let foundCat: CategoryGroup | undefined; - let foundTask: TaskItem | undefined; - - for (const cat of weeklyCategories) { - const t = cat.tasks.find((item) => item.id === taskId); - if (t) { - foundCat = cat; - foundTask = t; - break; - } - } - if (!foundTask || !foundCat) return; - - if ( - isWeeklyTaskGraceExpired({ - taskType: "WEEKLY", - challengeId: foundTask.challengeId, - createdAt: foundTask.createdAt ?? new Date(), - }) - ) { - return; - } - - setWeeklyCategories((prev) => - prev.map((cat) => ({ - ...cat, - tasks: cat.tasks.map((t) => - t.id === taskId ? { ...t, challengeId: newChallengeId } : t - ), - })) - ); - - const nowIso = new Date().toISOString(); - if (foundCat.id) { - const localTask: LocalTaskRecord = { - id: taskId, - userId: userId ?? null, - categoryId: foundCat.id, - challengeId: newChallengeId, - title: foundTask.text, - taskType: "WEEKLY", - isComplete: Boolean(foundTask.completed), - status: getTaskStatus(foundTask), - dueDate: foundTask.dueDate ?? null, - createdAt: foundTask.createdAt || nowIso, - updatedAt: nowIso, - completedAt: foundTask.completed ? nowIso : null, - syncState: "pending", - }; - - persistTask(localTask, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "UPDATE", - payload: { - taskId, - challengeId: newChallengeId, - }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId, 400)) - .catch(() => {}); - } - }, - [weeklyCategories, userId, persistTask] - ); - - const rolloverSummary = useMemo(() => { - return getRolloverSummary( - dailyCategories, - effectiveTodayDate, - selectedDateKey - ); - }, [dailyCategories, effectiveTodayDate, selectedDateKey]); - - const weeklyScopedCounts = useMemo(() => { - if (!linkableChallengeId) { - return { - totalChallengeGoals: 0, - completedChallengeGoals: 0, - totalPersonalGoals: 0, - completedPersonalGoals: 0, - totalTasks: 0, - completedTasks: 0, - }; - } - const allWeeklyTasks = weeklyCategories.flatMap((c) => c.tasks); - const scopedTasks = allWeeklyTasks.map((t) => ({ - ...t, - challengeId: - t.challengeId === linkableChallengeId ? linkableChallengeId : null, - })); - return countScopedTasks(scopedTasks); - }, [weeklyCategories, linkableChallengeId]); - - const handleRolloverIncompleteTasks = useCallback( - (options?: { sourceDateKey?: string; taskId?: string }) => { - const candidates = findRolloverCandidates( - dailyCategories, - effectiveTodayDate, - options - ); - if (candidates.length === 0) return; - - const candidateIds = candidates.map((c) => c.taskId); - const { updatedCategories, rolledOverCount } = - applyRolloverToCategories( - dailyCategories, - candidateIds, - effectiveTodayDate - ); - - setDailyCategories(updatedCategories); - - const nowIso = new Date().toISOString(); - const localTasks: LocalTaskRecord[] = []; - candidates.forEach((candidate) => { - if (candidate.categoryId) { - localTasks.push({ - id: candidate.taskId, - userId: userId ?? null, - categoryId: candidate.categoryId, - challengeId: candidate.task.challengeId ?? null, - title: candidate.title, - taskType: "DAILY", - isComplete: false, - status: (candidate.task.status as TaskStatus) || "TODO", - dueDate: effectiveTodayDate, - createdAt: candidate.task.createdAt || nowIso, - updatedAt: nowIso, - completedAt: null, - syncState: "pending", - }); - } - }); - - if (isLoggedIn && userId && candidateIds.length > 0) { - persistTasks(localTasks, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "ROLLOVER", - payload: { - taskIds: candidateIds, - targetDateKey: effectiveTodayDate, - }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId, 400)) - .catch(() => {}); - } else if (localTasks.length > 0) { - putLocalTasks(localTasks).catch(() => {}); - } - - logTaskSync("Incomplete tasks rolled over to Today", { - count: rolledOverCount, - targetDateKey: effectiveTodayDate, - }); - }, - [dailyCategories, effectiveTodayDate, userId, isLoggedIn, persistTasks] - ); - - const moveCategoryToDayAction = ( - catIdx: number, - targetDateKey: string, - sourceColumn: "daily" | "weekly" = "daily" - ) => { - const targetOpt = dayOptions.find((d) => d.dateKey === targetDateKey); - const isTargetPast = - targetOpt?.isPast ?? targetDateKey < effectiveTodayDate; - - if (sourceColumn === "weekly") { - if (checkIsDayLocked(targetDateKey)) return; - if (catIdx < 0 || catIdx >= weeklyCategories.length) return; - const sourceCat = weeklyCategories[catIdx]; - if (!sourceCat) return; - - if ( - sourceCat.tasks.some((t) => - isWeeklyTaskGraceExpired({ - taskType: "WEEKLY", - challengeId: t.challengeId, - createdAt: t.createdAt ?? new Date(), - }) - ) - ) { - return; - } - - const res = moveCategoryToDay({ - categoryIndex: catIdx, - sourceColumn: "weekly", - targetDateKey, - dailyCategories, - weeklyCategories, - }); - - setDailyCategories(res.dailyCategories); - setWeeklyCategories(res.weeklyCategories); - - if (res.movedCategory?.id) { - const nowIso = new Date().toISOString(); - const catId = res.movedCategory.id; - - const localCategory: LocalCategoryRecord = { - id: catId, - userId: userId ?? null, - name: res.movedCategory.name, - taskType: "DAILY", - sortOrder: dailyCategories.length, - createdAt: nowIso, - updatedAt: nowIso, - syncState: "pending", - }; - - const tasksToUpdate: LocalTaskRecord[] = res.movedTasks.map( - (t, idx) => ({ - id: t.id, - userId: userId ?? null, - categoryId: catId, - title: t.text || "", - taskType: "DAILY", - sortOrder: idx, - isComplete: Boolean(t.completed), - status: getTaskStatus(t), - dueDate: targetDateKey, - createdAt: t.createdAt || nowIso, - updatedAt: nowIso, - completedAt: t.completed ? nowIso : null, - syncState: "pending", - }) - ); - - const allCatsToUpdate: LocalCategoryRecord[] = [ - ...res.dailyCategories - .filter((c): c is typeof c & { id: string } => Boolean(c.id)) - .map((c, idx) => ({ - id: c.id, - userId: userId ?? null, - name: c.name, - taskType: "DAILY" as const, - sortOrder: idx, - createdAt: nowIso, - updatedAt: nowIso, - syncState: "pending" as const, - })), - ...res.weeklyCategories - .filter((c): c is typeof c & { id: string } => Boolean(c.id)) - .map((c, idx) => ({ - id: c.id, - userId: userId ?? null, - name: c.name, - taskType: "WEEKLY" as const, - sortOrder: idx, - createdAt: nowIso, - updatedAt: nowIso, - syncState: "pending" as const, - })), - ]; - - const mutations: Array> = [ - { - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "MOVE", - payload: { - categoryId: res.movedCategory.id, - taskType: "DAILY", - sortOrder: dailyCategories.length, - }, - createdAt: Date.now(), - retryCount: 0, - }, - ...res.movedTasks.map((t) => ({ - id: crypto.randomUUID(), - entityType: "TASK" as const, - action: "MOVE" as const, - payload: { - taskId: t.id, - categoryId: catId, - taskType: "DAILY", - dueDate: targetDateKey, - }, - createdAt: Date.now(), - retryCount: 0, - })), - ]; - - commitLocalBatch({ - categories: [localCategory, ...allCatsToUpdate], - tasks: tasksToUpdate, - mutations: - isLoggedIn && userId - ? mutations.map((mutation) => ({ ...mutation, userId })) - : [], - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - - if (isLoggedIn && userId) { - trackLogRocketEvent("WeeklyCategoryMovedToDay", { - categoryId: res.movedCategory.id, - targetDateKey, - }); - } - - logTaskSync("Weekly category moved to day via drag and drop", { - categoryId: res.movedCategory.id, - targetDateKey, - }); - } - return; - } - - // sourceColumn === "daily" - if (catIdx < 0 || catIdx >= dailyCategories.length) return; - const sourceCat = dailyCategories[catIdx]; - if (!sourceCat) return; - - const sourceDateKey = selectedDateKey; - if (checkIsDayLocked(sourceDateKey)) return; - const validation = validateMoveTaskChallengeDay( - sourceDateKey, - targetDateKey, - effectiveTodayDate, - { - isChallengeActive: hasChallengeContext, - isTargetDayLocked: checkIsDayLocked(targetDateKey), - } - ); - if (!validation.ok) return; - - if (sourceDateKey === targetDateKey) return; - - const res = moveCategoryToDay({ - categoryIndex: catIdx, - sourceColumn: "daily", - sourceDateKey, - targetDateKey, - dailyCategories, - weeklyCategories, - }); - - setDailyCategories(res.dailyCategories); - - if (res.movedTasks.length > 0 && sourceCat.id) { - const nowIso = new Date().toISOString(); - const catId = sourceCat.id; - - const tasksToUpdate: LocalTaskRecord[] = res.movedTasks.map( - (t, idx) => ({ - id: t.id, - userId: userId ?? null, - categoryId: catId, - title: t.text || "", - taskType: "DAILY", - sortOrder: idx, - isComplete: Boolean(t.completed), - status: getTaskStatus(t), - dueDate: targetDateKey, - createdAt: t.createdAt || nowIso, - updatedAt: nowIso, - completedAt: t.completed ? nowIso : null, - syncState: "pending", - }) - ); - - const mutations: Array> = - res.movedTasks.map((t) => ({ - id: crypto.randomUUID(), - entityType: "TASK" as const, - action: "MOVE" as const, - payload: { - taskId: t.id, - categoryId: catId, - taskType: "DAILY", - dueDate: targetDateKey, - }, - createdAt: Date.now(), - retryCount: 0, - })); - - commitLocalBatch({ - tasks: tasksToUpdate, - mutations: - isLoggedIn && userId - ? mutations.map((mutation) => ({ ...mutation, userId })) - : [], - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - - if (isLoggedIn && userId) { - trackLogRocketEvent("DailyCategoryMovedToDay", { - categoryId: catId, - targetDateKey, - tasksCount: res.movedTasks.length, - }); - } - - logTaskSync("Daily category moved to day via drag and drop", { - categoryId: catId, - tasksCount: res.movedTasks.length, - targetDateKey, - }); - } - }; - - const handleSaveEditCategory = (newName: string) => { - if (!editCategoryModal || !newName.trim()) return; - const oldName = editCategoryModal.name; - const trimmed = newName.trim(); - const catType = editCategoryModal.taskType; - const catId = - editCategoryModal.id || - (catType === "daily" - ? dailyCategoryNameToId.get(oldName) || - dailyCategories.find((c) => c.name === oldName)?.id - : weeklyCategoryNameToId.get(oldName) || - weeklyCategories.find((c) => c.name === oldName)?.id); - - if (oldName === trimmed) { - setEditCategoryModal(null); - return; - } - - setDailyCategories((prev) => - prev.map((cat) => - (catId && cat.id === catId) || cat.name === oldName - ? { ...cat, name: trimmed } - : cat - ) - ); - setWeeklyCategories((prev) => - prev.map((cat) => - (catId && cat.id === catId) || cat.name === oldName - ? { ...cat, name: trimmed } - : cat - ) - ); - - if (catId) { - persistCategory( - { - id: catId, - userId: userId ?? null, - name: trimmed, - taskType: catType === "daily" ? "DAILY" : "WEEKLY", - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - syncState: "pending", - }, - { - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "UPDATE", - payload: { categoryId: catId, name: trimmed }, - createdAt: Date.now(), - retryCount: 0, - } - ) - .then(() => scheduleSync(userId)) - .catch(() => {}); - } - - logTaskSync("Category updated", { categoryId: catId, name: trimmed }); - setEditCategoryModal(null); - }; - - const handleConfirmDeleteCategory = () => { - if (!deleteCategoryModal) return; - const targetName = deleteCategoryModal.name; - const catType = deleteCategoryModal.taskType; - const catId = - deleteCategoryModal.id || - dailyCategoryNameToId.get(targetName) || - weeklyCategoryNameToId.get(targetName) || - dailyCategories.find((c) => c.name === targetName)?.id || - weeklyCategories.find((c) => c.name === targetName)?.id; - - const dailyTargetCat = dailyCategories.find((c) => - catId ? c.id === catId : catType === "daily" && c.name === targetName - ); - const hasLockedTasks = Boolean( - dailyTargetCat?.tasks.some((t) => { - const dateKey = getTaskDateKey(t); - return checkIsDayLocked(dateKey); - }) - ); - - const weeklyTargetCat = weeklyCategories.find((c) => - catId ? c.id === catId : catType === "weekly" && c.name === targetName - ); - const hasGraceLockedTasks = Boolean( - weeklyTargetCat?.tasks.some((t) => - isWeeklyTaskGraceExpired({ - taskType: "WEEKLY", - challengeId: t.challengeId, - createdAt: t.createdAt ?? new Date(), - }) - ) - ); - - if (hasLockedTasks || hasGraceLockedTasks) { - setDeleteCategoryModal(null); - return; - } - - if (catType === "weekly") { - setWeeklyCategories((prev) => - prev.filter((cat) => - catId ? cat.id !== catId : cat.name !== targetName - ) - ); - setDailyCategories((prev) => - prev.filter((cat) => - catId ? cat.id !== catId : cat.name !== targetName - ) - ); - } else { - setDailyCategories((prev) => - prev.filter((cat) => - catId ? cat.id !== catId : cat.name !== targetName - ) - ); - } - - if (catId) { - deleteCategoryWithMutation(catId, { - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "DELETE", - payload: { categoryId: catId }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - } - - if (catId || targetName) { - setCollapsedCategoryIds((prev) => { - const next = new Set(prev); - if (catId) { - next.delete(catId); - next.delete(`daily:${catId}`); - next.delete(`weekly:${catId}`); - } - if (targetName) { - next.delete(targetName); - next.delete(`daily:name:${targetName}`); - next.delete(`weekly:name:${targetName}`); - } - writeCollapsedCategoryIds(userId, next); - collapsedCategoryIdsRef.current = next; - return next; - }); - } - - logTaskSync("Category deleted", { categoryId: catId, name: targetName }); - setDeleteCategoryModal(null); - }; - - const totalDailyTasks = dailyCategories.reduce( - (acc, cat) => acc + cat.tasks.length, - 0 - ); - const completedDailyTasks = dailyCategories.reduce( - (acc, cat) => acc + cat.tasks.filter((t) => t.completed).length, - 0 - ); - - const dailyTasksForSelectedDay = useMemo(() => { - return dailyCategories.flatMap((cat) => - cat.tasks.filter((t) => getTaskDateKey(t) === selectedDateKey) - ); - }, [dailyCategories, selectedDateKey, getTaskDateKey]); - - const completedDailyTasksForDay = dailyTasksForSelectedDay.filter( - (t) => t.completed - ).length; - const totalDailyTasksForDay = dailyTasksForSelectedDay.length; - - const dayTaskCounts = useMemo(() => { - const counts = new Map(); - for (const opt of dayOptions) { - counts.set(opt.dateKey, { total: 0, completed: 0 }); - } - for (const cat of dailyCategories) { - for (const task of cat.tasks) { - const key = getTaskDateKey(task); - const entry = counts.get(key); - if (entry) { - entry.total += 1; - if (task.completed) entry.completed += 1; - } else { - counts.set(key, { total: 1, completed: task.completed ? 1 : 0 }); - } - } - } - return counts; - }, [dayOptions, dailyCategories, getTaskDateKey]); - - const totalWeeklyTasks = weeklyCategories.reduce( - (acc, cat) => acc + cat.tasks.length, - 0 - ); - const completedWeeklyTasks = weeklyCategories.reduce( - (acc, cat) => acc + cat.tasks.filter((t) => t.completed).length, - 0 - ); - - const totalWeeklyTasksForWeek = useMemo(() => { - return weeklyCategories.reduce( - (acc, cat) => acc + cat.tasks.filter(isTaskInWeeklyWeek).length, - 0 - ); - }, [weeklyCategories, isTaskInWeeklyWeek]); - - const completedWeeklyTasksForWeek = useMemo(() => { - return weeklyCategories.reduce( - (acc, cat) => - acc + - cat.tasks.filter((t) => isTaskInWeeklyWeek(t) && t.completed) - .length, - 0 - ); - }, [weeklyCategories, isTaskInWeeklyWeek]); - - const visibleWeeklyTasksCount = useMemo( - () => - visibleWeeklyCategories.reduce( - (acc, cat) => acc + cat.tasks.filter(isTaskInWeeklyWeek).length, - 0 - ), - [visibleWeeklyCategories, isTaskInWeeklyWeek] - ); - - const handleExportDaily = useCallback( - (style: TaskExportStyle) => { - const exportCategories = dailyCategories.map((cat) => ({ - id: cat.id, - name: cat.name, - tasks: cat.tasks - .filter((t) => getTaskDateKey(t) === selectedDateKey) - .map((t) => ({ - id: t.id, - text: t.text, - completed: t.completed, - status: getTaskStatus(t), - challengeId: t.challengeId, - isChallengeGoal: Boolean( - linkableChallengeId && - t.challengeId === linkableChallengeId - ), - })), - })); - - return formatDailyTasksExport({ - dateKey: selectedDateKey, - dateLabel: formatFullDayDate(selectedDateKey), - dayNumber: hasChallengeContext - ? activeDayOption?.dayNumber - : undefined, - categories: exportCategories, - style, - }); - }, - [ - dailyCategories, - selectedDateKey, - getTaskDateKey, - hasChallengeContext, - activeDayOption, - linkableChallengeId, - ] - ); - - const handleExportWeekly = useCallback( - (style: TaskExportStyle) => { - const exportCategories = visibleWeeklyCategories.map((cat) => ({ - id: cat.id, - name: cat.name, - tasks: cat.tasks.filter(isTaskInWeeklyWeek).map((t) => ({ - id: t.id, - text: t.text, - completed: t.completed, - status: getTaskStatus(t), - challengeId: t.challengeId, - isChallengeGoal: Boolean( - linkableChallengeId && t.challengeId === linkableChallengeId - ), - })), - })); - - return formatWeeklyTasksExport({ - weekRangeLabel: weeklyRangeLabel || "Active Week", - categories: exportCategories, - style, - }); - }, - [ - visibleWeeklyCategories, - isTaskInWeeklyWeek, - weeklyRangeLabel, - linkableChallengeId, - ] - ); - const handleAddTodoSubmit = (e: React.FormEvent) => { - e.preventDefault(); - if (!newTodoText.trim()) return; - - const trimmedCustom = customCategory.trim(); - // If user typed a custom name that matches an existing weekly category, link to that parent category - const matchingWeekly = trimmedCustom - ? weeklyCategories.find( - (c) => c.name.toLowerCase() === trimmedCustom.toLowerCase() - ) || - userTasks?.categories?.find( - (c) => - c.taskType === "WEEKLY" && - c.name.toLowerCase() === trimmedCustom.toLowerCase() - ) - : undefined; - - const isNew = Boolean( - isCreatingCategory && trimmedCustom && !matchingWeekly - ); - const targetCategoryName = - (isCreatingCategory && trimmedCustom - ? matchingWeekly?.name || trimmedCustom - : selectedCategory) || "General"; - const taskType = addModalType === "daily" ? "DAILY" : "WEEKLY"; - const resolvedDueDate = - addModalType === "daily" - ? addTodoDateKey || selectedDateKey - : isViewingCurrentWeeklyWeek - ? null - : activeWeeklyAnchorDateKey; - - if (addModalType === "daily" && resolvedDueDate) { - if (checkIsDayLocked(resolvedDueDate)) { - return; - } - } - - const targetChallengeId = - addModalType === "weekly" - ? addTodoChallengeScope === "CHALLENGE" - ? linkableChallengeId - : null - : null; - - const nowIso = new Date().toISOString(); - const newTaskId = crypto.randomUUID(); - const nextCompleted = newTodoStatus === "COMPLETED"; - const newTask: TaskItem = { - id: newTaskId, - text: newTodoText.trim(), - completed: nextCompleted, - status: newTodoStatus, - dueDate: resolvedDueDate, - createdAt: nowIso, - challengeId: targetChallengeId, - }; - - let targetCatId: string | undefined = undefined; - - if (addModalType === "daily") { - const existingInDaily = dailyCategories.find( - (c) => c.name === targetCategoryName - ); - const existingInWeekly = weeklyCategories.find( - (c) => c.name === targetCategoryName - ); - const existingInServer = userTasks?.categories?.find( - (c) => c.name === targetCategoryName - ); - - targetCatId = - existingInDaily?.id || - existingInWeekly?.id || - existingInServer?.id || - (isNew - ? crypto.randomUUID() - : dailyCategoryNameToId.get(targetCategoryName) || - weeklyCategoryNameToId.get(targetCategoryName) || - crypto.randomUUID()); - - setDailyCategories((prev) => { - const existingIndex = prev.findIndex( - (c) => c.name === targetCategoryName - ); - if (existingIndex >= 0) { - return prev.map((cat, i) => - i === existingIndex - ? { - ...cat, - id: cat.id || targetCatId, - isCollapsed: cat.isCollapsed, - tasks: [...cat.tasks, newTask], - } - : cat - ); - } else { - return [ - ...prev, - { - id: targetCatId, - name: targetCategoryName, - isCollapsed: false, - tasks: [newTask], - }, - ]; - } - }); - } else { - const existingInWeekly = weeklyCategories.find( - (c) => c.name === targetCategoryName - ); - const existingInServer = userTasks?.categories?.find( - (c) => c.name === targetCategoryName - ); - - targetCatId = - existingInWeekly?.id || - existingInServer?.id || - (isNew - ? crypto.randomUUID() - : weeklyCategoryNameToId.get(targetCategoryName) || - crypto.randomUUID()); - - setWeeklyCategories((prev) => { - const existingIndex = prev.findIndex( - (c) => c.name === targetCategoryName - ); - if (existingIndex >= 0) { - return prev.map((cat, i) => - i === existingIndex - ? { - ...cat, - id: cat.id || targetCatId, - isCollapsed: cat.isCollapsed, - tasks: [...cat.tasks, newTask], - } - : cat - ); - } else { - return [ - ...prev, - { - id: targetCatId, - name: targetCategoryName, - isCollapsed: false, - tasks: [newTask], - }, - ]; - } - }); - } - - let initialSortOrder = 0; - if (isNew && targetCatId) { - const boardCategories = - addModalType === "daily" ? dailyCategories : weeklyCategories; - const highestOrder = boardCategories.reduce( - (max, c) => Math.max(max, c.sortOrder ?? 0), - -1 - ); - initialSortOrder = highestOrder + 1; - } - - const localCategories: LocalCategoryRecord[] = - isNew && targetCatId - ? [ - { - id: targetCatId, - userId: userId ?? null, - name: targetCategoryName, - taskType: addModalType === "daily" ? "DAILY" : "WEEKLY", - sortOrder: initialSortOrder, - createdAt: nowIso, - updatedAt: nowIso, - syncState: "pending", - }, - ] - : []; - - const localTasks: LocalTaskRecord[] = targetCatId - ? [ - { - id: newTaskId, - userId: userId ?? null, - categoryId: targetCatId, - challengeId: targetChallengeId, - title: newTodoText.trim(), - taskType, - isComplete: nextCompleted, - status: newTodoStatus, - dueDate: resolvedDueDate, - createdAt: nowIso, - updatedAt: nowIso, - completedAt: nextCompleted ? nowIso : null, - syncState: "pending", - }, - ] - : []; - - const mutations: Array> = []; - if (isNew && targetCatId) { - mutations.push({ - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "CREATE", - payload: { - id: targetCatId, - name: targetCategoryName, - taskType: addModalType === "daily" ? "DAILY" : "WEEKLY", - sortOrder: initialSortOrder, - }, - createdAt: Date.now(), - retryCount: 0, - }); - } - - mutations.push({ - id: crypto.randomUUID(), - entityType: "TASK", - action: "CREATE", - payload: { - id: newTaskId, - categoryId: targetCatId, - challengeId: targetChallengeId, - title: newTodoText.trim(), - taskType, - isComplete: nextCompleted, - status: newTodoStatus, - dueDate: resolvedDueDate, - }, - createdAt: Date.now() + 1, - retryCount: 0, - }); - - commitLocalBatch({ - categories: localCategories, - tasks: localTasks, - mutations: - isLoggedIn && userId - ? mutations.map((mutation) => ({ ...mutation, userId })) - : [], - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - - if (isLoggedIn && userId) { - trackLogRocketEvent("TaskCreated", { - taskType, - isNewCategory: isNew, - }); - } - - logTaskSync("Task created", { - id: newTaskId, - title: newTodoText.trim(), - dueDate: resolvedDueDate, - }); - - setNewTodoText(""); - setNewTodoStatus("TODO"); - setCustomCategory(""); - setIsCreatingCategory(false); - setAddModalType(null); - }; - - const handleAddSampleTask = useCallback( - (taskText: string) => { - const trimmed = taskText.trim(); - if (!trimmed) return; - const targetCategoryName = "Study Commitments"; - const targetDateKey = selectedDateKey || effectiveTodayDate; - const newTaskId = crypto.randomUUID(); - const newTask: TaskItem = { - id: newTaskId, - text: trimmed, - completed: false, - status: "TODO", - dueDate: targetDateKey, - challengeId: null, - }; - - const existingCat = dailyCategories.find( - (c) => c.name === targetCategoryName - ); - const targetCatId = existingCat?.id || crypto.randomUUID(); - - setDailyCategories((prev) => { - const existingIdx = prev.findIndex( - (c) => c.name === targetCategoryName - ); - if (existingIdx >= 0) { - return prev.map((cat, i) => - i === existingIdx - ? { - ...cat, - id: cat.id || targetCatId, - tasks: [...cat.tasks, newTask], - } - : cat - ); - } - return [ - ...prev, - { - id: targetCatId, - name: targetCategoryName, - isCollapsed: false, - sortOrder: 0, - tasks: [newTask], - }, - ]; - }); - - const nowIso = new Date().toISOString(); - if (!existingCat) { - putLocalCategory({ - id: targetCatId, - userId: userId ?? null, - name: targetCategoryName, - taskType: "DAILY", - sortOrder: 0, - createdAt: nowIso, - updatedAt: nowIso, - syncState: "pending", - }).catch(() => {}); - } - - putLocalTask({ - id: newTaskId, - userId: userId ?? null, - categoryId: targetCatId, - challengeId: null, - title: trimmed, - taskType: "DAILY", - isComplete: false, - status: "TODO", - dueDate: targetDateKey, - createdAt: nowIso, - updatedAt: nowIso, - completedAt: null, - syncState: "pending", - }).catch(() => {}); - }, - [selectedDateKey, effectiveTodayDate, dailyCategories, userId] - ); - - useEffect(() => { - if (typeof window === "undefined") return; - const handleSampleTaskEvent = (e: Event) => { - const customEvent = e as CustomEvent<{ title?: string }>; - if (customEvent.detail?.title) { - handleAddSampleTask(customEvent.detail.title); - } - }; - window.addEventListener(LOAD_SAMPLE_TASK_EVENT, handleSampleTaskEvent); - return () => { - window.removeEventListener( - LOAD_SAMPLE_TASK_EVENT, - handleSampleTaskEvent - ); - }; - }, [handleAddSampleTask]); - - // --------------------------------------------------------------------------- - // Drag and Drop Event Handlers - // --------------------------------------------------------------------------- - - const handleTaskDragStart = ( - e: React.DragEvent, - taskId: string, - catIdx: number, - column: "daily" | "weekly" - ) => { - e.stopPropagation(); - const pool = column === "daily" ? dailyCategories : weeklyCategories; - const sourceTask = pool[catIdx]?.tasks.find((t) => t.id === taskId); - const sourceDateKey = sourceTask - ? getTaskDateKey(sourceTask) - : column === "daily" - ? selectedDateKey - : undefined; - - setDraggedItem({ - type: "task", - id: taskId, - sourceCatIdx: catIdx, - sourceColumn: column, - sourceDateKey, - }); - e.dataTransfer.effectAllowed = "move"; - e.dataTransfer.setData( - "application/json", - JSON.stringify({ type: "task", taskId, catIdx, column, sourceDateKey }) - ); - - const targetEl = e.currentTarget as HTMLElement; - const cardEl = targetEl.closest('[data-drag-card="task"]'); - if (cardEl && e.dataTransfer && e.dataTransfer.setDragImage) { - const rect = cardEl.getBoundingClientRect(); - const offsetX = Math.max( - 16, - Math.min(e.clientX - rect.left, rect.width - 16) - ); - const offsetY = Math.max( - 12, - Math.min(e.clientY - rect.top, rect.height - 12) - ); - e.dataTransfer.setDragImage(cardEl, offsetX, offsetY); - } - }; - - const handleCategoryDragStart = ( - e: React.DragEvent, - catIdx: number, - column: "daily" | "weekly" - ) => { - e.stopPropagation(); - const sourceDateKey = column === "daily" ? selectedDateKey : undefined; - setDraggedItem({ - type: "category", - sourceCatIdx: catIdx, - sourceColumn: column, - sourceDateKey, - }); - e.dataTransfer.effectAllowed = "move"; - e.dataTransfer.setData( - "application/json", - JSON.stringify({ type: "category", catIdx, column, sourceDateKey }) - ); - - const targetEl = e.currentTarget as HTMLElement; - const cardEl = targetEl.closest( - '[data-drag-card="category"]' - ); - if (cardEl && e.dataTransfer && e.dataTransfer.setDragImage) { - const rect = cardEl.getBoundingClientRect(); - const offsetX = Math.max( - 20, - Math.min(e.clientX - rect.left, rect.width - 20) - ); - const offsetY = 20; - e.dataTransfer.setDragImage(cardEl, offsetX, offsetY); - } - }; - - const handleDragEnd = () => { - setDraggedItem(null); - setDragOverInfo(null); - }; - - const handleTaskDragOver = ( - e: React.DragEvent, - targetTaskId: string, - targetCatIdx: number, - targetColumn: "daily" | "weekly" - ) => { - if (!draggedItem) return; - if (draggedItem.type === "category") { - handleCategoryDragOver(e, targetCatIdx, targetColumn); - return; - } - if (draggedItem.type !== "task") return; - e.preventDefault(); - e.stopPropagation(); - - if ( - targetColumn === "daily" && - draggedItem.sourceColumn === "weekly" && - isPastDayLocked - ) { - e.dataTransfer.dropEffect = "none"; - return; - } - - e.dataTransfer.dropEffect = "move"; - const rect = e.currentTarget.getBoundingClientRect(); - const midY = rect.top + rect.height / 2; - const position = e.clientY < midY ? "above" : "below"; - - setDragOverInfo({ - type: "task", - targetId: targetTaskId, - targetCatIdx, - targetColumn, - position, - }); - }; - - const handleCategoryDragOver = ( - e: React.DragEvent, - targetCatIdx: number, - targetColumn: "daily" | "weekly" - ) => { - if (!draggedItem) return; - e.preventDefault(); - e.stopPropagation(); - - if ( - targetColumn === "daily" && - draggedItem.sourceColumn === "weekly" && - isPastDayLocked - ) { - e.dataTransfer.dropEffect = "none"; - return; - } - - e.dataTransfer.dropEffect = "move"; - if (draggedItem.type === "category") { - const rect = e.currentTarget.getBoundingClientRect(); - const midY = rect.top + rect.height / 2; - const position = e.clientY < midY ? "above" : "below"; - setDragOverInfo({ - type: "category", - targetCatIdx, - targetColumn, - position, - }); - } else if (draggedItem.type === "task") { - setDragOverInfo({ - type: "category", - targetCatIdx, - targetColumn, - }); - } - }; - - const handleColumnDragOver = ( - e: React.DragEvent, - targetColumn: "daily" | "weekly" - ) => { - if (!draggedItem) return; - if ( - targetColumn === "daily" && - draggedItem.sourceColumn === "weekly" && - isPastDayLocked - ) { - e.dataTransfer.dropEffect = "none"; - return; - } - e.preventDefault(); - e.dataTransfer.dropEffect = "move"; - if (!dragOverInfo || dragOverInfo.targetColumn !== targetColumn) { - setDragOverInfo({ - type: "column", - targetColumn, - }); - } - }; - - const handleDayPillDragOver = ( - e: React.DragEvent, - opt: ChallengeDayOption - ) => { - if (!draggedItem) return; - e.preventDefault(); - e.stopPropagation(); - - if (draggedItem.sourceColumn === "daily") { - const sourceDateKey = draggedItem.sourceDateKey || selectedDateKey; - if (checkIsDayLocked(sourceDateKey)) { - e.dataTransfer.dropEffect = "none"; - return; - } - const validation = validateMoveTaskChallengeDay( - sourceDateKey, - opt.dateKey, - effectiveTodayDate, - { - isChallengeActive: hasChallengeContext, - isTargetDayLocked: checkIsDayLocked(opt.dateKey), - } - ); - if (!validation.ok) { - e.dataTransfer.dropEffect = "none"; - if (!dragOverInfo || dragOverInfo.targetDateKey !== opt.dateKey) { - setDragOverInfo({ - type: "day", - targetDateKey: opt.dateKey, - }); - } - return; - } - } else if (draggedItem.sourceColumn === "weekly") { - if ( - checkIsDayLocked(opt.dateKey) || - (hasChallengeContext && opt.isPast) - ) { - e.dataTransfer.dropEffect = "none"; - if (!dragOverInfo || dragOverInfo.targetDateKey !== opt.dateKey) { - setDragOverInfo({ - type: "day", - targetDateKey: opt.dateKey, - }); - } - return; - } - } - - e.dataTransfer.dropEffect = "move"; - if (!dragOverInfo || dragOverInfo.targetDateKey !== opt.dateKey) { - setDragOverInfo({ - type: "day", - targetDateKey: opt.dateKey, - }); - } - }; - - const handleDayPillDrop = (e: React.DragEvent, opt: ChallengeDayOption) => { - e.preventDefault(); - e.stopPropagation(); - - if (!draggedItem) { - handleDragEnd(); - return; - } - - if (draggedItem.type === "category") { - if (draggedItem.sourceColumn === "daily") { - const sourceDateKey = draggedItem.sourceDateKey || selectedDateKey; - if (checkIsDayLocked(sourceDateKey)) { - handleDragEnd(); - return; - } - const validation = validateMoveTaskChallengeDay( - sourceDateKey, - opt.dateKey, - effectiveTodayDate, - { - isChallengeActive: hasChallengeContext, - isTargetDayLocked: checkIsDayLocked(opt.dateKey), - } - ); - if (!validation.ok) { - handleDragEnd(); - return; - } - moveCategoryToDayAction( - draggedItem.sourceCatIdx, - opt.dateKey, - "daily" - ); - } else if (draggedItem.sourceColumn === "weekly") { - if ( - checkIsDayLocked(opt.dateKey) || - (hasChallengeContext && opt.isPast) - ) { - handleDragEnd(); - return; - } - moveCategoryToDayAction( - draggedItem.sourceCatIdx, - opt.dateKey, - "weekly" - ); - } - handleDragEnd(); - return; - } - - if (draggedItem.type === "task" && draggedItem.id) { - if (draggedItem.sourceColumn === "daily") { - const sourceDateKey = draggedItem.sourceDateKey || selectedDateKey; - if (checkIsDayLocked(sourceDateKey)) { - handleDragEnd(); - return; - } - const validation = validateMoveTaskChallengeDay( - sourceDateKey, - opt.dateKey, - effectiveTodayDate, - { - isChallengeActive: hasChallengeContext, - isTargetDayLocked: checkIsDayLocked(opt.dateKey), - } - ); - if (!validation.ok) { - handleDragEnd(); - return; - } - moveTaskToDay( - draggedItem.id, - opt.dateKey, - draggedItem.sourceCatIdx, - "daily" - ); - } else if (draggedItem.sourceColumn === "weekly") { - if ( - checkIsDayLocked(opt.dateKey) || - (hasChallengeContext && opt.isPast) - ) { - handleDragEnd(); - return; - } - moveTaskToDay( - draggedItem.id, - opt.dateKey, - draggedItem.sourceCatIdx, - "weekly" - ); - } - } - - handleDragEnd(); - }; - - const handleTaskDrop = ( - e: React.DragEvent, - targetTaskId: string, - targetCatIdx: number, - targetColumn: "daily" | "weekly" - ) => { - e.preventDefault(); - e.stopPropagation(); - - if (!draggedItem) { - handleDragEnd(); - return; - } - - if (draggedItem.type === "category") { - handleCategoryDrop(e, targetCatIdx, targetColumn); - return; - } - - if (draggedItem.type !== "task" || !draggedItem.id) { - handleDragEnd(); - return; - } - - if ( - (targetColumn === "daily" || draggedItem.sourceColumn === "daily") && - isPastDayLocked - ) { - handleDragEnd(); - return; - } - - const targetCategories = - targetColumn === "daily" ? dailyCategories : weeklyCategories; - const targetCat = targetCategories[targetCatIdx]; - if (!targetCat) { - handleDragEnd(); - return; - } - - const targetIndexInCat = targetCat.tasks.findIndex( - (t) => t.id === targetTaskId - ); - const destIdx = - dragOverInfo?.position === "below" - ? targetIndexInCat + 1 - : targetIndexInCat; - - const isMovingWeeklyToDaily = - draggedItem.sourceColumn === "weekly" && targetColumn === "daily"; - const isMovingDailyToWeekly = - draggedItem.sourceColumn === "daily" && targetColumn === "weekly"; - const targetDueDate = isMovingWeeklyToDaily - ? selectedDateKey - : isMovingDailyToWeekly - ? null - : undefined; - - const res = moveTaskBetweenCategories({ - taskId: draggedItem.id, - sourceCategoryIndex: draggedItem.sourceCatIdx, - sourceColumn: draggedItem.sourceColumn, - targetCategoryIndex: targetCatIdx, - targetColumn, - targetTaskIndex: Math.max(0, destIdx), - targetDueDate, - dailyCategories, - weeklyCategories, - }); - - setDailyCategories(res.dailyCategories); - setWeeklyCategories(res.weeklyCategories); - - if (res.movedTask && res.targetCategoryId) { - const nowIso = new Date().toISOString(); - const targetCats = - res.targetTaskType === "DAILY" - ? res.dailyCategories - : res.weeklyCategories; - const targetCatGroup = targetCats[targetCatIdx]; - - if (targetCatGroup && targetCatGroup.tasks.length > 0) { - const tasksToUpdate: LocalTaskRecord[] = targetCatGroup.tasks.map( - (t, idx) => ({ - id: t.id, - userId: userId ?? null, - categoryId: res.targetCategoryId!, - title: t.text, - taskType: res.targetTaskType, - sortOrder: idx, - isComplete: t.completed, - status: getTaskStatus(t), - dueDate: t.dueDate ?? null, - createdAt: t.createdAt || nowIso, - updatedAt: nowIso, - completedAt: t.completed ? nowIso : null, - syncState: "pending", - }) - ); - - const taskIds = targetCatGroup.tasks - .map((t) => t.id) - .filter((id) => Boolean(id)); - - if (isLoggedIn && userId && taskIds.length > 0) { - persistTasks(tasksToUpdate, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "REORDER", - payload: { taskIds }, - createdAt: Date.now() + 1, - retryCount: 0, - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - } else { - putLocalTasks(tasksToUpdate).catch(() => {}); - } - } else { - const isMovedComplete = Boolean( - res.movedTask.completed ?? res.movedTask.isComplete - ); - const movedStatus = - (res.movedTask.status as TaskStatus) || - (isMovedComplete ? "COMPLETED" : "TODO"); - const movedLocalTask: LocalTaskRecord = { - id: res.movedTask.id, - userId: userId ?? null, - categoryId: res.targetCategoryId, - title: res.movedTask.text ?? res.movedTask.title ?? "", - taskType: res.targetTaskType, - sortOrder: destIdx, - isComplete: isMovedComplete, - status: movedStatus, - dueDate: res.movedTask.dueDate ?? null, - createdAt: res.movedTask.createdAt - ? new Date(res.movedTask.createdAt).toISOString() - : nowIso, - updatedAt: nowIso, - completedAt: isMovedComplete ? nowIso : null, - syncState: "pending", - }; - - if (isLoggedIn && userId) { - persistTask(movedLocalTask, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "MOVE", - payload: { - taskId: res.movedTask.id, - categoryId: res.targetCategoryId, - taskType: res.targetTaskType, - sortOrder: destIdx, - dueDate: res.movedTask.dueDate ?? null, - }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - } else { - putLocalTask(movedLocalTask).catch(() => {}); - } - } - - if (isLoggedIn && userId) { - trackLogRocketEvent("TaskMoved", { - taskId: res.movedTask.id, - targetTaskType: res.targetTaskType, - }); - } - - logTaskSync("Task moved via drag and drop", { - taskId: res.movedTask.id, - targetCatIdx, - targetColumn, - }); - } - - handleDragEnd(); - }; - - const handleCategoryDrop = ( - e: React.DragEvent, - targetCatIdx: number, - targetColumn: "daily" | "weekly" - ) => { - e.preventDefault(); - e.stopPropagation(); - - if (!draggedItem) { - handleDragEnd(); - return; - } - - if ( - (targetColumn === "daily" || draggedItem.sourceColumn === "daily") && - isPastDayLocked - ) { - handleDragEnd(); - return; - } - - if (draggedItem.type === "category") { - let destIndex: number; - if (draggedItem.sourceColumn === targetColumn) { - if (draggedItem.sourceCatIdx === targetCatIdx) { - handleDragEnd(); - return; - } - destIndex = calculateReorderIndex( - draggedItem.sourceCatIdx, - targetCatIdx, - dragOverInfo?.position || "above" - ); - } else { - destIndex = - dragOverInfo?.position === "below" - ? targetCatIdx + 1 - : targetCatIdx; - } - - const isMovingWeeklyToDaily = - draggedItem.sourceColumn === "weekly" && targetColumn === "daily"; - const isMovingDailyToWeekly = - draggedItem.sourceColumn === "daily" && targetColumn === "weekly"; - const targetDueDate = isMovingWeeklyToDaily - ? selectedDateKey - : isMovingDailyToWeekly - ? null - : undefined; - - const res = moveCategoryBetweenColumns({ - categoryIndex: draggedItem.sourceCatIdx, - sourceColumn: draggedItem.sourceColumn, - targetColumn, - targetIndex: destIndex, - targetDueDate, - dailyCategories, - weeklyCategories, - }); - - setDailyCategories(res.dailyCategories); - setWeeklyCategories(res.weeklyCategories); - - if (res.movedCategory?.id) { - const nowIso = new Date().toISOString(); - const catId = res.movedCategory.id; - const targetType = res.targetTaskType; - - const localCategory: LocalCategoryRecord = { - id: catId, - userId: userId ?? null, - name: res.movedCategory.name, - taskType: targetType, - sortOrder: destIndex, - createdAt: nowIso, - updatedAt: nowIso, - syncState: "pending", - }; - - // Cascade taskType and dueDate to all tasks inside this category. - const tasksToUpdate: LocalTaskRecord[] = ( - res.movedCategory.tasks ?? [] - ).map((t, idx) => ({ - id: t.id, - userId: userId ?? null, - categoryId: catId, - title: t.text, - taskType: targetType, - sortOrder: idx, - isComplete: t.completed, - status: getTaskStatus(t), - dueDate: t.dueDate ?? null, - createdAt: t.createdAt || nowIso, - updatedAt: nowIso, - completedAt: t.completed ? nowIso : null, - syncState: "pending", - })); - - // Persist updated sortOrder for all categories in both columns. - const allCatsToUpdate: LocalCategoryRecord[] = [ - ...res.dailyCategories - .filter((c): c is typeof c & { id: string } => Boolean(c.id)) - .map((c, idx) => ({ - id: c.id, - userId: userId ?? null, - name: c.name, - taskType: "DAILY" as const, - sortOrder: idx, - createdAt: c.createdAt - ? typeof c.createdAt === "string" - ? c.createdAt - : c.createdAt.toISOString() - : nowIso, - updatedAt: nowIso, - syncState: "pending" as const, - })), - ...res.weeklyCategories - .filter((c): c is typeof c & { id: string } => Boolean(c.id)) - .map((c, idx) => ({ - id: c.id, - userId: userId ?? null, - name: c.name, - taskType: "WEEKLY" as const, - sortOrder: idx, - createdAt: c.createdAt - ? typeof c.createdAt === "string" - ? c.createdAt - : c.createdAt.toISOString() - : nowIso, - updatedAt: nowIso, - syncState: "pending" as const, - })), - ]; - - const mutations: Array> = []; - - const dailyCatIds = res.dailyCategories - .map((c) => c.id) - .filter((id): id is string => Boolean(id)); - if (dailyCatIds.length > 0) { - mutations.push({ - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "REORDER", - payload: { categoryIds: dailyCatIds }, - createdAt: Date.now(), - retryCount: 0, - }); - } - - const weeklyCatIds = res.weeklyCategories - .map((c) => c.id) - .filter((id): id is string => Boolean(id)); - if (weeklyCatIds.length > 0) { - mutations.push({ - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "REORDER", - payload: { categoryIds: weeklyCatIds }, - createdAt: Date.now() + 1, - retryCount: 0, - }); - } - - if (draggedItem.sourceColumn !== targetColumn) { - mutations.push({ - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "MOVE", - payload: { - categoryId: res.movedCategory.id, - taskType: res.targetTaskType, - sortOrder: destIndex, - }, - createdAt: Date.now() + 2, - retryCount: 0, - }); - } - - if (isMovingWeeklyToDaily) { - for (const t of res.movedCategory.tasks ?? []) { - mutations.push({ - id: crypto.randomUUID(), - entityType: "TASK", - action: "MOVE", - payload: { - taskId: t.id, - categoryId: catId, - taskType: "DAILY", - dueDate: selectedDateKey, - }, - createdAt: Date.now(), - retryCount: 0, - }); - } - } - - commitLocalBatch({ - categories: [localCategory, ...allCatsToUpdate], - tasks: tasksToUpdate, - mutations: - isLoggedIn && userId - ? mutations.map((mutation) => ({ ...mutation, userId })) - : [], - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - - if (isLoggedIn && userId) { - trackLogRocketEvent("CategoryMoved", { - categoryId: res.movedCategory.id, - targetTaskType: res.targetTaskType, - }); - } - - logTaskSync("Category moved via drag and drop", { - categoryId: res.movedCategory.id, - targetColumn, - }); - } - } else if (draggedItem.type === "task" && draggedItem.id) { - // Dropping a task into a category header - const isMovingWeeklyToDaily = - draggedItem.sourceColumn === "weekly" && targetColumn === "daily"; - const isMovingDailyToWeekly = - draggedItem.sourceColumn === "daily" && targetColumn === "weekly"; - const targetDueDate = isMovingWeeklyToDaily - ? selectedDateKey - : isMovingDailyToWeekly - ? null - : undefined; - - const res = moveTaskBetweenCategories({ - taskId: draggedItem.id, - sourceCategoryIndex: draggedItem.sourceCatIdx, - sourceColumn: draggedItem.sourceColumn, - targetCategoryIndex: targetCatIdx, - targetColumn, - targetTaskIndex: 0, - targetDueDate, - dailyCategories, - weeklyCategories, - }); - - setDailyCategories(res.dailyCategories); - setWeeklyCategories(res.weeklyCategories); - - if (res.movedTask && res.targetCategoryId) { - const nowIso = new Date().toISOString(); - const isMovedComplete = Boolean( - res.movedTask.completed ?? res.movedTask.isComplete - ); - const movedStatus = - (res.movedTask.status as TaskStatus) || - (isMovedComplete ? "COMPLETED" : "TODO"); - const movedLocalTask: LocalTaskRecord = { - id: res.movedTask.id, - userId: userId ?? null, - categoryId: res.targetCategoryId, - title: res.movedTask.text ?? res.movedTask.title ?? "", - taskType: res.targetTaskType, - sortOrder: 0, - isComplete: isMovedComplete, - status: movedStatus, - dueDate: res.movedTask.dueDate ?? null, - createdAt: res.movedTask.createdAt - ? new Date(res.movedTask.createdAt).toISOString() - : nowIso, - updatedAt: nowIso, - completedAt: isMovedComplete ? nowIso : null, - syncState: "pending", - }; - - persistTask(movedLocalTask, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "MOVE", - payload: { - taskId: res.movedTask.id, - categoryId: res.targetCategoryId, - taskType: res.targetTaskType, - sortOrder: 0, - dueDate: res.movedTask.dueDate ?? null, - }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - } - } - - handleDragEnd(); - }; - - const handleColumnDrop = ( - e: React.DragEvent, - targetColumn: "daily" | "weekly" - ) => { - e.preventDefault(); - e.stopPropagation(); - - if (!draggedItem) { - handleDragEnd(); - return; - } - - if ( - (targetColumn === "daily" || draggedItem.sourceColumn === "daily") && - isPastDayLocked - ) { - handleDragEnd(); - return; - } - - const targetCategories = - targetColumn === "daily" ? dailyCategories : weeklyCategories; - - if (draggedItem.type === "category") { - const destIndex = targetCategories.length; - const isMovingWeeklyToDaily = - draggedItem.sourceColumn === "weekly" && targetColumn === "daily"; - const isMovingDailyToWeekly = - draggedItem.sourceColumn === "daily" && targetColumn === "weekly"; - const targetDueDate = isMovingWeeklyToDaily - ? selectedDateKey - : isMovingDailyToWeekly - ? null - : undefined; - - const res = moveCategoryBetweenColumns({ - categoryIndex: draggedItem.sourceCatIdx, - sourceColumn: draggedItem.sourceColumn, - targetColumn, - targetIndex: destIndex, - targetDueDate, - dailyCategories, - weeklyCategories, - }); - - setDailyCategories(res.dailyCategories); - setWeeklyCategories(res.weeklyCategories); - - if (res.movedCategory?.id) { - const nowIso = new Date().toISOString(); - const catId = res.movedCategory.id; - const targetType = res.targetTaskType; - - const localCategory: LocalCategoryRecord = { - id: catId, - userId: userId ?? null, - name: res.movedCategory.name, - taskType: targetType, - sortOrder: destIndex, - createdAt: nowIso, - updatedAt: nowIso, - syncState: "pending", - }; - - const tasksToUpdate: LocalTaskRecord[] = ( - res.movedCategory.tasks ?? [] - ).map((t, idx) => ({ - id: t.id, - userId: userId ?? null, - categoryId: catId, - title: t.text, - taskType: targetType, - sortOrder: idx, - isComplete: t.completed, - status: getTaskStatus(t), - dueDate: t.dueDate ?? null, - createdAt: t.createdAt || nowIso, - updatedAt: nowIso, - completedAt: t.completed ? nowIso : null, - syncState: "pending", - })); - - const allCatsToUpdate: LocalCategoryRecord[] = [ - ...res.dailyCategories - .filter((c): c is typeof c & { id: string } => Boolean(c.id)) - .map((c, idx) => ({ - id: c.id, - userId: userId ?? null, - name: c.name, - taskType: "DAILY" as const, - sortOrder: idx, - createdAt: c.createdAt - ? typeof c.createdAt === "string" - ? c.createdAt - : c.createdAt.toISOString() - : nowIso, - updatedAt: nowIso, - syncState: "pending" as const, - })), - ...res.weeklyCategories - .filter((c): c is typeof c & { id: string } => Boolean(c.id)) - .map((c, idx) => ({ - id: c.id, - userId: userId ?? null, - name: c.name, - taskType: "WEEKLY" as const, - sortOrder: idx, - createdAt: c.createdAt - ? typeof c.createdAt === "string" - ? c.createdAt - : c.createdAt.toISOString() - : nowIso, - updatedAt: nowIso, - syncState: "pending" as const, - })), - ]; - - const mutations: Array> = []; - - const dailyCatIds = res.dailyCategories - .map((c) => c.id) - .filter((id): id is string => Boolean(id)); - if (dailyCatIds.length > 0) { - mutations.push({ - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "REORDER", - payload: { categoryIds: dailyCatIds }, - createdAt: Date.now(), - retryCount: 0, - }); - } - - const weeklyCatIds = res.weeklyCategories - .map((c) => c.id) - .filter((id): id is string => Boolean(id)); - if (weeklyCatIds.length > 0) { - mutations.push({ - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "REORDER", - payload: { categoryIds: weeklyCatIds }, - createdAt: Date.now() + 1, - retryCount: 0, - }); - } - - if (draggedItem.sourceColumn !== targetColumn) { - mutations.push({ - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "MOVE", - payload: { - categoryId: res.movedCategory.id, - taskType: res.targetTaskType, - sortOrder: destIndex, - }, - createdAt: Date.now() + 2, - retryCount: 0, - }); - } - - commitLocalBatch({ - categories: [localCategory, ...allCatsToUpdate], - tasks: tasksToUpdate, - mutations: - isLoggedIn && userId - ? mutations.map((mutation) => ({ ...mutation, userId })) - : [], - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - } - } else if (draggedItem.type === "task" && draggedItem.id) { - if ( - targetColumn === "daily" && - draggedItem.sourceColumn === "weekly" - ) { - const sourceCat = weeklyCategories[draggedItem.sourceCatIdx]; - if (sourceCat) { - let targetDailyIdx = dailyCategories.findIndex( - (c) => - (sourceCat.id && c.id === sourceCat.id) || - c.name === sourceCat.name - ); - let currentDailyCats = dailyCategories; - if (targetDailyIdx === -1) { - const newCatId = crypto.randomUUID(); - const newDailyCat: CategoryGroup = { - id: newCatId, - name: sourceCat.name, - isCollapsed: false, - tasks: [], - }; - currentDailyCats = [...dailyCategories, newDailyCat]; - targetDailyIdx = currentDailyCats.length - 1; - - persistCategory( - { - id: newCatId, - userId: userId ?? null, - name: sourceCat.name, - taskType: "DAILY", - sortOrder: targetDailyIdx, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - syncState: "pending", - }, - { - id: crypto.randomUUID(), - entityType: "CATEGORY", - action: "CREATE", - payload: { - id: newCatId, - name: sourceCat.name, - taskType: "DAILY", - sortOrder: targetDailyIdx, - }, - createdAt: Date.now(), - retryCount: 0, - } - ).catch(() => {}); - } - - const res = moveTaskBetweenCategories({ - taskId: draggedItem.id, - sourceCategoryIndex: draggedItem.sourceCatIdx, - sourceColumn: "weekly", - targetCategoryIndex: targetDailyIdx, - targetColumn: "daily", - targetTaskIndex: - currentDailyCats[targetDailyIdx].tasks.length, - targetDueDate: selectedDateKey, - dailyCategories: currentDailyCats, - weeklyCategories, - }); - - setDailyCategories(res.dailyCategories); - setWeeklyCategories(res.weeklyCategories); - - if (res.movedTask && res.targetCategoryId) { - const nowIso = new Date().toISOString(); - const isMovedComplete = Boolean( - res.movedTask.completed ?? res.movedTask.isComplete - ); - const movedStatus = - (res.movedTask.status as TaskStatus) || - (isMovedComplete ? "COMPLETED" : "TODO"); - const movedLocalTask: LocalTaskRecord = { - id: res.movedTask.id, - userId: userId ?? null, - categoryId: res.targetCategoryId, - title: res.movedTask.text ?? res.movedTask.title ?? "", - taskType: res.targetTaskType, - sortOrder: currentDailyCats[targetDailyIdx].tasks.length, - isComplete: isMovedComplete, - status: movedStatus, - dueDate: res.movedTask.dueDate ?? selectedDateKey, - createdAt: res.movedTask.createdAt - ? new Date(res.movedTask.createdAt).toISOString() - : nowIso, - updatedAt: nowIso, - completedAt: isMovedComplete ? nowIso : null, - syncState: "pending", - }; - - persistTask(movedLocalTask, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "MOVE", - payload: { - taskId: res.movedTask.id, - categoryId: res.targetCategoryId, - taskType: res.targetTaskType, - sortOrder: - currentDailyCats[targetDailyIdx].tasks.length, - dueDate: selectedDateKey, - }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - } - } - } else if (targetCategories.length > 0) { - const lastCatIdx = targetCategories.length - 1; - const isMovingWeeklyToDaily = - draggedItem.sourceColumn === "weekly" && - targetColumn === "daily"; - const isMovingDailyToWeekly = - draggedItem.sourceColumn === "daily" && - targetColumn === "weekly"; - const targetDueDate = isMovingWeeklyToDaily - ? selectedDateKey - : isMovingDailyToWeekly - ? null - : undefined; - - const res = moveTaskBetweenCategories({ - taskId: draggedItem.id, - sourceCategoryIndex: draggedItem.sourceCatIdx, - sourceColumn: draggedItem.sourceColumn, - targetCategoryIndex: lastCatIdx, - targetColumn, - targetTaskIndex: targetCategories[lastCatIdx].tasks.length, - targetDueDate, - dailyCategories, - weeklyCategories, - }); - - setDailyCategories(res.dailyCategories); - setWeeklyCategories(res.weeklyCategories); - - if (res.movedTask && res.targetCategoryId) { - const nowIso = new Date().toISOString(); - const isMovedComplete = Boolean( - res.movedTask.completed ?? res.movedTask.isComplete - ); - const movedStatus = - (res.movedTask.status as TaskStatus) || - (isMovedComplete ? "COMPLETED" : "TODO"); - const movedLocalTask: LocalTaskRecord = { - id: res.movedTask.id, - userId: userId ?? null, - categoryId: res.targetCategoryId, - title: res.movedTask.text ?? res.movedTask.title ?? "", - taskType: res.targetTaskType, - sortOrder: targetCategories[lastCatIdx].tasks.length, - isComplete: isMovedComplete, - status: movedStatus, - dueDate: res.movedTask.dueDate ?? null, - createdAt: res.movedTask.createdAt - ? new Date(res.movedTask.createdAt).toISOString() - : nowIso, - updatedAt: nowIso, - completedAt: isMovedComplete ? nowIso : null, - syncState: "pending", - }; - - persistTask(movedLocalTask, { - id: crypto.randomUUID(), - entityType: "TASK", - action: "MOVE", - payload: { - taskId: res.movedTask.id, - categoryId: res.targetCategoryId, - taskType: res.targetTaskType, - sortOrder: targetCategories[lastCatIdx].tasks.length, - dueDate: res.movedTask.dueDate ?? null, - }, - createdAt: Date.now(), - retryCount: 0, - }) - .then(() => scheduleSync(userId)) - .catch(() => {}); - } - } - } - - handleDragEnd(); - }; - - return ( - <> - - {/* Mobile Segmented Switcher (< sm: 360px–639px) */} -
- - -
- -
- {/* Daily Todos */} -
handleColumnDragOver(e, "daily")} - onDrop={(e) => handleColumnDrop(e, "daily")} - className={`rounded-2xl border bg-surface-primary p-5 sm:p-6 shadow-md flex-col justify-between space-y-5 transition-all ${ - mobileActiveTab === "daily" ? "flex" : "hidden sm:flex" - } ${ - dragOverInfo?.type === "column" && - dragOverInfo.targetColumn === "daily" - ? "border-brand-2 ring-1 ring-brand-2/50 bg-surface-secondary" - : "border-border-default" - }`} - > -
- {/* Row 1: Section Title, Day Badge, and Completed Counter (Mirrors Weekly Todos card) */} -
-
-

- Daily Todos -

- - {activeDayOption.shortLabel} - {isActiveDayToday && ( - - )} - {isPastDayLocked && ( - - - Locked - - )} - -
-
- - {completedDailyTasksForDay}/{totalDailyTasksForDay}{" "} - Completed - -
-
- - {/* Row 2: Calendar Week Navigator & Export */} -
- - -
- - {/* 7-Day Pill Switcher (Fits all 7 days without horizontal scrolling) */} -
- {dayOptions.map((opt) => { - const isSelected = opt.dateKey === selectedDateKey; - const stats = dayTaskCounts.get(opt.dateKey) || { - total: 0, - completed: 0, - }; - const allDone = - stats.total > 0 && stats.completed === stats.total; - - const isDayDropTarget = - dragOverInfo?.type === "day" && - dragOverInfo.targetDateKey === opt.dateKey; - let isDropAllowedOnOpt = true; - if ( - draggedItem?.type === "task" || - draggedItem?.type === "category" - ) { - if (draggedItem.sourceColumn === "daily") { - const sourceKey = - draggedItem.sourceDateKey || selectedDateKey; - isDropAllowedOnOpt = - !checkIsDayLocked(sourceKey) && - validateMoveTaskChallengeDay( - sourceKey, - opt.dateKey, - effectiveTodayDate, - { - isChallengeActive: hasChallengeContext, - isTargetDayLocked: checkIsDayLocked( - opt.dateKey - ), - } - ).ok; - } else if (draggedItem.sourceColumn === "weekly") { - isDropAllowedOnOpt = - !checkIsDayLocked(opt.dateKey) && - (hasChallengeContext ? !opt.isPast : true); - } - } - - return ( - - ); - })} -
- -
- {/* Rollover Helper Banners */} - {isActiveDayToday && - rolloverSummary.totalPastIncompleteCount > 0 && - !isRolloverDismissed && - !isRolloverSnoozed && ( -
-