@page "{Transaction_UID}"
@using System.Text.Json
@model EnotaryoPH.Web.Pages.Participant.VideoCall.RoomModel
@{
}

@section Head {
    <style>
        .video-container {
            position: relative;
            padding-bottom: 56.25%; /* 16:9 aspect ratio */
            background: #000;
            border: 2px solid #444;

            width: 100%;
            overflow: hidden;
        }

        .video-container video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover; /* This will maintain the video's original aspect ratio and crop if necessary */
        }

        .video-element {
            position: absolute;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .participant-name {
            position: absolute;
            bottom: 10px;
            left: 10px;
            color: white;
            background: rgba(0,0,0,0.5);
            padding: 2px 8px;
            border-radius: 4px;
            z-index: 1;
        }

        .controls {
            position: fixed;
            bottom: 20px;
            left: 50%;
            /* transform: translateX(-50%); */
            background: rgba(0,0,0,0.8);
            padding: 10px;
            border-radius: 20px;
        }

        .participant-col {
            transition: all 0.3s ease;

            display:flex;
            justify-content: center;
            align-items: center;
        }
    </style>
}

<div class="container-fluid py-3" id="videoGrid-container">
    <div class="row g-2" id="videoGrid">
    </div>
</div>

<template id="templateVideo">
    <div class="video-container bg-light">
        <div class="participant-name">Participant Name</div>
    </div>
</template>

<input type="hidden" value="@JsonSerializer.Serialize(Model.Participants)" />

@section Scripts {
    <script type="text/javascript" src="~/dist/jfa.js"></script>
    <script>

        let participants = JSON.parse('@Html.Raw(JsonSerializer.Serialize(Model.Participants))');
        function updateGrid() {
            const videoGrid = document.getElementById('videoGrid');
            videoGrid.innerHTML = '';

            participants.forEach((participant, index) => {
                const col = document.createElement('div');
                col.className = 'participant-col';
                var tmpl = document.getElementById("templateVideo").cloneNode(true).content;
                let vidcontainer = tmpl.querySelector(".video-container")
                if (vidcontainer) {
                    vidcontainer.id = participant.Id;
                    vidcontainer.classList.add(participant.Id);
                    vidcontainer.classList.add(participant.Type == 'Notary' ? 'local-video-container' : 'remote-video-container');
                }
                let participantName = tmpl.querySelector(".participant-name")
                if (participantName) {
                    participantName.textContent = participant.DisplayName;
                }
                col.appendChild(tmpl);
                videoGrid.appendChild(col);
            });

            // Dynamically adjust grid columns based on participant count
            const count = participants.length;
            const cols = count <= 2 ? 'col-12 col-sm-12 offset-md-1 col-md-10 offset-lg-0 col-lg-6' :
                        count <= 4 ? 'col-6 col-sm-6 col-md-6 col-lg-6 col-xl-6' :
                        count <= 8 ? 'col-6 col-md-6 col-lg-4 col-xl-4' :
                        count <= 9 ? 'col-4' :
                        'col-6 col-sm-4 col-lg-3';

            document.querySelectorAll('.participant-col').forEach(el => {
                el.className = `participant-col ${cols}`;
            });

            const fluid = count <= 2 ? 'container-fluid' :
                count <= 8 ? 'container-xxl' :
                'container-xl'
            document.getElementById('videoGrid-container').className = `${fluid} py-3`;
        }

        async function initVideoCall() {
            let userAccessToken = '@Model.CommunicationUserToken';
            const videoCall = jfa.communication.videocall;
            let options = {
                onCreateLocalVideoStream: function(el) {
                    if (el) {
                        el.style['transform'] = '';
                        let notary = participants.find(p => p.RoomUserID == '@Model.CommunicationUserId');
                        document.getElementById(notary.Id).appendChild(el);
                    }
                },
                remoteVideoIsAvailableChanged: function(e) {
                    let participant = participants.find(p => p.RoomUserID == e.participantId);
                    if (participant) {
                        e.el.querySelector('video').style['object-fit'] = 'cover';
                        document.getElementById(participant.Id).appendChild(e.el);
                    }
                }
            }
            await videoCall.init(userAccessToken, options);
            videoCall.joinRoom('@Model.CommunicationRoomId');
        }

        if (document.readyState !== 'loading') {
            init();
        } else {
            document.addEventListener('DOMContentLoaded', init);
        }

        async function init() {
            updateGrid();
            window.addEventListener('resize', updateGrid);

            await initVideoCall();
        }
    </script>
}
