---
const title = 'Бесплатная консультация';
---

<div id="consultation-modal" class="modal-overlay" aria-hidden="true">
  <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="modal-title">
    <div class="modal-content">
      <div class="modal-header">
        <h2 id="modal-title" class="modal-title">{title}</h2>
        <button class="modal-close" aria-label="Закрыть" id="modal-close-btn">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>
      <p class="modal-description">
        Оставьте свои контактные данные, и мы свяжемся с вами в течение 15 минут
      </p>

      <!-- Honeypot поле для защиты от спама -->
        <input type="text" name="website" id="website-field" class="hidden-field" tabindex="-1" autocomplete="off" />

        <form class="modal-form" action="#" method="POST" id="consultation-form">
        <div class="form-group">
          <label for="name" class="form-label">Ваше имя</label>
          <input
              type="text"
              id="name"
              name="name"
              class="form-input"
              placeholder="Иван Иванов"
              required
          />
        </div>

        <div class="form-group">
          <label for="phone" class="form-label">Телефон</label>
          <input
              type="tel"
              id="phone"
              name="phone"
              class="form-input"
              placeholder="+7 (___) ___-__-__"
              required
          />
        </div>

        <div class="consent-checkbox">
          <input type="checkbox" id="consent" name="consent" required />
          <label for="consent">
            Я согласен на <a href="/privacy">обработку персональных данных</a> и принимаю <a href="/terms">условия использования</a>
          </label>
        </div>

        <button type="submit" class="modal-submit">
          Отправить заявку
        </button>

        <p class="form-privacy">
          Нажимая кнопку, вы соглашаетесь с
          <a href="/privacy" class="privacy-link">политикой конфиденциальности</a>
        </p>
      </form>
    </div>
  </div>
</div>

<script>
  (function() {
    const modal = document.getElementById('consultation-modal');
    const closeBtn = document.getElementById('modal-close-btn');
    const form = document.getElementById('consultation-form');

    function openModal() {
      if (!modal) return;
      modal.classList.add('active');
      modal.setAttribute('aria-hidden', 'false');
      document.body.style.overflow = 'hidden';
      modal.removeAttribute('inert');
      startAutoCloseTimer();
    }

    function closeModal() {
      if (!modal) return;
      document.activeElement?.blur();
      modal.classList.remove('active');
      modal.setAttribute('aria-hidden', 'true');
      document.body.style.overflow = '';
      document.body.setAttribute('inert', '');
      setTimeout(() => document.body.removeAttribute('inert'), 100);
      resetAutoCloseTimer();
    }

    // Таймер для автозакрытия
    let autoCloseTimer: ReturnType<typeof setTimeout> | null = null;

    function startAutoCloseTimer() {
      if (autoCloseTimer) clearTimeout(autoCloseTimer);
      autoCloseTimer = setTimeout(() => {
        closeModal();
      }, 5000);
    }

    function resetAutoCloseTimer() {
      if (autoCloseTimer) {
        clearTimeout(autoCloseTimer);
        autoCloseTimer = null;
      }
    }

    // Открытие по кастомному событию
    window.addEventListener('open-modal', (e: Event) => {
      const customEvent = e as CustomEvent<string>;
      if (customEvent.detail === 'consultation-modal') {
        openModal();
      }
    });

    // Закрытие по крестику
    closeBtn?.addEventListener('click', closeModal);

    // Закрытие по клику вне модального окна
    modal?.addEventListener('click', (e) => {
      if (e.target === modal) {
        closeModal();
      }
    });

    // Закрытие по Escape
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && modal?.classList.contains('active')) {
        closeModal();
      }
    });

    // Обработка отправки формы
    form?.addEventListener('submit', async (e) => {
      e.preventDefault();
      
      const formData = new FormData(form);
      const website = formData.get('website');
      
      if (website) {
        console.log('Spam detected');
        return;
      }
      
      const name = formData.get('name');
      const phone = formData.get('phone');
      
      if (!name || !phone) {
        (window as any).toast?.show('Пожалуйста, заполните имя и телефон', 'error', 3000);
        return;
      }
      
      try {
        const response = await fetch('/api/consultation', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ name, phone })
        });
        
        const result = await response.json();
        
        if (result.success) {
          (window as any).toast?.show('Спасибо! Мы свяжемся с вами в течение 15 минут.', 'success', 4000);
          form.reset();
          closeModal();
        } else {
          (window as any).toast?.show(result.error || 'Ошибка отправки', 'error', 4000);
        }
      } catch (error) {
        console.error('Error:', error);
        (window as any).toast?.show('Ошибка отправки. Попробуйте позже.', 'error', 4000);
      }
    });

    // Сброс таймера при активности пользователя
    modal?.addEventListener('mousemove', resetAutoCloseTimer);
    modal?.addEventListener('click', resetAutoCloseTimer);

    // Для Astro View Transitions
    document.addEventListener('astro:page-load', () => {
      // Переинициализация при навигации
    });
  })();
</script>

<style is:global>
  .modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(10, 25, 41, 0.85);
    backdrop-filter: blur(8px);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    padding: 2rem 1rem;
  }

  .modal-overlay.active {
    display: flex;
  }

  .modal-container {
    background: #ffffff;
    border-radius: 24px;
    box-shadow: 0 30px 60px -12px rgba(0, 0, 0, 0.4);
    max-width: 480px;
    width: 100%;
    max-height: 90vh;
    overflow-y: auto;
    position: relative;
    transform: translateY(-20px);
    transition: transform 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
  }

  .modal-overlay.active .modal-container {
    transform: translateY(0);
  }

  .modal-content {
    padding: 2.5rem 2rem 1.5rem;
  }

  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
    margin-bottom: 0.5rem;
  }

  .modal-close {
    background: #f1f5f9;
    border: none;
    cursor: pointer;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #64748b;
    flex-shrink: 0;
    transition: all 0.2s ease;
  }

  .modal-close:hover {
    background: #e2e8f0;
    color: #0f172a;
  }

  .modal-close:hover svg {
    transform: rotate(90deg);
  }

  .modal-close svg {
    transition: transform 0.2s ease;
  }

  .modal-title {
    font-size: 1.5rem;
    font-weight: 800;
    color: #0f172a;
    margin: 0;
    letter-spacing: -0.02em;
    line-height: 1.2;
  }

  .modal-description {
    color: #64748b;
    font-size: 0.95rem;
    text-align: center;
    margin: 0 0 1.5rem;
    line-height: 1.5;
  }

  .modal-form {
    display: flex;
    flex-direction: column;
    gap: 1rem;
  }

  .form-group {
    display: flex;
    flex-direction: column;
    gap: 0.4rem;
  }

  .form-label {
    font-size: 0.85rem;
    font-weight: 600;
    color: #0f172a;
  }

  .form-input {
    padding: 0.9rem 1rem;
    border: 2px solid #e2e8f0;
    border-radius: 14px;
    font-size: 1rem;
    font-family: inherit;
    transition: all 0.3s ease;
    outline: none;
    background: #f8fafc;
  }

  .form-input:focus {
    border-color: #d4af37;
    background: #fff;
    box-shadow: 0 0 0 4px rgba(212, 175, 55, 0.1);
  }

  .form-input::placeholder {
    color: #94a3b8;
  }

  .modal-submit {
    background: linear-gradient(135deg, #d4af37 0%, #eac26e 100%);
    color: #1e293b;
    border: none;
    padding: 0.9rem 1.5rem;
    border-radius: 14px;
    font-size: 1rem;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 4px 16px rgba(212, 175, 55, 0.3);
  }

  .modal-submit:hover {
    box-shadow: 0 8px 24px rgba(212, 175, 55, 0.5);
    transform: translateY(-2px);
  }

  .modal-submit:active {
    transform: translateY(0);
  }

  .form-privacy {
    font-size: 0.75rem;
    color: #94a3b8;
    text-align: center;
    margin: 0;
    line-height: 1.4;
  }

  .consent-checkbox {
    display: flex;
    align-items: flex-start;
    gap: 0.75rem;
    margin-bottom: 0.5rem;
  }

  .consent-checkbox input[type="checkbox"] {
    width: 18px;
    height: 18px;
    margin-top: 2px;
    accent-color: #d4af37;
    cursor: pointer;
    flex-shrink: 0;
  }

  .consent-checkbox label {
    font-size: 0.8rem;
    color: #64748b;
    line-height: 1.4;
    cursor: pointer;
  }

  .consent-checkbox a {
    color: #d4af37;
    text-decoration: underline;
  }

  .consent-checkbox a:hover {
    color: #b8962e;
  }

  .privacy-link {
    color: #d4af37;
    text-decoration: underline;
    text-underline-offset: 2px;
    transition: color 0.2s ease;
  }

  .privacy-link:hover {
    color: #b8962e;
    text-decoration: none;
  }

  .hidden-field {
    position: absolute;
    left: -9999px;
    opacity: 0;
    pointer-events: none;
  }

  @media (max-width: 480px) {
    .modal-overlay {
      padding: 0.5rem;
    }

    .modal-container {
      border-radius: 16px;
      max-height: 85vh;
      width: calc(100% - 1rem);
    }

    .modal-content {
      padding: 1.5rem 1.25rem 1.25rem;
    }

    .modal-header {
      margin-bottom: 0.4rem;
    }

    .modal-close {
      width: 28px;
      height: 28px;
    }

    .modal-close svg {
      width: 16px;
      height: 16px;
    }

    .modal-title {
      font-size: 1.25rem;
    }

    .modal-description {
      font-size: 0.85rem;
      margin-bottom: 1.25rem;
    }

    .modal-form {
      gap: 0.875rem;
    }

    .form-label {
      font-size: 0.8rem;
    }

    .form-input {
      padding: 0.8rem 0.9rem;
      font-size: 0.95rem;
      border-radius: 12px;
    }

    .modal-submit {
      padding: 0.85rem 1.25rem;
      font-size: 0.95rem;
      border-radius: 12px;
    }

    .form-privacy {
      font-size: 0.7rem;
    }
  }

  @media (max-width: 360px) {
    .modal-title {
      font-size: 1.1rem;
    }

    .modal-description {
      font-size: 0.8rem;
    }

    .form-input {
      padding: 0.75rem 0.8rem;
      font-size: 0.9rem;
    }

    .modal-submit {
      padding: 0.75rem 1rem;
      font-size: 0.9rem;
    }
  }
</style>
