{% extends "templates/home.html" %}
{% from "_macros.html" import swan_loader with context %}
{% if announcement_home is string %}
  {% set announcement = announcement_home %}
{% endif %}

{% block main %}
  <main class="container align-items-center">
    <div id="welcome" class="hidden text-center">
      <img src="{{ static_url('swan/logos/' + swan_logo_filename) }}" alt="SWAN Logo" class="mb-3" style="max-width: 150px; height: auto;">
      <h1 class="display-6 fw-light text-primary mb-1">Welcome to SWAN</h1>
      <p class="lead text-body-secondary mb-4">Your gateway to interactive analysis</p>

      <a href="{{ base_url }}spawn" class="btn btn-primary btn-lg px-4 mb-5">
        <i class="fa fa-rocket me-2"></i>Start new session
      </a>

      <div class="d-flex justify-content-center gap-3">
        <a href="https://swan.docs.cern.ch/" class="btn btn-outline-secondary">
          <i class="fa fa-book me-1"></i>Documentation
        </a>
        <a href="https://swan-gallery.web.cern.ch/" class="btn btn-outline-secondary">
          <i class="fa fa-th me-1"></i>Examples
        </a>
      </div>
    </div>

    {% call swan_loader(visible=false) %}
      <div>
        <h4 id="shutting-down">Stopping your session...</h4>
        <h4 id="shutdown-failed" class="hidden text-danger">
          There was an error stopping your session. Try again later.
        </h4>
      </div>
    {% endcall %}
  </main>
{% endblock %}

{% block script %}
{{ super() }}

<script type="text/javascript">
  require(['jhapi'], function (JHAPI) {
    const urlParams = new URLSearchParams(window.location.search);
    const welcome = document.getElementById('welcome');
    const loader = document.getElementById('swan-loader');
    const shuttingDownMsg = document.getElementById('shutting-down');
    const shutdownFailedMsg = document.getElementById('shutdown-failed');

    if (urlParams.has('changeconfig')) {
      urlParams.delete('changeconfig');
      // Show the loading spinner
      loader.classList.add('d-flex');
      loader.classList.remove('d-none');

      const base_url = window.jhdata.base_url;
      const user = window.jhdata.user;
      const api = new JHAPI(base_url);

      api.stop_server(user, {
        success: () => {
          window.location.replace(`{{base_url}}spawn?${urlParams}`);
        },
        error: () => {
          // Show the error message and stop the loading animation
          loader.classList.add('loader-error');
          shuttingDownMsg.classList.add('hidden');
          shutdownFailedMsg.classList.remove('hidden');
        }
      });
    } else {
      welcome.classList.remove('hidden');
    }
  });
</script>
{% endblock %}
