File size: 16,281 Bytes
6c5d46f
d26c264
d1e9766
 
6ab9aff
71badb3
f489e78
d1e9766
964aab3
1d9387a
2519d03
 
 
 
 
 
 
 
 
 
f489e78
a95320a
 
 
 
 
 
 
 
 
 
d1e9766
 
6ab9aff
80530b0
574dd1f
9b87f77
574dd1f
9b87f77
 
a95320a
 
 
 
 
71badb3
a95320a
 
 
 
 
 
71badb3
a95320a
 
 
 
 
 
 
 
 
 
 
 
 
 
71badb3
 
 
a95320a
71badb3
 
 
a95320a
71badb3
d1e9766
 
1577d6e
574dd1f
6ab9aff
a95320a
 
d1e9766
 
 
 
 
 
 
 
 
 
 
 
8223f53
 
 
 
 
 
 
6ab9aff
 
 
 
 
 
d26c264
1d9387a
 
d26c264
1d9387a
 
 
 
 
 
 
 
 
 
 
 
 
 
d26c264
 
a95320a
 
d1e9766
 
8223f53
a95320a
 
 
 
 
 
 
 
 
 
8223f53
d1e9766
8223f53
 
 
9b87f77
 
80530b0
9b87f77
 
 
 
80530b0
9b87f77
 
 
 
80530b0
9b87f77
 
80530b0
1577d6e
9b87f77
1577d6e
 
9b87f77
 
1577d6e
d1e9766
 
 
 
 
 
 
 
 
574dd1f
d1e9766
 
 
 
 
 
 
574dd1f
d1e9766
 
574dd1f
d1e9766
 
 
 
 
1d9387a
d1e9766
 
1577d6e
1d9387a
d1e9766
574dd1f
d1e9766
 
1d9387a
d1e9766
1d9387a
 
d1e9766
 
1d9387a
 
 
 
 
 
 
 
 
 
 
 
574dd1f
 
 
c07517b
574dd1f
 
 
 
 
 
 
 
 
 
1d9387a
 
574dd1f
1d9387a
8223f53
1577d6e
2519d03
 
 
 
 
 
 
 
 
 
 
 
 
574dd1f
1d9387a
d1e9766
8223f53
1d9387a
d1e9766
8223f53
71badb3
80530b0
d1e9766
 
105f096
 
 
a77ae0b
1577d6e
ff564fd
1d9387a
9efc80e
 
 
ff564fd
 
 
71badb3
1d9387a
d1e9766
1577d6e
ff564fd
 
d26c264
1d9387a
d26c264
ff564fd
 
 
 
 
d1e9766
 
1d9387a
80530b0
a537956
1d9387a
964aab3
 
 
8223f53
d26c264
6ab9aff
a537956
6ab9aff
964aab3
 
 
6ab9aff
 
 
 
 
 
1577d6e
6ab9aff
 
 
 
 
8223f53
 
6ab9aff
 
 
1d9387a
6ab9aff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80530b0
6ab9aff
 
 
574dd1f
6ab9aff
 
 
 
 
 
 
574dd1f
6ab9aff
 
 
 
 
 
574dd1f
6ab9aff
 
574dd1f
6ab9aff
 
 
d1e9766
 
8223f53
 
 
ff564fd
a77ae0b
 
574dd1f
71badb3
d1e9766
a95320a
d1e9766
71badb3
 
 
 
 
 
 
 
 
8223f53
d1e9766
 
574dd1f
a77ae0b
 
 
d1e9766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8223f53
d1e9766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8223f53
d1e9766
 
2519d03
574dd1f
2519d03
574dd1f
2519d03
 
574dd1f
2519d03
 
 
 
 
 
 
 
 
 
 
 
 
80530b0
 
 
2519d03
 
 
 
71badb3
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// web/src/components/sidebar/LeftSidebar.tsx
import React, { useMemo, useState } from "react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Badge } from "../ui/badge";

import { SavedChatSection } from "./SavedChatSection";

import { MailPlus, Users, GraduationCap } from "lucide-react";

import { toast } from "sonner";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "../ui/dialog";

import type {
  SavedChat,
  Workspace,
  LearningMode,
  Language,
  SpaceType,
  GroupMember,
  User,
  SavedItem,
} from "../../App";
import type { CourseDirectoryItem } from "../../lib/courseDirectory";

import clareAvatar from "../../assets/dfe44dab3ad8cd93953eac4a3e68bd1a5f999653.png";

// ✅ Theme-compatible divider (light/dark) + visibility
const Divider = () => (
  <div className="w-full border-t border-border/70 dark:border-border flex-shrink-0" />
);

type Props = {
  learningMode: LearningMode;
  language: Language;
  onLearningModeChange: (m: LearningMode) => void;
  onLanguageChange: (l: Language) => void;

  spaceType: SpaceType;
  groupMembers: GroupMember[];

  user: User | null;
  onLogin: (u: any) => void;
  onLogout: () => void;
  isLoggedIn: boolean;

  onEditProfile: () => void;

  savedItems: SavedItem[];
  recentlySavedId: string | null;
  onUnsave: (id: string) => void;
  onSave: (
    content: string,
    type: "export" | "quiz" | "summary",
    saveAsChat?: boolean,
    format?: "pdf" | "text",
    workspaceId?: string
  ) => void;

  savedChats: SavedChat[];
  onLoadChat: (chat: SavedChat) => void;
  onDeleteSavedChat: (id: string) => void;
  onRenameSavedChat: (id: string, newTitle: string) => void;

  currentWorkspaceId: string;
  workspaces: Workspace[];

  selectedCourse: string;
  availableCourses: CourseDirectoryItem[];

  // optional if you already wired backend
  onRenameGroupName?: (workspaceId: string, newName: string) => Promise<void> | void;
  onRenameGroupNo?: (workspaceId: string, newNo: number) => Promise<void> | void;
};

function gmailComposeLink(email: string, subject?: string, body?: string) {
  const to = `to=${encodeURIComponent(email)}`;
  const su = subject ? `&su=${encodeURIComponent(subject)}` : "";
  const bd = body ? `&body=${encodeURIComponent(body)}` : "";
  return `https://mail.google.com/mail/?view=cm&fs=1&${to}${su}${bd}`;
}

function norm(s: any) {
  return String(s ?? "").trim().toLowerCase();
}

function pickAny(obj: any, keys: string[]) {
  for (const k of keys) {
    const v = obj?.[k];
    if (v !== undefined && v !== null && String(v).trim() !== "") return v;
  }
  return undefined;
}

function toIntOrFallback(v: any, fb: number) {
  const n = Number(v);
  if (Number.isFinite(n) && n > 0) return Math.floor(n);
  return fb;
}

/**
 * Hard-stop sanitizer to prevent any "pencil/edit" artifacts
 * from appearing in the Group Name area due to backend-provided strings.
 */
function sanitizeGroupLabel(v: any, fallback: string) {
  let s = String(v ?? "").trim();
  if (!s) return fallback;

  // Remove known "edit" text patterns (case-insensitive)
  s = s.replace(/\b(edit|rename|pencil)\b/gi, "").trim();

  // Remove common emoji pencil and variants
  s = s.replace(/✏️|✏/g, "").trim();

  // Collapse excessive whitespace
  s = s.replace(/\s{2,}/g, " ").trim();

  return s || fallback;
}

export function LeftSidebar(props: Props) {
  const {
    isLoggedIn,
    spaceType,
    groupMembers,
    savedChats,
    onLoadChat,
    onDeleteSavedChat,
    onRenameSavedChat,
    currentWorkspaceId,
    workspaces,
    selectedCourse,
    availableCourses,
  } = props;

  const currentWorkspace = useMemo(
    () => workspaces.find((w) => w.id === currentWorkspaceId),
    [workspaces, currentWorkspaceId]
  );

  const isMyWorkspace = useMemo(() => {
    const ws: any = currentWorkspace as any;

    if (ws?.isPersonal === true) return true;
    if (String(ws?.spaceType || "").toLowerCase().includes("my")) return true;
    if (String(ws?.type || "").toLowerCase().includes("my")) return true;
    if (String(ws?.kind || "").toLowerCase().includes("my")) return true;

    const id = String(ws?.id || "").toLowerCase();
    const name = String(ws?.name || "").toLowerCase();
    if (id.includes("my") || id.includes("personal")) return true;
    if (name.includes("my space") || name.includes("personal")) return true;

    return false;
  }, [currentWorkspace]);

  const isTeamSpace = useMemo(() => {
    if (isMyWorkspace) return false;
    const st = String(spaceType || "").toLowerCase();
    return st === "group" || st === "team";
  }, [spaceType, isMyWorkspace]);

  // --------- CourseInfo resolution ---------
  const courseInfo = useMemo((): CourseDirectoryItem | null => {
    const list = Array.isArray(availableCourses) ? availableCourses : [];

    const selRaw = (selectedCourse || "").trim();
    const sel = norm(selRaw);
    if (sel) {
      const hit =
        list.find((c: any) => norm(c.id) === sel) ||
        list.find((c: any) => norm(c.name) === sel);
      if (hit) return hit as any;
    }

    const wsCourse = (currentWorkspace as any)?.courseInfo as
      | { id?: string; name?: string; instructor?: any; teachingAssistant?: any }
      | undefined;

    const wsId = norm(wsCourse?.id);
    if (wsId) return (list.find((c: any) => norm(c.id) === wsId) ?? (wsCourse as any)) as any;

    const wsName = norm(wsCourse?.name);
    if (wsName) return (list.find((c: any) => norm(c.name) === wsName) ?? (wsCourse as any)) as any;

    return null;
  }, [availableCourses, currentWorkspace, selectedCourse]);

  const courseName = useMemo(() => {
    return (courseInfo as any)?.name ?? (selectedCourse || "Course");
  }, [courseInfo, selectedCourse]);

  // --------- Group fields ---------
  const wsGroupNoRaw = useMemo(() => {
    const ws: any = currentWorkspace as any;
    return ws?.groupNo ?? ws?.groupNumber ?? ws?.groupIndex ?? ws?.group_id ?? ws?.groupId ?? 1;
  }, [currentWorkspace]);

  const wsGroupNameRaw = useMemo(() => {
    const ws: any = currentWorkspace as any;
    // If backend sends name/title containing ✏️ etc, we sanitize later before display
    return pickAny(ws, ["groupName", "name", "title"]) || "My Group";
  }, [currentWorkspace]);

  const memberCount = (groupMembers || []).length;

  // ✅ Final display values (sanitized)
  const groupName = useMemo(
    () => sanitizeGroupLabel(wsGroupNameRaw, "My Group"),
    [wsGroupNameRaw]
  );
  const groupNo = useMemo(
    () => toIntOrFallback(wsGroupNoRaw, 1),
    [wsGroupNoRaw]
  );

  // --------- Demo group mapping (My Space only) ---------
  const demoGroupMap: Record<string, { name: string; no: number }> = useMemo(
    () => ({
      "Introduction to AI": { name: "CS 101 Study Group", no: 1 },
      "Machine Learning": { name: "Study Sprint", no: 3 },
      "Data Visualization": { name: "Design Lab", no: 2 },
    }),
    []
  );

  const demoGroup = useMemo(() => {
    const hit = demoGroupMap[courseName];
    if (hit) return hit;
    return {
      name: sanitizeGroupLabel(wsGroupNameRaw, "My Group"),
      no: toIntOrFallback(wsGroupNoRaw, 1),
    };
  }, [demoGroupMap, courseName, wsGroupNameRaw, wsGroupNoRaw]);

  // Invite dialog state
  const [inviteOpen, setInviteOpen] = useState(false);
  const [inviteEmail, setInviteEmail] = useState("");

  const handleSendInvite = () => {
    if (!inviteEmail.trim()) {
      toast.error("Please enter an email to invite");
      return;
    }
    toast.success(`Invitation sent to ${inviteEmail}`);
    setInviteEmail("");
    setInviteOpen(false);
  };

  // --------- Contacts ---------
  const instructorName = (courseInfo as any)?.instructor?.name ?? "N/A";
  const instructorEmail = String((courseInfo as any)?.instructor?.email ?? "").trim();

  const taName = (courseInfo as any)?.teachingAssistant?.name ?? "N/A";
  const taEmail = String((courseInfo as any)?.teachingAssistant?.email ?? "").trim();

  return (
    <div className="h-full w-full flex flex-col min-h-0 bg-background text-foreground">
      {/* ================= TOP (non-scroll) ================= */}
      <div className="flex-shrink-0">
        <div className="mt-2 mb-4">
          <Divider />
        </div>

        {/* Course + Group */}
        <div className="px-4 pt-5 pb-6 space-y-4">
          {/* Course row */}
          <div className="flex items-start gap-3">
            <div className="w-6 flex items-start justify-center flex-shrink-0 pt-[2px]">
              <GraduationCap className="w-5 h-5 text-muted-foreground" />
            </div>
            <div className="text-[22px] leading-snug font-semibold truncate">{courseName}</div>
          </div>

          {/* ===== My Space (beautified) ===== */}
          {!isTeamSpace ? (
            <div className="space-y-2">
              <div className="flex items-center justify-between text-[15px]">
                <span className="text-muted-foreground">Group Name:</span>
                <span className="font-semibold truncate max-w-[60%] text-right">
                  {demoGroup.name}
                </span>
              </div>
              <div className="flex items-center justify-between text-[15px]">
                <span className="text-muted-foreground">Group Number:</span>
                <span className="font-semibold">{demoGroup.no}</span>
              </div>
            </div>
          ) : (
            /* ===== Team/Group (no pencil in group name area) ===== */
            <div className="rounded-2xl border bg-background overflow-hidden">
              <div className="px-4 pt-4 pb-3 space-y-3">
                {/* Line 1: group name (read-only) */}
                <div className="flex items-center gap-2">
                  <div className="text-[18px] font-semibold truncate">{groupName}</div>
                </div>

                {/* Line 2: Group {no} ({count}) + Invite */}
                <div className="flex items-center justify-between gap-3">
                  <div className="flex items-center gap-2">
                    <Users className="w-4 h-4 text-muted-foreground" />
                    <div className="text-[16px] font-medium">
                      Group <span className="font-semibold">{groupNo}</span> ({memberCount})
                    </div>
                  </div>

                  <Button
                    type="button"
                    variant="secondary"
                    className="h-9 px-3 text-[13px]"
                    onClick={() => setInviteOpen(true)}
                  >
                    <MailPlus className="w-4 h-4 mr-2" />
                    Invite
                  </Button>
                </div>
              </div>

              <div className="px-3 pb-3 space-y-2">
                {(groupMembers || []).map((member) => {
                  const isAI = !!(member as any).isAI;
                  const name = String((member as any).name || "");
                  const email = String((member as any).email || "");
                  const initials = name
                    ? name
                        .split(" ")
                        .filter(Boolean)
                        .map((n) => n[0])
                        .join("")
                        .toUpperCase()
                    : "?";

                  return (
                    <div
                      key={(member as any).id}
                      className="flex items-center gap-3 p-2 rounded-lg hover:bg-muted/50 transition-colors"
                    >
                      <div
                        className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                          isAI ? "overflow-hidden bg-background" : "bg-muted"
                        }`}
                      >
                        {isAI ? (
                          <img src={clareAvatar} alt="Clare" className="w-full h-full object-cover" />
                        ) : (
                          <span className="text-sm">{initials}</span>
                        )}
                      </div>

                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <p className="text-sm truncate">{name}</p>
                          {isAI && (
                            <Badge variant="secondary" className="text-xs">
                              AI
                            </Badge>
                          )}
                        </div>
                        <p className="text-xs text-muted-foreground truncate">{email}</p>
                      </div>

                      <div className="w-2 h-2 rounded-full bg-green-500 flex-shrink-0" title="Online" />
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>

        <div className="mt-1 mb-6">
          <Divider />
        </div>
      </div>

      {/* ================= MIDDLE (only scroll) ================= */}
      <div className="flex-1 min-h-0 overflow-hidden">
        <div className="h-full min-h-0 panelScroll px-0 py-0">
          <SavedChatSection
            isLoggedIn={isLoggedIn}
            savedChats={savedChats}
            onLoadChat={onLoadChat}
            onDeleteSavedChat={onDeleteSavedChat}
            onRenameSavedChat={onRenameSavedChat}
          />
        </div>
      </div>

      {/* ================= BOTTOM (fixed, non-scroll) ================= */}
      <div className="flex-shrink-0">
        <div className="mt-6 mb-4">
          <Divider />
        </div>

        <div className="px-4 py-4 space-y-2 text-[16px]">
          <div className="text-muted-foreground">
            Instructor:&nbsp;
            {instructorEmail ? (
              <a
                href={gmailComposeLink(
                  instructorEmail,
                  `[Clare] Question about ${courseName}`,
                  `Hi ${instructorName},\n\nI have a question about ${courseName}:\n\n(Write your question here)\n\nThanks,\n`
                )}
                target="_blank"
                rel="noopener noreferrer"
                className="text-primary hover:underline"
              >
                {instructorName}
              </a>
            ) : (
              <span className="text-muted-foreground/60">{instructorName}</span>
            )}
          </div>

          <div className="text-muted-foreground">
            TA:&nbsp;
            {taEmail ? (
              <a
                href={gmailComposeLink(
                  taEmail,
                  `[Clare] Help request for ${courseName}`,
                  `Hi ${taName},\n\nI need help with ${courseName}:\n\n(Write your question here)\n\nThanks,\n`
                )}
                target="_blank"
                rel="noopener noreferrer"
                className="text-primary hover:underline"
              >
                {taName}
              </a>
            ) : (
              <span className="text-muted-foreground/60">{taName}</span>
            )}
          </div>
        </div>
      </div>

      {/* Invite Dialog */}
      <Dialog open={inviteOpen} onOpenChange={setInviteOpen}>
        <DialogContent className="w-[600px] max-w-[600px] sm:max-w-[600px]" style={{ maxWidth: 600 }}>
          <DialogHeader>
            <DialogTitle>Invite member</DialogTitle>
            <DialogDescription>Send a quick email invite with the team details.</DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <Input
              type="email"
              placeholder="name@example.com"
              value={inviteEmail}
              onChange={(e) => setInviteEmail(e.target.value)}
            />
            <p className="text-xs text-muted-foreground">
              An invitation email with a join link will be sent to this address.
            </p>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setInviteOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleSendInvite}>Send invite</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}