'use client' import { useState, useEffect, useCallback, useMemo, useRef } from 'react' import { Button } from '@/components/ui/button' import { BookmarkCard } from '@/components/bookmark-card' import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet' import { ChevronLeft, ChevronRight, Share2 } from 'lucide-react' import { format, startOfMonth, endOfMonth, startOfWeek, endOfWeek, eachDayOfInterval, isSameDay, isSameMonth, addDays, addMonths, addYears, getDay, parseISO } from 'date-fns' import type { Bookmark } from '@/components/app-shell' import { Input } from '@/components/ui/input' import { toast } from 'sonner' import { fetchBookmarks } from '@/lib/bookmarks' import { cn } from '@/lib/utils' // Review L-4: a fixed, obviously-not-current placeholder. The real month and // today are set after mount (to avoid an SSR/client hydration mismatch), and // the calendar renders a skeleton until then instead of briefly presenting // this epoch as the current month. const INITIAL_DATE = new Date(2000, 0, 1) type CalendarView = 'day' | 'week' | 'month' | 'year' | 'list' // Month stays the default so the classic grid is what loads first. const VIEWS: { id: CalendarView; label: string }[] = [ { id: 'day', label: 'Day' }, { id: 'week', label: 'Week' }, { id: 'month', label: 'Month' }, { id: 'year', label: 'Year' }, { id: 'list', label: 'List' }, ] export function CalendarClient() { // currentMonth anchors every period view (day/week/month/year); List shows // all due dates and ignores it. const [currentMonth, setCurrentMonth] = useState(INITIAL_DATE) const [today, setToday] = useState(INITIAL_DATE) const [ready, setReady] = useState(false) const [view, setView] = useState('month') const [bookmarks, setBookmarks] = useState([]) const [selectedDay, setSelectedDay] = useState(null) const [selectedBookmark, setSelectedBookmark] = useState(null) const [loading, setLoading] = useState(true) const [sharedDates, setSharedDates] = useState([]) const [shareQuery, setShareQuery] = useState('') const [shareUsers, setShareUsers] = useState([]) // Debounced user search; failures keep the previous results silently. useEffect(() => { const q = shareQuery.trim() const t = setTimeout(async () => { if (q.length < 2) { setShareUsers([]); return } try { const res = await fetch(`/api/users/search?q=${encodeURIComponent(q)}`) if (res.ok) setShareUsers(await res.json()) } catch { /* transient; retried on next keystroke */ } }, q.length < 2 ? 0 : 250) return () => clearTimeout(t) }, [shareQuery]) useEffect(() => { const timer = setTimeout(() => { const now = new Date(); setCurrentMonth(now); setToday(now); setReady(true) }, 0) return () => clearTimeout(timer) }, []) // Review M-11: bookmark-change events and slow initial loads can overlap; // only the newest pass may publish its data. const loadSeq = useRef(0) const load = useCallback(async () => { const seq = ++loadSeq.current setLoading(true) try { const [mine, shared, dates] = await Promise.all([fetchBookmarks(), fetchBookmarks(new URLSearchParams({ shared: 'true' })), fetch('/api/shared-dates')]) if (seq !== loadSeq.current) return const sharedDatesJson = dates.ok ? await dates.json() : null if (seq !== loadSeq.current) return setBookmarks([...mine, ...shared]) if (sharedDatesJson) setSharedDates(sharedDatesJson) } catch { if (seq === loadSeq.current) toast.error('Could not load calendar') } finally { if (seq === loadSeq.current) setLoading(false) } }, []) useEffect(() => { const timer = setTimeout(load, 0); window.addEventListener('superbrain:bookmarks-changed', load); return () => { clearTimeout(timer); window.removeEventListener('superbrain:bookmarks-changed', load) } }, [load]) const days = useMemo(() => { const start = startOfMonth(currentMonth) const end = endOfMonth(currentMonth) return eachDayOfInterval({ start, end }) }, [currentMonth]) const startDayOfWeek = getDay(startOfMonth(currentMonth)) const bookmarksByDay = useMemo(() => { const map: Record = {} for (const b of bookmarks) { if (b?.dueDate) { const key = b.dueDate.slice(0, 10) if (!map[key]) map[key] = [] map[key].push(b) } } return map }, [bookmarks]) const sharedDateKeys = useMemo(() => new Set(sharedDates.map(s => s.date.slice(0, 10))), [sharedDates]) // Week columns follow the month grid's Sun..Sat order (date-fns default). const weekDays = useMemo(() => eachDayOfInterval({ start: startOfWeek(currentMonth), end: endOfWeek(currentMonth) }), [currentMonth]) const yearMonths = useMemo(() => Array.from({ length: 12 }, (_, i) => new Date(currentMonth.getFullYear(), i, 1)), [currentMonth]) // List view: every day with due bookmarks or a shared date, ascending; // ISO date keys sort chronologically as plain strings. const listGroups = useMemo(() => { const keys = Array.from(new Set([...Object.keys(bookmarksByDay), ...sharedDateKeys])).sort() return keys.map(key => ({ key, shared: sharedDates.filter(s => s.date.slice(0, 10) === key), bookmarks: [...(bookmarksByDay[key] ?? [])].sort((a, b) => (a.dueDate ?? '') < (b.dueDate ?? '') ? -1 : (a.dueDate ?? '') > (b.dueDate ?? '') ? 1 : 0), })) }, [bookmarksByDay, sharedDates, sharedDateKeys]) const periodLabel = useMemo(() => { if (view === 'day') return format(currentMonth, 'EEE, MMM d, yyyy') if (view === 'week') { const start = startOfWeek(currentMonth) const end = endOfWeek(currentMonth) return start.getFullYear() === end.getFullYear() ? `${format(start, 'MMM d')} – ${format(end, 'MMM d, yyyy')}` : `${format(start, 'MMM d, yyyy')} – ${format(end, 'MMM d, yyyy')}` } if (view === 'year') return format(currentMonth, 'yyyy') return format(currentMonth, 'MMMM yyyy') }, [view, currentMonth]) const step = (dir: -1 | 1) => setCurrentMonth(d => { if (view === 'day') return addDays(d, dir) if (view === 'week') return addDays(d, dir * 7) if (view === 'year') return addYears(d, dir) return addMonths(d, dir) }) const goToday = () => { const now = new Date(); setCurrentMonth(now); setToday(now) } // The selected-day detail panel, shared by Month/Week (below the grid) and // the Day view, where the anchor day is the view itself. const renderDayPanel = (day: Date) => { const key = format(day, 'yyyy-MM-dd') const dayBookmarks = bookmarksByDay[key] ?? [] const dayShared = sharedDates.filter(s => s.date.slice(0, 10) === key) return (

{format(day, 'EEEE, MMMM d, yyyy')}

setShareQuery(e.target.value)} />
{/* Review L-9: sharing a date is broader than the old label said. */}

Recipients will see your bookmarks due that day, including their notes.

{shareUsers.map(u => )} {dayShared.map(s =>
{s.creator.name || s.creator.email} shared with {s.recipient.name || s.recipient.email}
)} {dayBookmarks.length === 0 ? (

No bookmarks on this date

) : (
{dayBookmarks.map((b: Bookmark) => ( setSelectedBookmark(b)} /> ))}
)}
) } if (!ready) { return (

Calendar

Bookmarks organized by due date

) } return (

Calendar

Bookmarks organized by due date

{VIEWS.map(v => ( ))}
{view !== 'list' && (
{periodLabel}
)}
{view === 'month' &&
{['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(d => (
{d[0]}{d}
))} {Array.from({ length: startDayOfWeek }).map((_, i) => (
))} {days.map(day => { const key = format(day, 'yyyy-MM-dd') const dayBookmarks = bookmarksByDay[key] ?? [] const isSelected = selectedDay ? isSameDay(day, selectedDay) : false const isToday = isSameDay(day, today) return (
setSelectedDay(day)} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedDay(day) } }} className={`bg-card min-h-[64px] p-1 sm:min-h-[80px] sm:p-1.5 cursor-pointer transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary ${ isSelected ? 'ring-2 ring-primary ring-inset' : '' }`} > {format(day, 'd')}
{sharedDates.filter(s => s.date.slice(0, 10) === key).map(s =>

Shared: {s.creator.name || s.creator.email}

)} {dayBookmarks.slice(0, 2).map((b: Bookmark) => (
{ e.stopPropagation(); setSelectedBookmark(b) }} onKeyDown={(e: React.KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); setSelectedBookmark(b) } }}> {b.title ?? 'Untitled'}
))} {dayBookmarks.length > 2 && (
+{dayBookmarks.length - 2} more
)}
) })}
} {view === 'day' && renderDayPanel(currentMonth)} {view === 'week' && (
{weekDays.map(day => { const key = format(day, 'yyyy-MM-dd') return (
{format(day, 'EEE')}{' '} {format(day, 'd')}
) })} {weekDays.map(day => { const key = format(day, 'yyyy-MM-dd') const dayBookmarks = bookmarksByDay[key] ?? [] const isSelected = selectedDay ? isSameDay(day, selectedDay) : false return (
setSelectedDay(day)} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedDay(day) } }} className={cn('bg-card min-h-[160px] p-1.5 cursor-pointer transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary', isSelected && 'ring-2 ring-primary ring-inset')} >
{sharedDates.filter(s => s.date.slice(0, 10) === key).map(s =>

Shared: {s.creator.name || s.creator.email}

)} {dayBookmarks.slice(0, 4).map((b: Bookmark) => (
{ e.stopPropagation(); setSelectedBookmark(b) }} onKeyDown={(e: React.KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); setSelectedBookmark(b) } }}> {b.title ?? 'Untitled'}
))} {dayBookmarks.length > 4 && (
+{dayBookmarks.length - 4} more
)}
) })}
)} {view === 'year' && (
{yearMonths.map(month => { const monthKey = format(month, 'yyyy-MM') const monthDays = eachDayOfInterval({ start: startOfMonth(month), end: endOfMonth(month) }) const lead = getDay(startOfMonth(month)) const openMonth = () => { setCurrentMonth(month); setView('month') } return (
{ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openMonth() } }} className={cn('rounded-lg border bg-card p-2 cursor-pointer transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary', isSameMonth(month, currentMonth) ? 'border-primary/50' : 'border-border/60')} >

{format(month, 'MMMM')}

{['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((d, i) => {d})} {Array.from({ length: lead }).map((_, i) => )} {monthDays.map(day => { const key = format(day, 'yyyy-MM-dd') const hasItems = (bookmarksByDay[key]?.length ?? 0) > 0 || sharedDateKeys.has(key) return ( {format(day, 'd')} ) })}
) })}
)} {view === 'list' && ( listGroups.length === 0 ? (

No bookmarks with due dates

) : (
{listGroups.map(group => { const day = parseISO(group.key) return (
{format(day, 'EEEE, MMMM d, yyyy')}{isSameDay(day, today) ? ' · Today' : ''}
{group.shared.map(s =>

Shared: {s.creator.name || s.creator.email}

)} {group.bookmarks.map((b: Bookmark) => (
setSelectedBookmark(b)} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedBookmark(b) } }} className="cursor-pointer px-3 py-2 transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary" > {b.title ?? 'Untitled'}
))}
) })}
) )} {selectedDay && (view === 'month' || view === 'week') && renderDayPanel(selectedDay)} setSelectedBookmark(null)} onUpdate={load} />
) }