File size: 27,664 Bytes
67041f9
 
 
 
 
ba82e98
 
 
 
 
a09ca12
 
67041f9
 
 
 
a09ca12
67041f9
 
 
a09ca12
 
 
ba82e98
67041f9
 
 
a09ca12
67041f9
 
a09ca12
 
 
 
ba82e98
a09ca12
 
 
 
 
 
 
 
 
 
 
 
ba82e98
a09ca12
67041f9
 
a09ca12
67041f9
73d1bcc
67041f9
016f062
67041f9
016f062
a09ca12
016f062
a09ca12
 
 
 
 
 
 
 
 
 
 
ba82e98
a09ca12
67041f9
016f062
ba82e98
016f062
 
73d1bcc
016f062
ba82e98
a09ca12
 
 
 
73d1bcc
a09ca12
 
 
 
 
73d1bcc
a09ca12
ba82e98
a09ca12
73d1bcc
a09ca12
 
73d1bcc
a09ca12
 
73d1bcc
 
 
a09ca12
67041f9
 
 
 
 
 
 
 
 
 
 
 
 
a09ca12
ba82e98
a09ca12
 
67041f9
 
 
 
 
4fe3e32
67041f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba82e98
67041f9
 
 
 
 
 
 
 
 
 
 
 
ba82e98
 
67041f9
 
a09ca12
ba82e98
67041f9
 
016f062
ba82e98
a09ca12
ba82e98
 
a09ca12
ba82e98
 
016f062
 
a09ca12
 
ba82e98
67041f9
 
ba82e98
67041f9
 
 
 
ba82e98
 
67041f9
 
a09ca12
 
 
 
ba82e98
 
a09ca12
67041f9
73d1bcc
a09ca12
 
67041f9
 
a09ca12
ba82e98
 
 
a09ca12
67041f9
 
 
 
ba82e98
 
67041f9
ba82e98
67041f9
ba82e98
67041f9
 
 
 
 
 
a09ca12
67041f9
 
 
 
 
016f062
67041f9
a09ca12
67041f9
 
 
73d1bcc
67041f9
 
 
 
a09ca12
016f062
 
 
ba82e98
016f062
67041f9
 
73d1bcc
ba82e98
 
67041f9
ba82e98
 
 
 
a09ca12
67041f9
73d1bcc
a09ca12
ba82e98
 
a09ca12
67041f9
ba82e98
 
 
 
 
 
a09ca12
 
ba82e98
67041f9
a09ca12
67041f9
 
a09ca12
 
 
 
67041f9
 
ba82e98
73d1bcc
67041f9
73d1bcc
 
 
67041f9
 
 
 
a09ca12
67041f9
 
ba82e98
 
016f062
 
67041f9
 
 
 
 
 
a09ca12
ba82e98
73d1bcc
a09ca12
 
 
 
73d1bcc
a09ca12
 
 
 
 
ba82e98
 
67041f9
ba82e98
67041f9
ba82e98
 
 
67041f9
73d1bcc
 
67041f9
 
ba82e98
 
67041f9
016f062
73d1bcc
ba82e98
67041f9
 
 
a09ca12
67041f9
 
73d1bcc
016f062
a09ca12
73d1bcc
67041f9
ba82e98
 
67041f9
a09ca12
67041f9
 
016f062
 
73d1bcc
 
a09ca12
67041f9
a09ca12
 
 
73d1bcc
a09ca12
73d1bcc
 
67041f9
 
73d1bcc
67041f9
 
a09ca12
 
 
 
016f062
a09ca12
016f062
a09ca12
ba82e98
a09ca12
016f062
 
 
 
 
a09ca12
ba82e98
016f062
a09ca12
016f062
a09ca12
016f062
 
 
67041f9
a09ca12
 
67041f9
016f062
a09ca12
 
 
 
 
ba82e98
016f062
ba82e98
67041f9
73d1bcc
 
ba82e98
67041f9
a09ca12
 
ba82e98
a09ca12
ba82e98
 
a09ca12
ba82e98
 
 
a09ca12
67041f9
 
 
 
 
a09ca12
67041f9
 
a09ca12
67041f9
73d1bcc
a09ca12
 
 
 
 
67041f9
 
 
 
a09ca12
67041f9
 
a09ca12
67041f9
73d1bcc
a09ca12
 
67041f9
 
 
 
a09ca12
67041f9
 
 
 
 
 
a09ca12
 
 
 
73d1bcc
 
a09ca12
67041f9
a09ca12
 
 
016f062
a09ca12
 
 
67041f9
 
 
 
a09ca12
 
67041f9
 
 
 
 
 
 
 
 
 
a09ca12
016f062
ba82e98
 
016f062
73d1bcc
ba82e98
a09ca12
ba82e98
a09ca12
 
ba82e98
73d1bcc
 
67041f9
 
a09ca12
 
 
016f062
 
ba82e98
 
 
 
016f062
 
a09ca12
 
 
016f062
 
ba82e98
016f062
a09ca12
016f062
 
67041f9
 
 
 
a09ca12
 
 
67041f9
 
a09ca12
 
67041f9
a09ca12
ba82e98
 
a09ca12
 
ba82e98
67041f9
 
 
 
a09ca12
67041f9
 
a09ca12
ba82e98
 
a09ca12
67041f9
 
 
a09ca12
67041f9
 
 
 
 
ba82e98
 
67041f9
 
 
 
ba82e98
 
016f062
 
ba82e98
a09ca12
 
 
ba82e98
67041f9
ba82e98
a09ca12
 
ba82e98
73d1bcc
a09ca12
 
ba82e98
a09ca12
 
67041f9
ba82e98
 
 
 
 
 
 
67041f9
a09ca12
ba82e98
a09ca12
 
ba82e98
a09ca12
ba82e98
a09ca12
 
ba82e98
016f062
a09ca12
ba82e98
 
 
67041f9
 
ba82e98
 
67041f9
 
 
 
a09ca12
67041f9
016f062
67041f9
ba82e98
67041f9
 
ba82e98
67041f9
 
ba82e98
 
 
67041f9
 
 
 
 
ba82e98
 
73d1bcc
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// static/script.js

"use strict"; // より厳格なエラーチェック

// --- グローバル変数 ---
let learningData = null;    // 学習データ - { title: '...', items: [...] } の形式を想定
let currentItemIndex = 0;   // 現在表示中のアイテムインデックス
let currentMode = 'quiz';   // 現在のモード 'quiz' or 'summary'
let correctEffectTimeout;   // 正解エフェクト非表示用のタイマーID
let correctEffect = null;   // 正解エフェクト要素
let sideMenu = null;        // サイドメニュー要素
let menuOverlay = null;     // メニューオーバーレイ要素

// --- 共通関数 ---

/**
 * 指定されたURLに遷移します。遷移前にメニューを閉じます。
 * @param {string} url - 遷移先のURL
 */
function navigateTo(url) {
    closeMenu(); // 遷移前にメニューを閉じる
    setTimeout(() => {
        window.location.href = url;
    }, 100); // 少し遅延させて遷移
}

/**
 * サイドメニューを開きます。
 */
function openMenu() {
    console.log("Opening menu...");
    if (sideMenu && menuOverlay) {
        sideMenu.classList.add('open');
        menuOverlay.classList.add('open');
        document.body.classList.add('menu-open');
    } else {
        console.error("Side menu or overlay element not found. Cannot open menu.");
    }
}

/**
 * サイドメニューを閉じます。
 */
function closeMenu() {
    if (sideMenu && menuOverlay) {
        sideMenu.classList.remove('open');
        menuOverlay.classList.remove('open');
        document.body.classList.remove('menu-open');
    }
}


/**
 * ローディングスピナーを表示/非表示します。 learning.html の要素表示/非表示も制御します。
 * @param {boolean} show - trueで表示、falseで非表示
 * @param {string} buttonId - 操作対象のボタンID (input.html用)
 */
function toggleLoading(show, buttonId = 'generate-button') {
    const targetButton = document.getElementById(buttonId);

    // input.html の generate-button の処理
    if (targetButton && buttonId === 'generate-button') {
        const spinner = targetButton.querySelector('.loading-spinner');
        const buttonText = targetButton.querySelector('.button-text');
        if (show) {
            targetButton.disabled = true;
            if (spinner) spinner.style.display = 'inline-block';
            if (buttonText) buttonText.textContent = '生成中...';
        } else {
            targetButton.disabled = false;
            if (spinner) spinner.style.display = 'none';
            if (buttonText) buttonText.textContent = '生成する';
        }
    }

    // learning.html 用の汎用ローディング表示
    const loadingIndicator = document.getElementById('mode-indicator');
    const cardElement = document.getElementById('learning-card');
    const paginationElement = document.querySelector('.pagination'); // pagination要素を取得
    const optionsArea = document.getElementById('options-area');
    const tapToShowElement = document.getElementById('tap-to-show');

    const currentPathname = window.location.pathname;
    if (currentPathname.endsWith('/learning') || currentPathname.endsWith('/learning.html')) {
        if (show) {
            // ローディング開始時の処理
            if (loadingIndicator) {
                loadingIndicator.textContent = '読み込み中...';
                loadingIndicator.classList.add('loading');
            }
            if (cardElement) cardElement.style.opacity = '0.5';
            if (paginationElement) paginationElement.style.display = 'none'; // ★ 非表示にする
            if (optionsArea) optionsArea.style.display = 'none';
            if (tapToShowElement) tapToShowElement.style.display = 'none';
        } else {
            // ローディング終了時の処理
            if (loadingIndicator) {
                 loadingIndicator.classList.remove('loading');
                 // モード表示は displayCurrentItem で更新される
            }
            if (cardElement) cardElement.style.opacity = '1';
            // ★★★ ローディング終了時にページネーションを再表示 ★★★
            if (paginationElement) paginationElement.style.display = 'flex'; // CSSでのdisplay値 (通常flex) に戻す
            // optionsArea と tapToShowElement の表示は displayCurrentItem で適切に制御される
        }
    }
}

/**
 * エラーメッセージを表示します。
 * @param {string} message - 表示するエラーメッセージ
 * @param {string} elementId - メッセージを表示する要素のID (デフォルト: 'error-message')
 */
function displayErrorMessage(message, elementId = 'error-message') {
    const errorElement = document.getElementById(elementId);
    if (errorElement) {
        errorElement.textContent = message;
        errorElement.style.display = message ? 'block' : 'none';
    } else {
        if (message) {
            console.error(`Error element with ID "${elementId}" not found. Cannot display message: ${message}`);
        }
    }
}

// --- 画面遷移用関数 ---
function goToInput() {
    navigateTo('/input');
}

function goToHistory() {
    navigateTo('/history');
}

function goToSettings() {
    navigateTo('/settings');
}

function goToLearning(contentId) {
    if (contentId) {
        navigateTo(`/learning?id=${encodeURIComponent(contentId)}`);
    } else {
        console.error('goToLearning requires a content ID.');
        alert('学習コンテンツのIDが見つかりません。');
    }
}


// --- input.html 用の処理 ---

/**
 * 生成フォームの送信処理
 */
async function handleGenerateSubmit() {
    const urlInput = document.getElementById('youtube-url');
    const youtubeUrl = urlInput.value.trim();
    const errorMsgElementId = 'error-message';
    displayErrorMessage('', errorMsgElementId);

    if (!youtubeUrl) {
        displayErrorMessage('YouTubeリンクを入力してください。', errorMsgElementId);
        return false;
    }

    try {
        const urlObj = new URL(youtubeUrl);
        const validHostnames = ['www.youtube.com', 'youtube.com', 'youtu.be'];
        if (!validHostnames.includes(urlObj.hostname)) throw new Error('Invalid hostname');
        if (urlObj.hostname === 'youtu.be' && urlObj.pathname.length <= 1) throw new Error('Missing video ID for youtu.be');
        if (urlObj.hostname.includes('youtube.com')) {
            if (urlObj.pathname === '/watch' && !urlObj.searchParams.has('v')) throw new Error('Missing video ID parameter (v=...) for youtube.com/watch');
            if (urlObj.pathname.startsWith('/shorts/') && urlObj.pathname.length <= 8) throw new Error('Missing video ID for youtube.com/shorts/');
        }
    } catch (e) {
        console.warn("Invalid URL format:", e.message);
        displayErrorMessage('有効なYouTube動画のリンクを入力してください。(例: https://www.youtube.com/watch?v=...)', errorMsgElementId);
        return false;
    }

    toggleLoading(true, 'generate-button');

    try {
        const response = await fetch('/api/generate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
            body: JSON.stringify({ url: youtubeUrl }),
        });

        let result;
        try {
            result = await response.json();
        } catch (jsonError) {
            console.error('Failed to parse JSON response:', jsonError);
            throw new Error(response.ok ? 'サーバーからの応答形式が不正です。' : `サーバーエラー (${response.status})`);
        }

        // サーバーが返すJSON構造 { success: true, data: { id: '...' } } を期待
        if (response.ok && result && typeof result === 'object' && result.success && result.data && result.data.id) {
            console.log("Generation successful, navigating to learning page with ID:", result.data.id);
            goToLearning(result.data.id);
        } else {
            console.error('Generation API call failed or returned unexpected structure:', result);
            const serverMessage = (result && typeof result === 'object' && result.message) ||
                                  (result && typeof result === 'object' && result.error && result.error.message) ||
                                  (response.ok ? '生成に失敗しました (不明な応答形式)。' : `サーバーエラー (${response.status})`);
            displayErrorMessage(serverMessage, errorMsgElementId);
        }

    } catch (error) {
        console.error('Error during generation request:', error);
        const userMessage = error.message.includes('Failed to fetch') ? 'サーバーに接続できませんでした。' : `エラー: ${error.message}`;
        displayErrorMessage(userMessage, errorMsgElementId);
    } finally {
        toggleLoading(false, 'generate-button');
    }
    return false;
}


// --- learning.html 用の処理 ---

/**
 * learning.html の初期化: コンテンツデータを取得し、最初のアイテムを表示
 */
async function initializeLearningScreen() {
    console.log('Initializing Learning Screen...');
    const params = new URLSearchParams(window.location.search);
    const contentId = params.get('id');

    if (!contentId) {
        displayLearningError('学習コンテンツのIDが見つかりません。');
        return;
    }
    console.log('Content ID:', contentId);
    toggleLoading(true); // ★ ローディング開始 (ここでpaginationが消える)

    try {
        const response = await fetch(`/api/learning/${contentId}`);
        if (!response.ok) {
            let errorMessage = `サーバーからのデータ取得に失敗 (${response.status})`;
            try {
                const errorData = await response.json();
                errorMessage = errorData.message || errorMessage;
            } catch (e) { console.warn('Failed to parse error response as JSON.'); }
            throw new Error(errorMessage);
        }

        // サーバーからの応答がオブジェクト {success: ..., data: {...}} であると想定
        const result = await response.json();
        console.log('Fetched data object:', result);

        // 応答の形式をチェック
        if (!result || typeof result !== 'object' || !result.success || !result.data || !Array.isArray(result.data.items)) {
            console.error('Invalid data structure received from server:', result);
            throw new Error('サーバーから受け取ったデータの形式が正しくありません。');
        }

        // learningData を構築 (title と items を data から取得)
        learningData = {
            title: result.data.title || `学習セット (${contentId})`, // data.title があればそれを使う
            items: result.data.items // data.items を使う
        };

        // アイテム配列が空でないかチェック
        if (learningData.items.length === 0) {
             throw new Error('学習データが見つかりませんでした (アイテムが0件)。');
        }

        // タイトルを設定
        const titleElement = document.getElementById('learning-title');
        if (titleElement) {
            titleElement.textContent = learningData.title;
        } else {
            console.warn("Title element ('learning-title') not found.");
        }

        // 最初のアイテムを表示
        currentItemIndex = 0;
        displayCurrentItem();

    } catch (error) {
        console.error('Error initializing learning screen:', error);
        const message = (error instanceof SyntaxError) ? `サーバー応答の解析エラー: ${error.message}` : `読み込みエラー: ${error.message}`;
        displayLearningError(message); // エラー表示関数内で toggleLoading(false) が呼ばれる
    } finally {
        // ★ 成功時も失敗時もここでローディングを終了させる
        // displayLearningError内で呼ばれる場合もあるが、成功時はここで確実に呼ぶ
        toggleLoading(false); // ★ ローディング終了 (ここでpaginationが再表示される)
    }
}

/**
 * 現在の学習アイテムをカードに表示 (クイズ or 要約)
 */
function displayCurrentItem() {
    hideCorrectEffect();
    clearTimeout(correctEffectTimeout);

    const cardElement = document.getElementById('learning-card');
    const cardTextElement = document.getElementById('card-text');
    const answerTextElement = document.getElementById('answer-text');
    const tapToShowElement = document.getElementById('tap-to-show');
    const optionsArea = document.getElementById('options-area');
    const modeIndicator = document.getElementById('mode-indicator');

    if (!cardElement || !cardTextElement || !answerTextElement || !tapToShowElement || !optionsArea || !modeIndicator) {
        console.error("One or more required learning elements are missing.");
        displayLearningError("画面表示に必要な要素が見つかりません。"); // エラー表示内でtoggleLoading(false)される
        return;
    }
    if (!learningData || !learningData.items || currentItemIndex < 0 || currentItemIndex >= learningData.items.length) {
        console.error('Invalid learning data or index:', learningData, currentItemIndex);
        displayLearningError('表示する学習データが見つかりません。'); // エラー表示内でtoggleLoading(false)される
        return;
    }

    const item = learningData.items[currentItemIndex];

    // リセット
    cardTextElement.innerHTML = '';
    answerTextElement.style.display = 'none';
    answerTextElement.textContent = '';
    tapToShowElement.style.display = 'none';
    optionsArea.innerHTML = '';
    optionsArea.style.display = 'none';
    modeIndicator.classList.remove('loading');

    // サーバーレスポンスのキーに合わせて item.text を使用
    if (item.type === 'question' && item.text && item.answer) {
        currentMode = 'quiz';
        modeIndicator.textContent = 'クイズモード';
        cardTextElement.textContent = item.text; // 問題文
        answerTextElement.textContent = `答え: ${item.answer}`;

        if (item.options && Array.isArray(item.options) && item.options.length > 0) {
            optionsArea.style.display = 'block'; // ★ 表示
            item.options.forEach(option => {
                const button = document.createElement('button');
                button.classList.add('option-button');
                button.textContent = option;
                button.onclick = () => handleOptionClick(option);
                optionsArea.appendChild(button);
            });
            tapToShowElement.style.display = 'block'; // ★ 表示
        } else {
             console.warn(`Quiz item ${currentItemIndex} has no options.`);
             tapToShowElement.style.display = 'block'; // ★ 選択肢なくても解答表示は可能
        }
        cardElement.onclick = () => revealAnswer();
        tapToShowElement.onclick = () => revealAnswer();

    } else if (item.type === 'summary' && item.text) {
        currentMode = 'summary';
        modeIndicator.textContent = '要約モード';
        cardTextElement.innerHTML = item.text.replace(/\n/g, '<br>');
        cardElement.onclick = null;
        tapToShowElement.style.display = 'none'; // ★ 非表示
        optionsArea.style.display = 'none'; // ★ 非表示

    } else {
        console.warn('Unknown or invalid item type/data:', item);
        currentMode = 'unknown';
        modeIndicator.textContent = 'データエラー';
        cardTextElement.textContent = `[不正なデータ形式] ${item.text || 'この項目を表示できません。'}`;
        cardElement.onclick = null;
        tapToShowElement.style.display = 'none'; // ★ 非表示
        optionsArea.style.display = 'none'; // ★ 非表示
    }

    updatePagination(); // ★ ページネーションの表示/非表示ではなく、内容とボタン状態を更新
}

/**
 * クイズの選択肢がクリックされたときの処理
 * @param {string} selectedOption - ユーザーが選択した選択肢のテキスト
 */
function handleOptionClick(selectedOption) {
    if (currentMode !== 'quiz' || !learningData || !learningData.items || !learningData.items[currentItemIndex]) return;

     const answerTextElement = document.getElementById('answer-text');
     if (answerTextElement && answerTextElement.style.display === 'block') return; // 解答表示済み

    const currentItem = learningData.items[currentItemIndex];
    const correctAnswer = currentItem.answer;
    const isCorrect = selectedOption === correctAnswer;

    if (isCorrect) {
        console.log("Correct!");
        showCorrectEffect();
    } else {
        console.log("Incorrect...");
    }
    revealAnswer(selectedOption);
}


/**
 * クイズの解答を表示し、選択肢ボタンの状態を更新する
 * @param {string|null} [selectedOption=null] - ユーザーが選択した選択肢。nullの場合はカードタップ等による表示。
 */
function revealAnswer(selectedOption = null) {
    if (currentMode !== 'quiz' || !learningData || !learningData.items || !learningData.items[currentItemIndex]) return;

    const answerTextElement = document.getElementById('answer-text');
    const tapToShowElement = document.getElementById('tap-to-show');
    const optionsArea = document.getElementById('options-area');
    const cardElement = document.getElementById('learning-card');

    if (answerTextElement && answerTextElement.style.display === 'block') return; // 表示済み

    if (answerTextElement) answerTextElement.style.display = 'block'; // ★ 表示
    if (tapToShowElement) tapToShowElement.style.display = 'none'; // ★ 非表示
    if (cardElement) cardElement.onclick = null;

    if (optionsArea) {
        const correctAnswer = learningData.items[currentItemIndex].answer;
        const buttons = optionsArea.querySelectorAll('.option-button');
        buttons.forEach(button => {
            button.disabled = true;
            button.onclick = null;
            const buttonText = button.textContent;
            if (buttonText === correctAnswer) button.classList.add('correct');
            else if (buttonText === selectedOption) button.classList.add('incorrect');
            else button.classList.add('other-disabled');
        });
    }
}


/**
 * 次の学習アイテムへ移動
 */
function goToNext() {
    if (learningData && learningData.items && currentItemIndex < learningData.items.length - 1) {
        currentItemIndex++;
        displayCurrentItem(); // displayCurrentItem内で要素の表示/非表示が制御される
    } else {
        console.log("Already at the last item or no data.");
        if (learningData && learningData.items && currentItemIndex === learningData.items.length - 1) {
             alert("学習セットが完了しました!");
        }
    }
}

/**
 * 前の学習アイテムへ移動
 */
function goToPrev() {
    if (learningData && learningData.items && currentItemIndex > 0) {
        currentItemIndex--;
        displayCurrentItem(); // displayCurrentItem内で要素の表示/非表示が制御される
    } else {
        console.log("Already at the first item or no data.");
    }
}

/**
 * ページネーション(ページ番号とボタンの状態)を更新
 */
function updatePagination() {
    const pageInfo = document.getElementById('page-info');
    const prevButton = document.getElementById('prev-button');
    const nextButton = document.getElementById('next-button');

    if (!pageInfo || !prevButton || !nextButton) {
         console.warn("Pagination elements not found.");
         return;
    }
    // ★ ページネーション要素自体の表示/非表示は toggleLoading で行う
    // ここでは内容とボタンの状態のみ更新
    if (learningData && learningData.items && learningData.items.length > 0) {
        const totalItems = learningData.items.length;
        pageInfo.textContent = `${currentItemIndex + 1} / ${totalItems}`;
        prevButton.disabled = currentItemIndex === 0;
        nextButton.disabled = currentItemIndex === totalItems - 1;
    } else {
        pageInfo.textContent = '0 / 0';
        prevButton.disabled = true;
        nextButton.disabled = true;
    }
}

/**
 * learning.html でエラーが発生した場合の表示処理
 * @param {string} message - 表示するエラーメッセージ
 */
function displayLearningError(message) {
    const cardElement = document.getElementById('learning-card');
    const titleElement = document.getElementById('learning-title');
    const paginationElement = document.querySelector('.pagination');
    const optionsArea = document.getElementById('options-area');
    const modeIndicator = document.getElementById('mode-indicator');
    const tapToShow = document.getElementById('tap-to-show');

    if (titleElement) titleElement.textContent = 'エラー';
    if (modeIndicator) modeIndicator.textContent = 'エラー発生';
    if (cardElement) {
        cardElement.innerHTML = `<p class="main-text error-text">${message}</p>`; // CSSでスタイル調整用クラス追加
        cardElement.onclick = null;
    }
    // エラー時はページネーション等も非表示にする
    if (paginationElement) paginationElement.style.display = 'none';
    if (optionsArea) {
        optionsArea.innerHTML = '';
        optionsArea.style.display = 'none';
    }
    if (tapToShow) tapToShow.style.display = 'none';
    // ★ エラー表示関数内でも toggleLoading(false) を呼ぶことを確認(重複しても問題ない)
    toggleLoading(false);
}

/**
 * 正解時に「〇」エフェクトを表示する
 */
function showCorrectEffect() {
    if (correctEffect) {
        clearTimeout(correctEffectTimeout);
        correctEffect.classList.add('show');
        correctEffectTimeout = setTimeout(() => { hideCorrectEffect(); }, 1000);
    } else { console.warn("Correct effect element not found."); }
}

/**
 * 正解エフェクトを非表示にする
 */
function hideCorrectEffect() {
    if (correctEffect && correctEffect.classList.contains('show')) {
        correctEffect.classList.remove('show');
    }
    clearTimeout(correctEffectTimeout);
}


// --- settings.html 用の処理 ---

/**
 * トグルスイッチの状態が変更されたときの処理
 * @param {HTMLInputElement} checkbox - 変更されたチェックボックス要素
 * @param {string} type - トグルの種類 ('dark', 'notification' など)
 */
function handleToggleChange(checkbox, type) {
    const isChecked = checkbox.checked;
    console.log(`Toggle changed for ${type}: ${isChecked}`);
    if (type === 'dark') {
        document.body.classList.toggle('dark-mode', isChecked);
        try { localStorage.setItem('darkModeEnabled', isChecked); }
        catch (e) { console.warn('Could not save dark mode preference:', e); }
    } else if (type === 'notification') {
        console.log("Notification setting toggled:", isChecked);
        alert(`通知設定未実装 (設定: ${isChecked ? 'ON' : 'OFF'})`);
    }
}

/**
 * ログアウトボタンがクリックされたときの処理
 */
function handleLogout() {
    console.log("Logout button clicked");
    // TODO: 実際のログアウト処理
    alert("ログアウトしました。(開発中)");
    goToInput();
}

/**
 * ローカルストレージからダークモード設定を読み込み、bodyに適用する
 */
function applyDarkModePreference() {
     try {
        const darkModeEnabled = localStorage.getItem('darkModeEnabled') === 'true';
        document.body.classList.toggle('dark-mode', darkModeEnabled);
        // console.log(`Applied dark mode preference: ${darkModeEnabled}`);
    } catch (e) { console.warn('Could not load/apply dark mode preference:', e); }
}


// --- ページの初期化処理 ---
const pathname = window.location.pathname;
applyDarkModePreference(); // 最初に適用

document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM fully loaded. Path:', pathname);

    sideMenu = document.getElementById('side-menu');
    menuOverlay = document.getElementById('menu-overlay');
    if (!sideMenu || !menuOverlay) console.warn("Menu elements not found.");

    // learningページ固有の初期化
    if (pathname.endsWith('/learning') || pathname.endsWith('/learning.html')) {
        correctEffect = document.getElementById('correct-effect');
        if (!correctEffect) console.warn("Correct effect element not found.");
        initializeLearningScreen(); // ★ initializeLearningScreen を呼ぶ
    }

    // inputページ固有の初期化
    if (pathname === '/' || pathname.endsWith('/input') || pathname.endsWith('/input.html')) {
        console.log("Initializing Input page...");
        const form = document.getElementById('generate-form');
        if (form) form.addEventListener('submit', (e) => { e.preventDefault(); handleGenerateSubmit(); });
        else console.warn("Generate form not found.");
        const urlParams = new URLSearchParams(window.location.search);
        const initialUrl = urlParams.get('url');
        if (initialUrl) {
            const urlInput = document.getElementById('youtube-url');
            if (urlInput) urlInput.value = initialUrl;
        }
    }
    // historyページ固有の初期化
    else if (pathname.endsWith('/history') || pathname.endsWith('/history.html')) {
        console.log("Initializing History page...");
        // loadHistoryData();
    }
    // settingsページ固有の初期化
    else if (pathname.endsWith('/settings') || pathname.endsWith('/settings.html')) {
        console.log("Initializing Settings page...");
        try { // ダークモードトグル状態設定
            const darkModeEnabled = localStorage.getItem('darkModeEnabled') === 'true';
            const toggle = document.querySelector('input[type="checkbox"][onchange*="dark"]');
            if (toggle) toggle.checked = darkModeEnabled;
            else console.warn("Dark mode toggle not found.");
        } catch (e) { console.warn('Could not set dark mode toggle state:', e); }
    }

    updateFooterNavActiveState(pathname); // フッターアクティブ状態更新
    closeMenu(); // 念のためメニューを閉じる
});


/**
 * 現在のパスに基づいてフッターナビゲーションのアクティブ状態を更新
 */
 function updateFooterNavActiveState(currentPath) {
    const footerNav = document.querySelector('.footer-nav');
    if (!footerNav) return;
    const buttons = footerNav.querySelectorAll('button');
    buttons.forEach(button => {
        button.classList.remove('active');
        const onclickAttr = button.getAttribute('onclick');
        if (onclickAttr) {
            if ((currentPath === '/' || currentPath.endsWith('/input') || currentPath.endsWith('/input.html')) && onclickAttr.includes('goToInput')) button.classList.add('active');
            else if ((currentPath.endsWith('/history') || currentPath.endsWith('/history.html')) && onclickAttr.includes('goToHistory')) button.classList.add('active');
            else if ((currentPath.endsWith('/settings') || currentPath.endsWith('/settings.html')) && onclickAttr.includes('goToSettings')) button.classList.add('active');
        }
    });
}


// --- デバッグ用グローバル公開 ---

// --- END OF FILE script.js ---