-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
4319 lines (3880 loc) · 211 KB
/
Copy pathscript.js
File metadata and controls
4319 lines (3880 loc) · 211 KB
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ─── VIEWPORT INSTANT HEIGHT SYNC ─────────────────────
const syncAppViewportHeight = () => {
const height = (window.visualViewport && window.visualViewport.height) || window.innerHeight || document.documentElement.clientHeight;
document.documentElement.style.setProperty('--app-height', `${height}px`);
};
syncAppViewportHeight();
window.addEventListener('resize', syncAppViewportHeight);
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', syncAppViewportHeight);
window.visualViewport.addEventListener('scroll', syncAppViewportHeight);
}
const isTelegramWebView = () => /Telegram|TelegramBot|tgWebApp|TWebView/i.test(navigator.userAgent || '') || !!(window.Telegram && window.Telegram.WebApp);
const isApplication = () => isTelegramWebView() || (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) || (window.navigator && window.navigator.standalone) || new URLSearchParams(window.location.search).has('app') || localStorage.getItem('force_app_mode') === 'true';
// ─── INDEXEDDB OFFLINE STORAGE ─────────────────────────
const DB_NAME = 'codextrms_offline_db';
const DB_VERSION = 1;
const STORE_NAME = 'downloaded_videos';
function openOfflineDb() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: 'id' });
}
};
request.onsuccess = (e) => resolve(e.target.result);
request.onerror = (e) => reject(e.target.error);
});
}
async function saveVideoBlob(videoId, blob) {
try {
const db = await openOfflineDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readwrite');
const store = tx.objectStore(STORE_NAME);
const request = store.put({ id: videoId, blob: blob, savedAt: Date.now() });
request.onsuccess = () => resolve(true);
request.onerror = (e) => reject(e.target.error);
});
} catch (err) {
console.error('IndexedDB save error:', err);
return false;
}
}
async function getVideoBlob(videoId) {
try {
const db = await openOfflineDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readonly');
const store = tx.objectStore(STORE_NAME);
const request = store.get(videoId);
request.onsuccess = (e) => {
const res = e.target.result;
resolve(res ? res.blob : null);
};
request.onerror = (e) => reject(e.target.error);
});
} catch (err) {
console.error('IndexedDB get error:', err);
return null;
}
}
async function deleteVideoBlob(videoId) {
try {
const db = await openOfflineDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readwrite');
const store = tx.objectStore(STORE_NAME);
const request = store.delete(videoId);
request.onsuccess = () => resolve(true);
request.onerror = (e) => reject(e.target.error);
});
} catch (err) {
console.error('IndexedDB delete error:', err);
return false;
}
}
function safeOpenExternal(url) {
const opened = isTelegramWebView() ? null : window.open(url, '_blank');
if (!opened) window.location.href = url;
}
window.safeOpenExternal = safeOpenExternal;
const isCompactVideoViewport = () => (window.innerWidth || 0) <= 820;
const shouldUseCleanVideoMode = () => isTelegramWebView() || isCompactVideoViewport();
const setTelegramPlayerMode = (active) => {
document.body.classList.toggle('telegram-player-mode', active && shouldUseCleanVideoMode());
if (!active) {
document.body.classList.remove('telegram-settings-open');
const telegramSettingsSheet = document.getElementById('telegramSettingsSheet');
const telegramSpeedChoices = document.getElementById('telegramSpeedChoices');
if (telegramSettingsSheet) telegramSettingsSheet.setAttribute('aria-hidden', 'true');
if (telegramSpeedChoices) telegramSpeedChoices.classList.remove('open');
}
};
window.addEventListener('resize', () => {
const modal = document.getElementById('videoModal');
if (modal && modal.style.display === 'flex') {
setTelegramPlayerMode(true);
}
});
// DOM Elements
const notificationIcon = document.getElementById('notificationIcon');
const notificationsPanel = document.getElementById('notificationsPanel');
const closeNotifications = document.getElementById('closeNotifications');
const themeToggleBtn = document.getElementById('themeToggleBtn');
const progressMenuBtn = document.getElementById('progressMenuBtn');
const progressMenu = document.getElementById('progressMenu');
const navItems = document.querySelectorAll('.nav-item');
const sections = document.querySelectorAll('.section');
const continueItems = document.querySelectorAll('.continue-item');
const videoModal = document.getElementById('videoModal');
const videoPlayer = document.getElementById('videoPlayer');
const offlineIndicator = document.getElementById('offlineIndicator');
const overlay = document.getElementById('overlay');
const swipeArea = document.getElementById('swipeArea');
const gatewayBatchCard = document.getElementById('gatewayBatchCard');
const apnaCollegeBatchCard = document.getElementById('apnaCollegeBatchCard');
const chaiaurcodeBatchCard = document.getElementById('chaiaurcodeBatchCard');
const codewithharryBatchCard = document.getElementById('codewithharryBatchCard');
const batchDataModal = document.getElementById('batchDataModal');
const closeBatchData = document.getElementById('closeBatchData');
const batchDataTitle = document.getElementById('batchDataTitle');
const batchDataContent = document.getElementById('batchDataContent');
const backToSubjectsBtn = document.getElementById('backToSubjectsBtn');
const subjectSearchInput = document.getElementById('subjectSearchInput');
const subjectControls = document.getElementById('subjectControls');
const allSubjectsTabBtn = document.getElementById('allSubjectsTabBtn');
const favoriteSubjectsTabBtn = document.getElementById('favoriteSubjectsTabBtn');
const modalBatchBackBtn = document.getElementById('modalBatchBackBtn');
const subjectPathLabel = document.getElementById('subjectPathLabel');
const popularBatchSearch = document.getElementById('popularBatchSearch');
const getPopularBatchCards = () => document.querySelectorAll('.batch-grid .batch-card');
const popularBatchNoResults = document.getElementById('popularBatchNoResults');
const progressDetailsBtn = document.getElementById('progressDetailsBtn');
const progressShareBtn = document.getElementById('progressShareBtn');
const notificationBadge = document.getElementById('notificationBadge');
const NOTIFICATIONS_KEY = 'codextrms_notifications';
const NOTIFICATIONS_SEEN_KEY = 'codextrms_notifications_seen_at';
const readAppNotifications = () => {
try {
return JSON.parse(localStorage.getItem(NOTIFICATIONS_KEY) || '[]');
} catch {
return [];
}
};
const saveAppNotifications = (items) => {
localStorage.setItem(NOTIFICATIONS_KEY, JSON.stringify(items));
};
const getNotificationsSeenAt = () => Number(localStorage.getItem(NOTIFICATIONS_SEEN_KEY) || 0);
const renderNotifications = () => {
const list = document.getElementById('notificationsList');
const notifications = readAppNotifications().sort((a, b) => (Number(b.createdAt) || 0) - (Number(a.createdAt) || 0));
const seenAt = getNotificationsSeenAt();
const unseenCount = notifications.filter(item => (Number(item.createdAt) || 0) > seenAt).length;
if (notificationBadge) {
notificationBadge.textContent = String(unseenCount);
notificationBadge.style.display = unseenCount > 0 ? 'flex' : 'none';
}
const pBadge = document.getElementById('playerNotificationBadge');
if (pBadge) {
pBadge.textContent = String(unseenCount);
pBadge.style.display = unseenCount > 0 ? 'flex' : 'none';
}
if (list) {
list.innerHTML = notifications.length ? notifications.map(item => {
const createdAt = Number(item.createdAt) || Date.now();
const isNew = createdAt > seenAt;
return `
<div class="notification-item" style="${isNew ? 'background:rgba(0,240,255,0.07);margin:0 -8px;padding:12px 8px;border-radius:10px;' : ''}">
<div style="font-weight:700;font-size:0.9rem;color:var(--text-primary);">${escapeHtml(item.title || 'Notification')}</div>
<div style="font-size:0.8rem;color:var(--text-secondary);margin-top:4px;line-height:1.45;">${escapeHtml(item.body || '')}</div>
<div class="notification-time">${timeAgo(createdAt)}</div>
</div>
`;
}).join('') : '<p style="color:var(--text-secondary);font-size:0.86rem;line-height:1.45;">Abhi koi notification nahi hai.</p>';
}
};
const markNotificationsSeen = () => {
localStorage.setItem(NOTIFICATIONS_SEEN_KEY, String(Date.now()));
renderNotifications();
};
window.addNotification = (title, body = '') => {
const notifications = readAppNotifications();
notifications.unshift({
id: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
title,
body,
createdAt: Date.now()
});
saveAppNotifications(notifications.slice(0, 50));
renderNotifications();
};
renderNotifications();
// Keep the panel and backdrop in the same state. The old code enabled the
// backdrop even when a second tap closed the panel, blocking the screen.
const setNotificationsPanelOpen = (open) => {
if (!notificationsPanel || !overlay || !swipeArea) return;
notificationsPanel.classList.toggle('open', open);
notificationsPanel.setAttribute('aria-hidden', String(!open));
overlay.style.display = open ? 'block' : 'none';
swipeArea.style.display = open ? 'block' : 'none';
if (open) {
markNotificationsSeen();
document.dispatchEvent(new CustomEvent('codextrms:notifications-opened'));
}
};
if (notificationIcon) {
notificationIcon.addEventListener('click', () => {
setNotificationsPanelOpen(!notificationsPanel.classList.contains('open'));
});
}
if (closeNotifications) {
closeNotifications.addEventListener('click', () => setNotificationsPanelOpen(false));
}
// Theme Toggle
themeToggleBtn.addEventListener('click', () => {
document.body.dataset.theme = document.body.dataset.theme === 'light' ? 'dark' : 'light';
const isLight = document.body.dataset.theme === 'light';
const iconHtml = isLight ? '<i class="fas fa-sun"></i>' : '<i class="fas fa-moon"></i>';
themeToggleBtn.innerHTML = iconHtml;
const pThemeBtn = document.getElementById('playerThemeToggleBtn');
if (pThemeBtn) pThemeBtn.innerHTML = iconHtml;
});
const playerThemeToggleBtn = document.getElementById('playerThemeToggleBtn');
if (playerThemeToggleBtn) {
playerThemeToggleBtn.addEventListener('click', () => {
document.body.dataset.theme = document.body.dataset.theme === 'light' ? 'dark' : 'light';
const isLight = document.body.dataset.theme === 'light';
const iconHtml = isLight ? '<i class="fas fa-sun"></i>' : '<i class="fas fa-moon"></i>';
themeToggleBtn.innerHTML = iconHtml;
playerThemeToggleBtn.innerHTML = iconHtml;
});
}
const playerNotificationIcon = document.getElementById('playerNotificationIcon');
if (playerNotificationIcon) {
playerNotificationIcon.addEventListener('click', () => {
setNotificationsPanelOpen(!notificationsPanel.classList.contains('open'));
});
}
// Progress Menu Toggle
progressMenuBtn.addEventListener('click', (e) => {
e.stopPropagation();
progressMenu.style.display = progressMenu.style.display === 'block' ? 'none' : 'block';
});
// Close menu when clicking outside
document.addEventListener('click', () => {
progressMenu.style.display = 'none';
});
if (progressDetailsBtn) {
progressDetailsBtn.addEventListener('click', (event) => {
event.stopPropagation();
progressMenu.style.display = 'none';
showProgressDetails();
});
}
if (progressShareBtn) {
progressShareBtn.addEventListener('click', (event) => {
event.stopPropagation();
progressMenu.style.display = 'none';
shareProgress();
});
}
const LAST_ACTIVE_SECTION_KEY = 'codextrms_last_active_section';
const STREAM_BASE_API = 'https://stream.codextrms.in/stream/';
const STREAM_TICKET_ENDPOINT = `${new URL(STREAM_BASE_API).origin}/api/stream-ticket`;
const GATEWAY_FAVORITE_SUBJECTS_KEY = 'gateway_favorite_subjects';
const GATEWAY_VIEW_STATE_KEY = 'codextrms_gateway_view_state';
const requestVideoStreamSources = async (channelId, videoId) => {
if (!channelId || !videoId) throw new Error('Video details unavailable.');
const response = await fetch(STREAM_TICKET_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ channelId: String(channelId), videoId: String(videoId) }),
cache: 'no-store',
});
const payload = await response.json().catch(() => ({}));
if (!response.ok || !payload.streamUrl) {
throw new Error(payload.error || 'Secure video access unavailable.');
}
return [payload.streamUrl];
};
const normalizeStreamUrl = (url = '') => String(url || '')
.replace(/https?:\/\/stream\.codextrms\.in\/stream\//i, STREAM_BASE_API)
.replace(/stream\.codextrms\.in\/stream\//i, STREAM_BASE_API);
const buildPdfUrl = (channelId, fileId) => {
if (!channelId || !fileId) return '';
return `${STREAM_BASE_API}${channelId}/${fileId}`;
};
const VIDEO_STREAM_LOAD_TIMEOUT_MS = 6000;
const VIDEO_STREAM_RETRY_ROUNDS = 2;
const showVideoStreamError = (videoElement, sources, message, retryAction) => {
const loader = document.getElementById('videoLoaderOverlay');
if (!loader) return;
const text = loader.querySelector('.video-loader-text');
if (text) text.textContent = message || 'Video load nahi ho paayi. Connection check karke retry karein.';
let retryButton = loader.querySelector('[data-video-retry]');
if (!retryButton) {
retryButton = document.createElement('button');
retryButton.type = 'button';
retryButton.dataset.videoRetry = 'true';
retryButton.textContent = 'Retry';
retryButton.style.cssText = 'margin-top:12px;padding:8px 16px;border:0;border-radius:999px;background:var(--neon-blue);color:#07111f;font-weight:700;cursor:pointer;';
loader.appendChild(retryButton);
}
retryButton.onclick = () => {
retryButton.remove();
if (text) text.textContent = 'Loading secure video stream...';
if (typeof retryAction === 'function') retryAction();
else applyVideoStreamSource(videoElement, sources);
};
loader.style.display = 'flex';
};
const stopVideoStreamFallback = (videoElement) => {
if (!videoElement) return;
if (videoElement._streamLoadTimer) {
clearTimeout(videoElement._streamLoadTimer);
videoElement._streamLoadTimer = null;
}
videoElement._streamLoadToken = Symbol('stopped-stream-load');
videoElement._isStreamLoading = false;
videoElement.onerror = null;
videoElement.onloadedmetadata = null;
videoElement.oncanplay = null;
videoElement.onplaying = null;
videoElement.onstalled = null;
};
const applyVideoStreamSource = (videoElement, sources) => {
if (!videoElement || !sources || !sources.length) return;
const loader = document.getElementById('videoLoaderOverlay');
if (loader) {
loader.querySelector('[data-video-retry]')?.remove();
const loaderText = loader.querySelector('.video-loader-text');
if (loaderText) loaderText.textContent = 'Loading secure video stream...';
}
stopVideoStreamFallback(videoElement);
const loadToken = Symbol('stream-load');
const maxAttempts = sources.length * VIDEO_STREAM_RETRY_ROUNDS;
let attemptIndex = 0;
let settledSource = false;
videoElement._streamLoadToken = loadToken;
videoElement._isStreamLoading = true;
const clearLoadTimer = () => {
if (videoElement._streamLoadTimer) {
clearTimeout(videoElement._streamLoadTimer);
videoElement._streamLoadTimer = null;
}
};
const markSourceReady = () => {
if (videoElement._streamLoadToken !== loadToken) return;
settledSource = true;
videoElement._isStreamLoading = false;
clearLoadTimer();
};
const trySource = () => {
if (videoElement._streamLoadToken !== loadToken || settledSource) return;
clearLoadTimer();
if (attemptIndex >= maxAttempts) {
clearLoadTimer();
videoElement._isStreamLoading = false;
videoElement.pause();
videoElement.removeAttribute('src');
videoElement.load();
videoElement.onerror = null;
videoElement.onloadedmetadata = null;
videoElement.oncanplay = null;
videoElement.onplaying = null;
videoElement.onstalled = null;
showVideoStreamError(videoElement, sources);
return;
}
const source = sources[attemptIndex % sources.length];
let playableSource = source;
if (attemptIndex > 0) {
const separator = source.includes('?') ? '&' : '?';
playableSource = `${source}${separator}retry=${attemptIndex + 1}-${Date.now()}`;
}
attemptIndex += 1;
videoElement.pause();
settledSource = false;
videoElement.src = playableSource;
videoElement.load();
videoElement.play().catch(() => {});
videoElement._streamLoadTimer = setTimeout(() => {
if (videoElement._streamLoadToken === loadToken && !settledSource && videoElement.readyState < 2) {
trySource();
}
}, VIDEO_STREAM_LOAD_TIMEOUT_MS);
};
videoElement.onerror = () => {
trySource();
};
videoElement.onloadedmetadata = markSourceReady;
videoElement.oncanplay = markSourceReady;
videoElement.onplaying = markSourceReady;
videoElement.onstalled = () => {
if (videoElement._streamLoadToken !== loadToken || videoElement.readyState >= 2) {
markSourceReady();
}
};
trySource();
};
const loadSecureVideo = async (videoElement, channelId, videoId) => {
try {
const sources = await requestVideoStreamSources(channelId, videoId);
applyVideoStreamSource(videoElement, sources);
} catch (error) {
const message = error instanceof Error ? error.message : 'Secure video access unavailable.';
showVideoStreamError(videoElement, [], message, () => loadSecureVideo(videoElement, channelId, videoId));
}
};
const setActiveSection = (sectionId) => {
const targetSection = document.getElementById(sectionId);
if (!targetSection) return;
navItems.forEach(navItem => {
navItem.classList.toggle('active', navItem.dataset.section === sectionId);
});
sections.forEach(section => section.classList.remove('active'));
targetSection.classList.add('active');
const doubtSection = document.getElementById('doubt-section');
if (doubtSection) {
doubtSection.classList.toggle('ds-active', sectionId === 'testsSection');
}
if (sectionId === 'profileSection' && typeof initProfile === 'function') {
initProfile();
}
localStorage.setItem(LAST_ACTIVE_SECTION_KEY, sectionId);
};
// Navigation
navItems.forEach(item => {
item.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
// Close any open modals/overlays first
notificationsPanel.classList.remove('open');
markNotificationsSeen();
batchDataModal.classList.remove('active');
if (videoPlayer && videoPlayer.src && videoModal.style.display === 'flex' && !videoModal.classList.contains('is-floating')) {
minimizePremiumVideo();
} else if (!videoModal.classList.contains('is-floating')) {
videoModal.style.display = 'none';
}
overlay.style.display = 'none';
swipeArea.style.display = 'none';
localStorage.removeItem(GATEWAY_VIEW_STATE_KEY);
const sectionId = item.dataset.section;
setActiveSection(sectionId);
});
});
const savedSection = localStorage.getItem(LAST_ACTIVE_SECTION_KEY);
if (savedSection) {
setActiveSection(savedSection);
}
const filterPopularBatches = (searchTerm = '') => {
const normalizedTerm = searchTerm.trim().toLowerCase();
let visibleCount = 0;
getPopularBatchCards().forEach((card) => {
const titleEl = card.querySelector('.batch-title');
const instructorEl = card.querySelector('.batch-instructor');
const title = titleEl ? titleEl.textContent.toLowerCase() : '';
const instructor = instructorEl ? instructorEl.textContent.toLowerCase() : '';
const isVisible = !normalizedTerm || title.includes(normalizedTerm) || instructor.includes(normalizedTerm);
card.style.display = isVisible ? '' : 'none';
if (isVisible) visibleCount++;
});
if (popularBatchNoResults) {
popularBatchNoResults.style.display = visibleCount === 0 ? 'block' : 'none';
}
};
if (popularBatchSearch) {
popularBatchSearch.addEventListener('input', (event) => {
filterPopularBatches(event.target.value);
});
}
continueItems.forEach(item => {
item.addEventListener('click', () => {
const title = item.querySelector('.continue-title').textContent;
openPremiumVideo('', title, null);
});
});
// Batch data handling
let currentBatchData = [];
let currentBatchTitle = ''; // YE ADD KARO
let selectedSubject = null;
let selectedChapter = null;
let selectedSubjectIndex = -1;
let selectedChapterIndex = -1;
let selectedChannelId = '-1003345907635';
let subjectSearchTerm = '';
let subjectTab = 'all';
let currentBatchDataKey = '';
let isRestoringGatewayState = false;
let favoriteSubjects = JSON.parse(localStorage.getItem(GATEWAY_FAVORITE_SUBJECTS_KEY) || '[]');
const getCompletedLectureIds = () => JSON.parse(localStorage.getItem('completed_lectures') || '[]').map(String);
const ENROLLED_BATCHES_KEY = 'codextrms_enrolled_batches';
const PINNED_BATCHES_KEY = 'codextrms_pinned_batches';
const RECENT_SUBJECTS_KEY = 'codextrms_recent_subjects';
const LECTURE_PROGRESS_KEY = 'codextrms_lecture_progress';
const STUDY_STATS_KEY = 'codextrms_study_stats';
const VIDEO_COMMENTS_KEY = 'codextrms_video_comments';
const CATALOG_SNAPSHOT_KEY = 'codextrms_catalog_snapshot';
let currentCommentKey = '';
let editingVideoCommentIndex = -1;
const getGatewayBatchSources = () => [
{ title: 'GATEWAY – 1ST YEAR', dataKey: 'dataClass13' },
{ title: 'APNA COLLEGE', dataKey: 'dataClass11' },
{ title: 'CHAI AUR CODE', dataKey: 'dataClass101' },
{ title: 'CODE WITH HARRY', dataKey: 'dataClass114' },
{ title: 'SUPREME COURSE', dataKey: 'dataClass102' },
{ title: 'WEDDING MASTERY', dataKey: 'dataClass103' },
{ title: 'PROFESSOR OF HOW', dataKey: 'dataClass104' },
{ title: 'PW SKILLS', dataKey: 'dataClass105' },
{ title: 'Keerti Purswani HHLD', dataKey: 'dataClass106' },
{ title: 'Financial Modeling Fundamentals', dataKey: 'dataClass107' },
{ title: 'UDEMY', dataKey: 'dataClass108' },
{ title: 'TRADING', dataKey: 'dataClass109' },
{ title: 'DevOps', dataKey: 'dataClass110' },
{ title: 'HARKIRAT COHORT', dataKey: 'dataClass111' },
{ title: 'SHREYANSH CODING', dataKey: 'dataClass112' },
{ title: 'CAMPUS', dataKey: 'dataClass113' },
{ title: 'DROPSHIPPING', dataKey: 'dataClass14' },
{ title: 'JASON FEDIN', dataKey: 'dataClass15' },
{ title: 'INEURON', dataKey: 'dataClass116' },
{ title: 'ADCA', dataKey: 'dataClass115' },
{ title: 'EARNERS', dataKey: 'dataClass201' },
{ title: 'GATEWAY – 3RD SEM', dataKey: 'dataClass202' },
];
const resolveGatewayBatchSource = (data, title = '') => {
const sources = getGatewayBatchSources();
return sources.find(source => window[source.dataKey] === data)
|| sources.find(source => source.title === title)
|| sources.find(source => source.title.toLowerCase() === String(title).toLowerCase())
|| { title, dataKey: '' };
};
const getBatchThumbnailUrl = (dataKeyOrTitle = '') => {
const key = String(dataKeyOrTitle || '').toLowerCase();
const source = getGatewayBatchSources().find(item =>
item.dataKey === dataKeyOrTitle ||
item.title === dataKeyOrTitle ||
item.title.toLowerCase() === key
);
const dataKey = (source && source.dataKey) || dataKeyOrTitle;
const imageMap = {
dataClass13: (document.querySelector('#gatewayBatchCard img') && document.querySelector('#gatewayBatchCard img').src) || 'https://www.image2url.com/r2/default/images/1776470092513-1033b344-25d1-4b03-a148-0d4ee9e71ddb.webp',
dataClass11: (document.querySelector('#apnaCollegeBatchCard img') && document.querySelector('#apnaCollegeBatchCard img').src) || 'https://www.image2url.com/r2/default/images/1776470194797-536bb3c6-3692-4a7f-a090-496028f4b395.jpg',
dataClass101: (document.querySelector('#chaiaurcodeBatchCard img') && document.querySelector('#chaiaurcodeBatchCard img').src) || 'https://www.image2url.com/r2/default/images/1776470301414-0174d86c-2568-43db-b56b-e9030e9d9f0d.png',
dataClass114: (document.querySelector('#codewithharryBatchCard img') && document.querySelector('#codewithharryBatchCard img').src) || 'https://www.image2url.com/r2/default/images/1776470471033-4af32288-22ec-452b-b10f-bf8fb80637c6.jpg',
dataClass102: 'image/supreme.jpg',
dataClass103: 'image/rajaa.jpg',
dataClass104: 'image/poh.png',
dataClass105: 'image/pwskill.jpg',
dataClass106: 'image/keerti.jpg',
dataClass107: 'image/fmf.jpg',
dataClass108: 'image/udemy.jpg',
dataClass109: 'image/trading.jpg',
dataClass110: 'image/devops.png',
dataClass111: 'image/cohort.jpg',
dataClass112: 'image/Shreyansh.webp',
dataClass113: 'image/college.jpg',
dataClass115: 'image/adca.jpg',
dataClass116: 'image/ineuron.jpg',
dataClass17: 'image/chai.jpg',
dataClass14: 'image/dropshipping.jpg',
dataClass15: 'image/jasonfedin.jpg',
dataClass202: 'image/gw.jpg',
dataClass201: 'image/EARNERS.jpg',
};
return imageMap[dataKey] || '';
};
const getBatchThumbBackground = (dataKeyOrTitle = '') => {
const url = getBatchThumbnailUrl(dataKeyOrTitle);
return url
? `linear-gradient(180deg,rgba(5,8,18,0.1),rgba(5,8,18,0.55)),url('${String(url).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}') center/cover no-repeat`
: 'linear-gradient(45deg,var(--neon-blue),var(--neon-purple))';
};
const getCleanBatchThumbBackground = (dataKeyOrTitle = '') => {
const url = getBatchThumbnailUrl(dataKeyOrTitle);
return url
? `url('${String(url).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}') center/contain no-repeat`
: 'linear-gradient(45deg,var(--neon-blue),var(--neon-purple))';
};
const ensurePopularBatchCards = () => {
const grid = document.querySelector('.batch-grid');
if (!grid) return;
const existingKeys = new Set(
[...grid.querySelectorAll('.enroll-batch-btn')]
.map((btn) => btn.dataset.batchKey)
.filter(Boolean)
);
getGatewayBatchSources().forEach((source) => {
if (!source || !source.dataKey || existingKeys.has(source.dataKey)) return;
const card = document.createElement('div');
card.className = 'batch-card';
card.dataset.batchKey = source.dataKey;
card.dataset.batchTitle = source.title;
const imageUrl = getBatchThumbnailUrl(source.dataKey);
card.innerHTML = `
<div class="batch-image">
${imageUrl ? `<img src="${escapeHtml(imageUrl)}" alt="${escapeHtml(source.title)}">` : `<div style="height:100%;background:${getCleanBatchThumbBackground(source.dataKey)};"></div>`}
</div>
<div class="batch-details">
<h3 class="batch-title">${escapeHtml(source.title)}</h3>
<p class="batch-instructor">${escapeHtml(source.instructor || 'CODExTRMS Batch')}</p>
<div class="batch-meta">
<span><i class="fas fa-book-open"></i> Explore</span>
<button class="batch-btn enroll-batch-btn" data-batch-key="${escapeHtml(source.dataKey)}">Enroll Now</button>
</div>
</div>
`;
grid.appendChild(card);
existingKeys.add(source.dataKey);
});
};
const hydrateBatchThumbnails = () => {
document.querySelectorAll('.batch-image img').forEach((img) => {
const wrap = img.closest('.batch-image');
if (!wrap || !img.getAttribute('src')) return;
const safeUrl = String(img.getAttribute('src')).replace(/\\/g, '\\\\').replace(/'/g, "\\'");
wrap.style.setProperty('--batch-thumb', `url('${safeUrl}')`);
});
};
const readEnrolledBatches = () => {
try {
return JSON.parse(localStorage.getItem(ENROLLED_BATCHES_KEY) || '[]');
} catch {
return [];
}
};
const saveEnrolledBatches = (items) => {
localStorage.setItem(ENROLLED_BATCHES_KEY, JSON.stringify(items));
};
const readJson = (key, fallback) => {
try { return JSON.parse(localStorage.getItem(key) || JSON.stringify(fallback)); }
catch { return fallback; }
};
const saveJson = (key, value) => {
try { localStorage.setItem(key, JSON.stringify(value)); } catch {}
};
const buildCatalogSnapshot = () => {
const batches = {};
getGatewayBatchSources().forEach((source) => {
const data = window[source.dataKey] || [];
if (!Array.isArray(data) || data.length === 0) return;
batches[source.dataKey] = {
title: source.title,
subjects: data.map((subject, index) => ({
index,
name: (subject && subject.batch_name) || `Subject ${index + 1}`
}))
};
});
return { updatedAt: Date.now(), batches };
};
const detectCatalogNotifications = () => {
const current = buildCatalogSnapshot();
const previous = readJson(CATALOG_SNAPSHOT_KEY, null);
if (!previous || !previous.batches) {
saveJson(CATALOG_SNAPSHOT_KEY, current);
return;
}
Object.entries(current.batches).forEach(([dataKey, batch]) => {
const oldBatch = previous.batches[dataKey];
if (!oldBatch) {
if (typeof window.addNotification === 'function') window.addNotification('New batch added', `${batch.title} add hua hai.`);
return;
}
const oldSubjectNames = new Set((oldBatch.subjects || []).map(item => String(item.name).trim().toLowerCase()));
(batch.subjects || []).forEach((subject) => {
const subjectName = String(subject.name || '').trim();
if (subjectName && !oldSubjectNames.has(subjectName.toLowerCase())) {
if (typeof window.addNotification === 'function') window.addNotification('New subject added', `${subjectName} - ${batch.title}`);
}
});
});
saveJson(CATALOG_SNAPSHOT_KEY, current);
};
const getLectureProgress = (videoId) => {
const progress = readJson(LECTURE_PROGRESS_KEY, {});
return videoId ? progress[String(videoId)] || null : null;
};
const saveLectureProgress = (videoId, data) => {
if (!videoId) return;
const progress = readJson(LECTURE_PROGRESS_KEY, {});
progress[String(videoId)] = { ...progress[String(videoId)], ...data, updatedAt: Date.now() };
saveJson(LECTURE_PROGRESS_KEY, progress);
};
const getVideoCommentKey = (channelId, videoId) => `${channelId || 'channel'}:${videoId || 'video'}`;
const readVideoComments = (key) => readJson(VIDEO_COMMENTS_KEY, {})[key] || [];
const saveVideoComments = (key, comments) => {
const all = readJson(VIDEO_COMMENTS_KEY, {});
all[key] = comments;
saveJson(VIDEO_COMMENTS_KEY, all);
};
const updateStudyStats = (seconds) => {
const today = new Date().toISOString().slice(0, 10);
const yesterday = new Date(Date.now() - 86400000).toISOString().slice(0, 10);
const stats = readJson(STUDY_STATS_KEY, { totalSeconds: 0, todaySeconds: 0, streak: 0, lastDate: '' });
if (stats.lastDate !== today) {
stats.streak = stats.lastDate === yesterday ? (Number(stats.streak) || 0) + 1 : 1;
stats.todaySeconds = 0;
stats.lastDate = today;
}
stats.totalSeconds = (Number(stats.totalSeconds) || 0) + seconds;
stats.todaySeconds = (Number(stats.todaySeconds) || 0) + seconds;
saveJson(STUDY_STATS_KEY, stats);
if (typeof renderStudyStats === 'function') renderStudyStats();
};
const getBatchProgress = (data = []) => {
const completed = getCompletedLectureIds();
const lectures = data.flatMap(subject => subject.chapters || []).flatMap(chapter => chapter.lectures || []);
const total = lectures.filter(lecture => lecture.video_id).length;
const done = lectures.filter(lecture => lecture.video_id && completed.includes(String(lecture.video_id))).length;
return { total, done, pct: total ? Math.round((done / total) * 100) : 0 };
};
const getSubjectProgress = (subject) => {
const completed = getCompletedLectureIds();
const lectures = ((subject && subject.chapters) || []).flatMap(chapter => chapter.lectures || []);
const total = lectures.filter(lecture => lecture.video_id).length;
const done = lectures.filter(lecture => lecture.video_id && completed.includes(String(lecture.video_id))).length;
return { total, done, pct: total ? Math.round((done / total) * 100) : 0 };
};
const saveRecentSubject = (source, subjectIndex, subject) => {
if (!source || !source.dataKey || !subject) return;
const recent = readJson(RECENT_SUBJECTS_KEY, []).filter(item => !(item.dataKey === source.dataKey && item.subjectIndex === subjectIndex));
recent.unshift({
dataKey: source.dataKey,
title: source.title,
subjectIndex,
subjectTitle: subject.batch_name || 'Subject',
timestamp: Date.now()
});
saveJson(RECENT_SUBJECTS_KEY, recent.slice(0, 8));
if (typeof renderRecentSubjects === 'function') renderRecentSubjects();
};
const togglePinnedBatch = (dataKey) => {
const pinned = readJson(PINNED_BATCHES_KEY, []);
const next = pinned.includes(dataKey) ? pinned.filter(item => item !== dataKey) : [dataKey, ...pinned];
saveJson(PINNED_BATCHES_KEY, next);
if (typeof renderPinnedBatches === 'function') renderPinnedBatches();
showMiniToast(pinned.includes(dataKey) ? 'Batch unpinned.' : 'Batch pinned.');
};
const showMiniToast = (message) => {
const oldToast = document.getElementById('miniToast');
if (oldToast) oldToast.remove();
const toast = document.createElement('div');
toast.id = 'miniToast';
toast.style.cssText = 'position:fixed;bottom:90px;left:50%;transform:translateX(-50%);background:linear-gradient(45deg,var(--neon-blue),var(--neon-pink));color:#000;padding:10px 18px;border-radius:999px;font-weight:800;font-size:0.85rem;z-index:999999;box-shadow:0 10px 30px rgba(0,0,0,0.35);';
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => toast.remove(), 2200);
};
const enrollBatch = (dataKey) => {
const source = getGatewayBatchSources().find(item => item.dataKey === dataKey);
if (!source) return;
const enrolled = readEnrolledBatches();
if (enrolled.includes(dataKey)) {
saveEnrolledBatches(enrolled.filter(item => item !== dataKey));
showMiniToast('Batch Favorites se remove ho gaya.');
} else {
enrolled.unshift(dataKey);
saveEnrolledBatches(enrolled);
showMiniToast('Batch Favorites mein add ho gaya!');
}
updateEnrollButtons();
if (typeof renderPinnedBatches === 'function') renderPinnedBatches();
};
const updateEnrollButtons = () => {
const enrolled = readEnrolledBatches();
document.querySelectorAll('.enroll-batch-btn').forEach((btn) => {
const isEnrolled = enrolled.includes(btn.dataset.batchKey);
btn.textContent = isEnrolled ? 'Unenroll' : 'Enroll Now';
btn.classList.toggle('is-enrolled', isEnrolled);
});
};
const updatePinButtons = () => {
const pinned = readJson(PINNED_BATCHES_KEY, []);
document.querySelectorAll('.pin-batch-btn').forEach((btn) => {
const isPinned = pinned.includes(btn.dataset.batchKey);
btn.textContent = isPinned ? 'Pinned' : 'Pin';
btn.classList.toggle('is-enrolled', isPinned);
});
};
const saveGatewayViewState = (isOpen = true) => {
if (isRestoringGatewayState || !currentBatchTitle) return;
try {
localStorage.setItem(GATEWAY_VIEW_STATE_KEY, JSON.stringify({
isOpen,
title: currentBatchTitle,
dataKey: currentBatchDataKey,
subjectIndex: selectedSubjectIndex,
chapterIndex: selectedChapterIndex,
channelId: selectedChannelId,
updatedAt: Date.now()
}));
updateUrlState();
} catch {}
};
const updateUrlState = () => {
const modal = document.getElementById('videoModal');
const isVideoOpen = modal && modal.style.display === 'flex';
const batchModal = document.getElementById('batchDataModal');
const isBatchOpen = batchModal && batchModal.classList.contains('active');
const frameModal = document.getElementById('apnaCollegeFrameModal');
const isFrameOpen = frameModal && frameModal.style.display === 'flex';
let url = window.location.pathname;
if (isFrameOpen) {
url += '?batch=dataClass11';
} else if (isBatchOpen) {
const params = new URLSearchParams();
if (currentBatchDataKey) params.set('batch', currentBatchDataKey);
if (selectedSubjectIndex >= 0) params.set('subject', selectedSubjectIndex);
if (selectedChapterIndex >= 0) params.set('chapter', selectedChapterIndex);
if (isVideoOpen) {
const lastVideo = JSON.parse(sessionStorage.getItem('last_video') || '{}');
if (lastVideo.videoId) {
params.set('video', lastVideo.videoId);
}
}
url += '?' + params.toString();
}
const currentSearch = window.location.search;
const targetSearch = url.includes('?') ? url.substring(url.indexOf('?')) : '';
if (currentSearch !== targetSearch) {
window.history.pushState(null, '', url);
}
};
const restoreUrlState = () => {
const params = new URLSearchParams(window.location.search);
const batchKey = params.get('batch');
const subjectIndexStr = params.get('subject');
const chapterIndexStr = params.get('chapter');
const videoId = params.get('video');
if (!batchKey) return;
if (batchKey === 'dataClass11') {
window.location.replace('https://clg.codextrms.in/');
return;
}
const source = getGatewayBatchSources().find(item => item.dataKey === batchKey);
if (!source) return;
const data = window[source.dataKey] || [];
if (!Array.isArray(data) || data.length === 0) return;
currentBatchData = data;
currentBatchDataKey = source.dataKey;
currentBatchTitle = source.title;
selectedChannelId = source.channelId || '-1003345907635';
const subIdx = subjectIndexStr !== null ? parseInt(subjectIndexStr) : -1;
const chapIdx = chapterIndexStr !== null ? parseInt(chapterIndexStr) : -1;
selectedSubjectIndex = subIdx;
selectedChapterIndex = chapIdx;
// Mark batchDataModal as active before rendering
const batchDataModal = document.getElementById('batchDataModal');
const overlay = document.getElementById('overlay');
if (batchDataModal) {
batchDataModal.classList.add('active');
if (overlay) overlay.style.display = 'block';
if (subIdx >= 0 && subIdx < data.length) {
selectedSubject = data[subIdx];
renderChapters(selectedSubject, subIdx);
const chapters = selectedSubject.chapters || [];
if (chapIdx >= 0 && chapIdx < chapters.length) {
selectedChapter = chapters[chapIdx];
renderChapterDetails(selectedChapter, chapIdx);
if (videoId && selectedChapter.lectures) {
const lecture = selectedChapter.lectures.find(l => String(l.videoId) === String(videoId));
if (lecture) {
openPremiumVideo(lecture.videoId, lecture.title || 'Video', selectedChapter);
}
}
}
} else {
renderSubjects(data, source.title);
}
}
};
const openApnaCollegeIframe = () => {
let frameModal = document.getElementById('apnaCollegeFrameModal');
if (!frameModal) {
frameModal = document.createElement('div');
frameModal.id = 'apnaCollegeFrameModal';
frameModal.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:#0b0f19;z-index:999999;display:flex;flex-direction:column;animation:fadeIn 0.3s ease;';
// Header bar with back/close button
const header = document.createElement('div');
header.style.cssText = 'display:flex;align-items:center;justify-content:space-between;padding:12px 24px;background:#0d1527;border-bottom:1px solid rgba(255,255,255,0.06);height:60px;box-sizing:border-box;';
header.innerHTML = `
<div style="display:flex;align-items:center;gap:12px;">
<button id="closeApnaFrameBtn" style="background:transparent;border:none;color:#fff;font-size:0.9rem;font-weight:700;cursor:pointer;display:flex;align-items:center;gap:8px;padding:6px 12px;border-radius:6px;transition:all 0.2s;"><i class="fas fa-chevron-left"></i> BACK</button>
<span style="color:#fff;font-family:\'Poppins\',sans-serif;font-weight:700;font-size:1.1rem;letter-spacing:0.5px;">APNA COLLEGE</span>
</div>
<div style="color:var(--neon-blue,#00f0ff);font-family:\'Poppins\',sans-serif;font-weight:700;font-size:0.75rem;letter-spacing:1px;text-transform:uppercase;background:rgba(0,240,255,0.06);padding:4px 12px;border-radius:999px;border:1px solid rgba(0,240,255,0.15);">Integrated View</div>
`;
frameModal.appendChild(header);
// Loader spinner for iframe loading state
const spinner = document.createElement('div');
spinner.id = 'apnaFrameSpinner';