Spaces:
Running

File size: 34,262 Bytes
931ce2f
 
 
 
 
9993b81
931ce2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9993b81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
931ce2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9993b81
931ce2f
 
 
 
 
9993b81
 
 
 
931ce2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9993b81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
931ce2f
 
 
 
 
 
 
 
9993b81
931ce2f
 
 
 
 
 
 
9993b81
931ce2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9993b81
 
 
 
 
931ce2f
 
 
 
9993b81
931ce2f
 
9993b81
931ce2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9993b81
 
 
 
 
 
 
 
 
 
 
 
 
931ce2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9993b81
 
 
 
931ce2f
 
 
 
 
 
 
9993b81
 
 
 
 
 
931ce2f
 
 
 
 
 
 
 
 
 
 
 
9993b81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
931ce2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9993b81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
931ce2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9993b81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
931ce2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GhostChat - Anonymous WebRTC Chat with File Sharing</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .message-container {
            scrollbar-width: thin;
            scrollbar-color: #4B5563 #1F2937;
        }
        .message-container::-webkit-scrollbar {
            width: 6px;
        }
        .message-container::-webkit-scrollbar-track {
            background: #1F2937;
        }
        .message-container::-webkit-scrollbar-thumb {
            background-color: #4B5563;
            border-radius: 3px;
        }
        .typing-indicator::after {
            content: '...';
            position: absolute;
            animation: typing 1.5s infinite;
        }
        @keyframes typing {
            0% { content: '.'; }
            33% { content: '..'; }
            66% { content: '...'; }
        }
        .peer-id-input:focus + .peer-id-label,
        .peer-id-input:not(:placeholder-shown) + .peer-id-label {
            transform: translateY(-1.5rem) scale(0.85);
            color: #9CA3AF;
        }
        .file-preview {
            max-width: 300px;
            max-height: 200px;
            object-fit: contain;
        }
        .progress-bar {
            height: 4px;
            background-color: #4B5563;
            border-radius: 2px;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            background-color: #8B5CF6;
            transition: width 0.3s ease;
        }
        .file-dropzone {
            border: 2px dashed #4B5563;
            border-radius: 0.375rem;
            transition: all 0.2s ease;
        }
        .file-dropzone.active {
            border-color: #8B5CF6;
            background-color: rgba(139, 92, 246, 0.1);
        }
    </style>
</head>
<body class="bg-gray-900 text-gray-100 min-h-screen flex flex-col">
    <header class="bg-gray-800 py-4 px-6 shadow-lg">
        <div class="container mx-auto flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fas fa-ghost text-purple-500 text-2xl"></i>
                <h1 class="text-xl font-bold">GhostChat</h1>
            </div>
            <div id="connection-status" class="flex items-center space-x-2">
                <span class="text-sm text-gray-400">Status:</span>
                <span id="status-text" class="px-2 py-1 rounded-full text-xs bg-gray-700">Disconnected</span>
            </div>
        </div>
    </header>

    <main class="flex-1 container mx-auto p-4 md:p-6 flex flex-col md:flex-row gap-6">
        <!-- Connection Panel -->
        <div class="w-full md:w-1/3 lg:w-1/4 bg-gray-800 rounded-lg p-4 shadow-lg">
            <div class="space-y-6">
                <div>
                    <h2 class="text-lg font-semibold mb-3">Your Ghost ID</h2>
                    <div class="relative">
                        <input type="text" id="your-id" readonly 
                            class="w-full bg-gray-700 rounded px-3 py-2 text-sm font-mono cursor-not-allowed" 
                            placeholder="Generating...">
                        <button id="copy-id" class="absolute right-2 top-2 text-gray-400 hover:text-purple-500">
                            <i class="far fa-copy"></i>
                        </button>
                    </div>
                </div>

                <div>
                    <h2 class="text-lg font-semibold mb-3">Connect to Ghost</h2>
                    <div class="relative">
                        <input type="text" id="peer-id" 
                            class="peer-id-input w-full bg-gray-700 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-purple-500" 
                            placeholder=" ">
                        <label for="peer-id" class="peer-id-label absolute left-3 top-2 text-gray-400 text-sm transition-all duration-200">Enter Ghost ID</label>
                        <button id="connect-btn" class="w-full mt-4 bg-purple-600 hover:bg-purple-700 text-white py-2 px-4 rounded-md transition-colors">
                            Connect
                        </button>
                    </div>
                </div>

                <div class="pt-4 border-t border-gray-700">
                    <h3 class="text-sm font-semibold text-gray-400 mb-2">Quick Tips</h3>
                    <ul class="text-xs space-y-2 text-gray-300">
                        <li class="flex items-start space-x-2">
                            <i class="fas fa-info-circle text-purple-400 mt-0.5"></i>
                            <span>Share your Ghost ID to start chatting</span>
                        </li>
                        <li class="flex items-start space-x-2">
                            <i class="fas fa-shield-alt text-purple-400 mt-0.5"></i>
                            <span>All messages and files are end-to-end encrypted</span>
                        </li>
                        <li class="flex items-start space-x-2">
                            <i class="fas fa-user-secret text-purple-400 mt-0.5"></i>
                            <span>No accounts, no tracking, completely anonymous</span>
                        </li>
                        <li class="flex items-start space-x-2">
                            <i class="fas fa-file-upload text-purple-400 mt-0.5"></i>
                            <span>Drag & drop files to share them instantly</span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Chat Panel -->
        <div class="flex-1 flex flex-col bg-gray-800 rounded-lg shadow-lg overflow-hidden">
            <div class="p-4 border-b border-gray-700 flex justify-between items-center">
                <h2 class="text-lg font-semibold">
                    <span id="chat-with">Ghost Messages</span>
                    <span id="typing-indicator" class="typing-indicator text-sm text-gray-400 ml-2 hidden"></span>
                </h2>
                <button id="disconnect-btn" class="text-sm bg-gray-700 hover:bg-gray-600 px-3 py-1 rounded-md hidden">
                    Disconnect
                </button>
            </div>

            <div id="message-container" class="message-container flex-1 p-4 overflow-y-auto max-h-[60vh] space-y-3">
                <div class="text-center py-10 text-gray-500">
                    <i class="fas fa-comment-slash text-3xl mb-2"></i>
                    <p>No active connection. Connect to another Ghost to start chatting.</p>
                </div>
            </div>

            <div class="p-4 border-t border-gray-700 space-y-3">
                <!-- File dropzone -->
                <div id="file-dropzone" class="file-dropzone p-4 text-center cursor-pointer">
                    <input type="file" id="file-input" class="hidden" multiple>
                    <label for="file-input" class="cursor-pointer">
                        <div class="flex flex-col items-center justify-center space-y-2">
                            <i class="fas fa-cloud-upload-alt text-2xl text-purple-500"></i>
                            <p class="text-sm">Drag & drop files here or click to browse</p>
                            <p class="text-xs text-gray-500">Supports all file types (max 50MB)</p>
                        </div>
                    </label>
                </div>
                
                <!-- File upload progress -->
                <div id="upload-progress" class="hidden">
                    <div class="flex justify-between text-xs mb-1">
                        <span>Sending file...</span>
                        <span id="upload-percentage">0%</span>
                    </div>
                    <div class="progress-bar">
                        <div id="progress-fill" class="progress-fill" style="width: 0%"></div>
                    </div>
                </div>
                
                <!-- Message input -->
                <div class="flex space-x-2">
                    <input type="text" id="message-input" 
                        class="flex-1 bg-gray-700 rounded-l-md px-3 py-2 focus:outline-none focus:ring-1 focus:ring-purple-500" 
                        placeholder="Type a message..." disabled>
                    <button id="send-btn" class="bg-purple-600 hover:bg-purple-700 text-white px-4 rounded-r-md transition-colors" disabled>
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
                <p class="text-xs text-gray-500">
                    Press Enter to send. Messages disappear when you disconnect.
                </p>
            </div>
        </div>
    </main>

    <footer class="bg-gray-800 py-3 px-6 text-center text-sm text-gray-500">
        <p>GhostChat - Anonymous peer-to-peer messaging with file sharing. No logs, no tracking.</p>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // UI Elements
            const yourIdInput = document.getElementById('your-id');
            const peerIdInput = document.getElementById('peer-id');
            const connectBtn = document.getElementById('connect-btn');
            const disconnectBtn = document.getElementById('disconnect-btn');
            const messageInput = document.getElementById('message-input');
            const sendBtn = document.getElementById('send-btn');
            const messageContainer = document.getElementById('message-container');
            const statusText = document.getElementById('status-text');
            const chatWithText = document.getElementById('chat-with');
            const typingIndicator = document.getElementById('typing-indicator');
            const copyIdBtn = document.getElementById('copy-id');
            const fileInput = document.getElementById('file-input');
            const fileDropzone = document.getElementById('file-dropzone');
            const uploadProgress = document.getElementById('upload-progress');
            const progressFill = document.getElementById('progress-fill');
            const uploadPercentage = document.getElementById('upload-percentage');

            // PeerJS variables
            let peer;
            let conn;
            let dataConnection;
            let lastTypingTime = 0;
            const TYPING_INTERVAL = 2000; // 2 seconds
            const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB

            // Initialize Peer
            function initializePeer() {
                // Generate a random ID for this session
                const randomId = 'ghost-' + Math.random().toString(36).substr(2, 9);
                
                peer = new Peer(randomId, {
                    host: '0.peerjs.com',
                    port: 443,
                    path: '/',
                    secure: true,
                    debug: 3
                });

                peer.on('open', (id) => {
                    yourIdInput.value = id;
                    updateStatus('Ready to connect', 'bg-blue-600');
                });

                peer.on('connection', (connection) => {
                    if (conn && conn.open) {
                        connection.close();
                        return;
                    }
                    
                    setupConnection(connection);
                    updateStatus(`Connected to ${connection.peer.substr(0, 8)}...`, 'bg-green-600');
                    chatWithText.textContent = `Ghost ${connection.peer.substr(0, 8)}...`;
                });

                // Set up data channel for file transfers
                peer.on('call', (call) => {
                    call.answer(); // Automatically answer
                    
                    call.on('stream', (stream) => {
                        // Not used for file transfer, but required by PeerJS
                    });
                    
                    call.on('close', () => {
                        console.log('File transfer connection closed');
                    });
                });

                peer.on('error', (err) => {
                    console.error('Peer error:', err);
                    updateStatus('Connection error', 'bg-red-600');
                });

                peer.on('disconnected', () => {
                    updateStatus('Disconnected', 'bg-yellow-600');
                    setTimeout(() => initializePeer(), 5000); // Try to reconnect
                });

                peer.on('close', () => {
                    updateStatus('Disconnected', 'bg-gray-600');
                });
            }

            // Set up a connection
            function setupConnection(connection) {
                conn = connection;
                
                conn.on('open', () => {
                    updateStatus(`Connected to ${conn.peer.substr(0, 8)}...`, 'bg-green-600');
                    chatWithText.textContent = `Ghost ${conn.peer.substr(0, 8)}...`;
                    messageInput.disabled = false;
                    sendBtn.disabled = false;
                    disconnectBtn.classList.remove('hidden');
                    
                    // Clear previous messages
                    messageContainer.innerHTML = '';
                    
                    // Add welcome message
                    addMessage('system', 'You are now connected to another Ghost. Messages and files are end-to-end encrypted.', 'text-gray-400');
                    
                    // Set up data channel for file transfers
                    setupDataConnection();
                });

                conn.on('data', (data) => {
                    if (data.type === 'message') {
                        addMessage('remote', data.text, 'bg-gray-700');
                    } else if (data.type === 'typing') {
                        showTypingIndicator();
                    } else if (data.type === 'file-meta') {
                        // Show that a file is being received
                        addMessage('remote', `Sending you a file: ${data.name} (${formatFileSize(data.size)})`, 'bg-gray-700');
                    } else if (data.type === 'file-ack') {
                        // Acknowledge file receipt
                        addMessage('system', `File transfer completed: ${data.name}`, 'text-gray-400');
                    }
                });

                conn.on('close', () => {
                    handleDisconnection();
                });

                conn.on('error', (err) => {
                    console.error('Connection error:', err);
                    handleDisconnection();
                });
            }
            
            // Set up data connection for file transfers
            function setupDataConnection() {
                dataConnection = peer.connect(conn.peer, {
                    reliable: true,
                    serialization: 'none',
                    metadata: { type: 'data-channel' }
                });
                
                dataConnection.on('open', () => {
                    console.log('Data channel ready for file transfers');
                });
                
                dataConnection.on('data', (data) => {
                    if (data instanceof ArrayBuffer || data instanceof Blob) {
                        // Handle incoming file chunks
                        handleFileChunk(data);
                    }
                });
                
                dataConnection.on('close', () => {
                    console.log('Data channel closed');
                });
                
                dataConnection.on('error', (err) => {
                    console.error('Data channel error:', err);
                });
            }

            // Handle incoming file chunks
            let receivedFileChunks = [];
            let currentFileMeta = null;
            
            function handleFileChunk(chunk) {
                if (!currentFileMeta) {
                    // First chunk should be metadata
                    try {
                        const decoder = new TextDecoder();
                        const metaString = decoder.decode(chunk);
                        currentFileMeta = JSON.parse(metaString);
                        receivedFileChunks = [];
                        return;
                    } catch (e) {
                        console.error('Error parsing file metadata:', e);
                        return;
                    }
                }
                
                // Add chunk to array
                receivedFileChunks.push(chunk);
                
                // Update progress
                const receivedSize = receivedFileChunks.reduce((acc, chunk) => acc + chunk.byteLength, 0);
                const progress = Math.min(100, Math.round((receivedSize / currentFileMeta.size) * 100));
                
                if (progress === 100) {
                    // File transfer complete
                    const fileBlob = new Blob(receivedFileChunks, { type: currentFileMeta.type });
                    displayReceivedFile(fileBlob, currentFileMeta.name, currentFileMeta.size);
                    
                    // Send acknowledgment
                    if (conn && conn.open) {
                        conn.send({
                            type: 'file-ack',
                            name: currentFileMeta.name,
                            size: currentFileMeta.size
                        });
                    }
                    
                    currentFileMeta = null;
                    receivedFileChunks = [];
                }
            }
            
            // Display received file in chat
            function displayReceivedFile(fileBlob, fileName, fileSize) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `flex justify-start mb-3`;
                
                const fileUrl = URL.createObjectURL(fileBlob);
                const fileExtension = fileName.split('.').pop().toLowerCase();
                
                let fileContent = '';
                if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileExtension)) {
                    fileContent = `
                        <div class="bg-gray-700 rounded-lg p-3">
                            <img src="${fileUrl}" alt="${fileName}" class="file-preview rounded">
                            <div class="mt-2 text-sm">
                                <p>${fileName}</p>
                                <p class="text-xs text-gray-400">${formatFileSize(fileSize)}</p>
                                <a href="${fileUrl}" download="${fileName}" class="text-purple-400 hover:text-purple-300 text-xs mt-1 inline-block">
                                    <i class="fas fa-download mr-1"></i>Download
                                </a>
                            </div>
                        </div>
                    `;
                } else if (['mp4', 'webm', 'ogg'].includes(fileExtension)) {
                    fileContent = `
                        <div class="bg-gray-700 rounded-lg p-3">
                            <video controls class="file-preview rounded">
                                <source src="${fileUrl}" type="${fileBlob.type}">
                                Your browser does not support the video tag.
                            </video>
                            <div class="mt-2 text-sm">
                                <p>${fileName}</p>
                                <p class="text-xs text-gray-400">${formatFileSize(fileSize)}</p>
                                <a href="${fileUrl}" download="${fileName}" class="text-purple-400 hover:text-purple-300 text-xs mt-1 inline-block">
                                    <i class="fas fa-download mr-1"></i>Download
                                </a>
                            </div>
                        </div>
                    `;
                } else if (['mp3', 'wav', 'ogg'].includes(fileExtension)) {
                    fileContent = `
                        <div class="bg-gray-700 rounded-lg p-3">
                            <audio controls class="w-full">
                                <source src="${fileUrl}" type="${fileBlob.type}">
                                Your browser does not support the audio element.
                            </audio>
                            <div class="mt-2 text-sm">
                                <p>${fileName}</p>
                                <p class="text-xs text-gray-400">${formatFileSize(fileSize)}</p>
                                <a href="${fileUrl}" download="${fileName}" class="text-purple-400 hover:text-purple-300 text-xs mt-1 inline-block">
                                    <i class="fas fa-download mr-1"></i>Download
                                </a>
                            </div>
                        </div>
                    `;
                } else {
                    fileContent = `
                        <div class="bg-gray-700 rounded-lg p-3">
                            <div class="flex items-center">
                                <i class="fas fa-file ${getFileIconClass(fileExtension)} text-2xl mr-3"></i>
                                <div>
                                    <p class="text-sm">${fileName}</p>
                                    <p class="text-xs text-gray-400">${formatFileSize(fileSize)}</p>
                                    <a href="${fileUrl}" download="${fileName}" class="text-purple-400 hover:text-purple-300 text-xs mt-1 inline-block">
                                        <i class="fas fa-download mr-1"></i>Download
                                    </a>
                                </div>
                            </div>
                        </div>
                    `;
                }
                
                messageDiv.innerHTML = fileContent;
                messageContainer.appendChild(messageDiv);
                messageContainer.scrollTop = messageContainer.scrollHeight;
            }
            
            // Get appropriate icon class for file type
            function getFileIconClass(extension) {
                const iconMap = {
                    'pdf': 'text-red-500',
                    'doc': 'text-blue-500',
                    'docx': 'text-blue-500',
                    'xls': 'text-green-500',
                    'xlsx': 'text-green-500',
                    'ppt': 'text-orange-500',
                    'pptx': 'text-orange-500',
                    'zip': 'text-yellow-500',
                    'rar': 'text-yellow-500',
                    'txt': 'text-gray-400',
                    'csv': 'text-green-400',
                    'html': 'text-purple-500',
                    'js': 'text-yellow-300',
                    'json': 'text-gray-400'
                };
                
                return iconMap[extension] || 'text-gray-300';
            }

            // Handle disconnection
            function handleDisconnection() {
                updateStatus('Disconnected', 'bg-gray-600');
                messageInput.disabled = true;
                sendBtn.disabled = true;
                disconnectBtn.classList.add('hidden');
                
                if (messageContainer.children.length > 0) {
                    addMessage('system', 'The other Ghost has disappeared...', 'text-gray-400');
                }
            }

            // Update status UI
            function updateStatus(text, bgClass) {
                statusText.textContent = text;
                statusText.className = `px-2 py-1 rounded-full text-xs ${bgClass}`;
            }

            // Add a message to the UI
            function addMessage(type, text, additionalClasses = '') {
                const messageDiv = document.createElement('div');
                
                if (type === 'local') {
                    messageDiv.className = `flex justify-end`;
                    messageDiv.innerHTML = `
                        <div class="max-w-xs md:max-w-md lg:max-w-lg bg-purple-600 rounded-lg px-4 py-2 ${additionalClasses}">
                            <p>${text}</p>
                            <p class="text-xs text-purple-200 mt-1 text-right">just now</p>
                        </div>
                    `;
                } else if (type === 'remote') {
                    messageDiv.className = `flex justify-start`;
                    messageDiv.innerHTML = `
                        <div class="max-w-xs md:max-w-md lg:max-w-lg rounded-lg px-4 py-2 ${additionalClasses}">
                            <p>${text}</p>
                            <p class="text-xs text-gray-400 mt-1">ghost</p>
                        </div>
                    `;
                } else { // system
                    messageDiv.className = `flex justify-center`;
                    messageDiv.innerHTML = `
                        <div class="text-sm ${additionalClasses} px-4 py-2 text-center">
                            <p>${text}</p>
                        </div>
                    `;
                }
                
                messageContainer.appendChild(messageDiv);
                messageContainer.scrollTop = messageContainer.scrollHeight;
            }

            // Show typing indicator
            function showTypingIndicator() {
                typingIndicator.classList.remove('hidden');
                setTimeout(() => {
                    typingIndicator.classList.add('hidden');
                }, TYPING_INTERVAL);
            }
            
            // Format file size
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
            
            // Send file to peer
            async function sendFile(file) {
                if (!conn || !conn.open || !dataConnection || !dataConnection.open) {
                    alert('Not connected to another Ghost');
                    return;
                }
                
                if (file.size > MAX_FILE_SIZE) {
                    alert(`File too large. Maximum size is ${formatFileSize(MAX_FILE_SIZE)}`);
                    return;
                }
                
                // Show sending message
                addMessage('local', `Sending file: ${file.name} (${formatFileSize(file.size)})`, 'bg-purple-600');
                
                // Notify peer about incoming file
                conn.send({
                    type: 'file-meta',
                    name: file.name,
                    size: file.size,
                    type: file.type
                });
                
                // Show progress bar
                uploadProgress.classList.remove('hidden');
                progressFill.style.width = '0%';
                uploadPercentage.textContent = '0%';
                
                // Read file as array buffer
                const reader = new FileReader();
                reader.onload = async (event) => {
                    const arrayBuffer = event.target.result;
                    
                    // First send metadata
                    const meta = {
                        name: file.name,
                        size: file.size,
                        type: file.type
                    };
                    const metaString = JSON.stringify(meta);
                    const encoder = new TextEncoder();
                    const metaData = encoder.encode(metaString);
                    dataConnection.send(metaData);
                    
                    // Then send file in chunks
                    const CHUNK_SIZE = 16 * 1024; // 16KB chunks
                    const totalChunks = Math.ceil(arrayBuffer.byteLength / CHUNK_SIZE);
                    
                    for (let i = 0; i < totalChunks; i++) {
                        const start = i * CHUNK_SIZE;
                        const end = Math.min(start + CHUNK_SIZE, arrayBuffer.byteLength);
                        const chunk = arrayBuffer.slice(start, end);
                        
                        dataConnection.send(chunk);
                        
                        // Update progress
                        const progress = Math.round(((i + 1) / totalChunks) * 100);
                        progressFill.style.width = `${progress}%`;
                        uploadPercentage.textContent = `${progress}%`;
                        
                        // Small delay between chunks to prevent overwhelming the connection
                        await new Promise(resolve => setTimeout(resolve, 10));
                    }
                    
                    // Hide progress bar after a short delay
                    setTimeout(() => {
                        uploadProgress.classList.add('hidden');
                    }, 1000);
                };
                
                reader.readAsArrayBuffer(file);
            }

            // Event Listeners
            connectBtn.addEventListener('click', () => {
                const peerId = peerIdInput.value.trim();
                if (!peerId) {
                    alert('Please enter a Ghost ID to connect');
                    return;
                }
                
                if (conn && conn.open) {
                    alert('Already connected to a Ghost');
                    return;
                }
                
                const connection = peer.connect(peerId, {
                    reliable: true,
                    serialization: 'json'
                });
                
                setupConnection(connection);
            });

            disconnectBtn.addEventListener('click', () => {
                if (conn) {
                    conn.close();
                    handleDisconnection();
                }
            });

            messageInput.addEventListener('keyup', (e) => {
                // Send typing indicator
                const now = Date.now();
                if (now - lastTypingTime > TYPING_INTERVAL) {
                    if (conn && conn.open && messageInput.value) {
                        conn.send({ type: 'typing' });
                        lastTypingTime = now;
                    }
                }
                
                // Send message on Enter
                if (e.key === 'Enter' && messageInput.value.trim()) {
                    sendMessage();
                }
            });

            sendBtn.addEventListener('click', () => {
                if (messageInput.value.trim()) {
                    sendMessage();
                }
            });

            copyIdBtn.addEventListener('click', () => {
                yourIdInput.select();
                document.execCommand('copy');
                
                // Show copied tooltip
                const originalText = copyIdBtn.innerHTML;
                copyIdBtn.innerHTML = '<i class="fas fa-check"></i>';
                setTimeout(() => {
                    copyIdBtn.innerHTML = originalText;
                }, 2000);
            });
            
            // File input handling
            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    sendFile(e.target.files[0]);
                    fileInput.value = ''; // Reset input
                }
            });
            
            // Drag and drop handling
            fileDropzone.addEventListener('dragover', (e) => {
                e.preventDefault();
                fileDropzone.classList.add('active');
            });
            
            fileDropzone.addEventListener('dragleave', (e) => {
                e.preventDefault();
                fileDropzone.classList.remove('active');
            });
            
            fileDropzone.addEventListener('drop', (e) => {
                e.preventDefault();
                fileDropzone.classList.remove('active');
                
                if (e.dataTransfer.files.length > 0) {
                    sendFile(e.dataTransfer.files[0]);
                }
            });
            
            // Click on dropzone to open file dialog
            fileDropzone.addEventListener('click', () => {
                fileInput.click();
            });

            // Send message function
            function sendMessage() {
                const text = messageInput.value.trim();
                if (!text || !conn || !conn.open) return;
                
                conn.send({ type: 'message', text });
                addMessage('local', text);
                messageInput.value = '';
                messageInput.focus();
            }

            // Initialize the app
            initializePeer();
        });
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=stanx974/ghostchat" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>