(function () {
  var EVENT_URL =
    'https://uvnschool.ru/chtm/app/builder/event/~reg/xpgaFXxqaXMjaDvXxgvr1zJmR/3o5t1I23D8?hash=s3xKEOnfUA';

  var WRAPPER_ID = 'uvn-yb-bonuses-wrapper';


  /* =========================================
     Получаем gcId из URL пользователя
     ========================================= */

  function getGcId() {
    var match = window.location.pathname.match(
      /^\/user\/control\/user\/update\/id\/(\d+)\/?$/
    );

    return match ? match[1] : null;
  }


  /* =========================================
     Добавляем блок
     ========================================= */

  function addBonusControl() {
    var gcId = getGcId();

    /*
     * Работаем только на карточке пользователя.
     */
    if (!gcId) {
      return;
    }


    /*
     * Уже добавили.
     */
    if (document.getElementById(WRAPPER_ID)) {
      return;
    }


    var communicationBlock =
      document.querySelector(
        '.user-communication-buttons'
      );

    if (!communicationBlock) {
      return;
    }


    /* Общая строка */

    var wrapper =
      document.createElement('div');

    wrapper.id = WRAPPER_ID;

    wrapper.style.cssText =
      'display:flex;' +
      'align-items:center;' +
      'gap:6px;' +
      'margin-top:8px;' +
      'width:100%;';


    /* =====================================
       Выпадающий список
       ===================================== */

    var select =
      document.createElement('select');

    select.style.cssText =
      'height:32px;' +
      'padding:5px 30px 5px 9px;' +
      'font-size:12px;' +
      'line-height:1.4;' +
      'font-family:Arial,sans-serif;' +
      'color:#333;' +
      'background:#fff;' +
      'border:1px solid #ccc;' +
      'border-radius:6px;' +
      'cursor:pointer;' +
      'outline:none;';


    var options = [
      {
        value: '1',
        text: 'Все бонусы ЯБ'
      },
      {
        value: '2',
        text: 'ОСН 2.0'
      },
      {
        value: '3',
        text: 'Конспекты'
      },
      {
        value: '4',
        text: 'Доп. месяц доступа к ЯБ'
      }
    ];


    options.forEach(
      function (optionData) {
        var option =
          document.createElement('option');

        option.value =
          optionData.value;

        option.textContent =
          optionData.text;

        select.appendChild(option);
      }
    );


    /* =====================================
       Кнопка OK
       ===================================== */

    var button =
      document.createElement('button');

    button.type = 'button';

    button.textContent = 'OK';

    button.style.cssText =
      'height:32px;' +
      'padding:5px 12px;' +
      'font-size:12px;' +
      'line-height:1.4;' +
      'font-family:Arial,sans-serif;' +
      'font-weight:500;' +
      'color:#333;' +
      'background:#fff;' +
      'border:1px solid #ccc;' +
      'border-radius:6px;' +
      'cursor:pointer;';


    wrapper.appendChild(select);
    wrapper.appendChild(button);


    /*
     * Отдельный блок после стандартных
     * кнопок GetCourse.
     */
    communicationBlock.insertAdjacentElement(
      'afterend',
      wrapper
    );


    /* =====================================
       Отправка
       ===================================== */

    button.addEventListener(
      'click',
      function () {
        var currentGcId =
          getGcId();

        if (!currentGcId) {
          return;
        }


        var ybBonus =
          Number(select.value);


        button.disabled = true;
        select.disabled = true;

        button.style.opacity = '0.6';
        button.textContent = '...';


        fetch(
          EVENT_URL,
          {
            method: 'POST',

            headers: {
              'Content-Type':
                'application/json'
            },

            credentials:
              'same-origin',

            body:
              JSON.stringify({
                gcId: currentGcId,
                ybBonus: ybBonus
              })
          }
        )

        .then(function (response) {
          if (!response.ok) {
            throw new Error(
              'HTTP ' +
              response.status
            );
          }


          button.textContent = '✓';


          console.log(
            '[UVN YB BONUS] отправлено',
            {
              gcId: currentGcId,
              ybBonus: ybBonus
            }
          );


          setTimeout(
            function () {
              button.disabled = false;
              select.disabled = false;

              button.style.opacity = '';
              button.textContent = 'OK';
            },
            2000
          );
        })

        .catch(function (error) {
          console.error(
            '[UVN YB BONUS] ошибка:',
            error
          );


          button.textContent = '!';


          setTimeout(
            function () {
              button.disabled = false;
              select.disabled = false;

              button.style.opacity = '';
              button.textContent = 'OK';
            },
            2500
          );
        });
      }
    );
  }


  /* =========================================
     Контроль страницы
     ========================================= */

  function checkPage() {
    var gcId =
      getGcId();


    if (!gcId) {
      var oldWrapper =
        document.getElementById(
          WRAPPER_ID
        );

      if (oldWrapper) {
        oldWrapper.remove();
      }

      return;
    }


    addBonusControl();
  }


  checkPage();


  /*
   * GetCourse может отрисовать карточку
   * пользователя не сразу.
   */
  setInterval(
    checkPage,
    500
  );

})();
