/* GETCOURSE — CURATOR / TRAINING & MODULE v0.3.3
 * Separate curator-only interface.
 * Root training -> module cards
 * Module/subtraining -> lesson cards
 *
 * Works only when:
 *   isTeacher = true
 *   isAdmin   = false
 *   isManager = false
 */
(() => {
  'use strict';

  const VIEW_RE = /^\/teach\/control\/stream\/view\/id\/\d+\/?$/;

  function isCurator() {
    const u = window.userInfo || {};
    return !!u.isTeacher && !u.isAdmin && !u.isManager;
  }

  if (!VIEW_RE.test(location.pathname) || !isCurator()) return;

  document.documentElement.classList.add('psych-curator-training-loading');

  const clean = (value) => String(value || '').replace(/\s+/g, ' ').trim();

  function iconBook() {
    return `
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M5.5 4.75A2.75 2.75 0 0 1 8.25 2h10.25v16.25H8.25A2.75 2.75 0 0 0 5.5 21V4.75Z"
          stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M5.5 18.25A2.75 2.75 0 0 1 8.25 15.5H18.5"
          stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
      </svg>`;
  }

  function iconLayers() {
    return `
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="m12 3 8 4.5-8 4.5-8-4.5L12 3Z"
          stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
        <path d="m4 12 8 4.5 8-4.5M4 16.5 12 21l8-4.5"
          stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>`;
  }

  function iconArrow() {
    return `
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M5 12h14M14 7l5 5-5 5"
          stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>`;
  }


  function getCuratorLessonKind(value) {
    const description = clean(value).toLowerCase();

    if (description.includes('мастерская')) {
      return 'workshop';
    }

    if (description.includes('вебинар')) {
      return 'webinar';
    }

    return 'lesson';
  }

  function iconWorkshop() {
    return `
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <circle cx="9" cy="8.5" r="2.5"
          stroke="currentColor" stroke-width="1.7"/>
        <circle cx="16.5" cy="9.5" r="2"
          stroke="currentColor" stroke-width="1.7"/>
        <path d="M4.5 18.5c.55-3 2.25-4.7 4.5-4.7s3.95 1.7 4.5 4.7"
          stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
        <path d="M13.7 14.8c.75-.7 1.65-1.05 2.8-1.05 1.8 0 3.05 1.15 3.55 3.35"
          stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
      </svg>`;
  }

  function iconWebinar() {
    return `
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <rect x="4" y="5.5" width="16" height="11" rx="2"
          stroke="currentColor" stroke-width="1.7"/>
        <path d="M9 19h6M12 16.5V19"
          stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
        <path d="m10.2 9 4.2 2.5-4.2 2.5V9Z"
          fill="currentColor"/>
      </svg>`;
  }

  function getCuratorLessonMarker(lesson) {
    if (lesson.type === 'workshop') {
      return iconWorkshop();
    }

    if (lesson.type === 'webinar') {
      return iconWebinar();
    }

    return String(lesson.number).padStart(2, '0');
  }

  function iconBack() {
    return `
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M19 12H5M10 7l-5 5 5 5"
          stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>`;
  }

  function getPageTitle() {
    return clean(document.querySelector('.page-header h1')?.textContent) || 'Тренинг';
  }

  function getParentTrainingLink() {
    const breadcrumbs = [...document.querySelectorAll('.breadcrumb a[href*="/teach/control/stream/view/id/"]')];
    if (!breadcrumbs.length) return null;
    const currentId = location.pathname.match(/\/id\/(\d+)/)?.[1];
    const candidates = breadcrumbs.filter(a => !a.href.includes(`/id/${currentId}`));
    return candidates[candidates.length - 1] || null;
  }

  function getModules() {
    return [...document.querySelectorAll(
      '.xdget-trainingList .stream-table .training-row[data-training-id]'
    )].map((row, index) => {
      const link = row.querySelector('td > a[href*="/teach/control/stream/view/id/"]');
      const titleNode = row.querySelector('.stream-title');
      if (!link || !titleNode) return null;

      const rawMeta = clean(link.querySelector('div')?.textContent);
      const lessonMatch = rawMeta.match(/(\d+)\s+урок(?:ов|а)?/i);

      return {
        index: index + 1,
        id: row.dataset.trainingId || '',
        href: link.getAttribute('href') || '#',
        title: clean(titleNode.textContent),
        lessons: lessonMatch ? Number(lessonMatch[1]) : null
      };
    }).filter(Boolean);
  }

  function getLessons() {
    let lessonNumber = 0;

    return [...document.querySelectorAll(
      '.xdget-lessonList .lesson-list > li[data-lesson-id]'
    )].map(li => {
      const link = li.querySelector(
        'a.item-a[href*="/teach/control/lesson/view/"]'
      );
      const titleNode = li.querySelector('.link.title');
      if (!link || !titleNode) return null;

      const title = clean(
        [...titleNode.childNodes]
          .filter(node => !(
            node.nodeType === 1 &&
            node.classList?.contains(
              'lesson-list__video-watched'
            )
          ))
          .map(node => node.textContent || '')
          .join(' ')
      );

      const kind =
        clean(
          li.querySelector(
            '.description'
          )?.textContent
        );

      const type =
        getCuratorLessonKind(kind);

      const number =
        type === 'lesson'
          ? ++lessonNumber
          : null;

      const studentState =
        clean(
          li.querySelector(
            '.user-state-label'
          )?.textContent
        );

      const isClosed =
        li.classList.contains(
          'user-state-not_reached'
        ) ||
        /Недоступен/i.test(
          studentState
        );

      return {
        number,
        id: li.dataset.lessonId || '',
        href: link.getAttribute('href') || '#',
        title: title || (
          type === 'lesson'
            ? `Урок ${number}`
            : type === 'workshop'
              ? 'Мастерская'
              : 'Вебинар'
        ),
        kind: kind || (
          type === 'workshop'
            ? 'Мастерская'
            : type === 'webinar'
              ? 'Вебинар'
              : `Урок ${number}`
        ),
        type,
        studentState,
        isClosed
      };
    }).filter(Boolean);
  }

  function hideNativeManagement() {
    document.querySelectorAll([
      '.page-actions',
      '.content-menu',
      '.standard-page-menu',
      '.lesson-sort-block',
      '.link-change-sort',
      '.btn-change-sort',
      '.xdget-trainingChats',
      '.xdget-trainingAchievements'
    ].join(',')).forEach(el => {
      el.classList.add('psych-curator-native-management-hidden');
    });
  }

  function buildHeader({ title, subtitle, backLink }) {
    const header = document.createElement('section');
    header.className = 'psych-curator-training-hero';

    const back = backLink ? `
      <a class="psych-curator-training-back" href="${backLink.href}">
        ${iconBack()}
        <span>${clean(backLink.textContent) || 'Назад'}</span>
      </a>` : '';

    header.innerHTML = `
      ${back}
      <div class="psych-curator-training-hero__content">
        <span class="psych-curator-training-hero__icon">${iconBook()}</span>
        <div>
          <div class="psych-curator-training-hero__eyebrow">Кабинет куратора</div>
          <h1 class="psych-curator-training-hero__title"></h1>
          <p class="psych-curator-training-hero__subtitle"></p>
        </div>
      </div>
    `;

    header.querySelector('.psych-curator-training-hero__title').textContent = title;
    header.querySelector('.psych-curator-training-hero__subtitle').textContent = subtitle;
    return header;
  }


  function getCurrentTrainingId() {
    return location.pathname.match(/\/stream\/view\/id\/(\d+)/)?.[1] || '';
  }

  function buildAnswersFeedUrl(trainingId, status = '') {
    const base = '/teach/control/answers/unanswered';
    const parts = [
      ['filter[only_my_trainings]', '1'],
      ['filter[status]', status],
      ['filter[lesson_type]', ''],
      ['filter[marked]', ''],
      ['filter[sorting]', 'need_teacher_reaction_at DESC'],
      ['filter[answer_type]', 'mission_answer'],
      ['filter[learner_type]', 'only_my'],
      ['filter[training_with_disable_view]', '']
    ];

    const path = parts.map(([key, value]) =>
      `/${encodeURIComponent(key)}/${encodeURIComponent(value)}`
    ).join('');

    return `${base}${path}/training_id/${encodeURIComponent(trainingId)}`;
  }

  function parseTrainingAnswerCount(doc, trainingId) {
    /*
     * Важно: GetCourse не показывает тренинг в левом фильтре,
     * если по текущей выборке у него 0 ответов.
     *
     * Поэтому считаем ТОЛЬКО по собственному счётчику тренинга.
     * Нельзя использовать .selection-count или selected-пункт:
     * они могут содержать суммарное количество по всем тренингам
     * преподавателя и давать ложное значение для текущего training_id.
     */
    const direct = doc.querySelector(
      `.stream-count-${CSS.escape(String(trainingId))}`
    );

    if (direct) {
      const value = Number(
        clean(direct.textContent).replace(/\s+/g, '')
      );

      if (Number.isFinite(value)) {
        return value;
      }
    }

    /*
     * Если training_id запрошен, но его счётчика в боковом меню нет,
     * штатная лента GetCourse фактически сообщает: в этой выборке
     * у данного тренинга ответов нет.
     */
    return 0;
  }

  async function fetchTrainingAnswerCount(trainingId, status = '') {
    const response = await fetch(buildAnswersFeedUrl(trainingId, status), {
      credentials: 'same-origin'
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const html = await response.text();
    const doc = new DOMParser().parseFromString(html, 'text/html');

    const learner = doc.querySelector('#filter_learner_type')?.value;
    if (learner && learner !== 'only_my') {
      throw new Error('GetCourse did not keep learner_type=only_my');
    }

    return parseTrainingAnswerCount(doc, trainingId);
  }

  function buildAnswersOverview(trainingId, scope = 'training') {
    const section = document.createElement('section');
    section.className = 'psych-curator-answers-overview is-loading';
    if (scope === 'module') {
      section.classList.add('psych-curator-answers-overview--module');
    }

    const pendingUrl = buildAnswersFeedUrl(trainingId, 'unanswered');
    const allUrl = buildAnswersFeedUrl(trainingId, '');

    const heading =
      scope === 'module'
        ? 'Ответы по модулю'
        : 'Ответы по всему тренингу';

    const description =
      scope === 'module'
        ? 'Ответы учеников в уроках этого модуля'
        : 'Включая ответы из вложенных модулей';

    section.innerHTML = `
      <div class="psych-curator-answers-overview__icon">
        <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
          <path d="M5 5.5h14a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-7l-4.5 3v-3H5a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2Z"
            stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/>
          <path d="M8 10h8M8 13.5h5"
            stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
        </svg>
      </div>

      <div class="psych-curator-answers-overview__content">
        <div class="psych-curator-answers-overview__eyebrow">Ответы моих учеников</div>
        <h2>${heading}</h2>
        <p>${description}</p>

        <div class="psych-curator-answers-overview__stats">
          <a class="psych-curator-answer-stat is-pending" href="${pendingUrl}">
            <strong data-answer-pending>—</strong>
            <span>требуют внимания</span>
          </a>

          <a class="psych-curator-answer-stat" href="${allUrl}">
            <strong data-answer-total>—</strong>
            <span>всего ответов</span>
          </a>
        </div>
      </div>

      <a class="psych-curator-answers-overview__action" href="${pendingUrl}">
        <span>Открыть ответы</span>
        ${iconArrow()}
      </a>
    `;

    Promise.all([
      fetchTrainingAnswerCount(trainingId, 'unanswered'),
      fetchTrainingAnswerCount(trainingId, '')
    ]).then(([pending, total]) => {
      const pendingNode = section.querySelector('[data-answer-pending]');
      const totalNode = section.querySelector('[data-answer-total]');

      pendingNode.textContent = pending ?? '—';
      totalNode.textContent = total ?? '—';

      section.classList.remove('is-loading');

      if ((pending ?? 0) > 0) {
        section.classList.add('has-pending');
      }
    }).catch(error => {
      console.warn('[curator-training] Не удалось получить счётчики ответов:', error);
      section.classList.remove('is-loading');
      section.classList.add('has-error');

      const text = section.querySelector('.psych-curator-answers-overview__content > p');
      if (text) text.textContent = 'Откройте ленту ответов для просмотра актуальных данных';
    });

    return section;
  }

  function buildModulesView(modules) {
    const title = getPageTitle();
    const totalLessons = modules.reduce((sum, m) => sum + (m.lessons || 0), 0);

    const root = document.createElement('section');
    root.className = 'psych-curator-training-shell psych-curator-training-shell--modules';

    root.append(buildHeader({
      title,
      subtitle: `${modules.length} ${modules.length === 1 ? 'модуль' : modules.length >= 2 && modules.length <= 4 ? 'модуля' : 'модулей'} · ${totalLessons} уроков`,
      backLink: null
    }));

    const trainingId = getCurrentTrainingId();
    if (trainingId) {
      root.append(buildAnswersOverview(trainingId));
    }

    const sectionHead = document.createElement('div');
    sectionHead.className = 'psych-curator-training-section-head';
    sectionHead.innerHTML = `
      <h2>Модули тренинга</h2>
      <span>${modules.length}</span>
    `;
    root.append(sectionHead);

    const grid = document.createElement('div');
    grid.className = 'psych-curator-module-grid';

    modules.forEach(module => {
      const card = document.createElement('a');
      card.href = module.href;
      card.className = 'psych-curator-module-card';

      card.innerHTML = `
        <div class="psych-curator-module-card__top">
          <span class="psych-curator-module-card__icon">${iconLayers()}</span>
          <span class="psych-curator-module-card__number">${String(module.index).padStart(2, '0')}</span>
        </div>
        <div class="psych-curator-module-card__body">
          <div class="psych-curator-module-card__label">Модуль</div>
          <h3 class="psych-curator-module-card__title"></h3>
          <div class="psych-curator-module-card__meta"></div>
        </div>
        <div class="psych-curator-module-card__footer">
          <span>Открыть модуль</span>
          ${iconArrow()}
        </div>
      `;

      card.querySelector('.psych-curator-module-card__title').textContent = module.title;
      card.querySelector('.psych-curator-module-card__meta').textContent =
        module.lessons != null
          ? `${module.lessons} ${module.lessons === 1 ? 'урок' : module.lessons >= 2 && module.lessons <= 4 ? 'урока' : 'уроков'}`
          : 'Открыть содержание';

      grid.append(card);
    });

    root.append(grid);
    return root;
  }

  function buildLessonsView(lessons) {
    const title = getPageTitle();
    const parent = getParentTrainingLink();

    const root = document.createElement('section');
    root.className = 'psych-curator-training-shell psych-curator-training-shell--lessons';

    root.append(buildHeader({
      title,
      subtitle: `${lessons.length} ${lessons.length === 1 ? 'урок' : lessons.length >= 2 && lessons.length <= 4 ? 'урока' : 'уроков'} · все доступны куратору`,
      backLink: parent
    }));

    const trainingId = getCurrentTrainingId();
    if (trainingId) {
      root.append(buildAnswersOverview(trainingId, 'module'));
    }

    const sectionHead = document.createElement('div');
    sectionHead.className = 'psych-curator-training-section-head';
    sectionHead.innerHTML = `
      <h2>Уроки</h2>
      <span>${lessons.length}</span>
    `;
    root.append(sectionHead);

    const list = document.createElement('div');
    list.className = 'psych-curator-lesson-list';

    lessons.forEach(lesson => {
      const card = document.createElement('a');
      card.href = lesson.href;
      card.className = 'psych-curator-lesson-card';
      if (lesson.isClosed) card.classList.add('is-student-closed');

      card.innerHTML = `
        <div class="psych-curator-lesson-card__number ${lesson.type !== 'lesson' ? 'is-special is-' + lesson.type : ''}">${getCuratorLessonMarker(lesson)}</div>

        <div class="psych-curator-lesson-card__main">
          <div class="psych-curator-lesson-card__top">
            <span class="psych-curator-lesson-card__kind"></span>
            <span class="psych-curator-lesson-card__badge">Доступен куратору</span>
          </div>

          <h3 class="psych-curator-lesson-card__title"></h3>
          <div class="psych-curator-lesson-card__student-state"></div>
        </div>

        <div class="psych-curator-lesson-card__arrow">${iconArrow()}</div>
      `;

      card.querySelector('.psych-curator-lesson-card__kind').textContent = lesson.kind;
      card.querySelector('.psych-curator-lesson-card__title').textContent = lesson.title;

      const state = card.querySelector('.psych-curator-lesson-card__student-state');
      if (lesson.studentState) {
        state.textContent = lesson.isClosed
          ? `Для учеников: ${lesson.studentState}`
          : lesson.studentState;
      } else {
        state.textContent = 'Открыть содержание и задание';
      }

      list.append(card);
    });

    root.append(list);
    return root;
  }

  function release() {
    document.documentElement.classList.remove('psych-curator-training-loading');
    document.documentElement.classList.add('psych-curator-training-ready');
    document.body.classList.add('psych-curator-training-ready');
  }

  let started = false;

  function init() {
    if (started) return;

    /*
     * На странице тренинга преподавателя GetCourse не всегда выводит
     * .standard-page-content. В таком случае используем основной
     * контейнер страницы, в котором уже находится .xdget-root.
     */
    const container =
      document.querySelector('.standard-page-content') ||
      document.querySelector('.main-page-block > .container') ||
      document.querySelector('.xdget-root')?.parentElement;

    if (!container) return;

    const lessons = getLessons();
    const modules = getModules();

    if (!lessons.length && !modules.length) return;

    started = true;
    hideNativeManagement();

    const nativeTraining = document.querySelector('.xdget-root, .xdget-training');
    if (nativeTraining) nativeTraining.classList.add('psych-curator-native-training-hidden');

    const old = document.querySelector('.psych-curator-training-shell');
    if (old) old.remove();

    const view = lessons.length
      ? buildLessonsView(lessons)
      : buildModulesView(modules);

    container.append(view);
    release();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init, { once: true });
  } else {
    init();
  }

  new MutationObserver(() => {
    if (!started) init();
  }).observe(document.documentElement, { childList: true, subtree: true });

  setTimeout(init, 250);
  setTimeout(init, 700);
  setTimeout(init, 1400);

  setTimeout(() => {
    if (!document.querySelector('.psych-curator-training-shell')) {
      document.documentElement.classList.remove('psych-curator-training-loading');
    }
  }, 3500);
})();
