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

{% block internal_scripts %}
{{ super() }}

<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 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_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';
      secondsSpan.textContent = secondsLeft;

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

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

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


</script>
{% endblock %}