const PRACTICE_ID = 935747383;

const createPractices = async () => {
  const res = await fetch(`/teach/control/stream/view/id/${PRACTICE_ID}`);
  const data = await res.text();
  const parser = new DOMParser();
  const dom = parser.parseFromString(data, "text/html");
  const lessonsGC = dom.querySelectorAll(
    ".lesson-list li:not(.divider):not(.lesson-is-hidden)"
  );
  const lessonsCustom = document.querySelector('.hmns-practice-all');

  let dataLessons = Array.from(lessonsGC).map((item, index) => {
    let state = "";
    item.classList.forEach((el) => {
      if (/^user-state/.test(el)) {
        state = el;
      }
    });

    const descrEl = item.querySelector(".description");
    let descr = null;
    if (descrEl) {
      try {
        descr = JSON.parse(descrEl.innerText.trim());
      } catch (e) {
        descr = null;
      }
    }

    return {
      title: item
        .querySelector(".link.title")
        .innerText.replace("просмотрено", "")
        .trim(),
      number: index + 1,
      href: item.querySelector("a").href,
      state,
      descr
    };
  });

  // Обновляем счётчик на карточке
  const practiceCountEl = document.querySelector('.hmns-module-card_practices .hmns-module-card__count');
  if (practiceCountEl) {
    practiceCountEl.textContent = `${dataLessons.length} ${pluralize(dataLessons.length, 'урок', 'урока', 'уроков')}`;
  }

  lessonsCustom.innerHTML = "";

  // Группируем уроки по полю descr.group (если есть)
  let currentGroup = null;

  dataLessons.forEach((item) => {
    const group = item.descr?.group || null;

    if (group && group !== currentGroup) {
      currentGroup = group;
      lessonsCustom.insertAdjacentHTML(
        "beforeend",
        `<div class="hmns-files-group__title">${group}</div>`
      );
    }

    const badge = item.descr?.badge || "Практика";

    lessonsCustom.insertAdjacentHTML(
      "beforeend",
      `
<a href="${item.href}" class="hmns-practice">
	<span class="hmns-practice__time">${badge}</span>
    <span class="hmns-practice__name">${item.title}</span>
    <span class="hmns-practice__btn" data-redactor-class="hmns-practice__btn">
        Открыть
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M6 12L10 8L6 4" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"></path>
        </svg>
    </span>
</a>
`
    );
  });
};

document.addEventListener('DOMContentLoaded', () => {
    if(document.querySelector('.hmns-practice-all')) createPractices();
})