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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a68b118
9ba0fbc
 
a68b118
9ba0fbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a68b118
9ba0fbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a68b118
9ba0fbc
 
 
 
 
 
 
 
 
 
 
a68b118
9ba0fbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a68b118
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
document.addEventListener('DOMContentLoaded', () => {
    // DOM Elements
    const videoGrid = document.getElementById('videoGrid');
    const searchInput = document.getElementById('searchInput');
    const clearSearchBtn = document.getElementById('clearSearch');
    const videoModal = document.getElementById('videoModal');
    const videoPlayer = document.getElementById('videoPlayer');
    const modalVideoTitle = document.getElementById('modalVideoTitle');
    const closeModal = document.getElementById('closeModal');
    const loadingIndicator = document.getElementById('loadingIndicator');
    const errorMessage = document.getElementById('errorMessage');
    const retryBtn = document.getElementById('retryBtn');
    const gridViewBtn = document.getElementById('gridViewBtn');
    const listViewBtn = document.getElementById('listViewBtn');
    const pagination = document.getElementById('pagination');
    const visibleCount = document.getElementById('visibleCount');
    const totalCount = document.getElementById('totalCount');

    // State
    let videos = [];
    let filteredVideos = [];
    let currentPage = 1;
    let videosPerPage = 12;
    let currentPlayer = null;
    let viewMode = 'grid';
    let lastTapTime = 0;
    let lastDoubleTapX = 0;
    let doubleTapThreshold = 10; // px tolerance for tap position

    // Initialize the app
    init();

    function init() {
        fetchVideoData();
        setupEventListeners();
    }

    // Fetch video data from JSON
    async function fetchVideoData() {
        try {
            loadingIndicator.style.display = 'flex';
            errorMessage.style.display = 'none';
            videoGrid.innerHTML = '';

            const response = await fetch('database.json');
            if (!response.ok) {
                throw new Error(`Failed to load database.json: ${response.status}`);
            }

            const data = await response.json();
            
            // Check if data has the expected structure
            if (!data.videos || !Array.isArray(data.videos)) {
                throw new Error('Invalid database format: missing "videos" array');
            }

            // Filter out invalid entries
            videos = data.videos.filter(video => {
                if (!video.title || !video.url) {
                    console.warn('Invalid video entry:', video);
                    return false;
                }
                return true;
            });

            filteredVideos = [...videos];
            updateVideoCount();
            renderPagination();
            renderVideos();

            showToast('Videos loaded successfully!', 'success');
        } catch (error) {
            console.error('Error loading videos:', error);
            loadingIndicator.style.display = 'none';
            errorMessage.style.display = 'flex';
        }
    }

    // Set up event listeners
    function setupEventListeners() {
        // Search functionality
        searchInput.addEventListener('input', handleSearch);
        clearSearchBtn.addEventListener('click', clearSearch);

        // Modal controls
        closeModal.addEventListener('click', closeVideoModal);

        // Retry button
        retryBtn.addEventListener('click', fetchVideoData);

        // View toggle
        gridViewBtn.addEventListener('click', () => setViewMode('grid'));
        listViewBtn.addEventListener('click', () => setViewMode('list'));

        // Handle clicks outside the modal to close it
        window.addEventListener('click', (e) => {
            if (e.target === videoModal) {
                closeVideoModal();
            }
        });

        // Keyboard controls for modal
        window.addEventListener('keydown', (e) => {
            if (videoModal.style.display === 'block') {
                if (e.key === 'Escape') {
                    closeVideoModal();
                }
            }
        });
    }

    // Handle search input
    function handleSearch() {
        const searchTerm = searchInput.value.toLowerCase().trim();
        clearSearchBtn.style.display = searchTerm ? 'block' : 'none';
        
        if (searchTerm === '') {
            filteredVideos = [...videos];
        } else {
            filteredVideos = videos.filter(video => 
                video.title.toLowerCase().includes(searchTerm)
            );
        }
        
        currentPage = 1;
        updateVideoCount();
        renderPagination();
        renderVideos();
    }

    // Clear search
    function clearSearch() {
        searchInput.value = '';
        clearSearchBtn.style.display = 'none';
        filteredVideos = [...videos];
        currentPage = 1;
        updateVideoCount();
        renderPagination();
        renderVideos();
    }

    // Update video count display
    function updateVideoCount() {
        const start = (currentPage - 1) * videosPerPage;
        const end = Math.min(start + videosPerPage, filteredVideos.length);
        const count = Math.min(videosPerPage, filteredVideos.length - start);
        
        visibleCount.textContent = count > 0 ? end - start : 0;
        totalCount.textContent = filteredVideos.length;
    }

    // Set view mode (grid or list)
    function setViewMode(mode) {
        viewMode = mode;
        
        // Update active button
        gridViewBtn.classList.toggle('active', mode === 'grid');
        listViewBtn.classList.toggle('active', mode === 'list');
        
        // Update grid class
        videoGrid.classList.toggle('list-view', mode === 'list');
        
        // Re-render to apply changes
        renderVideos();
    }

    // Render videos in grid
    function renderVideos() {
        loadingIndicator.style.display = 'none';
        videoGrid.innerHTML = '';
        
        if (filteredVideos.length === 0) {
            videoGrid.innerHTML = `
                <div class="error-container" style="grid-column: 1 / -1;">
                    <i class="fas fa-search"></i>
                    <p>No videos found matching your search.</p>
                </div>
            `;
            return;
        }
        
        // Calculate pagination
        const start = (currentPage - 1) * videosPerPage;
        const end = Math.min(start + videosPerPage, filteredVideos.length);
        const currentPageVideos = filteredVideos.slice(start, end);
        
        // Create video cards
        currentPageVideos.forEach((video, index) => {
            const videoCard = document.createElement('div');
            videoCard.className = `video-card ${viewMode === 'list' ? 'list-view' : ''}`;
            
            // Determine if URL is from Hugging Face
            const isHuggingFaceUrl = video.url.includes('huggingface.co');
            
            // For HF URLs, append download=true if not already present
            let videoUrl = video.url;
            if (isHuggingFaceUrl && !videoUrl.includes('download=true')) {
                videoUrl = videoUrl.includes('?') ? 
                    `${videoUrl}&download=true` : 
                    `${videoUrl}?download=true`;
            }
            
            videoCard.innerHTML = `
                <div class="video-thumbnail">
                    <div class="thumbnail-placeholder">
                        <i class="fas fa-film fa-2x"></i>
                    </div>
                    <div class="play-icon">
                        <i class="fas fa-play fa-lg"></i>
                    </div>
                </div>
                <div class="video-info">
                    <h3 class="video-title">${video.title}</h3>
                </div>
            `;
            
            videoCard.addEventListener('click', () => {
                playVideo(video);
            });
            
            videoGrid.appendChild(videoCard);
        });
    }

    // Render pagination controls
    function renderPagination() {
        pagination.innerHTML = '';
        
        if (filteredVideos.length <= videosPerPage) {
            return; // No pagination needed
        }
        
        const totalPages = Math.ceil(filteredVideos.length / videosPerPage);
        
        // Previous button
        const prevBtn = document.createElement('button');
        prevBtn.className = `page-btn ${currentPage === 1 ? 'disabled' : ''}`;
        prevBtn.innerHTML = '<i class="fas fa-chevron-left"></i>';
        prevBtn.disabled = currentPage === 1;
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                goToPage(currentPage - 1);
            }
        });
        pagination.appendChild(prevBtn);
        
        // Page numbers with ellipsis
        const renderPageButton = (pageNum) => {
            const pageBtn = document.createElement('button');
            pageBtn.className = `page-btn ${currentPage === pageNum ? 'active' : ''}`;
            pageBtn.textContent = pageNum;
            pageBtn.addEventListener('click', () => goToPage(pageNum));
            pagination.appendChild(pageBtn);
        };
        
        // Determine visible page range
        const delta = 2; // Number of pages to show on each side of current
        const range = [];
        const rangeWithDots = [];
        let l;
        
        range.push(1);
        
        for (let i = currentPage - delta; i <= currentPage + delta; i++) {
            if (i > 1 && i < totalPages) {
                range.push(i);
            }
        }
        
        range.push(totalPages);
        
        for (let i of range) {
            if (l) {
                if (i - l === 2) {
                    rangeWithDots.push(l + 1);
                } else if (i - l !== 1) {
                    rangeWithDots.push('...');
                }
            }
            rangeWithDots.push(i);
            l = i;
        }
        
        rangeWithDots.forEach(item => {
            if (item === '...') {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'page-btn disabled';
                ellipsis.textContent = '...';
                pagination.appendChild(ellipsis);
            } else {
                renderPageButton(item);
            }
        });
        
        // Next button
        const nextBtn = document.createElement('button');
        nextBtn.className = `page-btn ${currentPage === totalPages ? 'disabled' : ''}`;
        nextBtn.innerHTML = '<i class="fas fa-chevron-right"></i>';
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                goToPage(currentPage + 1);
            }
        });
        pagination.appendChild(nextBtn);
    }

    // Navigate to a specific page
    function goToPage(pageNum) {
        currentPage = pageNum;
        updateVideoCount();
        renderPagination();
        renderVideos();
        
        // Scroll to top of video grid
        videoGrid.scrollIntoView({ behavior: 'smooth' });
    }

    // Play video in modal
    function playVideo(video) {
        // Clean up any existing player
        cleanupPlayer();
        
        // Update modal title
        modalVideoTitle.textContent = video.title;
        
        // Determine if URL is from Hugging Face
        const isHuggingFaceUrl = video.url.includes('huggingface.co');
        
        // For HF URLs, append download=true if not already present
        let videoUrl = video.url;
        if (isHuggingFaceUrl && !videoUrl.includes('download=true')) {
            videoUrl = videoUrl.includes('?') ? 
                `${videoUrl}&download=true` : 
                `${videoUrl}?download=true`;
        }
        
        // Set up video player
        videoPlayer.src = videoUrl;
        
        // Initialize Plyr
        currentPlayer = new Plyr(videoPlayer, {
            controls: [
                'play-large', 'play', 'progress', 'current-time', 'mute', 
                'volume', 'captions', 'settings', 'pip', 'airplay', 'fullscreen'
            ],
            keyboard: { focused: true, global: false },
            tooltips: { controls: true, seek: true },
            captions: { active: true, language: 'auto', update: true }
        });
        
        // Set up double-tap controls for mobile
        setupDoubleTapControls();
        
        // Show modal
        videoModal.style.display = 'block';
        document.body.style.overflow = 'hidden'; // Prevent scrolling while modal is open
        
        // Play the video (with error handling)
        try {
            currentPlayer.play().catch(error => {
                console.warn('Failed to autoplay video:', error);
                
                // Check if it's a format issue
                const fileExtension = videoUrl.split('.').pop().toLowerCase();
                if (fileExtension === 'mkv') {
                    showToast('MKV format may not be fully supported in your browser.', 'warning');
                }
            });
        } catch (error) {
            console.error('Error playing video:', error);
            showToast('Error playing video. Please try again.', 'error');
        }
    }

    // Set up double-tap controls for mobile
    function setupDoubleTapControls() {
        const playerElement = videoPlayer.closest('.player-container');
        
        const handleTap = (e) => {
            const now = Date.now();
            const tapX = e.touches ? e.touches[0].clientX : e.clientX;
            const playerWidth = playerElement.offsetWidth;
            const tapPosition = tapX / playerWidth; // 0 to 1 position
            
            if (now - lastTapTime < 300 && Math.abs(tapX - lastDoubleTapX) < doubleTapThreshold) {
                // Double tap detected
                e.preventDefault();
                
                if (tapPosition < 0.3) {
                    // Double tap on left side - rewind
                    currentPlayer.rewind(10);
                    showControlFeedback('left', 'Rewind 10s');
                } else if (tapPosition > 0.7) {
                    // Double tap on right side - forward
                    currentPlayer.forward(10);
                    showControlFeedback('right', 'Forward 10s');
                } else {
                    // Double tap in center - play/pause
                    if (currentPlayer.playing) {
                        currentPlayer.pause();
                    } else {
                        currentPlayer.play();
                    }
                }
            }
            
            lastTapTime = now;
            lastDoubleTapX = tapX;
        };
        
        // Add touch event listeners
        playerElement.addEventListener('touchstart', handleTap);
        
        // Store for cleanup
        playerElement.handleTapFunc = handleTap;
    }

    // Visual feedback for touch controls
    function showControlFeedback(position, text) {
        const playerElement = videoPlayer.closest('.player-container');
        
        // Create a feedback element
        const feedback = document.createElement('div');
        feedback.className = `tap-feedback ${position}`;
        feedback.innerHTML = `
            <div class="feedback-icon">
                <i class="fas fa-${position === 'left' ? 'backward' : position === 'right' ? 'forward' : 'play'}"></i>
            </div>
            <div class="feedback-text">${text}</div>
        `;
        
        // Style it
        feedback.style.position = 'absolute';
        feedback.style.top = '50%';
        feedback.style.transform = 'translateY(-50%)';
        feedback.style.color = 'white';
        feedback.style.backgroundColor = 'rgba(0,0,0,0.6)';
        feedback.style.padding = '15px';
        feedback.style.borderRadius = '50%';
        feedback.style.display = 'flex';
        feedback.style.flexDirection = 'column';
        feedback.style.alignItems = 'center';
        feedback.style.opacity = '0';
        feedback.style.animation = 'fadeInOut 1s ease-in-out';
        
        if (position === 'left') {
            feedback.style.left = '15%';
        } else if (position === 'right') {
            feedback.style.right = '15%';
        } else {
            feedback.style.left = '50%';
            feedback.style.transform = 'translate(-50%, -50%)';
        }
        
        // Add animation
        const keyframes = `
            @keyframes fadeInOut {
                0% { opacity: 0; }
                20% { opacity: 1; }
                80% { opacity: 1; }
                100% { opacity: 0; }
            }
        `;
        
        const style = document.createElement('style');
        style.textContent = keyframes;
        document.head.appendChild(style);
        
        // Add to player
        playerElement.appendChild(feedback);
        
        // Remove after animation
        setTimeout(() => {
            feedback.remove();
            style.remove();
        }, 1000);
    }

    // Close video modal and clean up player
    function closeVideoModal() {
        // Clean up player first
        cleanupPlayer();
        
        // Hide modal
        videoModal.style.display = 'none';
        document.body.style.overflow = ''; // Restore scrolling
    }

    // Clean up video player
    function cleanupPlayer() {
        // If a player instance exists, destroy it
        if (currentPlayer) {
            // Make sure video is paused
            try {
                currentPlayer.pause();
            } catch (e) {
                console.warn('Error pausing player:', e);
            }
            
            // Try-catch to handle potential Plyr errors
            try {
                currentPlayer.destroy();
            } catch (e) {
                console.warn('Error destroying Plyr instance:', e);
            }
            
            currentPlayer = null;
        }
        
        // Directly manipulate the video element as a failsafe
        videoPlayer.pause();
        videoPlayer.removeAttribute('src');
        videoPlayer.load(); // Important: this resets the video element
        
        // Remove any event listeners from the player container
        const playerElement = videoPlayer.closest('.player-container');
        if (playerElement && playerElement.handleTapFunc) {
            playerElement.removeEventListener('touchstart', playerElement.handleTapFunc);
            delete playerElement.handleTapFunc;
        }
        
        // Clear any existing feedback elements
        const feedbacks = document.querySelectorAll('.tap-feedback');
        feedbacks.forEach(el => el.remove());
    }

    // Show toast message
    function showToast(message, type = 'info') {
        const toastContainer = document.getElementById('toastContainer');
        
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        toast.textContent = message;
        
        toastContainer.appendChild(toast);
        
        // Remove toast after animation completes
        setTimeout(() => {
            toast.remove();
        }, 3000);
    }
});