{% extends 'otree/Base.html' %}


{% block internal_styles %}
    {{ super() }}
    <style>
        body {
            background-color: #c0c0c0;
        }

        .card {
            background: white;
            border: 1px solid #3b84c3;
            border-radius: 5px;
            box-shadow: 0 0 20px #999;
            /*width: 940px; */
            margin: 22px auto;
        }

        .card-body {
            margin-top: 10px;
        }

        .page-header {
           border: 1px solid #c0c0c0;
        }

        .otree-wait-page {
            max-width:970px
        }

        .progress-bar {
            width: 100%;
        }

        #are-you-there {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            border: 2px solid #3b84c3;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 0 20px rgba(0,0,0,0.5);
            z-index: 1000;
            text-align: center;
            min-width: 300px;
        }

        #are-you-there p {
            margin-bottom: 15px;
            font-size: 16px;
        }

        #are-you-there button {
            background: #3b84c3;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }

        #are-you-there button:hover {
            background: #2a5a8a;
        }

        #are-you-there-seconds {
            font-weight: bold;
            color: #dc3545;
        }
    </style>
{% endblock %}
{% comment %}this template is used by rooms, where js_vars does not exist{% endcomment %}
{% block body_main %}{% if is_defined('js_vars') and js_vars %}<script>var js_vars = {{ js_vars }};</script>{% endif %}
<div class="otree-wait-page container">
    <div class="card">
        <h4 class="otree-wait-page__title card-header" id="_otree-title">
            {% block title %}{{ title_text }}{% endblock %}
        </h4>
        <div class="card-body">
            <div id="_otree-server-error" class="alert alert-danger" style="display:none">
                {{ "An error occurred."|gettext }}
            </div>
            <div id="inactivity-overlay" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 999;"></div>
            <div id="are-you-there" style="display: none">
                <p>Are you still there?</p>
                <p>Click the below button within <span id="are-you-there-seconds"></span> seconds.</p>
                <button onclick="confirmActive()">I'm still active</button>
            </div>    
            {% block content %}
            <p class="otree-wait-page__body">{{ body_text }}</p>
            {% endblock %}
            <div class="progress">
                <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"></div>
            </div>
        </div>
    </div>
    {% if is_defined('view.is_debug') and view.is_debug %}
        {% include 'otree/includes/debug_info.html' %}
    {% endif %}
</div>
{% endblock %}

{% block internal_scripts %}
    {{ super() }}
    <!-- this is an HTML file rather than JavaScript static file because context variables need to be passed to it -->
<script type="text/javascript">
    var GBAT_INACTIVE_INITIAL_TIMEOUT_MSEC = {{ GBAT_INACTIVE_INITIAL_TIMEOUT }} * 1000;
    var GBAT_INACTIVE_CONFIRMATION_TIMEOUT_MSEC = {{ GBAT_INACTIVE_CONFIRMATION_TIMEOUT }} * 1000;

$(document).ready(function () {

    var socket;

    initWebSocket();

    function initWebSocket() {
        socket = makeReconnectingWebSocket("{{ view.socket_url() }}");
        socket.onmessage = function(e) {
            var data = JSON.parse(e.data);

            // Handle errors
            if (data.error) {
                // maybe the div's default text doesn't get shown
                $("#_otree-server-error").text(data.error);
                $("#_otree-server-error").show();
                return;
            }

            window.location.reload();

        };
    }

    {% if is_defined('view.group_by_arrival_time') and view.group_by_arrival_time %}

        {% comment %}
        Refresh the whole page. This is documented behavior that enables things like
        allowing people to proceed if they have been waiting too long.
        We also make it random to prevent load times from syncing up
        due to reload mechanisms. This will ensure that the page gets
        reloaded regularly, which is useful e.g. for intergenerational
        games.
        {% endcomment %}

        var RELOAD_PARAM = "?reload=1";

        var SECOND = 1000;
        // the randomness is useful so that when there are many players,
        // the GBAT page loads get spaced apart. I think this helps wait pages
        // finish quicker, and may prevent some other bugs.
        window.setInterval(function () {
          window.location.href = window.location.pathname + RELOAD_PARAM;
        }, (10 + Math.random() * 60) * SECOND);



        // Inactivity detection
        var inactivityTimer;
        var inactivityCheckInterval;
        var countdownInterval;
        
        // Create a unique key for this specific wait page URL
        var currentUrl = window.location.pathname + window.location.search;
        var storageKey = 'inactivity_' + btoa(currentUrl).replace(/[^a-zA-Z0-9]/g, '');
        
        // Cache DOM elements
        var modal = document.getElementById('are-you-there');
        var overlay = document.getElementById('inactivity-overlay');
        var secondsSpan = document.getElementById('are-you-there-seconds');
        var titleElement = document.querySelector('title');
        const ORIGINAL_TITLE_TEXT = document.getElementById('_otree-title').textContent;
        
        // Helper functions
        function hideModal() {
            modal.style.display = 'none';
            overlay.style.display = 'none';
            clearInterval(countdownInterval);
            localStorage.removeItem(storageKey + '_modal');
            
            // Restore original title
            titleElement.textContent = ORIGINAL_TITLE_TEXT;
        }
        
        function redirectToInactive() {
            localStorage.removeItem(storageKey);
            localStorage.removeItem(storageKey + '_modal');
            var currentUrl = window.location.pathname + window.location.search;
            window.location.href = '/GBATInactive?return_url=' + encodeURIComponent(currentUrl);
        }
        
        function startCountdown(secondsLeft) {
            countdownInterval = setInterval(function() {
                secondsLeft--;
                secondsSpan.textContent = secondsLeft;
                
                // Update tab title with countdown
                var minutes = Math.floor(secondsLeft / 60);
                var seconds = secondsLeft % 60;
                var timeIndicator = '(' + minutes + ':' + (seconds < 10 ? '0' : '') + seconds + ') Please confirm';
                titleElement.textContent = timeIndicator;
                
                // Update localStorage with current countdown state
                var modalData = JSON.parse(localStorage.getItem(storageKey + '_modal') || '{}');
                modalData.secondsLeft = secondsLeft;
                localStorage.setItem(storageKey + '_modal', JSON.stringify(modalData));
                
                if (secondsLeft <= 0) {
                    clearInterval(countdownInterval);
                    redirectToInactive();
                }
            }, 1000);
        }
        
        function startInactivityTimer() {
            clearTimeout(inactivityTimer);
            inactivityTimer = setTimeout(showInactivityModal, GBAT_INACTIVE_INITIAL_TIMEOUT_MSEC);
            
            // Store the timer start time in localStorage
            var timerData = {
                startTime: Date.now(),
                timeout: GBAT_INACTIVE_INITIAL_TIMEOUT_MSEC
            };
            localStorage.setItem(storageKey, JSON.stringify(timerData));
        }
        
        function showInactivityModal() {
            var secondsLeft = GBAT_INACTIVE_CONFIRMATION_TIMEOUT_MSEC / 1000;
            
            overlay.style.display = 'block';
            modal.style.display = 'block';
            secondsSpan.textContent = secondsLeft;
                                    
            // Store modal state in localStorage
            var modalData = {
                showTime: Date.now(),
                timeout: GBAT_INACTIVE_CONFIRMATION_TIMEOUT_MSEC,
                isActive: true
            };
            localStorage.setItem(storageKey + '_modal', JSON.stringify(modalData));
            
            // Start countdown
            startCountdown(secondsLeft);
        }
        
        function confirmActive() {
            hideModal();
            startInactivityTimer(); // Reset timer for another minute
        }
        
        // Make confirmActive globally accessible
        window.confirmActive = confirmActive;
        
        // Check localStorage on page load to restore state
        function checkStoredState() {
            var storedTimer = localStorage.getItem(storageKey);
            var storedModal = localStorage.getItem(storageKey + '_modal');
            
            if (storedTimer) {
                var timerData = JSON.parse(storedTimer);
                var elapsed = Date.now() - timerData.startTime;
                var remaining = timerData.timeout - elapsed;
                
                if (remaining <= 0) {
                    // Timer has expired, show modal
                    showInactivityModal();
                } else {
                    // Timer is still running, restart it with remaining time
                    inactivityTimer = setTimeout(showInactivityModal, remaining);
                }
            }
            
            if (storedModal) {
                var modalData = JSON.parse(storedModal);
                var modalElapsed = Date.now() - modalData.showTime;
                var modalRemaining = modalData.timeout - modalElapsed;
                
                if (modalRemaining <= 0) {
                    // Modal timeout has expired, redirect
                    redirectToInactive();
                } else {
                    // Modal is still active, show it with remaining time
                    overlay.style.display = 'block';
                    modal.style.display = 'block';
                    var remainingSeconds = Math.ceil(modalRemaining / 1000);
                    secondsSpan.textContent = remainingSeconds;
                    
                    // Restart countdown
                    startCountdown(remainingSeconds);
                }
            }
        }
        
        // Check stored state first, then start new timer if needed
        checkStoredState();
        
        // Start inactivity timer (only if no stored state was found)
        if (!localStorage.getItem(storageKey) && !localStorage.getItem(storageKey + '_modal')) {
            startInactivityTimer();
        }

        // Reset timer on user activity
        document.addEventListener('mousemove', function(e) {
            // If modal is showing, confirm active instead of just resetting timer
            if (modal.style.display === 'block') {
                confirmActive();
            } else {
                startInactivityTimer();
            }
        });
        document.addEventListener('keypress', startInactivityTimer);
        document.addEventListener('click', function(e) {
            // Don't reset timer if clicking on the inactivity modal
            if (e.target.closest('#are-you-there')) {
                return;
            }
            startInactivityTimer();
        });


    {% endif %}


 });
 </script>
 {% endblock %}

