const body = document.body;
const menuToggle = document.querySelector('.menu-toggle');
const nav = document.querySelector('.nav');
const faqButtons = document.querySelectorAll('.faq-question');
const bookingForm = document.getElementById('booking-form');
const formStatus = document.getElementById('form-status');
const promoModal = document.getElementById('promo-modal');
const promoPanel = promoModal?.querySelector('.promo-modal__panel') ?? null;
const closePopupControls = document.querySelectorAll('[data-close-popup]');
const popupStorageKey = 'amberSpaPromoClosed';

let lastFocusedElement = null;

if (menuToggle && nav) {
  menuToggle.addEventListener('click', () => {
    const expanded = menuToggle.getAttribute('aria-expanded') === 'true';
    menuToggle.setAttribute('aria-expanded', String(!expanded));
    body.classList.toggle('menu-open', !expanded);
  });

  nav.querySelectorAll('a').forEach((link) => {
    link.addEventListener('click', () => {
      menuToggle.setAttribute('aria-expanded', 'false');
      body.classList.remove('menu-open');
    });
  });
}

faqButtons.forEach((button) => {
  button.addEventListener('click', () => {
    const item = button.closest('.faq-item');
    const isOpen = button.getAttribute('aria-expanded') === 'true';

    faqButtons.forEach((otherButton) => {
      otherButton.setAttribute('aria-expanded', 'false');
      otherButton.closest('.faq-item')?.classList.remove('is-open');
    });

    if (!isOpen && item) {
      button.setAttribute('aria-expanded', 'true');
      item.classList.add('is-open');
    }
  });
});

function setFormStatus(message, type) {
  if (!formStatus) return;
  formStatus.textContent = message;
  formStatus.classList.remove('is-success', 'is-error');

  if (type) {
    formStatus.classList.add(type === 'success' ? 'is-success' : 'is-error');
  }
}

if (bookingForm) {
  bookingForm.addEventListener('submit', async (event) => {
    event.preventDefault();
    setFormStatus('', '');

    if (!bookingForm.reportValidity()) {
      return;
    }

    const submitButton = bookingForm.querySelector('button[type="submit"]');
    const formData = new FormData(bookingForm);

    if (submitButton instanceof HTMLButtonElement) {
      submitButton.disabled = true;
      submitButton.textContent = 'Отправляем...';
    }

    try {
      const response = await fetch(bookingForm.action, {
        method: 'POST',
        body: formData,
        headers: {
          'X-Requested-With': 'XMLHttpRequest'
        }
      });

      const contentType = response.headers.get('content-type') || '';
      let result = null;

      if (contentType.includes('application/json')) {
        result = await response.json();
      } else {
        throw new Error('Сервис временно недоступен. Попробуйте позже или свяжитесь по телефону.');
      }

      if (!response.ok || !result.success) {
        throw new Error(result.message || 'Не удалось отправить заявку.');
      }

      bookingForm.reset();
      setFormStatus(result.message || 'Заявка отправлена. Мы скоро свяжемся с вами.', 'success');
    } catch (error) {
      const fallbackMessage = 'Ошибка отправки. Попробуйте позже или свяжитесь по телефону.';
      const safeMessage = error instanceof Error && !error.message.includes('JSON')
        ? error.message
        : fallbackMessage;

      setFormStatus(safeMessage, 'error');
    } finally {
      if (submitButton instanceof HTMLButtonElement) {
        submitButton.disabled = false;
        submitButton.textContent = 'Отправить заявку';
      }
    }
  });
}

function closePromoModal() {
  if (!promoModal) return;
  promoModal.classList.remove('is-visible');
  promoModal.setAttribute('aria-hidden', 'true');
  body.classList.remove('modal-open');
  window.sessionStorage.setItem(popupStorageKey, 'true');

  if (lastFocusedElement instanceof HTMLElement) {
    lastFocusedElement.focus();
  }
}

function openPromoModal() {
  if (!promoModal) return;
  lastFocusedElement = document.activeElement;
  promoModal.classList.add('is-visible');
  promoModal.setAttribute('aria-hidden', 'false');
  body.classList.add('modal-open');

  if (promoPanel instanceof HTMLElement) {
    promoPanel.focus();
  }
}

closePopupControls.forEach((control) => {
  control.addEventListener('click', closePromoModal);
});

document.addEventListener('keydown', (event) => {
  if (event.key === 'Escape') {
    closePromoModal();
  }
});

window.addEventListener('load', () => {
  const popupDismissed = window.sessionStorage.getItem(popupStorageKey) === 'true';

  if (!popupDismissed) {
    window.setTimeout(openPromoModal, 3200);
  }
});
