$(function () {

  let courseName = ''; // ← ВПИШИ НАЗВАНИЕ ТРЕНИНГА

  $.get('/sales/control/userProduct/my')
    .done(function (data) {

      const html = $('<div>').html(data);
      const rows = html.find('.table-notitle tbody tr');

      let datesString = null;
      let daysLeft = 0;

      rows.each(function () {
        const name = $(this).find('td').eq(0).text().toLowerCase();

        if (name.includes(courseName.toLowerCase())) {

          datesString = $(this).find('td').eq(1).text().replace(/\s+/g, ' ').trim();

          const leftText = $(this).find('td').eq(3).text().replace(/\s+/g, ' ').trim();

          const match = leftText.match(/(\d+)/);

          if (match) {
            daysLeft = parseInt(match[1]);
          } else if (leftText.includes('минут')) {
            daysLeft = 1;
          } else {
            daysLeft = 0;
          }
        }
      });

      if (!datesString) return;

      const daysAll = calculateTotalDays(datesString);

      const percent = Math.max(0, Math.min(100, Math.floor((daysLeft / daysAll) * 100)));

      updateCircle(percent);

      $('.new-access__time').text(daysLeft + ' дней');

    });

  function calculateTotalDays(dateString) {

    const months = {
      Янв: 0, Фев: 1, Мар: 2, Апр: 3,
      Май: 4, Июн: 5, Июл: 6, Авг: 7,
      Сен: 8, Окт: 9, Ноя: 10, Дек: 11
    };

    const parts = dateString.split(' ');

    // пример:
    // с 1 Янв 2024 по 1 Янв 2025

    const from = new Date(parts[3], months[parts[2]], parts[1]);
    const to = new Date(parts[7], months[parts[6]], parts[5]);

    return Math.abs((to - from) / 86400000);
  }

  function updateCircle(percent) {

    const radius = 25;
    const circumference = 2 * Math.PI * radius;

    const circle = $('#progress-access');

    circle.attr('stroke-dasharray', circumference);

    const offset = circumference - (percent / 100) * circumference;

    circle.attr('stroke-dashoffset', offset);

    $('.user-progress__scale-text').text(percent + '%');
  }

});