{% extends 'otree/Base_UserFacing.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;
        }

        #seconds-until-marked-inactive {
            font-weight: bold;
            color: #dc3545;
        }
    </style>
{% endblock %}

{% 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?"|gettext }}</p>
                <p id="msg-act-within-n-seconds"></p>
                {% comment %}Translators: button the user presses to confirm that they are still active{% endcomment %}
                <button onclick="confirmActive()">{{ "I'm still active"|gettext }}</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>
</div>
{% endblock %}

{% block live %}
  {% if has_live_method %}
    <form id="liveform"></form>
    <script src="{% static 'otree/js/live.js' %}" id="otree-live" data-socket-url="{{ view.live_url() }}"></script>
  {% endif %}
{% endblock %}


{% block debug_info %}
    {% if is_defined('view.is_debug') and view.is_debug %}
        <br>
        {% include 'otree/includes/debug_info.html' %}
    {% endif %}
{% 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">

$(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();

        };
    }

 });
 </script>
 {% if view.preserve_unsubmitted_inputs %}
  <script src="{% static 'otree/js/preserve_unsubmitted_inputs.js' %}"></script>
 {% endif %}

{% if is_defined('view.group_by_arrival_time') and view.group_by_arrival_time %}
<script>
    {% 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 GBAT_INACTIVE_SECONDS_UNTIL_PROMPT_MSEC = {{ GBAT_INACTIVE_SECONDS_UNTIL_PROMPT }} * 1000;
    var GBAT_INACTIVE_SECONDS_TO_CONFIRM_MSEC = {{ GBAT_INACTIVE_SECONDS_TO_CONFIRM }} * 1000;

    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 actWithinNSecondsSpan = document.getElementById('msg-act-within-n-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--;
        let secondsLeftSpan = `<span id="seconds-until-marked-inactive">${secondsLeft}</span>`;
        actWithinNSecondsSpan.innerHTML = `{{ 'Click the below button within ${secondsLeftSpan} seconds.'|gettext }}`;

        // Update tab title with countdown
        var minutes = Math.floor(secondsLeft / 60);
        var seconds = secondsLeft % 60;
        let maybeLeadingZero = seconds < 10 ? '0' : '';
        // translators: when a wait page detects that a user is inactive, the page tab alerts them to click a button to show they are active.
        let msgPleaseConfirm = '{{"Please confirm"|gettext}}';
        titleElement.textContent = `(${minutes}:${maybeLeadingZero}${seconds}) ${msgPleaseConfirm}`;

        // 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_SECONDS_UNTIL_PROMPT_MSEC);

      // Store the timer start time in localStorage
      var timerData = {
        startTime: Date.now(),
        timeout: GBAT_INACTIVE_SECONDS_UNTIL_PROMPT_MSEC
      };
      localStorage.setItem(storageKey, JSON.stringify(timerData));
    }

    function showInactivityModal() {
      var secondsLeft = GBAT_INACTIVE_SECONDS_TO_CONFIRM_MSEC / 1000;

      overlay.style.display = 'block';
      modal.style.display = 'block';

      // Store modal state in localStorage
      var modalData = {
        showTime: Date.now(),
        timeout: GBAT_INACTIVE_SECONDS_TO_CONFIRM_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);

          // 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();
    }

    function startInactivityTimerOrConfirmActive() {
      if (modal.style.display === 'block') {
        confirmActive();
      } else {
        startInactivityTimer();
      }
    }

    // Reset timer on user activity
    document.addEventListener('mousemove', startInactivityTimerOrConfirmActive);
    window.addEventListener('focus', startInactivityTimerOrConfirmActive);

</script>
{% endif %}
{% endblock %}