/**
 * Модальные окна
 */
export class Modal {
  constructor(selector, options = {}) {
    this.modal =
      typeof selector === 'string'
        ? document.querySelector(selector)
        : selector;

    if (!this.modal) {
      console.warn('Модальное окно не найдено:', selector);
      return;
    }

    this.options = {
      closeOnEscape: true,
      closeOnOverlay: true,
      focusTrap: true,
      animation: 'fade',
      ...options
    };

    this.isOpen = false;
    this.previousFocus = null;

    this.init();
  }

  init() {
    this.createOverlay();
    this.bindEvents();
    this.setupAccessibility();
  }

  createOverlay() {
    if (!this.modal.querySelector('.modal__overlay')) {
      const overlay = document.createElement('div');
      overlay.className = 'modal__overlay';
      this.modal.insertBefore(overlay, this.modal.firstChild);
    }

    this.overlay = this.modal.querySelector('.modal__overlay');
  }

  bindEvents() {
    // Кнопки открытия
    document
      .querySelectorAll(`[data-modal-open="${this.modal.id}"]`)
      .forEach(btn => {
        btn.addEventListener('click', e => {
          e.preventDefault();
          this.open();
        });
      });

    // Кнопки закрытия
    this.modal.querySelectorAll('[data-modal-close]').forEach(btn => {
      btn.addEventListener('click', e => {
        e.preventDefault();
        this.close();
      });
    });

    // Закрытие по оверлею
    if (this.options.closeOnOverlay) {
      this.overlay.addEventListener('click', () => this.close());
    }

    // Закрытие по Escape
    if (this.options.closeOnEscape) {
      document.addEventListener('keydown', e => {
        if (e.key === 'Escape' && this.isOpen) {
          this.close();
        }
      });
    }
  }

  setupAccessibility() {
    this.modal.setAttribute('role', 'dialog');
    this.modal.setAttribute('aria-modal', 'true');

    if (!this.modal.getAttribute('aria-labelledby')) {
      const title = this.modal.querySelector('.modal__title');
      if (title) {
        title.id = title.id || `modal-title-${Date.now()}`;
        this.modal.setAttribute('aria-labelledby', title.id);
      }
    }
  }

  open() {
    if (this.isOpen) return;

    this.previousFocus = document.activeElement;

    document.body.classList.add('modal-open');
    this.modal.classList.add('modal--open');

    this.isOpen = true;

    // Фокус на модальном окне
    if (this.options.focusTrap) {
      this.trapFocus();
    }

    // Событие открытия
    this.modal.dispatchEvent(new CustomEvent('modal:open'));
  }

  close() {
    if (!this.isOpen) return;

    document.body.classList.remove('modal-open');
    this.modal.classList.remove('modal--open');

    this.isOpen = false;

    // Возврат фокуса
    if (this.previousFocus) {
      this.previousFocus.focus();
    }

    // Событие закрытия
    this.modal.dispatchEvent(new CustomEvent('modal:close'));
  }

  trapFocus() {
    const focusableElements = this.modal.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );

    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];

    if (firstElement) {
      firstElement.focus();
    }

    this.modal.addEventListener('keydown', e => {
      if (e.key === 'Tab') {
        if (e.shiftKey) {
          if (document.activeElement === firstElement) {
            e.preventDefault();
            lastElement.focus();
          }
        } else {
          if (document.activeElement === lastElement) {
            e.preventDefault();
            firstElement.focus();
          }
        }
      }
    });
  }
}

/**
 * Инициализация всех модальных окон
 */
export const initModal = () => {
  document.querySelectorAll('.modal').forEach(modal => {
    new Modal(modal);
  });
};
