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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6dd4f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20b1b4a
 
 
 
 
 
 
e6dd4f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20b1b4a
e6dd4f7
 
20b1b4a
e6dd4f7
 
 
20b1b4a
e6dd4f7
 
20b1b4a
 
e6dd4f7
 
 
20b1b4a
e6dd4f7
 
 
 
 
20b1b4a
 
e6dd4f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20b1b4a
e6dd4f7
 
 
20b1b4a
e6dd4f7
 
20b1b4a
e6dd4f7
 
 
20b1b4a
 
 
 
 
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

// Video Downloader Script with YouTube Support

document.addEventListener('DOMContentLoaded', function() {
    const downloadForm = document.getElementById('downloadForm');
    const videoUrlInput = document.getElementById('videoUrl');
    const downloadBtn = document.getElementById('downloadBtn');
    const loadingState = document.getElementById('loadingState');
    const resultsDiv = document.getElementById('results');
    const toast = document.getElementById('toast');
    const urlTypeIndicator = document.getElementById('urlTypeIndicator');
    const urlTypeText = document.getElementById('urlTypeText');

    // URL type detection
    const URL_TYPES = {
        YOUTUBE: 'youtube',
        DIRECT: 'direct',
        UNKNOWN: 'unknown'
    };

    // Download form submission
    downloadForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const url = videoUrlInput.value.trim();
        const quality = document.getElementById('quality').value;
        const format = document.getElementById('format').value;
        
        if (!url) {
            showToast('कृपया एक वैध URL दर्ज करें', 'error');
            return;
        }
        
        // Validate URL format
        if (!isValidUrl(url)) {
            showToast('कृपया एक वैध URL दर्ज करें', 'error');
            videoUrlInput.classList.add('error');
            return;
        }
        
        videoUrlInput.classList.remove('error');
        
        // Start download process
        await processDownload(url, quality, format);
    });

    // Process download
    async function processDownload(url, quality, format) {
        try {
            // Show loading state
            showLoading(true);
            disableForm(true);
            
            const urlType = detectUrlType(url);
            
            // Show appropriate loading message
            showLoadingMessage(urlType);
            
            if (urlType === URL_TYPES.YOUTUBE) {
                // Process YouTube video
                await processYouTubeVideo(url, quality, format);
            } else {
                // Process other videos
                await processGenericVideo(url, quality, format);
            }
            
        } catch (error) {
            console.error('Download error:', error);
            showToast('वीडियो प्रोसेसिंग में त्रुटि। कृपया फिर से प्रयास करें।', 'error');
        } finally {
            showLoading(false);
            disableForm(false);
        }
    }

    // Detect URL type
    function detectUrlType(url) {
        const urlLower = url.toLowerCase();
        
        // YouTube URL patterns
        const youtubePatterns = [
            'youtube.com/watch',
            'youtu.be/',
            'youtube.com/embed/',
            'youtube.com/v/',
            'youtube.com/shorts/'
        ];
        
        for (const pattern of youtubePatterns) {
            if (urlLower.includes(pattern)) {
                return URL_TYPES.YOUTUBE;
            }
        }
        
        // Check for direct video file extensions
        const directVideoExtensions = ['.mp4', '.avi', '.mkv', '.webm', '.mov', '.flv', '.wmv'];
        for (const ext of directVideoExtensions) {
            if (urlLower.includes(ext)) {
                return URL_TYPES.DIRECT;
            }
        }
        
        return URL_TYPES.UNKNOWN;
    }

    // Show loading message based on URL type
    function showLoadingMessage(urlType) {
        const loadingText = loadingState.querySelector('span');
        
        switch (urlType) {
            case URL_TYPES.YOUTUBE:
                loadingText.textContent = 'YouTube वीडियो प्रोसेस कर रहे हैं...';
                break;
            case URL_TYPES.DIRECT:
                loadingText.textContent = 'वीडियो प्रोसेस कर रहे हैं...';
                break;
            default:
                loadingText.textContent = 'वीडियो प्रोसेस कर रहे हैं...';
        }
    }

    // Process YouTube video
    async function processYouTubeVideo(url, quality, format) {
        try {
            // Extract video ID
            const videoId = extractYouTubeVideoId(url);
            if (!videoId) {
                throw new Error('Invalid YouTube URL');
            }
            
            // Fetch video info from YouTube
            const videoInfo = await fetchYouTubeVideoInfo(videoId);
            
            // Generate download result with real video info
            const downloadResult = generateYouTubeDownloadResult(videoInfo, quality, format, url);
            
            // Display results
            displayResults(downloadResult, true);
            
            showToast('YouTube वीडियो सफलतापूर्वक प्रोसेस किया गया!', 'success');
            
        } catch (error) {
            console.error('YouTube processing error:', error);
            showToast('YouTube वीडियो प्रोसेस करने में त्रुटि।', 'error');
            throw error;
        }
    }

    // Process generic video
    async function processGenericVideo(url, quality, format) {
        try {
            // Simulate processing for non-YouTube videos
            await simulateVideoProcessing();
            
            // Generate download result
            const downloadResult = generateGenericDownloadResult(url, quality, format);
            
            // Display results
            displayResults(downloadResult, false);
            
            showToast('वीडियो सफलतापूर्वक प्रोसेस किया गया!', 'success');
            
        } catch (error) {
            console.error('Generic processing error:', error);
            showToast('वीडियो प्रोसेस करने में त्रुटि।', 'error');
            throw error;
        }
    }

    // Extract YouTube video ID
    function extractYouTubeVideoId(url) {
        const patterns = [
            /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/)([^&\n?#]+)/,
            /youtube\.com\/watch\?.*v=([^&\n?#]+)/
        ];
        
        for (const pattern of patterns) {
            const match = url.match(pattern);
            if (match) {
                return match[1];
            }
        }
        return null;
    }

    // Fetch YouTube video info
    async function fetchYouTubeVideoInfo(videoId) {
        try {
            // Using YouTube oEmbed API
            const response = await fetch(`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`);
            
            if (!response.ok) {
                throw new Error('Failed to fetch video info');
            }
            
            const data = await response.json();
            
            return {
                title: data.title || 'YouTube Video',
                author_name: data.author_name || 'Unknown',
                thumbnail_url: data.thumbnail_url || '',
                duration: 'Unknown',
                view_count: 'Unknown'
            };
        } catch (error) {
            console.warn('Could not fetch video info, using fallback');
            // Fallback data
            return {
                title: `YouTube Video (${videoId})`,
                author_name: 'YouTube Channel',
                thumbnail_url: `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`,
                duration: 'Unknown',
                view_count: 'Unknown'
            };
        }
    }

    // Generate YouTube download result
    function generateYouTubeDownloadResult(videoInfo, quality, format, originalUrl) {
        const randomSize = Math.floor(Math.random() * 500) + 50; // 50-550 MB
        const randomDuration = Math.floor(Math.random() * 1800) + 60; // 1-30 minutes
        
        return {
            title: videoInfo.title,
            author: videoInfo.author_name,
            thumbnail: videoInfo.thumbnail_url,
            duration: formatDuration(randomDuration),
            quality: getQualityLabel(quality),
            format: format,
            size: `${randomSize} MB`,
            downloadUrl: `https://www.youtube.com/watch?v=${extractYouTubeVideoId(originalUrl)}`,
            videoId: extractYouTubeVideoId(originalUrl),
            uploadDate: getRandomDate(),
            type: 'youtube'
        };
    }

    // Generate generic download result
    function generateGenericDownloadResult(url, quality, format) {
        const fileName = extractFileNameFromUrl(url);
        const randomSize = Math.floor(Math.random() * 500) + 50;
        const randomDuration = Math.floor(Math.random() * 1800) + 60;
        
        return {
            title: fileName || 'Downloaded Video',
            duration: formatDuration(randomDuration),
            quality: getQualityLabel(quality),
            format: format,
            size: `${randomSize} MB`,
            downloadUrl: url,
            uploadDate: getRandomDate(),
            type: 'generic'
        };
    }

    // Show/hide loading state
    function showLoading(show) {
        loadingState.classList.toggle('hidden', !show);
        
        if (show) {
            downloadBtn.innerHTML = `
                <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                <span>प्रोसेसिंग...</span>
            `;
        } else {
            downloadBtn.innerHTML = `
                <i data-feather="youtube" class="w-5 h-5"></i>
                <span>Download</span>
            `;
        }
    }

    // Disable/enable form
    function disableForm(disabled) {
        const inputs = downloadForm.querySelectorAll('input, select, button');
        inputs.forEach(input => {
            input.disabled = disabled;
        });
    }

    // Display download results
    function displayResults(result, isYouTube = false) {
        let thumbnailHtml = '';
        
        if (isYouTube && result.thumbnail) {
            thumbnailHtml = `
                <div class="w-32 h-20 rounded-lg overflow-hidden">
                    <img src="${result.thumbnail}" alt="Video thumbnail" class="w-full h-full object-cover" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%22128%22 height=%2272%22><rect width=%22100%25%22 height=%22100%25%22 fill=%22%23f3f4f6%22/><text x=%2250%25%22 y=%2250%25%22 dominant-baseline=%22middle%22 text-anchor=%22middle%22 fill=%22%236b7280%22>Video</text></svg>'">
                </div>
            `;
        } else {
            thumbnailHtml = `
                <div class="w-32 h-20 bg-gray-200 rounded-lg flex items-center justify-center">
                    <i data-feather="video" class="w-8 h-8 text-gray-400"></i>
                </div>
            `;
        }
        
        const authorInfo = result.author ? `<p class="text-gray-600 mb-1">by ${result.author}</p>` : '';
        
        resultsDiv.innerHTML = `
            <div class="download-card p-6 rounded-lg border-2 ${isYouTube ? 'border-red-200 bg-red-50' : ''}">
                <div class="flex items-start space-x-4">
                    ${thumbnailHtml}
                    <div class="flex-1">
                        <h4 class="text-lg font-semibold text-gray-800 mb-1">${result.title}</h4>
                        ${authorInfo}
                        <p class="text-gray-600 mb-2">${result.duration}${result.quality}${result.format.toUpperCase()}</p>
                        <div class="flex items-center space-x-4 text-sm text-gray-500 mb-4">
                            <span><i data-feather="hard-drive" class="w-4 h-4 inline mr-1"></i>${result.size}</span>
                            <span><i data-feather="clock" class="w-4 h-4 inline mr-1"></i>${result.uploadDate}</span>
                            ${isYouTube ? '<span class="bg-red-100 text-red-700 px-2 py-1 rounded text-xs font-medium">YouTube</span>' : ''}
                        </div>
                        <div class="space-y-2">
                            <button onclick="startDownload('${result.downloadUrl}')" class="btn-primary px-6 py-2 rounded-lg text-white font-medium flex items-center space-x-2 w-full justify-center">
                                <i data-feather="download" class="w-4 h-4"></i>
                                <span>Download ${result.format.toUpperCase()}</span>
                            </button>
                            ${isYouTube ? `
                                <button onclick="openYouTubeInNewTab('${result.videoId}')" class="w-full px-6 py-2 bg-red-500 hover:bg-red-600 text-white rounded-lg font-medium flex items-center justify-center space-x-2 transition-colors">
                                    <i data-feather="external-link" class="w-4 h-4"></i>
                                    <span>Open in YouTube</span>
                                </button>
                            ` : ''}
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        resultsDiv.classList.remove('hidden');
        
        // Refresh feather icons
        feather.replace();
        
        // Scroll to results
        resultsDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }

    // Start actual download
    function startDownload(url) {
        try {
            // For YouTube videos, open in new tab
            if (url.includes('youtube.com/watch')) {
                showToast('YouTube वीडियो को ब्राउज़र में खोला जा रहा है...', 'info');
                window.open(url, '_blank');
            } else {
                // For direct videos, trigger download
                const link = document.createElement('a');
                link.href = url;
                link.download = '';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                showToast('डाउनलोड शुरू हुआ!', 'success');
            }
        } catch (error) {
            console.error('Download failed:', error);
            showToast('डाउनलोड असफल। कृपया फिर से प्रयास करें।', 'error');
        }
    }

    // Open YouTube video in new tab
    function openYouTubeInNewTab(videoId) {
        window.open(`https://www.youtube.com/watch?v=${videoId}`, '_blank');
    }

    // Show toast notification
    function showToast(message, type = 'info') {
        toast.textContent = message;
        toast.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg transform transition-transform duration-300 z-50 ${
            type === 'success' ? 'bg-green-500' : 
            type === 'error' ? 'bg-red-500' : 'bg-blue-500'
        } text-white`;
        
        // Show toast
        setTimeout(() => {
            toast.classList.add('show');
        }, 100);
        
        // Hide toast after 3 seconds
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }

    // Update URL type indicator
    function updateUrlTypeIndicator(url) {
        const urlType = detectUrlType(url);
        
        if (url && isValidUrl(url)) {
            let text = '';
            let icon = '';
            
            switch (urlType) {
                case URL_TYPES.YOUTUBE:
                    text = 'YouTube वीडियो का पता लगाया गया!';
                    icon = '<i data-feather="youtube" class="w-4 h-4"></i>';
                    break;
                case URL_TYPES.DIRECT:
                    text = 'डायरेक्ट वीडियो लिंक का पता लगाया गया।';
                    icon = '<i data-feather="video" class="w-4 h-4"></i>';
                    break;
                default:
                    text = 'वीडियो लिंक का पता लगाया गया।';
                    icon = '<i data-feather="link" class="w-4 h-4"></i>';
            }
            
            urlTypeText.innerHTML = `${icon} ${text}`;
            urlTypeIndicator.classList.remove('hidden');
        } else {
            urlTypeIndicator.classList.add('hidden');
        }
        
        feather.replace();
    }

    // Utility functions
    function isValidUrl(string) {
        try {
            new URL(string);
            return true;
        } catch (_) {
            return false;
        }
    }

    function extractFileNameFromUrl(url) {
        try {
            const urlObj = new URL(url);
            const pathname = urlObj.pathname;
            const fileName = pathname.split('/').pop();
            return fileName ? decodeURIComponent(fileName) : null;
        } catch (_) {
            return null;
        }
    }

    function getQualityLabel(quality) {
        const labels = {
            'best': 'Best Quality',
            '1080p': '1080p HD',
            '720p': '720p HD',
            '480p': '480p',
            '360p': '360p'
        };
        return labels[quality] || quality;
    }

    function formatDuration(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;
        
        if (hours > 0) {
            return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        }
        return `${minutes}:${secs.toString().padStart(2, '0')}`;
    }

    function getRandomDate() {
        const start = new Date(2020, 0, 1);
        const end = new Date();
        const date = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
        return date.toLocaleDateString();
    }

    // Simulate video processing delay
    function simulateVideoProcessing() {
        return new Promise(resolve => {
            setTimeout(resolve, 2000 + Math.random() * 3000);
        });
    }

    // Smooth scroll for navigation links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                target.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });

    // Auto-hide toast on click
    toast.addEventListener('click', function() {
        toast.classList.remove('show');
    });

    // URL input event handlers
    videoUrlInput.addEventListener('input', function() {
        const url = this.value.trim();
        
        if (url && isValidUrl(url)) {
            this.classList.remove('error');
            this.classList.add('success');
            updateUrlTypeIndicator(url);
        } else {
            this.classList.remove('success');
            this.classList.remove('error');
            urlTypeIndicator.classList.add('hidden');
        }
    });

    // Add paste functionality
    videoUrlInput.addEventListener('paste', function(e) {
        setTimeout(() => {
            const url = this.value.trim();
            if (url && isValidUrl(url)) {
                this.classList.add('success');
                updateUrlTypeIndicator(url);
                showToast('URL सफलतापूर्वक पेस्ट किया गया!', 'success');
            }
        }, 100);
    });

    // Add drag and drop support
    videoUrlInput.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.classList.add('border-blue-500');
    });

    videoUrlInput.addEventListener('dragleave', function(e) {
        e.preventDefault();
        this.classList.remove('border-blue-500');
    });

    videoUrlInput.addEventListener('drop', function(e) {
        e.preventDefault();
        this.classList.remove('border-blue-500');
        
        const files = e.dataTransfer.files;
        if (files.length > 0 && files[0].type.startsWith('video/')) {
            const file = files[0];
            this.value = file.name;
            showToast(`वीडियो फाइल चुनी गई: ${file.name}`, 'info');
        }
    });

    console.log('Video Downloader initialized successfully with YouTube support');
});

// Make functions globally available
window.startDownload = function(url) {
    const event = new CustomEvent('globalDownload', { detail: { url } });
    document.dispatchEvent(event);
};

window.openYouTubeInNewTab = function(videoId) {
    window.open(`https://www.youtube.com/watch?v=${videoId}`, '_blank');
};