{% extends 'base.html' %}
{% load static %}
{% load i18n %}
{% load index %}
{% load dash_slash %}

{% get_current_language as LANGUAGE_CODE %}


{% block title %} {% trans 'AI-Powered Paper Summarization about the arXiv paper' %} {{ arxiv_id|dash_slash }} {% endblock %}
{% block extra_head_tags %}
  <meta name="description" content="{% trans 'Easy-to-read summary of the arXiv paper' %} {{ arxiv_id|dash_slash }} {% trans 'entitled ' %}{% if details %}{{ details.title }}{% else %}{{ paper.title }}{% endif %}" />
  <link rel="canonical" href="https://www.summarizepaper.com/{{LANGUAGE_CODE}}/arxiv-id/{{ arxiv_id }}/" />
  <script>
    MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']]
      },
      svg: {
        fontCache: 'global'
      }
    };
    </script>
    <script type="text/javascript" id="MathJax-script" async
      src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js">
    </script>

  <style>

.paper-container {
  background-color: #f2f2f2;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0px 0px 10px #ccc;
  margin-bottom: 20px;
}

.paper-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 20px;
}

.paper-details p {
  font-size: 18px;
  margin-bottom: 10px;
}

.paper-details strong {
  font-weight: bold;
}

.paper-details a {
  color: #337ab7;
  text-decoration: none;
}

.paper-summary,
.paper-notes,
.paper-lay-summary {
  padding: 20px;
  border: 1px solid #e5e5e5;
  margin-bottom: 20px;
}

.paper-summary h3,
.paper-notes h3,
.paper-lay-summary h3 {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
}

.paper-summary p,
.paper-notes p,
.paper-lay-summary p {
  font-size: 16px;
  line-height: 1.5;
  color: #333;
}

/*new*/

.main-content2 {
     padding: 16px;
   }

   .title {
     font-size: 2xl;
     font-weight: bold;
     font-family: sans-serif;
     margin-bottom: 12px;
   }

   .subtitle {
     font-size: 1xl;
     font-family: serif;
     margin-bottom: 18px;
   }

   .info-block {
     display: flex;
     align-items: center;
     margin-bottom: 6px;
   }

   .info-icon {
     width: 16px;
     height: 16px;
     margin-right: 6px;
   }

   .info-text {
     font-size: 14px;
     font-weight: normal;
     margin-right: 6px;
     flex-grow: 1;
     text-overflow: ellipsis;
     overflow: hidden;
   }

   @media (min-width: 768px) {
     .main-content2 {
       padding: 16px 32px;
     }

     .title {
       font-size: 4xl;
     }
     .message-tabs li {
       font-size: 24px!important;
     }
   }

   .message-box {
      background-color: #f2f2f2;
      padding: 20px;
      border-radius: 20px;
      box-shadow: 2px 2px 10px #ddd;
      margin: 20px 20px;
      text-align: left;
    }

    .message-title {
      font-size: 24px;
      font-weight: bold;
      margin: 0 0 20px 0;
    }

    .message-box p {
      font-size: 18px;
      margin: 0;
    }

    .message-tabs {
      display: flex;
      list-style: none;
      margin: 0;
      padding: 0;
      border-bottom: 1px solid #ddd;
    }

    .message-tabs li {
      flex: 1;
      text-align: center;
      padding: 20px 0;
      cursor: pointer;
      font-size: 13px;
    }

    .message-tabs .active {
      font-weight: bold;
      border-bottom: 2px solid #333;
    }

    .message-header {
      font-size: 36px;
      font-weight: bold;
      margin: 0 0 20px 0;
      text-align: center;
    }

    .message-content {
      margin-top: 20px;
    }

    .message-tab {
      /*padding: 20px;*/
      font-size:18px;
      text-align: justify;
    }

    input[type="submit"] {
      background-color: #4CAF50;
      color: white;
      padding: 12px 20px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      margin-top: 10px;
    }

    input[type="submit"]:hover {
      background-color: #3e8e41;
    }

    input[type='submit'] {
      padding: 10px 20px;
      font-size: 18px;
    }

  #progress-bar {
    max-width: 100%;
    height: 50px;
    border-radius: 25px;
    background-color: lightgrey;
    position: relative;
    margin: 10px auto;
  }

  #progress {
    height: 100%;
    background-color: green;
    border-radius: 25px;
    position: absolute;
    left: 0;
    top: 0;
    transition: width 0.5s ease-in-out;
  }

  #progress-text {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-size: 20px;
    font-weight: bold;
    color: white;
  }

  #loading-message {
    font-size: 20px;
    font-weight: bold;
    text-align: center;
    color:red;
    padding: 20px;
  }
 

 @media only screen and (max-width: 600px) {
   #progress-bar {
     height: 30px;
   }
   #progress-text {
     font-size: 16px;
   }
   input[type='submit'] {
      padding: 10px 20px;
      font-size: 14px;
    }
 }

 .center {
   display: flex;
   justify-content: center;
   align-items: center;
   height: 100%;
 }
 @keyframes blink {
    0% { opacity: 1; }
    50% { opacity: 0; }
    100% { opacity: 1; }
  }

  #popover {
    display: none;
    position: fixed;
    background-color: black;
    color: white;
    padding: 10px;
    z-index: 1;
    right: 20px;
  }
  #popover2 {
    display: none;
    position: fixed;
    background-color: black;
    color: white;
    padding: 10px;
    z-index: 1;
    right: 20px;
  }
  .small-button {
    width: 150px;
    height: 35px;
    background-color:grey!important;
    font-size: 14px!important; /* adjust the font size as needed */
  }

  .chatbot-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom:10px;
  margin-top:30px;
  width: 100%;
  height: 100%;
}



.chatbot-header {
  background-color: #f7f7f7;
  /*display: flex;*/
  text-align:center;
  /*justify-content: center;
  align-items: center;*/
  padding: 10px;
  border-bottom: 1px solid #ccc;
}

.chatbot-body {
  width: 700px;
  height: 400px;
  background-color: #fff;
  border: 1px solid #ccc;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  font-family: sans-serif;
}

.chatbot-body .chatbot-messages {
  height: 300px;
  overflow-y: auto;
  padding: 10px;
}

.chatbot-form {
  display: flex;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #ccc;
}

.chatbot-form input[type="text"] {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 5px;
}

.chatbot-form button {
  padding: 10px;
  border: none;
  border-radius: 5px;
  background-color: #4CAF50;
  color: #fff;
  cursor: pointer;
  margin-left: 10px;
}


.chatbot-body .chatbot-messages .chatbot-message {
    font-weight: bold;
    color: #000;
    margin-bottom: 5px;
    margin-top: 15px;
    margin-right: 10px;
    text-align: justify;
}

.chatbot-body .chatbot-messages .chatbot-response {
    color: #555;
    margin-left: 20px;
    margin-right: 10px;
    text-align: justify;
}

/* Small devices (phones, 576px and up) */
@media (min-width: 300px) {
  .chatbot-body {
    width: 100%;
    max-width: 300px;
    height: 100%;
    max-height: 400px;
  }
}

/* Small devices (phones, 576px and up) */
@media (min-width: 576px) {
  .chatbot-body {
    width: 100%;
    max-width: 400px;
    height: 100%;
    max-height: 400px;
  }
}

/* Medium devices (tablets, 768px and up) */
@media (min-width: 768px) {
  .chatbot-body {
    width: 100%;
    max-width: 500px;
    height: 100%;
    max-height: 400px;
  }
}

@media (min-width: 900px) {
  .chatbot-body {
    width: 100%;
    max-width: 700px;
    height: 100%;
    max-height: 400px;
  }
}

.chatbot-message {
  position: relative;
}


.blinking-square {
  display: inline-block;
  width: 10px;
  height: 10px;
  border: 1px solid black;
  background-color: black; /* Add this line to set the background color to black */
  /*position: absolute;*/
  top: 5px; /* Position the square at the top of the chatbot-messages div */
  /*right: 0;*/
  margin-left:10px;
  animation: blink 1s infinite;
}

@keyframes blink {
  50% {
    opacity: 0;
  }
}

#loading-spinner {
  margin-left: 5px;
}





#chatbot-toggle {
  display: block;
  width: 200px;
  margin: 0 auto;
  text-align: center;
  padding: 10px;
  background-color: #f5f5f5;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-weight: bold;
  text-decoration: none;
  color: #333;
}

#chatbot-toggle:hover {
  background-color: #e8e8e8;
}


.chatbot-instructions p {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
}



.chatbot-instructions {
  display: none;
  margin: 20px auto;
  width: 80%;
  max-width: 600px;
  padding: 20px;
  background-color: #f5f5f5;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.chatbot-instructions ol {
    counter-reset: my-counter;
    list-style-type: none;
    padding-left: 0;
}

.chatbot-instructions ol li {
    counter-increment: my-counter;
    margin-bottom: 10px;
    position: relative;
}

.chatbot-instructions ol li:before {
    content: counter(my-counter) ".";
    background-color: #2196f3;
    border-radius: 50%;
    color: #fff;
    display: inline-block;
    font-size: 16px;
    font-weight: bold;
    height: 24px;
    line-height: 24px;
    margin-right: 10px;
    text-align: center;
    width: 24px;
}

.chatbot-instructions ol li:last-child {
    margin-bottom: 0;
}

.chatbot-instructions ol li:last-child:before {
    content: counter(my-counter) ".";
    background-color: #2196f3;
    border-radius: 50%;
    color: #fff;
    display: inline-block;
    font-size: 16px;
    font-weight: bold;
    height: 24px;
    line-height: 24px;
    margin-right: 10px;
    text-align: center;
    width: 24px;
}

.label {
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: bold;
  margin-right: 8px;
}

.keywords {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px;
  max-width: 100%;
}


.keyword {
  display: inline-block;
  margin-right:8px;
  margin-left:8px;
  background-color: #f5f5f5;
  color: #333;
  font-size: 14px;
  font-weight: bold;
  padding: 4px 8px;
  border-radius: 4px;
  box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
}

@media only screen and (max-width: 600px) {
  .keyword {
    font-size: 12px;
    padding: 3px 6px;
    margin: 5px;
  }
  .label {
    display: inline-block;
    align-items: center;
    font-size: 14px;
  }
}

.key-points-container {
  background-color: #f5f5f5;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  margin: 20px 0;
}

.key-points-header {
  background-color: #eee;
  padding: 5px;
  border-radius: 5px 5px 0 0;
  text-align: center;
}

.key-points-header h3 {
  margin: 0;
}


.key-points-body ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.key-points-body {
  background-color: #f2f2f2;
  border-radius: 5px;
  padding: 20px;
}

.key-points-body li {
  position: relative;
  padding-left: 1.5em;
  margin-bottom: 0.5em;
  line-height: 1.5;
  font-size: 18px;
}

.key-points-body li:before {
  content: "";
  position: absolute;
  left: 0;
  top: 0.6em;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #3CB371;
}

.paper-resources {
      font-family: Arial, sans-serif;
      font-size: 16px;
      color: #333;
      background-color: #f8f9a0;
      padding: 10px;
      border-radius: 5px;
      margin-top: 20px;
      display: inline-block;
  }

  .paper-resources a {
      color: #007bff;
      text-decoration: none;
  }

  .paper-resources a:hover {
      text-decoration: underline;
  }

  .disclaimer {
  background-color: #f2f2f2;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
  margin-left: 20px;
  margin-right: 20px;

}

.disclaimer p {
  font-size: 16px;
  line-height: 1.5;
  margin: 0;
  color: #333;
}

.disclaimer strong {
  font-weight: bold;
  color: #0052cc;
}

.latest-papers {
     background-color: #f8f8f8;
     padding: 20px;
     text-align: center;
   }

   .latest-papers h2 {
     font-size: 24px;
     font-weight: bold;
     margin-bottom: 10px;
   }

   .paper-list {
     display: flex;
     flex-wrap: wrap;
     justify-content: center;
   }

   .paper {
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border-radius: 5px;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1);
  padding: 10px;
  margin: 10px;
  width: 120px;
  height: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.2s ease-in-out;
  height: 120px; /* set a fixed height */
  justify-content: space-between;
}

.paper:hover {
  box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.3);
  transform: scale(1.1);
}

.paper a {
  font-family: "Open Sans", sans-serif;
  color: #000000;
  font-size: 14px;
  text-decoration: none;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
}

.paper a:hover {
  color: #007bff;
}

.paper .category {
  font-size: 14px;
  margin-top: 5px;
  text-align: center;
  font-family: "Open Sans", sans-serif;
}

   @media (min-width: 768px) {
     .paper {
       width: 150px;
       height: 150px;
     }

     .paper a {
       font-size: 16px;
     }
   }

   .score {
      font-size: 16px;
      font-weight: bold;
      text-align: center;
      color: #fff;
      background-color: #007bff;
      border-radius: 4px;
      padding: 4px 8px;
      margin-top: 8px;
    }


</style>
{% endblock %}

{% block header_class %}{% endblock %}

{% block content %}
<div class="main-content2">

{% if errormess %}
<div style="text-align:center;color:red;">
  <p><strong>{{ errormess }}</strong></p>
</div>
{% else %}

{% if alpaper %}

  {% if paper.title %}
    <div class="title"><h2>{{ paper.title }}</h2></div>
  {% endif %}
  {% if keywords %}
    <div class="keywords">
      <span class="label">{% trans 'AI-generated keywords:' %}
      {% for kw in keywords %}
        <span class="keyword">{{ kw }}</span>
      {% endfor %}
      </span>
    </div>
  {% endif %}
  {% if notes %}
  <div class="key-points-container">
  <div class="key-points-header">
    <h3>{% trans 'AI-generated Key Points' %}</h3>
    {% if not public %}
    <p style="display: inline-block; margin-top:10px;"><small><span class='warning-sign'>&#9888;</span>{% trans 'The license of the paper does not allow us to build upon its content and the key points are generated using the paper metadata rather than the full article.' %}</small></p>
    {% endif %}
  </div>
  <div class="key-points-body">
    <ul>
      {% for point in notes2 %}
      <li>{{ point }}</li>
      {% endfor %}
    </ul>
  </div>
  <div class="paper-resources">
    {% trans 'Also access our AI generated:' %}
      <a href="#results" onclick="switchTab(0)">{% trans 'Comprehensive summary' %}</a>,
      <a href="#results" onclick="switchTab(2)">{% trans 'Lay summary' %}</a>,
      <a href="#results" onclick="switchTab(3)">{% trans 'Blog-like article' %}</a>;
      {% trans ' or ask questions about this paper to our' %} <a href="#assistant">{% trans 'AI assistant' %}</a>.
  </div>
</div>
  {% else %}
    {% if sumlang %}
    <div class="info-block" style="margin-top: 20px; border: 1px solid #ccc; padding: 10px; background-color: #f7f7f7;">
        <span style="font-weight: bold;">{% trans 'Summaries already available in other languages:' %}</span>
        {% for l in sumlang %}
            <a href="/{{ l }}/arxiv-id/{{ arxiv_id }}" style="margin-left: 10px;">{{ l }}</a>{% if not forloop.last %}, {% endif %}
        {% endfor %}
    </div>
  {% endif %}
  {% endif %}
    <div class="subtitle">
      {% if paper.authors.all %}
        <p><b>{% trans 'Authors:' %}</b>
          {% for author in paper.authors.all %}
            {{ author.name }}{% if author.affiliation %} ({{ author.affiliation }}){% endif %}{% if not forloop.last %}, {% endif %}
          {% endfor %}
        </p>
      {% endif %}
    </div>
    {% if paper.journal_ref %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-book"></i> {{ paper.journal_ref }}</div>
    </div>
    {% endif %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-link"></i> {% if paper.link_homepage %}<a href="{{ paper.link_homepage }}" target="_blank">{% endif %}arXiv: {{ arxiv_id|dash_slash }}{% if paper.link_homepage %}</a>{% endif %}{% if paper.link_doi %} - <a href="{{ paper.link_doi }}" target="_blank">DOI</a>{% endif %}{% if paper.category %} ({{ paper.category }}){% endif %}</div>
    </div>
    {% if paper.comments %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-comment"></i> {{ paper.comments }}</div>
    </div>
    {% endif %}
    {% if paper.license %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-id-badge"></i> {% trans 'License:' %} <a href="{{ paper.license }}" target="_blank">{{ cc_format }}</a></div>
    </div>
    {% else %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-id-badge"></i> {% trans 'License:' %} <a href="http://arxiv.org/licenses/assumed-1991-2003/" target="_blank">ASSUMED 1991-2003</a></div>
    </div>
    {% endif %}
    <div class="paper-details">
    {% if paper.abstract %}
      <p style="text-align: justify;"><strong>{% trans 'Abstract:' %}</strong> <span class="math style="width: 1.796em; display: inline-block;">{{ paper.abstract }}</span></p>
    {% endif %}
    </div>
    {% if paper.published_arxiv %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-clock"></i> {% trans 'Submitted to arXiv on' %} {{ paper.published_arxiv|date:"d M. Y" }}</div>
    </div>
    {% endif %}
  </div>

  <div class="chatbot-container" id="assistant">
    <div class="chatbot-body">
    <div class="chatbot-header">
      <h3>{% trans 'Ask questions about this paper to our AI assistant' %}</h3>
      <p style="margin-top:-10px;"><small>{% blocktrans %}You can also <a href="/{{ LANGUAGE_CODE }}/chat/" class="btn btn-primary">chat with multiple papers at once here</a>.{% endblocktrans %}</small></p>
      {% if not public %}
      <p style="max-width: 400px;display: inline-block; margin-top:-10px;"><small><span class='warning-sign'>&#9888;</span>{% trans 'The license of the paper does not allow us to build upon its content and the AI assistant only knows about the paper metadata rather than the full article.' %}</small></p>
      {% endif %}
    </div>
    </div>
    <div class="chatbot-body">
      <div class="chatbot-messages">
        {% if chathistory %}
          {% for chat in chathistory %}
            <div class="chatbot-message">{{ chat.user }} - {{ chat.query }}</div>
            <div class="chatbot-response">{% trans 'AI' %} - {{ chat.response }}</div>
          {% endfor %}
        {% endif %}
      </div>
      <form class="chatbot-form">
        <input type="text" placeholder="{% trans 'Type your question here' %}">
        <button type="submit" id="send-btn">{% trans 'Send' %}</button>
      </form>
      <div id="loading-spinner" style="display: none;text-align:right;">
      <i class="fa fa-spinner fa-spin"></i> {% trans 'Loading...' %}
    </div>
    </div>
  </div>
  <a id="chatbot-toggle" href="#">{% trans 'AI assistant instructions?' %}</a>
  <div class="chatbot-instructions" style="display: none;">
    <p>{% trans 'Welcome to our AI assistant! Here are some important things to keep in mind:' %}</p>
    <ol>
        <li>{% trans 'The assistant will only answer questions related to this specific paper.' %}</li>
        <li>{% trans 'Please note that this is not a bot for casual chatting.' %}</li>
        <li>{% trans 'If you want the answer in a language other than the language you chose for navigating the website, simply add "TRANSLATE IN LANGUAGE L" at the end of your query (replace "LANGUAGE L" with the language of your choice).' %}</li>
        <li>{% trans 'For example, you could ask "Can you extract the most important aspect of the paper? TRANSLATE IN SPANISH".' %}</li>
        {% if not request.user.is_authenticated %}
        <li>{% trans 'If you want to keep the history of your questions/answers you should create an account.' %}</li>
        {% endif %}
    </ol>
  </div>


  <div class="message-box" id="results">
    <h1 class="message-header">{% trans 'Results of the summarizing process for the arXiv paper:' %} {{ arxiv_id|dash_slash }}</h1>
    {% if not public %}
    <p class="message-header2"><small><span class="warning-sign">&#9888;</span>{% trans "This paper's license doesn't allow us to build upon its content and the summarizing process is here made with the paper's metadata rather than the article." %}</small></p>
    {% endif %}
    <ul class="message-tabs">
      <li class="active" onclick="switchTab(0)">{% trans 'Comprehensive Summary' %}</li>
      <li onclick="switchTab(1)">{% trans 'Key points' %}</li>
      <li onclick="switchTab(2)">{% trans "Layman's Summary" %}</li>
      <li onclick="switchTab(3)">{% trans 'Blog article' %}</li>
    </ul>
    <div class="message-content">
      <div class="message-tab">{% if sumpaper.summary %}{{ sumpaper.summary }}{% else %}{% trans 'The summary is not ready yet' %}{% endif %}</div>
      <div class="message-tab" style="display:none;">
        {% if sumpaper.notes %}
        <ul style="list-style: none;padding-left: 20px; text-indent: -10px;">
        {% for note in notes %}
          <li>{{ note }}</li>
        {% endfor %}
        </ul>
        {% else %}{% trans 'The key points are not ready yet' %}{% endif %}
      </div>
      <div class="message-tab" style="display:none;white-space: pre-line;">{% if sumpaper.lay_summary %}{{ sumpaper.lay_summary }}{% else %}{% trans "The Layman's summary is not ready yet" %}{% endif %}</div>
      <div class="message-tab" style="display:none;">{% if sumpaper.blog %}{{ sumpaper.blog|safe }}{% else %}{% trans 'The blog article is not ready yet' %}{% endif %}</div>
    </div>

    {% if paper.updated %}
    <div class="info-block" style="margin-top:20px;">
      <div class="info-text"><i class="fas fa-clock"></i> {% trans 'Created on' %} {{ paper.updated|date:"d M. Y" }}</div>
    </div>
    {% endif %}
    {% if sumlang %}
    <div class="info-block" style="margin-top:20px;">
      <div class="info-text"> {% trans 'Available in other languages:' %}
          {% for l in sumlang %}<a href="/{{ l }}/arxiv-id/{{ arxiv_id }}">{{ l }}</a>{% if not forloop.last %}, {% endif %}{% endfor %}
      </div>
    </div>
    {% endif %}
    <form id="download-form" action="{% url 'arxividpage' arxiv_id=arxiv_id %}" method="post">
      {% csrf_token %}
      <input type="hidden" name="local_date" id="localDateInput">
      <input type="submit" id="submitButton" value="{% trans 'Download as pdf' %}" name="download_pdf" class="small-button">
      <span id="spinner" class="fa fa-spinner fa-spin" style="display: none;"></span>
    </form>
  </div>

  <script>
const form = document.getElementById('download-form');
const submitButton = document.getElementById('submitButton');
const localDateInput = document.getElementById('localDateInput');
const spinner = document.getElementById('spinner');

submitButton.addEventListener('click', () => {
  const date = new Date().toLocaleString();
  localDateInput.value = date;
  spinner.style.display = 'inline-block';
  // Remove scintillation class after animation finishes
  setTimeout(() => {
    spinner.style.display = 'none';
  }, 1000);

  // Prevent default form submission
  //form.submit();

  /*submitButton.disabled = true;*/

  // Wait for 5 seconds before submitting the form
    //form.submit();

});
</script>

  <div style="text-align: center;">
  <p>
    <form action="{% url 'vote' paper.arxiv_id %}" method="post">
      {% csrf_token %}
      <input type="hidden" name="paper_id" value="{{ paper.arxiv_id }}">
      <button type="submit" name="direction" value="up" style="cursor: pointer;">
        <i class="fa fa-thumbs-up" style="font-size: 36px;color:blue;"></i>
      </button>
    </form>
    
    <!--<a href="{% url 'vote' paper.arxiv_id %}">
      <i class="fa fa-thumbs-up" style="font-size: 36px;"></i>
    </a>-->
  </p>
  <p id="totvote">{% trans 'Assess the quality of the AI-generated content by voting' %} 
    <span id="popover-link">
      <i class="fas fa-question-circle"></i>
    </span>
    <p>{% trans 'Score:' %} {{ total_votes }}</p>
  </p>
  <div id="popover">
    <p><strong>{% trans 'Why do we need votes?' %}</strong></p>
    <p>{% trans 'Votes are used to determine whether we need to re-run our summarizing tools. If the count reaches -10, our tools can be restarted.' %}</p>
  </div>
  <p>
    <form action="{% url 'vote' paper.arxiv_id %}" method="post">
      {% csrf_token %}
      <input type="hidden" name="paper_id" value="{{ paper.arxiv_id }}">
      <button type="submit" name="direction" value="down" style="cursor: pointer;">
        <i class="fa fa-thumbs-down" style="font-size: 36px; color:blue;"></i>
      </button>
    </form>

    <!--<a href="{% url 'vote' paper.arxiv_id %}">
      <i class="fa fa-thumbs-down" style="font-size: 36px;"></i>
    </a>-->
  </p>
  {% if error_message %}
  <div style="text-align:center;color:red;">
    <p><strong>{{ error_message }}</strong></p>
  </div>
  {% endif %}
</div>

  {% if not sumpaper.summary or not sumpaper.notes or not sumpaper.lay_summary or not sumpaper.blog or toolong or total_votes < -9 or user.is_staff %}
  <div class="center" style="margin:10px;">
    {% if toolong %}
    <p>{% trans 'The previous summary was created more than a year ago and can be re-run (if necessary) by clicking on the Run button below.' %}</p>
    {% elif total_votes < -9 %}
    <p>{% trans 'The summaries have many downvotes and can be re-run with our tools if necessary by clicking on the Run button below.' %}</p>
    {% elif not sumpaper.summary or not sumpaper.notes or not sumpaper.lay_summary or not sumpaper.blog %}
    <p>{% trans 'Some bits of the article are not summarized yet, you can re-run the summarizing process by clicking on the Run button below.' %}</p>
    {% elif user.is_staff %}
    <p>{% trans 'Hi, because you are a staff member you can Run the AI tools!' %}</p>
    {% endif %}
    </div>
    <div class="center" style="margin-bottom:20px;">
  <form action="{% url 'arxividpage' arxiv_id=arxiv_id %}" method="post">
    {% csrf_token %}
    <input type="submit" value="{% trans 'Run' %}" name="run_button">
  </form>
  </div>
  {% if not public %}
  <p style="text-align: center; margin-top: 10px; color: red;max-width: 600px; width: 90%; margin-left: auto; margin-right: auto;"><small><span class='warning-sign'>&#9888;</span>{% trans 'The license of this specific paper does not allow us to build upon its content and the summarizing tools will be run using the paper metadata rather than the full article. However, it still does a good job, and you can also try our tools on papers with more open licenses.' %}</small></p>
  {% endif %}
  {% endif %}
  
  {% if relpapers %}
  <section class="latest-papers" id="closest">
    <h2>{% trans 'Similar papers summarized with our AI tools' %}</h2>
    <div class="paper-list">
      {% for paper in relpapers %}
        <div class="paper">
          <div class="score">{{ scores|index:forloop.counter0 }}%</div>
          <a href="/{{ LANGUAGE_CODE }}/arxiv-id/{{ paper.to_paper.arxiv_id }}" title="{{ paper.to_paper.title }}">{{ paper.to_paper.title|truncatechars:80 }}</a>
          <div class="category">{{ paper.to_paper.category }}</div>
      </div>
      {% endfor %}
    </div>
    <div style="font-size: 18px; font-weight: bold; margin-bottom: 10px;">
      <p style="display: inline-block;">{% trans 'Navigate through even more similar papers through a ' %}</p>
      <a href="/{{ LANGUAGE_CODE }}/tree/{{ arxiv_id }}" style="display: inline-block; text-decoration: none; background-color: #007bff; color: #fff; padding: 5px 10px; border-radius: 5px;">{% trans 'tree representation' %}</a>
    </div>
      </section>
  {% endif %}

  <div class="center" style="margin-bottom:20px;">
    <form action="{% url 'arxividpage' arxiv_id=arxiv_id %}" method="post">
      {% csrf_token %}
      
      <input type="submit" value="{% if relpapers %}{% trans 'Search again for closest papers' %}{% else %}{% trans 'Search for closest papers' %}{% endif %}" name="close_button" style="background-color: #333;">
      
      <p style="text-align: center;">
      <label style="color: orange;">(Beta)</label>
      <span id="popover-link2">
        <i class="fas fa-question-circle"></i>
      </span></p>
    </form>
    <div id="popover2">
      <p><strong>{% trans 'Look for similar papers (in beta version)' %}</strong></p>
      <p>{% trans 'By clicking on the button above, our algorithm will scan all papers in our database to find the closest based on the contents of the full papers and not just on metadata. Please note that it only works for papers that we have generated summaries for and you can rerun it from time to time to get a more accurate result while our database grows.' %}</p>
    </div>
  </div>
  <div class="disclaimer">
    <p><strong>{% trans 'Disclaimer:' %}</strong> {% trans 'The AI-based summarization tool and virtual assistant provided on this website may not always provide accurate and complete summaries or responses. We encourage you to carefully review and evaluate the generated content to ensure its quality and relevance to your needs.' %}</p>
  </div>
 

{% else %}

{% if exist == 0 %}
<p>{% trans 'There is no existing article with the given arXiv ID:' %} {{ arxiv_id }}. {% blocktrans %} Try again your <a href="/{{LANGUAGE_CODE}}/">search</a> with a new arXiv ID.{% endblocktrans %}</p>
{% else %}

  {% if close %}
  <h1>{% trans 'Running our tool to find closest papers' %}</h1>
  {% else %}
  <h1>{% trans 'Running summarizing tools on a new article' %}</h1>
  {% endif %}
  {% if run or run2 or close %}
  <p style="font-size:20px;"><strong>{% trans 'We are now running our AI tools on the requested article. This process may take a few minutes so please bear with us.' %}</strong></p>
  {% else %}
  <p style="font-size:20px;"><strong>{% trans 'This is the first time this article is requested and our AI summarizing tools have never been run on it. We can run our tools now if you click on the button "Run" donw the page but first make sure that it is the right article.' %}</strong></p>
  {% endif %}
  <hr>

  {% if robot %}
  <div style="text-align:center;color:red;">
    <p><strong>{% trans 'You are trying to run too many papers in too short a period of time. Are you a robot? If not, wait and retry!' %}</strong></p>
  </div>
  {% endif %}

  {% if toomany %}
  <div style="text-align:center;color:red;">
    <p><strong>{% trans 'You are limited to running 10 papers in a period of 24 hours. Please come back tomorrow or contact us if you need to run more articles using our tools.' %}</strong></p>
  </div>
  {% endif %}

  {% if run or run2 or close %}
    <div class="info-block">
      <p> {% trans 'We are analysing the following arXiv article:' %} {{ arxiv_id|dash_slash }}</p>
    </div>
  {% else %}
    <div class="title"><h2>{{ details.title }}</h2></div>
    <div class="subtitle">
      {% if details.authors %}
        <p>
          {% with affiliations=details.affiliation %}
          {% for author in details.authors %}
            {{ author }}{% if affiliations|index:forloop.counter0 %} ({{ affiliations|index:forloop.counter0 }}){% endif %}{% if not forloop.last %}, {% endif %}
          {% endfor %}
          {% endwith %}
        </p>
      {% endif %}
    </div>
    {% if details.journal_ref %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-book"></i> {{ details.journal_ref }}</div>
    </div>
    {% endif %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-link"></i> {% if details.link_homepage %}<a href="{{ details.link_homepage }}" target="_blank">{% endif %}arXiv: {{ arxiv_id|dash_slash }}{% if details.link_homepage %}</a>{% endif %}{% if details.link_doi %} - <a href="{{ details.link_doi }}" target="_blank">DOI</a>{% endif %}{% if details.category %} ({{ details.category }}){% endif %}</div>
    </div>
    {% if details.comments %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-comment"></i> {{ details.comments }}</div>
    </div>
    {% endif %}
    {% if details.license %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-id-badge"></i> {% trans 'License:' %} <a href="{{ details.license }}" target="_blank">{{ cc_format }}</a></div>
    </div>
    {% else %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-id-badge"></i> {% trans 'License:' %} <a href="http://arxiv.org/licenses/assumed-1991-2003/" target="_blank">ASSUMED 1991-2003</a></div>
    </div>
    {% endif %}
    <div class="paper-details">
    {% if details.abstract %}
      <p style="text-align: justify;"><strong>{% trans 'Abstract:' %}</strong> <span class="math style="width: 1.796em; display: inline-block;">{{ details.abstract }}</span></p>
    {% endif %}
    </div>
    {% if details.published_arxiv %}
    <div class="info-block">
      <div class="info-text"><i class="fas fa-clock"></i> {% trans 'Submitted to arXiv on' %} {{ details.published_arxiv|date:"d M. Y" }}</div>
    </div>
    {% endif %}

    <div class="center">
    <form action="{% url 'arxividpage' arxiv_id=arxiv_id %}" method="post">
      {% csrf_token %}
      <input type="submit" value="{% trans 'Run' %}" name="run_button">
    </form>
    </div>
    {% if not public %}
    <p style="text-align: center; margin-top: 10px; color: red;max-width: 600px; width: 90%; margin-left: auto; margin-right: auto;"><small><span class='warning-sign'>&#9888;</span>{% trans 'The license of this specific paper does not allow us to build upon its content and the summarizing tools will be run using the paper metadata rather than the full article. However, it still does a good job, and you can also try our tools on papers with more open licenses.' %}</small></p>
    {% endif %}
    {% endif %}


{% endif %}

{% if close %}
{{ arxiv_id|json_script:"arxiv_id" }}

<div class="main-content2">

<div class="loading" style="text-align:center;margin-bottom:40px;"><img src="{% static "summarizer/images/snake.gif" %}" alt="{% trans 'Loading...' %}" style="display:inline-block;"></div>

<div id="progtextupdate" style="font-size:20px;color:red; text-align: center;animation: blink 2s linear infinite;"></div>

  <div id="loading-message"></div>
  <div id="progress-bar">
    <div id="progress" style="width: 0%">
      <div id="progress-text"></div>
    </div>
  </div>
</div>
{% endif %}

{% if run2 %}
{{ arxiv_id|json_script:"arxiv_id" }}

<div class="main-content2">

<div class="loading" style="text-align:center;margin-bottom:40px;"><img src="{% static "summarizer/images/snake.gif" %}" alt="{% trans 'Loading...' %}" style="display:inline-block;"></div>

<div id="progtextupdate" style="font-size:20px;color:red; text-align: center;animation: blink 2s linear infinite;"></div>

  <div id="loading-message"></div>
  <div id="progress-bar">
    <div id="progress" style="width: 0%">
      <div id="progress-text"></div>
    </div>
  </div>
</div>

{% endif %}
</div>

{% if run %}
{{ arxiv_id|json_script:"arxiv_id" }}

<div class="main-content2">

<div id="progtextupdate" style="font-size:20px;color:red; text-align: center;animation: blink 2s linear infinite;"></div>

<div id="loading-message"></div>
<div id="progress-bar">
  <div id="progress" style="width: 0%">
    <div id="progress-text"></div>
  </div>
</div>

<div class="title" style="margin-top:40px;"></div>
<div class="subtitle"></div>
<div class="jr"></div>
<div class="link"></div>
<div class="com"></div>
<div class="license"></div>
<div class="paper-details"></div>
<div class="publ"></div>

<div class="message-box">
  <h1 class="message-header"></h1>
  <p class="message-header2"></p>

  <ul class="message-tabs">
    <li class="active" onclick="switchTab(0)">{% trans 'Comprehensive Summary' %}</li>
    <li onclick="switchTab(1)">{% trans 'Key points' %}</li>
    <li onclick="switchTab(2)">{% trans "Layman's Summary" %}</li>
    <li onclick="switchTab(3)">{% trans 'Blog article' %}</li>
  </ul>
  <div class="message-content">
    <div id="sum" class="message-tab">
      <div class="loading" style="text-align:center;"><img src="{% static "summarizer/images/snake.gif" %}" alt="{% trans 'Loading...' %}" style="display:inline-block;"></div>
    </div>
    <div id="notes" class="message-tab" style="display:none;">
      <div class="loading" style="text-align:center;"><img src="{% static "summarizer/images/snake.gif" %}" alt="{% trans 'Loading...' %}" style="display:inline-block;"></div>
    </div>
    <div id="laysum" class="message-tab" style="display:none;white-space: pre-line;">
      <div class="loading" style="text-align:center;"><img src="{% static "summarizer/images/snake.gif" %}" alt="{% trans 'Loading...' %}" style="display:inline-block;"></div>
    </div>
    <div id="blog" class="message-tab" style="display:none;">
      <div class="loading" style="text-align:center;"><img src="{% static "summarizer/images/snake.gif" %}" alt="{% trans 'Loading...' %}" style="display:inline-block;"></div>
    </div>
  </div>
</div>

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

{% block scripts %}
  {% if run or run2 or close %}

  <script>
  const arxivRoomName = JSON.parse(document.getElementById('arxiv_id').textContent);
  const language = "{{ language }}"
  //console.log(language);

{% if onhero %}
  const socketl = new WebSocket(
      'wss://'
      + window.location.host
      + '/ws/arxivid/'
      + arxivRoomName
      + '/'
      + language
      + '/'
  );
{% else %}
  const socketl = new WebSocket(
      'ws://'
      + window.location.host
      + '/ws/arxivid/'
      + arxivRoomName
      + '/'
      + language
      + '/'
  );
{% endif %}

  socketl.onopen = function(event) {
      console.log('WebSocket connection established.');
      //console.log('jkkk');
      {% if run or run2 %}
      socketl.send(JSON.stringify({
          'command': 'start_background_task'
      }));
      {% elif close %}
      socketl.send(JSON.stringify({
          'command': 'start_close_task'
      }));
      {% endif %}
      //console.log('jkkddk');
      // You can now send messages over the WebSocket connection.
  }



  socketl.onmessage = function(e) {
    const data = JSON.parse(e.data);
    //console.log('oklmmm',data.message);

    if(data.type=='progress_update'){
      document.getElementById("loading-message").innerHTML = data.message.loading_message;
      document.getElementById("progress").style.width = data.message.progress + "%";
      if(data.message.progress !=0){
        document.getElementById("progress-text").innerHTML = data.message.progress + "%";
      }
      //console.log(data.message.progress);
      if(data.message.progress == 100){
        document.getElementById("progress-bar").style.display = "none";
        document.getElementById("progtextupdate").style.animation = "none";
      }
    }
    if(data.type=='progress_text_update'){
      //console.log('progresstextupdate');

      document.getElementById("progtextupdate").innerHTML = data.message.loading_message;
      document.getElementById("progress").style.width = data.message.progress + "%";
      document.getElementById("progress-text").innerHTML = data.message.progress + "%";
      if(data.message.progress == 5){
        data.message.progress = parseInt(data.message.progress) + 2;
        document.getElementById("progress").style.width = data.message.progress + "%";
      }
      if(data.message.progress == 100){
        document.getElementById("progress-bar").style.display = "none";
        document.getElementById("progtextupdate").style.animation = "none";
        {% if run2 or run or close %}
        var pathname = window.location.pathname;

        {% if close and treeval == '1' %}
        pathname = pathname.replace(/\/$/, '') + '#closest';
        {% endif %}

        {% if close and treeval == '0' %}
        pathname = pathname.replace('arxiv-id', 'tree').replace(/\/$/, '') + '#closest';;
        {% endif %}

        // Replace all occurrences of '--' with '/'
        pathname = pathname.replace(/--/g, '/');

        // Reload the page with the updated pathname
        window.location.href = window.location.protocol + '//' + window.location.host + pathname;
        //window.location.href = 'http://127.0.0.1:8000/fr/arxiv-id/1412.5598v1#closest'
        //window.location.href = window.location.protocol +'//'+ window.location.host + window.location.pathname;
        //location.reload(true);
        //location.reload(true);
        {% endif %}
      }
    }

    {% if run %}
    var arxname = arxivRoomName
    arxname = arxname.replace(/--/g, '/');

    if(data.type=='progress_sum_update'){

      document.getElementsByClassName("message-header")[0].innerHTML = "{% trans 'Results of the summarizing process for the arXiv paper (1/4):' %} "+arxname;
      document.getElementById("sum").innerHTML = data.message;
      MathJax.typeset();

      //document.querySelector("#sum_.loading").style.display = "none";
    }
    if(data.type=='progress_notes_update'){
      //alert(data.message);
      document.getElementsByClassName("message-header")[0].innerHTML = "{% trans 'Results of the summarizing process for the arXiv paper (2/4):' %} "+arxname;
      //console.log(data.message);
      if (Array.isArray(data.message)) {
        const bulletPoints = data.message.map((item) => `<li>${item}</li>`).join('');
        document.getElementById("notes").innerHTML = `<ul style="list-style: none;padding-left: 20px; text-indent: -10px;">${bulletPoints}</ul>`;
      } else {
        document.getElementById("notes").innerHTML = data.message;
      }
      MathJax.typeset();

      //document.querySelector("#notes_.loading").style.display = "none";
    }
    if(data.type=='progress_laysum_update'){
      //alert(data.message);
      document.getElementsByClassName("message-header")[0].innerHTML = "{% trans 'Results of the summarizing process for the arXiv paper (3/4):' %} "+arxname;
      document.getElementById("laysum").innerHTML = data.message;
      MathJax.typeset();

      //document.querySelector("#longsum_.loading").style.display = "none";
    }
    if(data.type=='progress_blog_update'){
      //alert(data.message);
      document.getElementsByClassName("message-header")[0].innerHTML = "{% trans 'Results of the summarizing process for the arXiv paper (4/4):' %} "+arxname;
      document.getElementById("blog").innerHTML = data.message;
      MathJax.typeset();

      //document.querySelector("#longsum_.loading").style.display = "none";
    }
    if(data.type=='progress_arxiv_update'){
      //console.log('progressarxivupdate');
      //alert(document.getElementsByClassName("title2")[0]);
      document.getElementsByClassName("title")[0].innerHTML = "<h2>"+data.message.title+"</h2>";
      var authorsContainer = document.getElementsByClassName("subtitle")[0];
      var authorsHTML = "";
      //alert(data.message.authors.length)
      for (var i = 0; i < data.message.authors.length; i++) {
        if (i==data.message.authors.length-1){
          authorsHTML += data.message.authors[i];
          if (data.message.affiliation[i]!=''){
            authorsHTML += " ("+data.message.affiliation[i]+")";
          }
        }
        else{
          authorsHTML += data.message.authors[i];
          if (data.message.affiliation[i]!=''){
            authorsHTML += " ("+data.message.affiliation[i]+")";
          }
          authorsHTML += ", ";

        }
      }
      authorsHTML = "<p>"+authorsHTML+"</p>"
      authorsContainer.innerHTML = authorsHTML;

      var jrContainer = document.getElementsByClassName("jr")[0];
      if (data.message.journal_ref){
        //alert(data.message.journal_ref)
        var jrHTML = '<div class="info-block"><div class="info-text"><i class="fas fa-book"></i> ';
        jrHTML += data.message.journal_ref;
        jrHTML += '</div></div>';
        jrContainer.innerHTML = jrHTML;
      }

      var linkContainer = document.getElementsByClassName("link")[0];
        //alert(data.message.journal_ref)
      var linkHTML = '<div class="info-block"><div class="info-text"><i class="fas fa-link"></i> ';
      if (data.message.link_homepage){
        linkHTML += '<a href="'+data.message.link_homepage+'" target="_blank">';
      }
        arxname = arxivRoomName.replace(/--/g, '/');
        linkHTML += "arXiv: "+arxname;
      if (data.message.link_homepage){
        linkHTML += '</a>';
      }
      if (data.message.link_doi){
        linkHTML += ' - <a href="'+data.message.link_doi+'" target="_blank">DOI</a>';
      }
      if (data.message.category){
        linkHTML += ' ('+data.message.category+')';
      }
        linkHTML += '</div></div>';
        linkContainer.innerHTML = linkHTML;


      var comContainer = document.getElementsByClassName("com")[0];
      if (data.message.comments){
        //alert(data.message.journal_ref)
        var comHTML = '<div class="info-block"><div class="info-text"><i class="fas fa-comment"></i> ';
        comHTML += data.message.comments;
        comHTML += '</div></div>';
        comContainer.innerHTML = comHTML;
      }

      var liContainer = document.getElementsByClassName("license")[0];
      if (data.message.license){
        //alert(data.message.journal_ref)
        const parts = data.message.license.split('/');
        //console.log('parts'+parts);

        const license = parts[parts.length - 3];
        const version = parts[parts.length - 2];
        //console.log('ici'+license.toUpperCase());
        if (license.toUpperCase() != 'NONEXCLUSIVE-DISTRIB'){
          var ccFormat = 'CC ' + license.toUpperCase() + ' ' + version;

        } else {
          var ccFormat = license.toUpperCase() + ' ' + version;
        }

        if (license.trim().toUpperCase() != "BY" && license.trim().toUpperCase() != "BY-SA" && license.trim().toUpperCase() != "BY-NC-SA" && license.trim().toUpperCase() != "ZERO") {
            document.getElementsByClassName("message-header2")[0].innerHTML+="<small><span class='warning-sign'>&#9888;</span>{% trans 'The license of the paper does not allow us to build upon its content and the summarizing process is here made with the paper metadata rather than the article.' %}</small>";
        }


        //console.log(ccFormat); // Output: CC BY-NC-SA 4.0

        var liHTML = '<div class="info-block"><div class="info-text"><i class="fas fa-id-badge"></i> ';
        liHTML += '{% trans "License:" %} <a href="'+data.message.license+'" target="_blank">'+ccFormat+'</a>';
        liHTML += '</div></div>';
        liContainer.innerHTML = liHTML;
      }
      else{
        document.getElementsByClassName("message-header2")[0].innerHTML+="<small><span class='warning-sign'>&#9888;</span>{% trans 'The license of the paper does not allow us to build upon its content and the summarizing process is here made with the paper metadata rather than the article.' %}</small>";
      }

      var absContainer = document.getElementsByClassName("paper-details")[0];
      if (data.message.abstract){
        //alert(data.message.journal_ref)
        var absHTML = '<p style="text-align: justify;"><strong>{% trans "Abstract:" %}</strong> <span class="math style="width: 1.796em; display: inline-block;">';
        absHTML += data.message.abstract;
        absHTML += '</span></p>';
        absContainer.innerHTML = absHTML;
        MathJax.typeset();
      }

      var publContainer = document.getElementsByClassName("publ")[0];
      if (data.message.published_arxiv){
        //alert(data.message.journal_ref)
        var publHTML = '<div class="info-block"><div class="info-text"><i class="fas fa-clock"></i> ';
        publHTML += '{% trans "Submitted to arXiv on" %} '+data.message.published_arxiv;
        publHTML += '</div></div>';
        publContainer.innerHTML = publHTML;
      }

      }
      {% endif %}
  };

  socketl.onclose = function(e) {
    /*updateCache(arxivRoomName); do not need in production because once started, can't stop the code from running in background*/
    console.error('WebSocket closed with code: ' + e.code);
  };

</script>

<!--
<script>
function updateCache(arxiv_id) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/update-cache/?arxiv_id=' + arxiv_id, true);
    xhr.onload = function() {
        if (xhr.status === 200) {
            console.log('Cache updated for arxiv_id: ' + arxiv_id);
        }
    };
    xhr.send();
}
</script>
-->
{% else %}
{{ arxiv_id|json_script:"arxiv_id" }}

{% if alpaper %}

<script>
    const chatbotToggle = document.querySelector('#chatbot-toggle');
    const chatbotInstructions = document.querySelector('.chatbot-instructions');

    chatbotToggle.addEventListener('click', () => {
      event.preventDefault();
      chatbotInstructions.style.display = chatbotInstructions.style.display === 'none' ? 'block' : 'none';
    });
</script>

<script>

function addTheListeners() {
  //alert('ok');
  if (socketl && socketl.readyState === WebSocket.OPEN) {
    //console.log('adding...')
    socketl.addEventListener("open", function(event) {
      //console.log("WebSocket connected");
      connecting = false;
      //alert(socketl+' '+socketl.readyState);
    });

    socketl.addEventListener("message", function(event) {
      //socketl.onmessage = function(event) {
      //console.log('Received message:', event);
      const messageb = JSON.parse(event.data).message;
      const chatbotResponse = document.createElement('div');
      chatbotResponse.classList.add('chatbot-response');
      chatbotResponse.innerText = "{% trans 'AI -' %} "+messageb;
      chatbotMessages.appendChild(chatbotResponse);
      var blinkingSquare = document.querySelector(".blinking-square");

      blinkingSquare.remove();

      var loadingSpinner = document.getElementById("loading-spinner");
      loadingSpinner.style.display = "none";

      /*var messagesContainer = document.querySelector(".chatbot-messages");

      // Function to scroll the container to the bottom
      function scrollToBottom() {
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
      }*/
      MathJax.typeset();

      // Scroll the container to the bottom
      scrollToBottom();


    });

    socketl.addEventListener("close", function(event) {
      // If the WebSocket connection is closed, display an error message
      var messagesContainer = document.querySelector(".chatbot-messages");
      var errorMessage = document.createElement("div");
      errorMessage.innerHTML = "{% trans 'Error: WebSocket connection closed (reload the page).' %}";
      messagesContainer.appendChild(errorMessage);
      console.log("WebSocket disconnected: ");
    });

    socketl.addEventListener("error", function(event) {
      console.error("WebSocket error: " + event);
    });
    isListenerAdded = true;

  } else if (socketl && socketl.readyState === WebSocket.CONNECTING) {
    //console.log("WebSocket connecting 2...");
    setTimeout(function() {
      addTheListeners();
      //console.log("wait 2");
    }, 1000);
  } else {
    console.error("WebSocket is not open 2");
  }
}
</script>

<script>
  const arxivRoomName = JSON.parse(document.getElementById('arxiv_id').textContent);
  const language = "{{ language }}"
  //console.log(language);
  const user = "{{ request.user }}"
  const ip = "{{ hashed_ip_address }}"
  var count = 0

  {% if not public %}
  count=1
  {% endif %}
  
  let isListenerAdded = false;

  const chatbotMessages = document.querySelector('.chatbot-messages');
  const chatbotForm = document.querySelector('.chatbot-form');
  const chatbotInput = chatbotForm.querySelector('input[type="text"]');

  var sendBtn = document.getElementById("send-btn");
  let socketl=null;
  let connecting = false;

  sendBtn.addEventListener('click', function(event) {
    event.preventDefault();

    if (socketl === null) {
      console.log('connecting...')
    {% if onhero %}
    socketl = new WebSocket(
        'wss://'
        + window.location.host
        + '/ws/arxivid/'
        + arxivRoomName
        + '/'
        + language
        + '/'
    );
    {% else %}
    socketl = new WebSocket(
        'ws://'
        + window.location.host
        + '/ws/arxivid/'
        + arxivRoomName
        + '/'
        + language
        + '/'
    );
    {% endif %}
    connecting = true;
  }


//chatbotForm.addEventListener('submit', function(event) {
  //event.preventDefault();
  //alert('ok');
  var inputValue = chatbotInput.value.trim();
  var messagesContainer = document.querySelector(".chatbot-messages");

  /*if (socketl.readyState !== WebSocket.OPEN) {
    var errorMessage = document.createElement("div");
    errorMessage.innerHTML = "{% trans 'Error: WebSocket connection closed. Reload the page.' %}";
    messagesContainer.appendChild(errorMessage);
    return;
  }*/

  if (inputValue === "") {
    return;
  }

  const messagec = chatbotInput.value;
  chatbotInput.value = '';
  const chatbotMessage = document.createElement('div');
  chatbotMessage.classList.add('chatbot-message');
  chatbotMessage.innerText = "{% if request.user.is_authenticated %}{{ request.user }} -{% else %}{% trans 'You -' %}{% endif %} "+messagec;
  const blinkingSquare = document.createElement('span');
  blinkingSquare.classList.add('blinking-square');
  chatbotMessage.appendChild(blinkingSquare);
  chatbotMessages.appendChild(chatbotMessage);
  //var messagesContainer = document.querySelector(".chatbot-messages");
  var loadingSpinner = document.getElementById("loading-spinner");
  loadingSpinner.style.display = "block";
  MathJax.typeset();

  // Function to scroll the container to the bottom
  /*function scrollToBottom() {
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }*/

  // Scroll the container to the bottom
  scrollToBottom();

  sendWebSocketMessage(messagec,user,ip,count);
  //socketl.send(JSON.stringify({message: messagec}));

  if (!isListenerAdded) {
    addTheListeners();
  }
});

</script>


<script>

function sendWebSocketMessage(message2,user,ip,count) {
  if (socketl && socketl.readyState === WebSocket.OPEN) {
    //console.log('sending...')
    socketl.send(JSON.stringify({message: message2, user:user, ip:ip, count:count}));
  } else if (socketl && socketl.readyState === WebSocket.CONNECTING) {
    //console.log("WebSocket connecting...");
    setTimeout(function() {
      sendWebSocketMessage(message2,user,ip,count);
      //console.log("wait");
    }, 1000);
  } else {
    console.error("WebSocket is not open");
  }
}

</script>

<script>
  // Define a function that scrolls to the bottom of the chatbot-messages div
  function scrollToBottom() {
    var messagesContainer = document.querySelector(".chatbot-messages");
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }

  // Call the scrollToBottom function when the page is fully loaded
  window.addEventListener("load", scrollToBottom);
</script>

{% endif %}

{% endif %}
{% if alpaper %}

<script>
document.getElementById("popover-link").addEventListener("mouseover", function(event) {
  var popover = document.getElementById("popover");
  popover.style.display = "block";
  popover.style.left = (event.clientX - 40) + "px";
  popover.style.top = (event.clientY + 20) + "px";
});

document.getElementById("popover-link").addEventListener("mouseout", function() {
  var popover = document.getElementById("popover");
  popover.style.display = "none";
});
</script>

<script>
  document.getElementById("popover-link2").addEventListener("mouseover", function(event) {
    var popover2 = document.getElementById("popover2");
    popover2.style.display = "block";
    popover2.style.left = (event.clientX - 40) + "px";
    popover2.style.top = (event.clientY + 20) + "px";
  });
  
  document.getElementById("popover-link2").addEventListener("mouseout", function() {
    var popover2 = document.getElementById("popover2");
    popover2.style.display = "none";
  });
  </script>

{% endif %}

<script>
function switchTab(tabIndex) {
  var tabs = document.querySelectorAll(".message-tabs li");
  var contents = document.querySelectorAll(".message-tab");
  for (var i = 0; i < tabs.length; i++) {
    tabs[i].classList.remove("active");
    contents[i].style.display = "none";
  }
  tabs[tabIndex].classList.add("active");
  contents[tabIndex].style.display = "block";
}
</script>


{% endblock %}
