summaryrefslogtreecommitdiff
path: root/src/components/Flashcard/StudyCard.tsx
blob: 4e554b45175e5d7cc0cee3320f8857d5153b31de (plain)
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
"use client";

import { useState, useEffect } from "react";
import { CardResponse } from "@/lib/types/cards";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { processReview, gradeCard } from "@/actions/srs";
import "./cards.css";

interface StudyCardProps {
  card: CardResponse;
  userId: number;
  onComplete: (newCard: CardResponse) => void;
  onSkip?: () => void;
}

export default function StudyCard({ card, userId, onComplete, onSkip }: StudyCardProps) {
  const [isFlipped, setIsFlipped] = useState(false);
  const [startTime, setStartTime] = useState(0);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  // Reset the timer when a new card is shown
  useEffect(() => {
    setIsFlipped(false);
    setStartTime(Date.now());
  }, [card.id]);

  // Toggle card flip
  const flipCard = () => {
    if (!isFlipped) {
      setIsFlipped(true);
    }
  };

  // Calculate time spent on card in milliseconds
  const getReviewTime = () => {
    return Date.now() - startTime;
  };

  // Handle card grading (Good/Again)
  const handleGrade = async (isCorrect: boolean) => {
    if (isSubmitting) return;
    
    setIsSubmitting(true);
    
    try {
      const result = await gradeCard(userId, card.id, isCorrect);
      
      if ('error' in result) {
        console.error("Error grading card:", result.error);
      } else {
        onComplete(result as CardResponse);
      }
    } catch (error) {
      console.error("Error processing review:", error);
    } finally {
      setIsSubmitting(false);
    }
  };

  // Handle detailed grading with accuracy level
  const handleDetailedGrade = async (accuracy: number) => {
    if (isSubmitting) return;
    
    setIsSubmitting(true);
    
    try {
      const reviewTime = getReviewTime();
      const result = await processReview(userId, card.id, accuracy, reviewTime);
      
      if ('error' in result) {
        console.error("Error processing review:", result.error);
      } else {
        onComplete(result as CardResponse);
      }
    } catch (error) {
      console.error("Error processing review:", error);
    } finally {
      setIsSubmitting(false);
    }
  };

  // Calculate progress percentage for the card
  const getProgressPercentage = () => {
    const { interval, easeFactor } = card.progress;
    // Assuming max interval is 365 days and max ease factor is 4.0
    const intervalProgress = Math.min(interval / 365, 1) * 70; // 70% weight to interval
    const easeProgress = Math.min((easeFactor - 1) / 3, 1) * 30; // 30% weight to ease factor
    return intervalProgress + easeProgress;
  };

  // Format content based on card type
  const formatCardContent = (content: string, isBack: boolean = false) => {
    // You can add more sophisticated formatting here based on card type
    return content;
  };

  // Render IPA pronunciation if available
  const renderIPA = () => {
    if (card.expression.ipa && card.expression.ipa.length > 0) {
      return (
        <div className="text-gray-500 text-sm mt-2">
          /{card.expression.ipa[0].ipa}/
        </div>
      );
    }
    return null;
  };

  // Render senses/meanings if available
  const renderSenses = () => {
    if (card.expression.senses && card.expression.senses.length > 0) {
      return (
        <div className="mt-4">
          {card.expression.senses.map((sense, index) => (
            <div key={index} className="mb-3">
              {sense.pos && <span className="text-xs font-medium text-blue-600 mr-2">{sense.pos}</span>}
              {sense.senses && sense.senses.map((subsense, i) => (
                <div key={i} className="mt-1">
                  {subsense.glosses && subsense.glosses.map((gloss, j) => (
                    <div key={j} className="text-sm">{j+1}. {gloss}</div>
                  ))}
                </div>
              ))}
            </div>
          ))}
        </div>
      );
    }
    return null;
  };

  // Show bookmarked status if applicable
  const renderBookmarked = () => {
    if (card.expression.isBookmarked) {
      return <div className="absolute top-2 right-2 text-yellow-500">★</div>;
    }
    return null;
  };

  return (
    <div className="flex flex-col items-center">
      <div className={cn("flashcard-container", { flipped: isFlipped })} onClick={flipCard}>
        <div className="flashcard">
          {/* Front of card */}
          <div className="flashcard-front">
            <Card className="w-full h-full flex flex-col justify-center items-center p-6 relative">
              {renderBookmarked()}
              <div className="text-2xl font-bold">{card.expression.spelling}</div>
              {!isFlipped && renderIPA()}
              <div className="mt-4 text-lg">{formatCardContent(card.text)}</div>
              {card.note && <div className="mt-2 text-sm text-gray-500">{card.note}</div>}
              {!isFlipped && (
                <div className="mt-6 text-sm text-gray-400">
                  Click to flip
                </div>
              )}
            </Card>
          </div>
          
          {/* Back of card */}
          <div className="flashcard-back">
            <Card className="w-full h-full flex flex-col justify-between p-6 relative">
              {renderBookmarked()}
              <div>
                <div className="text-2xl font-bold">{card.expression.spelling}</div>
                {renderIPA()}
                <div className="mt-4 text-lg">{formatCardContent(card.text, true)}</div>
                {card.note && <div className="mt-2 text-sm text-gray-500">{card.note}</div>}
                {renderSenses()}
              </div>
              
              <div className="flex flex-col mt-6">
                <div className="text-sm text-gray-500 mb-2">
                  How well did you remember this?
                </div>
                <div className="flex justify-between gap-2">
                  <Button
                    variant="destructive"
                    onClick={() => handleGrade(false)}
                    disabled={isSubmitting}
                    className="flex-1"
                  >
                    Again
                  </Button>
                  <Button
                    variant="default"
                    onClick={() => handleGrade(true)}
                    disabled={isSubmitting} 
                    className="flex-1"
                  >
                    Good
                  </Button>
                </div>
                
                {/* Optional: Detailed grading */}
                <div className="grid grid-cols-4 gap-2 mt-3">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleDetailedGrade(0.2)}
                    disabled={isSubmitting}
                    className="text-red-500"
                  >
                    Forgot
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleDetailedGrade(0.6)}
                    disabled={isSubmitting}
                    className="text-orange-500"
                  >
                    Hard
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleDetailedGrade(0.8)}
                    disabled={isSubmitting}
                    className="text-green-500"
                  >
                    Good
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleDetailedGrade(1.0)}
                    disabled={isSubmitting}
                    className="text-blue-500"
                  >
                    Easy
                  </Button>
                </div>
              </div>
            </Card>
          </div>
        </div>
      </div>
      
      {/* Progress bar */}
      <div className="w-full mt-4">
        <Progress value={getProgressPercentage()} className="h-2" />
        <div className="flex justify-between text-xs text-gray-500 mt-1">
          <span>Interval: {card.progress.interval} days</span>
          <span>Ease: {card.progress.easeFactor.toFixed(1)}</span>
        </div>
      </div>
      
      {/* Skip button */}
      {onSkip && (
        <Button
          variant="ghost"
          onClick={onSkip}
          className="mt-4"
          disabled={isSubmitting}
        >
          Skip
        </Button>
      )}
    </div>
  );
}