(function () {
  'use strict';

  /* Отдельная страница тикетов обслуживается talks_user, здесь её не трогаем */
  if (window.controllerId === 'conversation' && window.actionId === 'index') return;

  const BODY_CLASS = 'psych-talks-drawer-ui';
  const OPEN_CLASS = 'psych-talks-drawer-open';
  const DRAWER_CLASS = 'psych-talks-drawer';
  const BACKDROP_CLASS = 'psych-talks-drawer-backdrop';

  const qs = (s, r = document) => r.querySelector(s);
  const qsa = (s, r = document) => Array.from(r.querySelectorAll(s));

  function isVisible(el) {
    if (!el) return false;
    const st = getComputedStyle(el);
    if (st.display === 'none' || st.visibility === 'hidden' || Number(st.opacity) === 0) return false;
    const r = el.getBoundingClientRect();
    return r.width > 0 && r.height > 0;
  }

  function ensureBackdrop() {
    let backdrop = qs('.' + BACKDROP_CLASS);
    if (backdrop) return backdrop;

    backdrop = document.createElement('div');
    backdrop.className = BACKDROP_CLASS;
    backdrop.setAttribute('aria-hidden', 'true');

    backdrop.addEventListener('click', () => {
      const drawer = getActiveDrawer();
      if (!drawer) return;

      /*
       * Не ломаем внутреннюю механику GetCourse:
       * сначала ищем нативную кнопку закрытия и кликаем по ней.
       */
      const close =
        qs('.close', drawer) ||
        qs('[class*="close"]', drawer) ||
        qs('[data-action="close"]', drawer) ||
        qs('button[aria-label*="закры" i]', drawer) ||
        qs('button[title*="закры" i]', drawer);

      if (close) close.click();
    });

    document.body.appendChild(backdrop);
    return backdrop;
  }

  function getActiveDrawer() {
    return qsa('.talks-widget-window')
      .filter(el => !el.closest('.psych-talks-page-only'))
      .find(isVisible) || null;
  }

  function decorateWindow(win) {
    if (!win || win.dataset.psychTalksDrawerReady === '1') return;

    win.dataset.psychTalksDrawerReady = '1';
    win.classList.add(DRAWER_CLASS);

    qsa('input[type="text"], input[type="search"], textarea', win).forEach(el => {
      el.classList.add('psych-talks-drawer-field');
    });

    qsa('button, .btn', win).forEach(el => {
      const label = (el.textContent || '').trim();
      if (/отправ|созда|напис|ответ/i.test(label)) {
        el.classList.add('psych-talks-drawer-primary');
      }
    });
  }

  function syncState() {
    document.body.classList.add(BODY_CLASS);

    const windows = qsa('.talks-widget-window');
    windows.forEach(decorateWindow);

    const active = windows.find(isVisible);
    const backdrop = ensureBackdrop();

    document.body.classList.toggle(OPEN_CLASS, !!active);

    if (active) {
      active.classList.add('psych-talks-drawer--active');
      backdrop.classList.add('is-visible');
      backdrop.setAttribute('aria-hidden', 'false');
    } else {
      backdrop.classList.remove('is-visible');
      backdrop.setAttribute('aria-hidden', 'true');
    }

    windows.forEach(win => {
      if (win !== active) win.classList.remove('psych-talks-drawer--active');
    });
  }

  function init() {
    let raf = 0;

    const schedule = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        syncState();
      });
    };

    syncState();

    const observer = new MutationObserver(schedule);
    observer.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ['class', 'style', 'hidden']
    });

    window.addEventListener('resize', schedule, { passive: true });
    window.addEventListener('orientationchange', schedule, { passive: true });

    [150, 400, 900, 1600].forEach(delay => setTimeout(schedule, delay));
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init, { once: true });
  } else {
    init();
  }
})();
