File size: 31,798 Bytes
8e5f1c9
 
e665557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28a4120
e665557
 
 
28a4120
 
 
 
e665557
28a4120
e665557
 
 
 
28a4120
e665557
 
 
 
 
 
 
 
 
 
 
 
 
8e5f1c9
36f63dd
 
e665557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e5f1c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36f63dd
8e5f1c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36f63dd
8e5f1c9
 
36f63dd
 
 
 
 
 
 
 
8e5f1c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fb0a37
8e5f1c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36f63dd
8e5f1c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
/* NCAkit - Main JavaScript */

// ============================================
// πŸ” LOGIN CREDENTIALS (Easy to find if forgotten!)
// ============================================
const AUTH_CONFIG = {
    username: "robiul",
    password: "Robi1234",
    storageKey: "ncakit_logged_in"
};

// ============================================
// AUTHENTICATION FUNCTIONS
// ============================================
function checkAuth() {
    return localStorage.getItem(AUTH_CONFIG.storageKey) === "true";
}

function showApp() {
    document.getElementById('loginOverlay').classList.add('hidden');
    document.getElementById('mainApp').classList.remove('hidden');
}

function showLogin() {
    document.getElementById('loginOverlay').classList.remove('hidden');
    document.getElementById('mainApp').classList.add('hidden');
}

function handleLogin(e) {
    e.preventDefault();
    const username = document.getElementById('loginUsername').value.trim();
    const password = document.getElementById('loginPassword').value;
    const errorEl = document.getElementById('loginError');

    // Debug logging
    console.log('Login attempt:', { username, passwordLength: password.length });
    console.log('Expected:', { username: AUTH_CONFIG.username, password: AUTH_CONFIG.password });

    if (username === AUTH_CONFIG.username && password === AUTH_CONFIG.password) {
        console.log('Login SUCCESS!');
        localStorage.setItem(AUTH_CONFIG.storageKey, "true");
        errorEl.classList.add('hidden');
        showApp();
    } else {
        console.log('Login FAILED - credentials mismatch');
        errorEl.textContent = "❌ Incorrect username or password";
        errorEl.classList.remove('hidden');
    }
}

function handleLogout() {
    localStorage.removeItem(AUTH_CONFIG.storageKey);
    showLogin();
    // Clear form
    document.getElementById('loginUsername').value = '';
    document.getElementById('loginPassword').value = '';
}

// Wait for DOM to be ready
document.addEventListener('DOMContentLoaded', function () {

    // ============================================
    // AUTHENTICATION CHECK ON PAGE LOAD
    // ============================================
    if (checkAuth()) {
        showApp();
    } else {
        showLogin();
    }

    // Login form handler
    document.getElementById('loginForm').addEventListener('submit', handleLogin);

    // Logout button handler
    document.getElementById('logoutBtn').addEventListener('click', handleLogout);

    // ============================================
    // TAB SWITCHING
    // ============================================
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            btn.classList.add('active');
            document.getElementById(btn.dataset.tab + '-tab').classList.add('active');
        });
    });

    // ============================================
    // STORY REELS MODULE
    // ============================================
    document.getElementById('storyForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const status = document.getElementById('storyStatus');
        status.className = 'status processing';
        status.innerHTML = '⏳ Starting generation...';
        status.classList.remove('hidden');

        const data = {
            script: document.getElementById('storyScript').value,
            image_style: document.getElementById('storyStyle').value,
            voice: document.getElementById('storyVoice').value
        };

        try {
            const res = await fetch('/api/story/story-reel', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await res.json();

            if (result.job_id) {
                status.innerHTML = `βœ… Job started! ID: ${result.job_id}<br>Checking status...`;
                pollStatus(result.job_id, 'story');
            }
        } catch (err) {
            status.className = 'status error';
            status.innerHTML = '❌ Error: ' + err.message;
        }
    });

    // Generic poll status for story/video
    async function pollStatus(jobId, type) {
        const status = document.getElementById(type + 'Status');
        const endpoint = type === 'story' ? '/api/story/story-reel/' : '/api/video/short-video/';

        const check = async () => {
            try {
                const res = await fetch(endpoint + jobId + '/status');
                const data = await res.json();

                const progress = data.progress || 0;
                status.innerHTML = `
                    <div>Status: <strong>${data.status}</strong></div>
                    <div class="progress-bar"><div class="progress-fill" style="width: ${progress}%"></div></div>
                `;

                if (data.status === 'ready') {
                    status.className = 'status success';
                    const downloadUrl = type === 'story' ? `/api/story/story-reel/${jobId}` : `/api/video/short-video/${jobId}`;
                    status.innerHTML += `<br><a href="${downloadUrl}" class="btn btn-primary" style="margin-top: 1rem; display: inline-block;">πŸ“₯ Download Video</a>`;
                } else if (data.status === 'failed') {
                    status.className = 'status error';
                    status.innerHTML = '❌ Failed: ' + (data.error || 'Unknown error');
                } else {
                    setTimeout(check, 2000);
                }
            } catch (err) {
                setTimeout(check, 3000);
            }
        };
        check();
    }

    // ============================================
    // VIDEO CREATOR MODULE
    // ============================================

    // Add scene
    document.getElementById('addScene').addEventListener('click', () => {
        const container = document.getElementById('scenesContainer');
        const count = container.querySelectorAll('.scene-text').length + 1;
        container.innerHTML += `
            <div class="form-group">
                <label>Scene ${count} - Text</label>
                <textarea class="scene-text" rows="2" placeholder="Enter narration..." required></textarea>
            </div>
            <div class="form-group">
                <label>Keywords</label>
                <input type="text" class="scene-keywords" placeholder="nature, forest">
            </div>
        `;
    });

    // Video Form
    document.getElementById('videoForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const status = document.getElementById('videoStatus');
        status.className = 'status processing';
        status.innerHTML = '⏳ Creating video...';
        status.classList.remove('hidden');

        const scenes = [];
        document.querySelectorAll('.scene-text').forEach((textarea, i) => {
            const keywords = document.querySelectorAll('.scene-keywords')[i]?.value || '';
            scenes.push({
                text: textarea.value,
                searchTerms: keywords.split(',').map(k => k.trim()).filter(k => k)
            });
        });

        const data = {
            scenes: scenes,
            config: {
                voice: document.getElementById('videoVoice').value,
                music: document.getElementById('videoMusic').value || null
            }
        };

        try {
            const res = await fetch('/api/video/short-video', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await res.json();

            if (result.videoId) {
                status.innerHTML = `βœ… Video started! ID: ${result.videoId}`;
                pollStatus(result.videoId, 'video');
            }
        } catch (err) {
            status.className = 'status error';
            status.innerHTML = '❌ Error: ' + err.message;
        }
    });

    // ============================================
    // FACT IMAGE MODULE
    // ============================================
    document.getElementById('factForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const status = document.getElementById('factStatus');
        status.className = 'status processing';
        status.innerHTML = '⏳ Generating fact video...';
        status.classList.remove('hidden');

        const heading = document.getElementById('factHeading').value.trim();

        const data = {
            model: document.getElementById('factModel').value,
            image_prompt: document.getElementById('factImagePrompt').value,
            fact_text: document.getElementById('factText').value,
            duration: parseInt(document.getElementById('factDuration').value)
        };

        if (heading) {
            data.fact_heading = heading;
            data.heading_background = {
                enabled: true,
                color: document.getElementById('headingBgColor').value,
                padding: 22,
                corner_radius: parseInt(document.getElementById('headingBgRadius').value)
            };
        }

        try {
            const res = await fetch('/api/fact-image/', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await res.json();

            if (res.ok && result.job_id) {
                status.innerHTML = `βœ… Job started! ID: ${result.job_id}<br>Checking status...`;
                pollFactStatus(result.job_id);
            } else {
                status.className = 'status error';
                // Show validation errors
                let errorMsg = result.detail || 'Unknown error';
                if (Array.isArray(result.detail)) {
                    errorMsg = result.detail.map(e => e.msg).join(', ');
                }
                status.innerHTML = '❌ Error: ' + errorMsg;
            }
        } catch (err) {
            status.className = 'status error';
            status.innerHTML = '❌ Error: ' + err.message;
        }
    });

    async function pollFactStatus(jobId) {
        const status = document.getElementById('factStatus');

        const check = async () => {
            try {
                const res = await fetch(`/api/fact-image/${jobId}/status`);
                const data = await res.json();

                const progress = data.progress || 0;
                status.innerHTML = `
                    <div>Status: <strong>${data.status}</strong></div>
                    <div class="progress-bar"><div class="progress-fill" style="width: ${progress}%"></div></div>
                `;

                if (data.status === 'ready') {
                    status.className = 'status success';
                    status.innerHTML += `<br><a href="/api/fact-image/${jobId}" class="btn btn-primary" style="margin-top: 1rem; display: inline-block;">πŸ“₯ Download Video</a>`;
                } else if (data.status === 'failed') {
                    status.className = 'status error';
                    status.innerHTML = '❌ Failed: ' + (data.error || 'Unknown error');
                } else {
                    setTimeout(check, 2000);
                }
            } catch (err) {
                setTimeout(check, 3000);
            }
        };
        check();
    }

    // ============================================
    // TRENDS MODULE
    // ============================================
    document.getElementById('trendingForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const results = document.getElementById('trendingResults');
        results.innerHTML = '<p>⏳ Loading trends...</p>';

        const data = {
            country: document.getElementById('trendCountry').value,
            limit: parseInt(document.getElementById('trendLimit').value)
        };

        try {
            const res = await fetch('/api/trends/trending-now', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await res.json();

            if (result.success) {
                let html = '<div style="background: var(--bg-secondary); border-radius: 8px; padding: 1rem; max-height: 400px; overflow-y: auto;">';
                result.trends.forEach(t => {
                    html += `<div style="padding: 0.5rem 0; border-bottom: 1px solid var(--border);">
                        <span style="color: var(--accent); font-weight: bold;">#${t.rank}</span> ${t.topic}
                    </div>`;
                });
                html += '</div>';
                results.innerHTML = html;
            } else {
                results.innerHTML = '<p style="color: var(--error);">❌ Error: ' + (result.detail || 'Failed') + '</p>';
            }
        } catch (err) {
            results.innerHTML = '<p style="color: var(--error);">❌ Error: ' + err.message + '</p>';
        }
    });

    document.getElementById('keywordForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const results = document.getElementById('keywordResults');
        results.innerHTML = '<p>⏳ Analyzing keyword...</p>';

        const data = {
            keyword: document.getElementById('researchKeyword').value,
            region: document.getElementById('researchRegion').value,
            timeframe: document.getElementById('researchTimeframe').value,
            category: document.getElementById('researchCategory').value,
            search_type: document.getElementById('researchType').value
        };

        try {
            const res = await fetch('/api/trends/keyword-research', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await res.json();

            if (result.success) {
                let html = '<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">';

                html += '<div style="background: var(--bg-secondary); border-radius: 8px; padding: 1rem;">';
                html += '<h4 style="margin-bottom: 0.5rem;">πŸ“Œ Related Topics</h4>';
                if (result.related_topics.top && result.related_topics.top.length > 0) {
                    result.related_topics.top.slice(0, 10).forEach(t => {
                        html += `<div style="padding: 0.25rem 0; font-size: 0.9rem;">${t.topic} <span style="color: var(--text-secondary);">(${t.value})</span></div>`;
                    });
                } else {
                    html += '<p style="color: var(--text-secondary); font-size: 0.9rem;">No data</p>';
                }
                html += '</div>';

                html += '<div style="background: var(--bg-secondary); border-radius: 8px; padding: 1rem;">';
                html += '<h4 style="margin-bottom: 0.5rem;">πŸ” Related Queries</h4>';
                if (result.related_queries.top && result.related_queries.top.length > 0) {
                    result.related_queries.top.slice(0, 10).forEach(q => {
                        html += `<div style="padding: 0.25rem 0; font-size: 0.9rem;">${q.query} <span style="color: var(--text-secondary);">(${q.value})</span></div>`;
                    });
                } else {
                    html += '<p style="color: var(--text-secondary); font-size: 0.9rem;">No data</p>';
                }
                html += '</div>';

                html += '</div>';
                results.innerHTML = html;
            } else {
                results.innerHTML = '<p style="color: var(--error);">❌ Error: ' + (result.detail || 'Failed') + '</p>';
            }
        } catch (err) {
            results.innerHTML = '<p style="color: var(--error);">❌ Error: ' + err.message + '</p>';
        }
    });

    // ============================================
    // QUIZ REEL MODULE
    // ============================================
    let quizCount = 1;

    document.getElementById('addQuizBtn').addEventListener('click', () => {
        quizCount++;
        const container = document.getElementById('quizContainer');
        const quizHtml = `
            <div class="quiz-item" style="background: var(--bg-secondary); padding: 1.5rem; border-radius: 12px; margin-bottom: 1rem;">
                <h4 style="color: var(--accent); margin-bottom: 1rem;">Quiz ${quizCount}</h4>
                <div class="form-group">
                    <label>Hook (Category)</label>
                    <input type="text" class="quiz-hook" placeholder="e.g., IQ TEST, MATH QUIZ">
                </div>
                <div class="form-group">
                    <label>Question *</label>
                    <input type="text" class="quiz-question" placeholder="Enter your question" required>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Option A *</label>
                        <input type="text" class="quiz-option-a" placeholder="Answer A" required>
                    </div>
                    <div class="form-group">
                        <label>Option B *</label>
                        <input type="text" class="quiz-option-b" placeholder="Answer B" required>
                    </div>
                    <div class="form-group">
                        <label>Option C *</label>
                        <input type="text" class="quiz-option-c" placeholder="Answer C" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Correct Answer *</label>
                        <select class="quiz-correct" required>
                            <option value="A">A</option>
                            <option value="B">B</option>
                            <option value="C">C</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>Explain (shown after answer)</label>
                    <input type="text" class="quiz-explain" placeholder="Brief explanation">
                </div>
            </div>
        `;
        container.insertAdjacentHTML('beforeend', quizHtml);
    });

    document.getElementById('removeQuizBtn').addEventListener('click', () => {
        const container = document.getElementById('quizContainer');
        const items = container.querySelectorAll('.quiz-item');
        if (items.length > 1) {
            items[items.length - 1].remove();
            quizCount--;
        }
    });

    async function pollQuizStatus(jobId, statusDiv) {
        const checkStatus = async () => {
            try {
                const res = await fetch(`/api/quiz/${jobId}/status`);
                const status = await res.json();

                if (status.status === 'ready') {
                    statusDiv.className = 'status success';
                    statusDiv.innerHTML = `βœ… Video Ready! <a href="${status.video_url}" target="_blank" style="color: var(--accent);">Download Video</a>`;
                    return;
                } else if (status.status === 'failed') {
                    statusDiv.className = 'status error';
                    statusDiv.innerHTML = `❌ Failed: ${status.error}`;
                    return;
                } else {
                    statusDiv.innerHTML = `⏳ ${status.status}... ${status.progress}%`;
                    setTimeout(checkStatus, 2000);
                }
            } catch (err) {
                statusDiv.className = 'status error';
                statusDiv.innerHTML = `❌ Error: ${err.message}`;
            }
        };
        checkStatus();
    }

    document.getElementById('quizForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const status = document.getElementById('quizStatus');
        status.className = 'status';
        status.classList.remove('hidden');
        status.innerHTML = '⏳ Starting quiz video generation...';

        const quizItems = document.querySelectorAll('.quiz-item');
        const quizzes = [];

        quizItems.forEach(item => {
            quizzes.push({
                hook: item.querySelector('.quiz-hook').value || '',
                question: item.querySelector('.quiz-question').value,
                options: {
                    A: item.querySelector('.quiz-option-a').value,
                    B: item.querySelector('.quiz-option-b').value,
                    C: item.querySelector('.quiz-option-c').value
                },
                correct: item.querySelector('.quiz-correct').value,
                explain: item.querySelector('.quiz-explain').value || ''
            });
        });

        const data = {
            quizzes: quizzes,
            voice: document.getElementById('quizVoice').value
        };

        try {
            const res = await fetch('/api/quiz/generate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await res.json();

            if (result.job_id) {
                status.innerHTML = `⏳ Job started: ${result.job_id} (${quizzes.length} quizzes)`;
                pollQuizStatus(result.job_id, status);
            } else {
                status.className = 'status error';
                status.innerHTML = `❌ Error: ${result.detail || 'Failed to start'}`;
            }
        } catch (err) {
            status.className = 'status error';
            status.innerHTML = '❌ Error: ' + err.message;
        }
    });

    // ============================================
    // TEXT STORY MODULE
    // ============================================
    document.getElementById('tsAddMessage').addEventListener('click', () => {
        const container = document.getElementById('tsMessagesContainer');
        const count = container.querySelectorAll('.ts-message-item').length + 1;
        const html = `
            <div class="ts-message-item" style="background: var(--bg-secondary); padding: 1rem; border-radius: 8px; margin-bottom: 0.5rem;">
                <div class="form-row" style="align-items: flex-end;">
                    <div class="form-group" style="flex: 0 0 100px;">
                        <label>Sender</label>
                        <select class="ts-sender">
                            <option value="B">B (Other)</option>
                            <option value="A">A (You)</option>
                        </select>
                    </div>
                    <div class="form-group" style="flex: 1;">
                        <label>Message ${count}</label>
                        <input type="text" class="ts-text" placeholder="Type message..." required>
                    </div>
                    <button type="button" class="btn btn-secondary ts-remove" style="height: 42px;">βœ•</button>
                </div>
            </div>
        `;
        container.insertAdjacentHTML('beforeend', html);
    });

    document.getElementById('tsMessagesContainer').addEventListener('click', (e) => {
        if (e.target.classList.contains('ts-remove')) {
            const items = document.querySelectorAll('.ts-message-item');
            if (items.length > 1) {
                e.target.closest('.ts-message-item').remove();
            }
        }
    });

    // Toggle Manual/AI mode - make global
    window.toggleTsMode = function () {
        const mode = document.querySelector('input[name="tsMode"]:checked').value;
        document.getElementById('tsAiSection').style.display = mode === 'ai' ? 'block' : 'none';
        document.getElementById('tsManualSection').style.display = mode === 'manual' ? 'block' : 'none';
    };

    document.getElementById('textStoryForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const status = document.getElementById('textStoryStatus');
        status.className = 'status processing';
        status.classList.remove('hidden');

        const mode = document.querySelector('input[name="tsMode"]:checked').value;
        let messages = [];

        if (mode === 'ai') {
            const prompt = document.getElementById('tsAiPrompt').value.trim();
            if (!prompt) {
                status.className = 'status error';
                status.innerHTML = '❌ Please enter a prompt for AI!';
                return;
            }

            status.innerHTML = 'πŸ€– AI generating conversation...';

            try {
                const aiRes = await fetch('/api/text-story/ai-generate', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        prompt: prompt,
                        person_a_name: document.getElementById('tsPersonA').value || 'You',
                        person_b_name: document.getElementById('tsPersonB').value || 'My Ex',
                        message_count: parseInt(document.getElementById('tsAiMsgCount').value),
                        tone: document.getElementById('tsAiTone').value
                    })
                });
                const aiData = await aiRes.json();

                if (aiData.messages) {
                    messages = aiData.messages;
                    status.innerHTML = `πŸ€– Generated ${messages.length} messages. Now creating video...`;
                } else {
                    status.className = 'status error';
                    status.innerHTML = '❌ AI failed: ' + (aiData.detail || 'Unknown error');
                    return;
                }
            } catch (err) {
                status.className = 'status error';
                status.innerHTML = '❌ AI Error: ' + err.message;
                return;
            }
        } else {
            const messageItems = document.querySelectorAll('.ts-message-item');
            messageItems.forEach(item => {
                const sender = item.querySelector('.ts-sender').value;
                const text = item.querySelector('.ts-text').value.trim();
                if (text) {
                    messages.push({ sender, text });
                }
            });

            if (messages.length < 2) {
                status.className = 'status error';
                status.innerHTML = '❌ Need at least 2 messages!';
                return;
            }
        }

        status.innerHTML = '⏳ Starting video generation...';

        const data = {
            person_a_name: document.getElementById('tsPersonA').value || 'You',
            person_b_name: document.getElementById('tsPersonB').value || 'My Ex',
            person_b_avatar: document.getElementById('tsAvatar').value || null,
            messages: messages,
            ending_text: document.getElementById('tsEnding').value || null,
            voice_a: document.getElementById('tsVoiceA').value,
            voice_b: document.getElementById('tsVoiceB').value
        };

        try {
            const res = await fetch('/api/text-story/generate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            const result = await res.json();

            if (result.job_id) {
                status.innerHTML = `⏳ Job started: ${result.job_id}`;
                pollTextStoryStatus(result.job_id);
            } else {
                status.className = 'status error';
                status.innerHTML = `❌ Error: ${result.detail || 'Failed to start'}`;
            }
        } catch (err) {
            status.className = 'status error';
            status.innerHTML = '❌ Error: ' + err.message;
        }
    });

    async function pollTextStoryStatus(jobId) {
        const status = document.getElementById('textStoryStatus');
        const poll = async () => {
            try {
                const res = await fetch(`/api/text-story/${jobId}/status`);
                const data = await res.json();

                if (data.status === 'ready') {
                    status.className = 'status success';
                    status.innerHTML = `βœ… Video ready! <a href="${data.video_url}" target="_blank" class="btn btn-primary" style="margin-left: 1rem;">πŸ“₯ Download</a>`;
                } else if (data.status === 'failed') {
                    status.className = 'status error';
                    status.innerHTML = '❌ Failed: ' + (data.error || 'Unknown error');
                } else {
                    const step = data.current_step || 'Processing';
                    status.innerHTML = `⏳ ${step} (${data.progress}%)`;
                    setTimeout(poll, 2000);
                }
            } catch (err) {
                setTimeout(poll, 3000);
            }
        };
        poll();
    }

    // ============================================
    // GEMINI CHATBOT
    // ============================================
    const chatBtn = document.getElementById('chatBtn');
    const chatModal = document.getElementById('chatModal');
    const chatClose = document.getElementById('chatClose');
    const chatForm = document.getElementById('chatForm');
    const chatInput = document.getElementById('chatInput');
    const chatMessages = document.getElementById('chatMessages');

    if (chatBtn) {
        chatBtn.addEventListener('click', () => {
            chatModal.classList.toggle('hidden');
        });

        chatClose.addEventListener('click', () => {
            chatModal.classList.add('hidden');
        });

        chatForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const message = chatInput.value.trim();
            if (!message) return;

            addMessage(message, 'user');
            chatInput.value = '';

            const loadingId = addMessage('⏳ Thinking...', 'bot');

            try {
                const res = await fetch('/api/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message })
                });
                const data = await res.json();

                document.getElementById(loadingId).remove();

                if (data.reply) {
                    addMessage(data.reply, 'bot');
                } else if (data.error) {
                    addMessage('❌ ' + data.error, 'bot');
                }
            } catch (err) {
                document.getElementById(loadingId).remove();
                addMessage('❌ Error: ' + err.message, 'bot');
            }
        });

        function addMessage(text, type) {
            const id = 'msg-' + Date.now();
            const div = document.createElement('div');
            div.id = id;
            div.className = 'chat-message ' + type;
            div.textContent = text;
            chatMessages.appendChild(div);
            chatMessages.scrollTop = chatMessages.scrollHeight;
            return id;
        }
    }

}); // End DOMContentLoaded