import { useEffect, useState } from "react"; import { Link } from "react-router-dom"; export default function Sidebar({ userId, onUserIdChange, sessionId, sessions, onSwitchSession, onDeleteSession, onClearChat, onClearDb, onNewSession, }) { const groups = groupSessionsByRecency(sessions); const initial = (userId || "U").slice(0, 1).toUpperCase(); // Draft-edit the user id locally; commit on Enter or blur. Committing on // every keystroke made the field impossible to edit (an empty field // snapped back to demo_user mid-typing and each keystroke switched users). const [draft, setDraft] = useState(userId); useEffect(() => { setDraft(userId); }, [userId]); function commitUserId() { const v = (draft || "").trim(); if (v && v !== userId) onUserIdChange(v); else setDraft(userId); // empty or unchanged — revert the draft } return ( ); } // ---------- Helpers ---------- function NewChatIcon() { return ( ); } function truncate(s, n) { if (!s) return ""; return s.length > n ? s.slice(0, n).trimEnd() + "..." : s; } function groupSessionsByRecency(sessions) { const today = startOfDay(new Date()); const yesterday = new Date(today.getTime() - 86400000); const sevenDaysAgo = new Date(today.getTime() - 7 * 86400000); const thirtyDaysAgo = new Date(today.getTime() - 30 * 86400000); const groups = { today: { label: "Today", items: [] }, yesterday:{ label: "Yesterday", items: [] }, week: { label: "Previous 7 days", items: [] }, month: { label: "Previous 30 days", items: [] }, older: { label: "Older", items: [] }, }; for (const s of sessions) { const t = parseTime(s.last_active_at); if (!t) { groups.older.items.push(s); continue; } if (t >= today) groups.today.items.push(s); else if (t >= yesterday) groups.yesterday.items.push(s); else if (t >= sevenDaysAgo) groups.week.items.push(s); else if (t >= thirtyDaysAgo) groups.month.items.push(s); else groups.older.items.push(s); } return [groups.today, groups.yesterday, groups.week, groups.month, groups.older]; } function startOfDay(d) { return new Date(d.getFullYear(), d.getMonth(), d.getDate()); } function parseTime(s) { try { return new Date(s); } catch { return null; } }