{% assign event = '' %}

{% for training_event in training_events.available %}
  {% assign event = event | append: training_event.title | append: ',' | append: training_event.sessions.first.day | append: ',' | append: training_event.sessions.first.month | append: ',' | append: training_event.sessions.first.year | append: ',' | append: training_event.sessions.first.id | append: '$$' %}
{% endfor %}


<div class="wrapper-cal">
  <div class="calendar">
    <div class="calendar-header">
      <button id="prev">
        <i class="far fa-chevron-left"></i>
      </button>
      <span id="monthYear"></span>
      <button id="next">
        <i class="far fa-chevron-right"></i>
      </button>
    </div>
    <div class="day-names">
      <div>
        <span class="lang-en-US">Sun</span>
        <span class="lang-es">Dom</span>
        <span class="lang-fr">Dim</span>
        <span class="lang-de">So</span>
        <span class="lang-en-GB">Sun</span>
        <span class="lang-nl">Zo</span>
        <span class="lang-pt-BR">Dom</span>
      </div>
      <div>
        <span class="lang-en-US">Mon</span>
        <span class="lang-es">Lun</span>
        <span class="lang-fr">Lun</span>
        <span class="lang-de">Mo</span>
        <span class="lang-en-GB">Mon</span>
        <span class="lang-nl">Ma</span>
        <span class="lang-pt-BR">Lun</span>
      </div>
      <div>
        <span class="lang-en-US">Tue</span>
        <span class="lang-es">Mar</span>
        <span class="lang-fr">Mar</span>
        <span class="lang-de">Di</span>
        <span class="lang-en-GB">Tue</span>
        <span class="lang-nl">Di</span>
        <span class="lang-pt-BR">Mar</span>
      </div>
      <div>
        <span class="lang-en-US">Wed</span>
        <span class="lang-es">Mié</span>
        <span class="lang-fr">Mer</span>
        <span class="lang-de">Mi</span>
        <span class="lang-en-GB">Wed</span>
        <span class="lang-nl">Mi</span>
        <span class="lang-pt-BR">Mié</span>
      </div>
      <div>
        <span class="lang-en-US">Thu</span>
        <span class="lang-es">Jue</span>
        <span class="lang-fr">Jue</span>
        <span class="lang-de">Do</span>
        <span class="lang-en-GB">Thu</span>
        <span class="lang-nl">Do</span>
        <span class="lang-pt-BR">Jue</span>
      </div>
      <div>
        <span class="lang-en-US">Fri</span>
        <span class="lang-es">Vie</span>
        <span class="lang-fr">Ven</span>
        <span class="lang-de">Fr</span>
        <span class="lang-en-GB">Fri</span>
        <span class="lang-nl">Vr</span>
        <span class="lang-pt-BR">Vie</span>
      </div>
      <div>
        <span class="lang-en-US">Sat</span>
        <span class="lang-es">Sáb</span>
        <span class="lang-fr">Sam</span>
        <span class="lang-de">Sa</span>
        <span class="lang-en-GB">Sat</span>
        <span class="lang-nl">Za</span>
        <span class="lang-pt-BR">Sáb</span>
      </div>
    </div>
    <div class="calendar-grid" id="calendarGrid"></div>
    <div class="calendar-footer">
      <div class="agenda">
        <div class="red-agenda"></div>
        <div class="agenda-desc">
          <span class="lang-en-US">Today</span>
          <span class="lang-es">Hoy</span>
          <span class="lang-fr">Aujourd'hui</span>
          <span class="lang-de">Heute</span>
          <span class="lang-en-GB">Today</span>
          <span class="lang-nl">Vandaag</span>
          <span class="lang-pt-BR">Hoje</span>
        </div>
      </div>
      <div class="agenda">
        <div class="blue-agenda"></div>
        <div class="agenda-desc">
          <span class="lang-en-US">Upcoming Event</span>
          <span class="lang-es">Evento próximo</span>
          <span class="lang-fr">Événement à venir</span>
          <span class="lang-de">Ereignis in der Zukunft</span>
          <span class="lang-en-GB">Upcoming Event</span>
          <span class="lang-nl">Aankomende evenement</span>
          <span class="lang-pt-BR">Evento futuro</span>
        </div>
      </div>
    </div>
  </div>
  <div class="event-info" id="eventInfo">
    <span class="lang-en-US">Select a date</span>
    <span class="lang-es">Seleccionar una fecha</span>
    <span class="lang-fr">Sélectionner une date</span>
    <span class="lang-de">Datum auswählen</span>
    <span class="lang-en-GB">Select a date</span>
    <span class="lang-nl">Selecteer een datum</span>
    <span class="lang-pt-BR">Selecionar uma data</span>
  </div>
</div>

<style>
  .calendar-footer {
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  .agenda {
    display: flex;
    gap: 10px;
  }
  .red-agenda {
    width: 15px;
    height: 15px;
    background-color: #bd0074;
    border-radius: 50%;
  }
  .blue-agenda {
    width: 15px;
    height: 15px;
    background-color: #BF9ACA;
    border-radius: 50%;
  }
  .wrapper-cal {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f4f4f4;
    flex-direction: column;
  }
  .calendar {
    background: #fff;
    padding: 1.5rem;
    box-shadow: 0 4px 24px 0 rgba(0, 0, 0, 0.1);
    width: 100%;
  }

  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
  }

  .calendar-header button {
    background: none;
    border: none;
    font-size: 1rem;
    cursor: pointer;
    color: #0000007a;
  }

  .calendar-header span {
    font-size: 1rem;
    font-weight: bold;
    color: #5f676e;
  }

  .day-names,
  .calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    text-align: center;
  }

  .day-names div {
    font-weight: 400;
    color: #5f676e;
    padding-bottom: 0.5rem;
    font-size: 0.85rem;
  }
  .calendar-grid div {
    padding: 0.7rem 0;
    border-radius: 50%;
    position: relative;
    font-size: 0.9rem;
    color: #222;
    width: 40px;
    height: 40px;
    line-height: 36px;
    margin: 2px auto;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #5f676e;
  }
  .agenda-desc {
    font-weight: 400;
    color: #5f676e;
  }
  .calendar-grid div:hover {
    background: #8080802e;
    color: #5f676e !important;
  }

  .other-month {
    color: #ccc !important;
  }

  .fade-message {
    animation: fadeSlideIn 0.4s ease both;
  }

  .today {
    background-color: #bd0074;
    color: #fff !important;
    font-weight: 500;
  }

  .has-event {
    background-color: #BF9ACA;
    color: #fff !important;
    font-weight: 500;
  }

  .today.has-event {
    background-color: purple;
    color: #fff !important;
    font-weight: 500;
  }

  .event-info {
    margin-top: 1rem;
    background: #eee;
    padding: 1rem;
    border-radius: 8px;
    font-size: 0.95rem;
    text-align: center;
    width: 100%;
    min-height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .event-card {
    background: white;
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 0.5rem;
    text-align: left;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    width: 100%;
    animation: fadeSlideIn 0.4s ease both;
  }

  .event-card h4 {
    margin: 0 0 0.25rem 0.8rem;
  }

  .event-card .date {
    color: #555;
    font-size: 0.85rem;
    margin-bottom: 0.5rem;
    margin-left: 0.8rem;
  }

  .event-card a {
    display: inline-block;
    margin-top: 0.5rem;
    text-decoration: none;
    padding: 0.4rem 0.8rem;
    border-radius: 6px;
    font-size: 0.85rem;
  }

  .selected-day {
    outline: 2px solid #9C9C9C;
    background: #8080802e;
    color: #5f676e !important;
  }
  @keyframes fadeSlideIn {
    0% {
      opacity: 0;
      transform: translateY(10px);
    }
    100% {
      opacity: 1;
      transform: translateY(0);
    }
  }
</style>

<script>
  const rawEventData = "{{ event | strip_newlines }}";
  // Month name to number mapping for consistent comparison
  // Supports multiple languages as used in the application
  const monthNames = {
    // English
    'January': 0, 'january': 0, 'Jan': 0, 'jan': 0,
    'February': 1, 'february': 1, 'Feb': 1, 'feb': 1,
    'March': 2, 'march': 2, 'Mar': 2, 'mar': 2,
    'April': 3, 'april': 3, 'Apr': 3, 'apr': 3,
    'May': 4, 'may': 4,
    'June': 5, 'june': 5, 'Jun': 5, 'jun': 5,
    'July': 6, 'july': 6, 'Jul': 6, 'jul': 6,
    'August': 7, 'august': 7, 'Aug': 7, 'aug': 7,
    'September': 8, 'september': 8, 'Sep': 8, 'sep': 8,
    'October': 9, 'october': 9, 'Oct': 9, 'oct': 9,
    'November': 10, 'november': 10, 'Nov': 10, 'nov': 10,
    'December': 11, 'december': 11, 'Dec': 11, 'dec': 11,

    // Spanish
    'enero': 0, 'Enero': 0,
    'febrero': 1, 'Febrero': 1,
    'marzo': 2, 'Marzo': 2,
    'abril': 3, 'Abril': 3,
    'mayo': 4, 'Mayo': 4,
    'junio': 5, 'Junio': 5,
    'julio': 6, 'Julio': 6,
    'agosto': 7, 'Agosto': 7,
    'septiembre': 8, 'Septiembre': 8,
    'octubre': 9, 'Octubre': 9,
    'noviembre': 10, 'Noviembre': 10,
    'diciembre': 11, 'Diciembre': 11,

    // French
    'janvier': 0, 'Janvier': 0,
    'février': 1, 'Février': 1,
    'mars': 2, 'Mars': 2,
    'avril': 3, 'Avril': 3,
    'mai': 4, 'Mai': 4,
    'juin': 5, 'Juin': 5,
    'juillet': 6, 'Juillet': 6,
    'août': 7, 'Août': 7,
    'septembre': 8, 'Septembre': 8,
    'octobre': 9, 'Octobre': 9,
    'novembre': 10, 'Novembre': 10,
    'décembre': 11, 'Décembre': 11,

    // German
    'Januar': 0, 'januar': 0,
    'Februar': 1, 'februar': 1,
    'März': 2, 'märz': 2,
    'April': 3, 'april': 3,
    'Mai': 4, 'mai': 4,
    'Juni': 5, 'juni': 5,
    'Juli': 6, 'juli': 6,
    'August': 7, 'august': 7,
    'September': 8, 'september': 8,
    'Oktober': 9, 'oktober': 9,
    'November': 10, 'november': 10,
    'Dezember': 11, 'dezember': 11,

    // Dutch
    'januari': 0, 'Januari': 0,
    'februari': 1, 'Februari': 1,
    'maart': 2, 'Maart': 2,
    'april': 3, 'April': 3,
    'mei': 4, 'Mei': 4,
    'juni': 5, 'Juni': 5,
    'juli': 6, 'Juli': 6,
    'augustus': 7, 'Augustus': 7,
    'september': 8, 'September': 8,
    'oktober': 9, 'Oktober': 9,
    'november': 10, 'November': 10,
    'december': 11, 'December': 11,

    // Portuguese (Brazil)
    'janeiro': 0, 'Janeiro': 0,
    'fevereiro': 1, 'Fevereiro': 1,
    'março': 2, 'Março': 2,
    'abril': 3, 'Abril': 3,
    'maio': 4, 'Maio': 4,
    'junho': 5, 'Junho': 5,
    'julho': 6, 'Julho': 6,
    'agosto': 7, 'Agosto': 7,
    'setembro': 8, 'Setembro': 8,
    'outubro': 9, 'Outubro': 9,
    'novembro': 10, 'Novembro': 10,
    'dezembro': 11, 'Dezembro': 11
  };

  const events = rawEventData
    .split('$$')
    .filter(e => e)
    .map(item => {
      const [title, day, month, year, id] = item.split(',');
      return {
        title: title.trim(),
        day: parseInt(day),
        month: month.trim(),
        monthNumber: monthNames[month.trim()] || 0,
        year: parseInt(year),
        id: id.trim()
      };
    });

  const monthYear = document.getElementById('monthYear');
  const calendarGrid = document.getElementById('calendarGrid');
  const prevBtn = document.getElementById('prev');
  const nextBtn = document.getElementById('next');
  const eventInfo = document.getElementById('eventInfo');

  let currentDate = new Date();
  let selectedDayElement = null;

  function renderCalendar(date) {
    const year = date.getFullYear();
    const month = date.getMonth();

    const firstDayOfMonth = new Date(year, month, 1);
    const startDay = firstDayOfMonth.getDay();

    const lastDateOfMonth = new Date(year, month + 1, 0).getDate();
    const lastDatePrevMonth = new Date(year, month, 0).getDate();

    let locale = 'en-US';
    if (lang === 'es') {
      locale = 'es';
    } else if (lang === 'fr') {
      locale = 'fr';
    } else if (lang === 'de') {
      locale = 'de';
    } else if (lang === 'en-GB') {
      locale = 'en-GB';
    } else if (lang === 'nl') {
      locale = 'nl';
    } else if (lang === 'pt-BR') {
      locale = 'pt-BR';
    }

    const monthName = date.toLocaleString(locale, { month: 'long' });
    monthYear.textContent = `${monthName} ${year}`;
    calendarGrid.innerHTML = '';

    const today = new Date();
    const isToday = (d) =>
      d.getDate() === today.getDate() &&
      d.getMonth() === today.getMonth() &&
      d.getFullYear() === today.getFullYear();

    for (let i = 0; i < 42; i++) {
      const dayCell = document.createElement('div');
      let dayNum, actualMonth = month, actualYear = year;

      if (i < startDay) {
        dayNum = lastDatePrevMonth - startDay + i + 1;
        actualMonth = month - 1;
        if (actualMonth < 0) {
          actualMonth = 11;
          actualYear -= 1;
        }
        dayCell.classList.add('other-month');
      } else if (i >= startDay + lastDateOfMonth) {
        dayNum = i - (startDay + lastDateOfMonth) + 1;
        actualMonth = month + 1;
        if (actualMonth > 11) {
          actualMonth = 0;
          actualYear += 1;
        }
        dayCell.classList.add('other-month');
      } else {
        dayNum = i - startDay + 1;
      }

      dayCell.textContent = dayNum;
      const displayDate = new Date(actualYear, actualMonth, dayNum);

      const isTodayDate = isToday(displayDate);
      const matchingEvents = events.filter(ev =>
        ev.day === dayNum &&
        ev.monthNumber === actualMonth &&
        ev.year === actualYear
      );

      if (isTodayDate) dayCell.classList.add('today');
      if (matchingEvents.length > 0) dayCell.classList.add('has-event');

        dayCell.addEventListener('click', () => {
        if (selectedDayElement) {
            selectedDayElement.classList.remove('selected-day');
        }
        dayCell.classList.add('selected-day');
        selectedDayElement = dayCell;
        renderEventInfo(displayDate, matchingEvents);
        });

      calendarGrid.appendChild(dayCell);
    }
  }

  function renderEventInfo(dateObj, matchedEvents) {
    if (matchedEvents.length === 0) {
      eventInfo.innerHTML = `<p class="fade-message">${lang === 'es' ? 'No hay eventos para la fecha seleccionada' : lang === 'fr' ? 'Aucun événement pour la date sélectionnée' : lang === 'de' ? 'Keine Ereignisse für die ausgewählte Datum' : lang === 'en-GB' ? 'No events for selected date' : lang === 'nl' ? 'Geen evenementen voor de geselecteerde datum' : lang === 'pt-BR' ? 'Nenhum evento para a data selecionada' : 'No events for selected date'}</p>`;
      return;
    }

    eventInfo.innerHTML = matchedEvents.map(ev => {
      const eventDate = new Date(ev.year, ev.monthNumber, ev.day);
      const formattedDate = eventDate.toLocaleDateString(locale, {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });

      return `
      <div class="event-card">
        <h4>${ev.title}</h4>
        <div class="date">${formattedDate}</div>
        <a href="/app/training_sessions/${ev.id}" class="nintex-card-link">
        <span class="lang-en-US">View</span>
        <span class="lang-es">Ver</span>
        <span class="lang-fr">Voir</span>
        <span class="lang-de">Ansehen</span>
        <span class="lang-en-GB">View</span>
        <span class="lang-nl">Bekijken</span>
        <span class="lang-pt-BR">Ver</span>

      </a>
      </div>
    `}).join('');
  }

  prevBtn.addEventListener('click', () => {
    currentDate.setMonth(currentDate.getMonth() - 1);
    renderCalendar(currentDate);
    eventInfo.innerHTML = `${lang === 'es' ? 'Seleccionar una fecha' : lang === 'fr' ? 'Sélectionner une date' : lang === 'de' ? 'Datum auswählen' : lang === 'en-GB' ? 'Select a date' : lang === 'nl' ? 'Selecteer een datum' : lang === 'pt-BR' ? 'Selecionar uma data' : 'Select a date'}`;
  });

  nextBtn.addEventListener('click', () => {
    currentDate.setMonth(currentDate.getMonth() + 1);
    renderCalendar(currentDate);
    eventInfo.innerHTML = `${lang === 'es' ? 'Seleccionar una fecha' : lang === 'fr' ? 'Sélectionner une date' : lang === 'de' ? 'Datum auswählen' : lang === 'en-GB' ? 'Select a date' : lang === 'nl' ? 'Selecteer een datum' : lang === 'pt-BR' ? 'Selecionar uma data' : 'Select a date'}`;
  });

  renderCalendar(currentDate);
</script>