File size: 9,979 Bytes
a6d0aac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Analytics Service
 * Frontend client for tracking passage attempts, word difficulty, and hint usage.
 * Sends summary data to backend Redis analytics service.
 */

export class AnalyticsService {
  constructor() {
    // Generate unique session ID for this browser session
    this.sessionId = this._generateUUID();

    // Current passage tracking state
    this.currentPassage = null;

    // Base URL - uses same origin as the app
    this.baseUrl = window.location.origin;

  }

  /**
   * Generate a UUID v4
   */
  _generateUUID() {
    // Use crypto.randomUUID if available, otherwise fallback
    if (typeof crypto !== 'undefined' && crypto.randomUUID) {
      return crypto.randomUUID();
    }
    // Fallback for older browsers
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

  /**
   * Start tracking a new passage attempt.
   * Call this when a new passage is loaded.
   *
   * @param {Object} book - Book info {title, author}
   * @param {Array} blanks - Array of blank objects with originalWord
   * @param {number} level - Current game level
   * @param {number} round - Current round number
   */
  startPassage(book, blanks, level, round) {
    this.currentPassage = {
      passageId: this._generateUUID(),
      sessionId: this.sessionId,
      bookTitle: book?.title || 'Unknown',
      bookAuthor: book?.author || 'Unknown',
      level: level || 1,
      round: round || 1,
      words: blanks.map(blank => ({
        word: blank.originalWord || '',
        length: (blank.originalWord || '').length,
        attemptsToCorrect: 0,
        hintsUsed: [],
        finalCorrect: false
      })),
      startTime: Date.now()
    };

    console.debug('πŸ“Š Analytics: Started passage', {
      passageId: this.currentPassage.passageId,
      book: this.currentPassage.bookTitle,
      blanks: this.currentPassage.words.length,
      level,
      round
    });
  }

  /**
   * Record an attempt on a specific word.
   * Call this each time the user submits an answer for a blank.
   *
   * @param {number} blankIndex - Index of the blank in the passage
   * @param {boolean} correct - Whether the attempt was correct
   */
  recordAttempt(blankIndex, correct) {
    if (!this.currentPassage) {
      console.warn('πŸ“Š Analytics: No active passage to record attempt');
      return;
    }

    if (blankIndex < 0 || blankIndex >= this.currentPassage.words.length) {
      console.warn('πŸ“Š Analytics: Invalid blank index', blankIndex);
      return;
    }

    const wordData = this.currentPassage.words[blankIndex];
    wordData.attemptsToCorrect++;

    if (correct) {
      wordData.finalCorrect = true;
    }

    console.debug('πŸ“Š Analytics: Recorded attempt', {
      word: wordData.word,
      attempt: wordData.attemptsToCorrect,
      correct
    });
  }

  /**
   * Record all attempts at once (batch mode).
   * Use when results come in as an array.
   *
   * @param {Array} results - Array of {blankIndex, isCorrect} objects
   */
  recordAttemptsBatch(results) {
    if (!this.currentPassage) {
      console.warn('πŸ“Š Analytics: No active passage to record attempts');
      return;
    }

    results.forEach(result => {
      if (result.blankIndex !== undefined) {
        this.recordAttempt(result.blankIndex, result.isCorrect);
      }
    });
  }

  /**
   * Record a hint request for a specific word.
   *
   * @param {number} blankIndex - Index of the blank
   * @param {string} hintType - Type of hint requested (e.g., 'part_of_speech', 'synonym', 'first_letter')
   */
  recordHint(blankIndex, hintType) {
    if (!this.currentPassage) {
      console.warn('πŸ“Š Analytics: No active passage to record hint');
      return;
    }

    if (blankIndex < 0 || blankIndex >= this.currentPassage.words.length) {
      console.warn('πŸ“Š Analytics: Invalid blank index for hint', blankIndex);
      return;
    }

    const wordData = this.currentPassage.words[blankIndex];
    wordData.hintsUsed.push(hintType || 'unknown');

    console.debug('πŸ“Š Analytics: Recorded hint', {
      word: wordData.word,
      hintType,
      totalHints: wordData.hintsUsed.length
    });
  }

  /**
   * Complete the current passage and send analytics to backend.
   *
   * @param {boolean} passed - Whether the user passed the passage
   * @returns {Promise<Object>} - Response from analytics API
   */
  async completePassage(passed) {
    if (!this.currentPassage) {
      console.warn('πŸ“Š Analytics: No active passage to complete');
      return { success: false, message: 'No active passage' };
    }

    // Calculate summary statistics
    const totalBlanks = this.currentPassage.words.length;
    const correctOnFirstTry = this.currentPassage.words.filter(
      w => w.attemptsToCorrect === 1 && w.finalCorrect
    ).length;
    const totalHintsUsed = this.currentPassage.words.reduce(
      (sum, w) => sum + w.hintsUsed.length, 0
    );

    const data = {
      passageId: this.currentPassage.passageId,
      sessionId: this.currentPassage.sessionId,
      bookTitle: this.currentPassage.bookTitle,
      bookAuthor: this.currentPassage.bookAuthor,
      level: this.currentPassage.level,
      round: this.currentPassage.round,
      words: this.currentPassage.words,
      totalBlanks,
      correctOnFirstTry,
      totalHintsUsed,
      passed,
      timestamp: new Date().toISOString()
    };

    console.debug('πŸ“Š Analytics: Completing passage', {
      passageId: data.passageId,
      passed,
      correctOnFirstTry,
      totalBlanks,
      totalHintsUsed
    });

    // Clear current passage state
    this.currentPassage = null;

    // Send to backend
    try {
      const response = await fetch(`${this.baseUrl}/api/analytics/passage`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const result = await response.json();
      return result;

    } catch (error) {
      // Don't throw - analytics failure shouldn't break the game
      console.warn('πŸ“Š Analytics: Failed to send (non-critical)', error.message);
      return { success: false, message: error.message };
    }
  }

  /**
   * Cancel tracking for current passage without sending.
   * Use if the user abandons a passage mid-attempt.
   */
  cancelPassage() {
    if (this.currentPassage) {
      console.debug('πŸ“Š Analytics: Cancelled passage', {
        passageId: this.currentPassage.passageId
      });
      this.currentPassage = null;
    }
  }

  /**
   * Check if there's an active passage being tracked.
   * @returns {boolean}
   */
  isTrackingPassage() {
    return this.currentPassage !== null;
  }

  /**
   * Get current passage statistics (for UI display).
   * @returns {Object|null}
   */
  getCurrentStats() {
    if (!this.currentPassage) return null;

    const totalBlanks = this.currentPassage.words.length;
    const correctOnFirstTry = this.currentPassage.words.filter(
      w => w.attemptsToCorrect === 1 && w.finalCorrect
    ).length;
    const totalCorrect = this.currentPassage.words.filter(w => w.finalCorrect).length;
    const totalHintsUsed = this.currentPassage.words.reduce(
      (sum, w) => sum + w.hintsUsed.length, 0
    );

    return {
      passageId: this.currentPassage.passageId,
      bookTitle: this.currentPassage.bookTitle,
      level: this.currentPassage.level,
      round: this.currentPassage.round,
      totalBlanks,
      correctOnFirstTry,
      totalCorrect,
      totalHintsUsed,
      words: this.currentPassage.words.map(w => ({
        word: w.word,
        attempts: w.attemptsToCorrect,
        hintsUsed: w.hintsUsed.length,
        correct: w.finalCorrect
      }))
    };
  }

  // ===== ADMIN API METHODS =====

  /**
   * Get analytics summary (admin dashboard data).
   * @returns {Promise<Object>}
   */
  async getSummary() {
    try {
      const response = await fetch(`${this.baseUrl}/api/analytics/summary`);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('πŸ“Š Analytics: Failed to get summary', error);
      throw error;
    }
  }

  /**
   * Get recent passage attempts.
   * @param {number} count - Number of entries (max 200)
   * @returns {Promise<Object>}
   */
  async getRecentPassages(count = 50) {
    try {
      const response = await fetch(`${this.baseUrl}/api/analytics/recent?count=${count}`);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('πŸ“Š Analytics: Failed to get recent passages', error);
      throw error;
    }
  }

  /**
   * Export all analytics data.
   * @returns {Promise<Object>}
   */
  async exportAll() {
    try {
      const response = await fetch(`${this.baseUrl}/api/analytics/export`);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('πŸ“Š Analytics: Failed to export', error);
      throw error;
    }
  }

  /**
   * Get statistics for a specific word.
   * @param {string} word
   * @returns {Promise<Object>}
   */
  async getWordStats(word) {
    try {
      const response = await fetch(`${this.baseUrl}/api/analytics/word/${encodeURIComponent(word)}`);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('πŸ“Š Analytics: Failed to get word stats', error);
      throw error;
    }
  }
}

// Export singleton instance
export const analyticsService = new AnalyticsService();