<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/peerjs@1.5.4/dist/peerjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.0/qrious.min.js"></script>
    <style>
        #drop-zone {
            width: 98vw;
            height: 200px;
            border: 2px dashed #cccccc;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #cccccc;
            font-size: 1.5em;
            margin: 10px 0;
            cursor: pointer;
        }

        #drop-zone.dragover {
            border-color: #00bfff;
            color: #00bfff;
        }

        #qr-code {
            margin-top: 20px;
        }

        #progress-container {
            margin-top: 20px;
            width: 100%;
        }

        #progress-bar {
            width: 0;
            height: 20px;
            background-color: #00bfff;
            transition: width 0.3s;
        }
    </style>
</head>

<body>
    <div id="progress-container" style="display: none;">
        <div id="progress-bar"></div>
    </div>
    <div id="drop-zone">Drop your file here or click to select a file</div>
    <div id="status"></div>
    <a href="#" id="share-link"></a>
    <button id="copy-share-link" style="display: none;" onclick="copyShareURL()">Copy Share Link</button>
    <br>
    <!-- <canvas id="qr-code"></canvas> -->
    <input type="file" id="file-input" style="display: none;">
    <script>
        const peer = new Peer();
        const dropZone = document.getElementById('drop-zone');
        const status = document.getElementById('status');
        const shareLink = document.getElementById('share-link');
        const copyShareLinkButton = document.getElementById('copy-share-link');
        // const qrCodeCanvas = document.getElementById('qr-code');
        const progressContainer = document.getElementById('progress-container');
        const progressBar = document.getElementById('progress-bar');
        const fileInput = document.getElementById('file-input');
        const CHUNK_SIZE = 64 * 1024; // 64 KB chunks
        let fileData = null, fileName = null, conn = null;

        // Show peer ID
        peer.on('open', (id) => {
            // status.innerText = 'Waiting for file...';
        });

        // Handle drag and drop
        dropZone.addEventListener('dragover', (event) => {
            event.preventDefault();
            dropZone.classList.add('dragover');
        });

        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('dragover');
        });

        dropZone.addEventListener('drop', (event) => {
            event.preventDefault();
            dropZone.classList.remove('dragover');
            const file = event.dataTransfer.files[0];
            handleFile(file);
        });

        dropZone.addEventListener('click', () => {
            fileInput.click();
        });

        fileInput.addEventListener('change', (event) => {
            const file = event.target.files[0];
            handleFile(file);
        });

        function handleFile(file) {
            if (file) {
                status.innerText = file.name;
                const reader = new FileReader();
                reader.onload = function () {
                    fileData = reader.result;
                    fileName = file.name;

                    const fileKey = peer.id;
                    const url = `${window.location.href}r.html?fileKey=${fileKey}`;
                    // shareLink.innerText = url;
                    // shareLink.setAttribute('href', url);
                    copyShareLinkButton.style.display = 'block'
                    copyShareLinkButton.setAttribute('title', url)
                    shareURL = url;

                    // const qr = new QRious({
                    //     element: qrCodeCanvas,
                    //     value: url,
                    //     size: 200
                    // });


                    peer.on('connection', (c) => {
                        conn = c;
                        // status.innerText = 'Recipient connected. Waiting for file request...';

                        conn.on('open', () => {
                            conn.on('data', (request) => {
                                if (request === 'request-file') {
                                    sendFileInChunks();
                                }
                            });
                        });
                    });
                };
                reader.readAsArrayBuffer(file);
            }
        }

        function sendFileInChunks() {
            const totalChunks = Math.ceil(fileData.byteLength / CHUNK_SIZE);
            let currentChunk = 0;

            progressContainer.style.display = 'block';

            const sendNextChunk = () => {
                if (currentChunk < totalChunks) {
                    const start = currentChunk * CHUNK_SIZE;
                    const end = Math.min(start + CHUNK_SIZE, fileData.byteLength);
                    const chunk = fileData.slice(start, end);

                    conn.send({
                        chunk,
                        currentChunk,
                        totalChunks,
                        fileName
                    });

                    // status.innerText = `Sending chunk ${currentChunk + 1} of ${totalChunks}`;
                } else {
                    status.innerText = 'File transfer complete!';
                }
            };

            conn.on('data', (ack) => {
                if (ack === 'ack') {
                    currentChunk++;
                    const progress = (currentChunk / totalChunks) * 100;
                    progressBar.style.width = progress + '%';

                    if (currentChunk < totalChunks) {
                        sendNextChunk();
                    }
                }
            });

            sendNextChunk();
        }
    </script>
    <script>
        let shareURL = ''

        function copyShareURL() {
            copyToClipboard(shareURL)
        }
        function copyToClipboard(text) {
            if (navigator.clipboard && window.isSecureContext) {
                // Modern approach for secure contexts (HTTPS)
                navigator.clipboard.writeText(text)
                    .then(() => {
                        copyShareLinkButton.innerText = 'Copied'
                        // Success!
                        console.log("Text copied to clipboard");
                        // Optional: Provide user feedback (e.g., a toast message)
                        // alert("Text copied to clipboard!"); // Simple alert
                    })
                    .catch(err => {
                        console.error("Failed to copy: ", err);
                        // Fallback to the older method if modern API fails
                        fallbackCopyTextToClipboard(text);
                    });
            } else {
                // Older approach for insecure contexts or browsers that don't support the Clipboard API
                fallbackCopyTextToClipboard(text);
            }
        }

        function fallbackCopyTextToClipboard(text) {
            var textArea = document.createElement("textarea");
            textArea.value = text;

            // Avoid scrolling to bottom
            textArea.style.top = "0";
            textArea.style.left = "0";
            textArea.style.position = "fixed";

            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                var successful = document.execCommand('copy');
                var msg = successful ? 'successful' : 'unsuccessful';
                console.log('Fallback: Copying text command was ' + msg);
                if (successful) {
                    // alert("Text copied to clipboard!"); // Simple alert
                } else {
                    alert("Copying text failed. Please copy manually.");
                }
            } catch (err) {
                console.error('Fallback: Oops, unable to copy', err);
                alert("Copying text failed. Please copy manually.");
            }

            document.body.removeChild(textArea);
        }
    </script>
</body>

</html>