{% extends "base.html" %}
{% load i18n %}

{% block title %}Chat with {{ other_user.username }} - RaktaPulse{% endblock %}

{% block head %}
<style>
    .chat-container {
        height: calc(100vh - 250px);
        display: flex;
        flex-direction: column;
    }
    .chat-messages {
        flex-grow: 1;
        overflow-y: auto;
        padding: 20px;
        background: #f8f9fa;
        border-radius: 12px;
        margin-bottom: 20px;
        display: flex;
        flex-direction: column;
        gap: 15px;
    }
    .message {
        max-width: 75%;
        padding: 12px 16px;
        border-radius: 16px;
        position: relative;
        font-size: 0.95rem;
        line-height: 1.4;
    }
    .message-sent {
        align-self: flex-end;
        background-color: var(--pulse-red);
        color: white;
        border-bottom-right-radius: 4px;
    }
    .message-received {
        align-self: flex-start;
        background-color: white;
        color: var(--text-primary);
        border-bottom-left-radius: 4px;
        border: 1px solid var(--border-color);
    }
    .message-time {
        font-size: 0.7rem;
        opacity: 0.7;
        margin-top: 4px;
        display: block;
    }
    #videoGrid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 10px;
        background: #000;
        border-radius: 12px;
        overflow: hidden;
        position: relative;
    }
    .video-wrapper {
        position: relative;
        aspect-ratio: 4/3;
        background: #222;
    }
    video {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    .video-label {
        position: absolute;
        bottom: 10px;
        left: 10px;
        background: rgba(0,0,0,0.5);
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 0.8rem;
    }
    .call-controls {
        display: flex;
        justify-content: center;
        gap: 15px;
        padding: 15px;
        background: rgba(0,0,0,0.8);
        border-bottom-left-radius: 12px;
        border-bottom-right-radius: 12px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="glass-card chat-container">
        <div class="d-flex align-items-center gap-3 pb-3 mb-3 border-bottom">
            <a href="{% url 'inbox' %}" class="btn btn-link text-secondary p-0">
                <i class="bi bi-arrow-left fs-4"></i>
            </a>
            <div class="rounded-circle overflow-hidden border border-danger-subtle" style="width: 45px; height: 45px;">
                {% if other_user.profile.profile_pic %}
                    <img src="{{ other_user.profile.profile_pic.url }}" alt="{{ other_user.username }}" class="w-100 h-100 object-fit-cover">
                {% else %}
                    <div class="bg-danger bg-opacity-10 w-100 h-100 d-flex align-items-center justify-content-center">
                        <i class="bi bi-person-fill text-danger"></i>
                    </div>
                {% endif %}
            </div>
            <div>
                <h6 class="fw-bold mb-0">
                    <a href="{% url 'public_profile' other_user.username %}" class="text-decoration-none text-dark">
                        {{ other_user.first_name }} {{ other_user.last_name|default:other_user.username }}
                    </a>
                </h6>
                <small class="text-success d-flex align-items-center gap-1">
                    <span class="rounded-circle bg-success" style="width: 8px; height: 8px;"></span> Online
                </small>
            </div>
            <div class="ms-auto d-flex gap-2 align-items-center">
                <button id="startAudioCall" class="btn btn-outline-secondary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;" title="Audio Call">
                    <i class="bi bi-telephone-fill"></i>
                </button>
                <button id="startVideoCall" class="btn btn-outline-danger rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;" title="Video Call">
                    <i class="bi bi-camera-video-fill"></i>
                </button>
                <div class="dropdown">
                    <button class="btn btn-link text-secondary p-0" data-bs-toggle="dropdown">
                        <i class="bi bi-three-dots-vertical fs-5"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end shadow border-0">
                        <li>
                            <form action="{% url 'delete_messages' other_user.username %}" method="POST" onsubmit="return confirm('Are you sure you want to delete all messages in this conversation?');">
                                {% csrf_token %}
                                <button type="submit" class="dropdown-item text-danger d-flex align-items-center gap-2">
                                    <i class="bi bi-trash"></i> Delete Conversation
                                </button>
                            </form>
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="chat-messages" id="chatMessages">
            {% for msg in chat_messages %}
                <div class="message {% if msg.sender == user %}message-sent{% else %}message-received{% endif %}">
                    {% if msg.message_type == 'text' %}
                        {{ msg.content }}
                    {% elif msg.message_type == 'image' %}
                        <img src="{{ msg.attachment.url }}" class="img-fluid rounded-3 mb-2" style="max-height: 300px; cursor: pointer;" onclick="window.open(this.src)">
                        {% if msg.content %}<p class="mb-0">{{ msg.content }}</p>{% endif %}
                    {% elif msg.message_type == 'video' %}
                        <video src="{{ msg.attachment.url }}" controls class="rounded-3 mb-2 w-100" style="max-height: 300px;"></video>
                        {% if msg.content %}<p class="mb-0">{{ msg.content }}</p>{% endif %}
                    {% elif msg.message_type == 'file' %}
                        <div class="d-flex align-items-center gap-2 p-2 bg-black bg-opacity-10 rounded-3">
                            <i class="bi bi-file-earmark-arrow-down-fill fs-4"></i>
                            <div class="overflow-hidden">
                                <a href="{{ msg.attachment.url }}" target="_blank" class="text-reset text-decoration-none d-block text-truncate small fw-bold">
                                    {{ msg.attachment.name|cut:"chat_attachments/" }}
                                </a>
                                <small class="opacity-75">{{ msg.attachment.size|filesizeformat }}</small>
                            </div>
                        </div>
                        {% if msg.content %}<p class="mt-2 mb-0">{{ msg.content }}</p>{% endif %}
                    {% elif msg.message_type == 'sticker' %}
                        <div class="display-4">{{ msg.sticker_id }}</div>
                    {% endif %}
                    <span class="message-time {% if msg.sender == user %}text-white-50{% else %}text-secondary{% endif %}">
                        {{ msg.timestamp|date:"g:i a" }}
                    </span>
                </div>
            {% empty %}
                <div class="text-center my-auto text-secondary">
                    <p class="mb-0">No messages yet. Say hi!</p>
                </div>
            {% endfor %}
        </div>

        <form method="post" enctype="multipart/form-data" class="d-flex flex-column gap-2" id="messageForm">
            {% csrf_token %}
            <div id="attachmentPreview" class="p-2 border rounded-3 bg-light d-none align-items-center gap-2">
                <div id="previewContent" class="flex-grow-1 small text-truncate"></div>
                <button type="button" class="btn btn-sm btn-outline-danger border-0 rounded-circle" onclick="clearAttachment()">
                    <i class="bi bi-x"></i>
                </button>
            </div>
            
            <div class="d-flex gap-2 align-items-center">
                <div class="dropdown">
                    <button type="button" class="btn btn-outline-secondary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-plus-lg"></i>
                    </button>
                    <ul class="dropdown-menu shadow border-0 p-2">
                        <li><a class="dropdown-item rounded-2 d-flex align-items-center gap-2" href="#" onclick="document.getElementById('fileInput').click()">
                            <i class="bi bi-file-earmark-plus text-primary"></i> Document
                        </a></li>
                        <li><a class="dropdown-item rounded-2 d-flex align-items-center gap-2" href="#" onclick="openCamera()">
                            <i class="bi bi-camera text-danger"></i> Camera
                        </a></li>
                        <li><a class="dropdown-item rounded-2 d-flex align-items-center gap-2" href="#" onclick="document.getElementById('fileInput').setAttribute('accept', 'image/*,video/*'); document.getElementById('fileInput').click()">
                            <i class="bi bi-images text-success"></i> Photos & Videos
                        </a></li>
                    </ul>
                </div>

                <button type="button" class="btn btn-outline-secondary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-emoji-smile"></i>
                </button>
                <div class="dropdown-menu p-3 shadow border-0" style="width: 300px;">
                    <h6 class="dropdown-header px-0 mb-2">Select Sticker</h6>
                    <div class="d-grid gap-2 text-center" id="stickerGrid" style="grid-template-columns: repeat(4, 1fr);">
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('🩸')">🩸</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('💉')">💉</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('❤️')">❤️</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('🩹')">🩹</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('🩺')">🩺</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('🏥')">🏥</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('🚑')">🚑</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('🆘')">🆘</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('⭐')">⭐</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('🏆')">🏆</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('🙌')">🙌</div>
                        <div class="fs-2 p-2 sticker-item" style="cursor: pointer;" onclick="sendSticker('🙏')">🙏</div>
                    </div>
                </div>

                <input type="text" name="content" id="messageInput" class="form-control rounded-pill px-4" placeholder="Type your message..." autocomplete="off">
                <input type="file" name="attachment" id="fileInput" class="d-none" onchange="handleFileSelect(this)">
                <input type="hidden" name="sticker_id" id="stickerInput">
                
                <button type="submit" class="btn btn-danger rounded-circle d-flex align-items-center justify-content-center" style="width: 45px; height: 45px;">
                    <i class="bi bi-send-fill"></i>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Camera Modal -->
<div class="modal fade" id="cameraModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-0 overflow-hidden">
            <div class="modal-body p-0 position-relative">
                <video id="cameraVideo" autoplay playsinline class="w-100 bg-black"></video>
                <canvas id="cameraCanvas" class="d-none"></canvas>
                <div class="position-absolute bottom-0 start-0 end-0 p-4 d-flex justify-content-center gap-3">
                    <button type="button" class="btn btn-light rounded-circle p-3 shadow" onclick="capturePhoto()">
                        <i class="bi bi-camera-fill fs-4"></i>
                    </button>
                    <button type="button" class="btn btn-outline-light rounded-circle p-3" data-bs-dismiss="modal">
                        <i class="bi bi-x-lg"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Call Modal -->
<div class="modal fade" id="callModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content bg-dark border-0 overflow-hidden rounded-4">
            <div class="modal-body p-0">
                <div id="videoGrid">
                    <div class="video-wrapper" id="localVideoWrapper">
                        <video id="localVideo" autoplay muted playsinline></video>
                        <div class="video-label">{% trans "You" %}</div>
                    </div>
                    <div class="video-wrapper" id="remoteVideoWrapper" style="display: none;">
                        <video id="remoteVideo" autoplay playsinline></video>
                        <div class="video-label" id="remoteLabel">{{ other_user.username }}</div>
                    </div>
                </div>
                <div class="call-controls">
                    <div id="callStatus" class="position-absolute top-0 start-50 translate-middle-x mt-3 text-white-50 small">Connecting...</div>
                    <button id="toggleMic" class="btn btn-outline-light rounded-circle d-flex align-items-center justify-content-center" style="width: 45px; height: 45px;"><i class="bi bi-mic-fill"></i></button>
                    <button id="toggleVideo" class="btn btn-outline-light rounded-circle d-flex align-items-center justify-content-center" style="width: 45px; height: 45px;"><i class="bi bi-camera-video-fill"></i></button>
                    <button id="endCall" class="btn btn-danger rounded-pill px-4 fw-bold">{% trans "End Call" %}</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Audio Assets -->
<audio id="incomingRing" loop>
    <source src="https://assets.mixkit.co/active_storage/sfx/2358/2358-preview.mp3" type="audio/mpeg">
</audio>
<audio id="outgoingRing" loop>
    <source src="https://assets.mixkit.co/active_storage/sfx/1359/1359-preview.mp3" type="audio/mpeg">
</audio>

<!-- Incoming Call UI -->
<div id="incomingCallUI" class="position-fixed top-0 start-50 translate-middle-x mt-4 glass-card p-3 shadow-lg border-danger animate__animated animate__fadeInDown" style="display: none; z-index: 9999; min-width: 320px; border: 2px solid var(--pulse-red) !important;">
    <div class="d-flex align-items-center gap-3">
        <div class="bg-danger bg-opacity-10 p-2 rounded-circle">
            <i class="bi bi-telephone-inbound-fill text-danger fs-4"></i>
        </div>
        <div class="flex-grow-1">
            <h6 class="mb-0 fw-bold">{% trans "Incoming Call" %}</h6>
            <small class="text-secondary">{{ other_user.username }} {% trans "is calling..." %}</small>
        </div>
        <div class="d-flex gap-2">
            <button id="rejectCall" class="btn btn-light rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;"><i class="bi bi-x-lg"></i></button>
            <button id="acceptCall" class="btn btn-danger rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;"><i class="bi bi-check-lg"></i></button>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="https://unpkg.com/peerjs@1.5.2/dist/peerjs.min.js"></script>
<script>
    // Chat UI logic
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.scrollTop = chatMessages.scrollHeight;

    // Video/Audio Call Logic
    const MY_USERNAME = "{{ user.username }}";
    const OTHER_USERNAME = "{{ other_user.username }}";
    const PEER_ID_PREFIX = "raktapulse_";
    
    // Sanitize username for PeerJS ID (only alphanumeric, -, _)
    const sanitizeId = (id) => id.replace(/[^a-zA-Z0-9-_]/g, '_');
    
    // Initialize PeerJS with STUN servers for reliability
    let peer = new Peer(PEER_ID_PREFIX + sanitizeId(MY_USERNAME), {
        config: {
            'iceServers': [
                { url: 'stun:stun.l.google.com:19302' },
                { url: 'stun:stun1.l.google.com:19302' },
                { url: 'stun:stun2.l.google.com:19302' },
                { url: 'stun:stun3.l.google.com:19302' },
                { url: 'stun:stun4.l.google.com:19302' },
            ]
        },
        debug: 3
    });
    
    let localStream;
    let currentCall;

    // Helper to get local stream with fallback
    async function getLocalStream(videoRequested) {
        const constraints = {
            audio: true,
            video: videoRequested ? {
                width: { ideal: 640 },
                height: { ideal: 480 },
                facingMode: "user"
            } : false
        };

        try {
            console.log('Attempting to get media with constraints:', constraints);
            return await navigator.mediaDevices.getUserMedia(constraints);
        } catch (err) {
            console.warn('Initial media request failed, trying fallback...', err);
            
            if (videoRequested) {
                // If video failed, try audio only
                try {
                    console.log('Falling back to audio only...');
                    return await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
                } catch (audioErr) {
                    console.error('Audio fallback also failed', audioErr);
                    throw audioErr;
                }
            }
            throw err;
        }
    }
    
    const callModal = new bootstrap.Modal(document.getElementById('callModal'));
    const incomingCallUI = document.getElementById('incomingCallUI');
    const localVideo = document.getElementById('localVideo');
    const remoteVideo = document.getElementById('remoteVideo');
    const remoteVideoWrapper = document.getElementById('remoteVideoWrapper');
    const callStatus = document.getElementById('callStatus');
    const incomingRing = document.getElementById('incomingRing');
    const outgoingRing = document.getElementById('outgoingRing');
    
    function playRingtone(type) {
        if (type === 'incoming') incomingRing.play().catch(e => console.log('Audio blocked'));
        if (type === 'outgoing') outgoingRing.play().catch(e => console.log('Audio blocked'));
    }

    function stopRingtones() {
        incomingRing.pause();
        incomingRing.currentTime = 0;
        outgoingRing.pause();
        outgoingRing.currentTime = 0;
    }

    // Handle Peer Open
    peer.on('open', (id) => {
        console.log('My peer ID is: ' + id);
    });

    // Handle incoming calls
    peer.on('call', (call) => {
        console.log('Incoming call from: ' + call.peer);
        if (call.peer === PEER_ID_PREFIX + sanitizeId(OTHER_USERNAME)) {
            currentCall = call;
            incomingCallUI.style.display = 'block';
            playRingtone('incoming');
            
            setTimeout(() => {
                if (incomingCallUI.style.display === 'block') {
                    incomingCallUI.style.display = 'none';
                    stopRingtones();
                }
            }, 30000);
        }
    });

    // Start Call Function
    async function startCall(videoEnabled = true) {
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            alert('Your browser does not support video/audio calls or is not using a secure connection (HTTPS).');
            return;
        }

        try {
            callStatus.innerText = "Requesting permissions...";
            localStream = await getLocalStream(videoEnabled);
            
            localVideo.srcObject = localStream;
            callModal.show();
            callStatus.innerText = "Calling...";
            playRingtone('outgoing');
            
            const call = peer.call(PEER_ID_PREFIX + sanitizeId(OTHER_USERNAME), localStream);
            handleCall(call);
        } catch (err) {
            console.error('Failed to get local stream', err);
            let msg = 'Could not access camera or microphone. Please check your permissions and hardware.';
            if (err.name === 'NotAllowedError') msg = 'Permission denied. Please allow camera/microphone access in your browser settings.';
            if (err.name === 'NotFoundError') msg = 'No camera or microphone found on your device.';
            alert(msg);
        }
    }

    function handleCall(call) {
        currentCall = call;
        call.on('stream', (remoteStream) => {
            console.log('Received remote stream');
            stopRingtones();
            callStatus.innerText = "Connected";
            remoteVideo.srcObject = remoteStream;
            remoteVideoWrapper.style.display = 'block';
        });
        call.on('close', () => {
            endCall();
        });
        call.on('error', (err) => {
            console.error('Call error:', err);
            stopRingtones();
            endCall();
        });
    }

    // Button Listeners
    document.getElementById('startVideoCall').addEventListener('click', () => startCall(true));
    document.getElementById('startAudioCall').addEventListener('click', () => startCall(false));

    document.getElementById('acceptCall').addEventListener('click', async () => {
        incomingCallUI.style.display = 'none';
        stopRingtones();
        try {
            callStatus.innerText = "Answering...";
            // Try to get video if possible, but fallback to audio
            localStream = await getLocalStream(true);
            localVideo.srcObject = localStream;
            callModal.show();
            currentCall.answer(localStream);
            handleCall(currentCall);
        } catch (err) {
            console.error('Failed to get local stream', err);
            currentCall.close();
            alert('Could not access camera or microphone.');
        }
    });

    document.getElementById('rejectCall').addEventListener('click', () => {
        incomingCallUI.style.display = 'none';
        stopRingtones();
        if (currentCall) currentCall.close();
    });

    document.getElementById('endCall').addEventListener('click', () => {
        endCall();
    });

    function endCall() {
        stopRingtones();
        if (currentCall) currentCall.close();
        if (localStream) {
            localStream.getTracks().forEach(track => track.stop());
        }
        callModal.hide();
        remoteVideoWrapper.style.display = 'none';
        localVideo.srcObject = null;
        remoteVideo.srcObject = null;
    }

    // Toggle Mic/Video
    document.getElementById('toggleMic').addEventListener('click', function() {
        if (!localStream) return;
        const audioTrack = localStream.getAudioTracks()[0];
        if (audioTrack) {
            audioTrack.enabled = !audioTrack.enabled;
            this.innerHTML = audioTrack.enabled ? '<i class="bi bi-mic-fill"></i>' : '<i class="bi bi-mic-mute-fill"></i>';
            this.classList.toggle('btn-outline-light');
            this.classList.toggle('btn-danger');
        }
    });

    document.getElementById('toggleVideo').addEventListener('click', function() {
        if (!localStream) return;
        const videoTrack = localStream.getVideoTracks()[0];
        if (videoTrack) {
            videoTrack.enabled = !videoTrack.enabled;
            this.innerHTML = videoTrack.enabled ? '<i class="bi bi-camera-video-fill"></i>' : '<i class="bi bi-camera-video-off-fill"></i>';
            this.classList.toggle('btn-outline-light');
            this.classList.toggle('btn-danger');
        }
    });

    // Messaging Enhancements
    const attachmentPreview = document.getElementById('attachmentPreview');
    const previewContent = document.getElementById('previewContent');
    const cameraModal = new bootstrap.Modal(document.getElementById('cameraModal'));
    const cameraVideo = document.getElementById('cameraVideo');
    const cameraCanvas = document.getElementById('cameraCanvas');
    let cameraStream = null;

    window.handleFileSelect = function(input) {
        if (input.files && input.files[0]) {
            const file = input.files[0];
            previewContent.innerText = `Selected: ${file.name} (${(file.size / 1024).toFixed(1)} KB)`;
            attachmentPreview.classList.remove('d-none');
            attachmentPreview.classList.add('d-flex');
        }
    }

    window.clearAttachment = function() {
        document.getElementById('fileInput').value = '';
        attachmentPreview.classList.remove('d-flex');
        attachmentPreview.classList.add('d-none');
    }

    window.openCamera = async function() {
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            alert('Your browser does not support camera access or is not using HTTPS.');
            return;
        }

        try {
            cameraStream = await getLocalStream(true);
            cameraVideo.srcObject = cameraStream;
            cameraModal.show();
        } catch (err) {
            console.error('Camera error:', err);
            let msg = 'Could not access camera.';
            if (err.name === 'NotAllowedError') msg = 'Camera permission denied.';
            if (err.name === 'NotFoundError') msg = 'No camera found on your device.';
            alert(msg);
        }
    }

    document.getElementById('cameraModal').addEventListener('hidden.bs.modal', () => {
        if (cameraStream) {
            cameraStream.getTracks().forEach(track => track.stop());
            cameraStream = null;
        }
    });

    window.capturePhoto = function() {
        const context = cameraCanvas.getContext('2d');
        cameraCanvas.width = cameraVideo.videoWidth;
        cameraCanvas.height = cameraVideo.videoHeight;
        context.drawImage(cameraVideo, 0, 0);
        
        cameraCanvas.toBlob((blob) => {
            const file = new File([blob], "camera_capture.jpg", { type: "image/jpeg" });
            const dataTransfer = new DataTransfer();
            dataTransfer.items.add(file);
            document.getElementById('fileInput').files = dataTransfer.files;
            
            previewContent.innerText = "Captured photo ready to send";
            attachmentPreview.classList.remove('d-none');
            attachmentPreview.classList.add('d-flex');
            cameraModal.hide();
        }, 'image/jpeg');
    }

    window.sendSticker = function(sticker) {
        document.getElementById('stickerInput').value = sticker;
        document.getElementById('messageForm').submit();
    }

    // Handle cleanup on page unload
    window.addEventListener('beforeunload', () => {
        endCall();
        peer.destroy();
        if (cameraStream) {
            cameraStream.getTracks().forEach(track => track.stop());
        }
    });
</script>
{% endblock %}
