/* GETCOURSE — AUTHENTICATOR PAGE / v1.0
 * Только визуальная адаптация штатной формы GetCourse.
 * Не меняет action, CSRF, secret, submit и yiiActiveForm.
 */
(function () {
  'use strict';

  function isPage() {
    return (
      location.pathname === '/pl/user/profile/enable-google-auth' ||
      (
        window.controllerId === 'profile' &&
        window.actionId === 'enable-google-auth'
      )
    );
  }

  function step(number, title, text) {
    const el = document.createElement('div');
    el.className = 'psych-ga-step-head';
    el.innerHTML = `
      <span class="psych-ga-step-head__number">${number}</span>
      <div>
        <div class="psych-ga-step-head__title">${title}</div>
        ${text ? `<div class="psych-ga-step-head__text">${text}</div>` : ''}
      </div>
    `;
    return el;
  }

  function init() {
    if (!isPage()) return;

    const page = document.querySelector('.standard-page-content');
    const container = document.querySelector('.ga-form-container');
    const form = container?.querySelector('form#w0');
    const qr = container?.querySelector('.code-container');
    const keyBlock = qr?.nextElementSibling;
    const codeField = form?.querySelector('#googleauthform-code');
    const submit = form?.querySelector('.submit-button');

    if (!page || !container || !form || !qr || !codeField || !submit) {
      console.warn('[authenticator-page] Native form elements not found.');
      return;
    }

    document.documentElement.classList.add('psych-ga-page');
    page.classList.add('psych-ga-page__content');
    container.classList.add('psych-ga-card');

    if (!container.querySelector('.psych-ga-back')) {
      const back = document.createElement('a');
      back.className = 'psych-ga-back';
      back.href = '/my-profile';
      back.textContent = '← Вернуться в профиль';
      container.insertBefore(back, container.firstChild);
    }

    const intro = Array.from(container.children).find(el =>
      el.querySelector && el.querySelector('.ga-header')
    );

    if (intro) {
      intro.classList.add('psych-ga-native-intro');

      const header = intro.querySelector('.ga-header');
      const paragraph = intro.querySelector('p');

      if (header) {
        header.textContent = 'Двухфакторная аутентификация';
      }

      if (paragraph) {
        paragraph.textContent =
          'Подключите приложение-аутентификатор, чтобы дополнительно защитить вход в аккаунт.';
      }
    }

    if (!qr.previousElementSibling?.classList.contains('psych-ga-step-head')) {
      qr.parentNode.insertBefore(
        step(
          '1',
          'Отсканируйте QR-код',
          'Откройте Google Authenticator или другое совместимое приложение и добавьте новый аккаунт.'
        ),
        qr
      );
    }

    qr.classList.add('psych-ga-qr');

    if (keyBlock) {
      keyBlock.classList.add('psych-ga-key');
    }

    const codeSection =
      codeField.closest('.mt-3.clearfix') ||
      codeField.parentElement;

    if (
      codeSection &&
      !codeSection.previousElementSibling?.classList.contains('psych-ga-step-head')
    ) {
      codeSection.parentNode.insertBefore(
        step(
          '2',
          'Введите код из приложения',
          'После сканирования в приложении появится шестизначный код.'
        ),
        codeSection
      );
    }

    codeField.setAttribute('inputmode', 'numeric');
    codeField.setAttribute('autocomplete', 'one-time-code');
    codeField.setAttribute('maxlength', '6');

    submit.textContent = 'Подтвердить подключение';

    const wrap = submit.closest('.submit-button-container');
    if (wrap) {
      wrap.classList.add('psych-ga-submit-wrap');
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init, { once: true });
  } else {
    init();
  }
})();