---
import { CONTACT_CONSTANTS } from "@constants/constants.ts";
import SocialIcons from "@components/base/SocialIcons.astro";
---

<section id="contact" class="py-24 bg-[var(--color-navy-dark)] relative overflow-hidden">
  <!-- Декоративные элементы -->
  <div class="absolute inset-0">
    <!-- Диагональный градиент -->
    <div class="absolute inset-0 bg-gradient-to-br from-[var(--color-navy)] via-[var(--color-navy)]/95 to-[var(--color-navy-dark)]"></div>

    <!-- Сетка -->
    <div
      class="absolute inset-0 opacity-[0.02]"
      style="background-image: linear-gradient(45deg, var(--color-gold) 1px, transparent 1px), linear-gradient(-45deg, var(--color-gold) 1px, transparent 1px); background-size: 50px 50px;"
    ></div>

    <!-- Световые пятна -->
    <div class="absolute top-0 right-0 w-[500px] h-[500px] bg-[var(--color-gold)]/5 rounded-full blur-[150px]"></div>
    <div class="absolute bottom-0 left-0 w-[400px] h-[400px] bg-[var(--color-blue-primary)]/5 rounded-full blur-[120px]"></div>
  </div>

  <div class="container mx-auto px-4 md:px-8 lg:px-16 relative z-10">
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-20 items-center">

      <!-- Левая часть - заголовок и контакты -->
      <div>
        <!-- Бейдж -->
        <div class="inline-flex items-center gap-3 mb-8">
          <span class="w-3 h-3 bg-[var(--color-gold)] rotate-45"></span>
          <span class="text-[var(--color-gold)] text-xs font-bold uppercase tracking-[0.2em]">
            Связаться со мной
          </span>
        </div>

        <!-- Заголовок -->
        <h2 class="text-4xl md:text-5xl lg:text-6xl font-bold text-[var(--color-white)] mb-6 leading-[0.95]">
          ГОТОВЫ<br />
          <span class="text-[var(--color-gold)]">НАЧАТЬ?</span>
        </h2>

        <!-- Описание -->
        <p class="text-[var(--color-gray-400)] text-lg mb-10 leading-relaxed">
          Оставьте заявку на бесплатную консультацию. Проанализирую вашу ситуацию
          и расскажу о перспективах дела.
        </p>

        <!-- Телефон -->
        <button
          data-consultation-modal
          class="group flex items-center gap-4 p-6 bg-[var(--color-navy)] border border-[var(--color-gray-600)]/20 rounded-xl hover:border-[var(--color-gold)]/30 transition-all mb-8 cursor-pointer"
        >
          <div class="w-14 h-14 bg-[var(--color-gold)] rounded-lg flex items-center justify-center flex-shrink-0 group-hover:scale-110 transition-transform">
            <svg class="w-6 h-6 text-[var(--color-white)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"></path>
            </svg>
          </div>
          <div class="text-left">
            <div class="text-[var(--color-gray-500)] text-xs uppercase tracking-wider mb-1">Позвонить сейчас</div>
            <div class="text-2xl font-bold text-[var(--color-white)] group-hover:text-[var(--color-gold)] transition-colors">{CONTACT_CONSTANTS.phone}</div>
          </div>
        </button>

        <!-- Мессенджеры -->
        <div class="flex items-center gap-4">
          <span class="text-[var(--color-gray-500)] text-sm">Или напишите:</span>
          <SocialIcons variant="messenger" />
        </div>

        <!-- Гарантия -->
        <div class="mt-10 flex items-start gap-4 p-4 bg-[var(--color-gold)]/5 border border-[var(--color-gold)]/10">
          <div class="w-10 h-10 bg-[var(--color-gold)]/10 flex items-center justify-center flex-shrink-0">
            <svg class="w-5 h-5 text-[var(--color-gold)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
            </svg>
          </div>
          <div>
            <div class="text-[var(--color-white)] font-bold text-sm mb-1">Конфиденциальность гарантирована</div>
            <div class="text-[var(--color-gray-500)] text-xs">Вся информация защищена адвокатской тайной</div>
          </div>
        </div>
      </div>

      <!-- Правая часть - форма или блок авторизации -->
      <div class="relative">
        <!-- Фоновое свечение -->
        <div class="absolute -inset-4 bg-[var(--color-gold)]/5 rounded-2xl blur-2xl"></div>

        <!-- Блок для неавторизованных -->
        <div id="auth-required-block" class="relative bg-[var(--color-navy)] border border-[var(--color-gray-600)]/10 p-12 text-center">
          <!-- Иконка замка -->
          <div class="w-20 h-20 bg-gradient-to-br from-[var(--color-gold)] to-[var(--color-gold-hover)] rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg shadow-[var(--color-gold)]/30">
            <svg class="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
          </div>

          <!-- Заголовок -->
          <h3 class="text-xl font-bold text-[var(--color-white)] mb-3">
            Требуется авторизация
          </h3>

          <!-- Описание -->
          <p class="text-[var(--color-gray-400)] text-sm mb-8">
            Для отправки заявки на консультацию необходимо войти в систему
            или зарегистрироваться.
          </p>

          <!-- Кнопки действий -->
          <div class="flex flex-col sm:flex-row gap-4 justify-center">
            <a
              id="login-link"
              href="/auth/login"
              class="inline-flex items-center justify-center gap-2 px-6 py-3 bg-[var(--color-gold)] hover:bg-[var(--color-gold-hover)] text-white font-bold rounded-lg transition-all hover:shadow-lg hover:shadow-[var(--color-gold)]/30"
            >
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1" />
              </svg>
              Войти
            </a>

            <a
              id="register-link"
              href="/auth/register"
              class="inline-flex items-center justify-center gap-2 px-6 py-3 bg-[var(--color-navy)] border-2 border-[var(--color-gold)] text-[var(--color-gold)] font-bold rounded-lg hover:bg-[var(--color-gold)] hover:text-white transition-all"
            >
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
              </svg>
              Зарегистрироваться
            </a>
          </div>
        </div>

        <!-- Форма для авторизованных (скрыта по умолчанию) -->
        <div id="consultation-form-block" class="relative bg-[var(--color-navy)] border border-[var(--color-gray-600)]/10 p-8 hidden">
          <h3 class="text-2xl font-bold text-[var(--color-white)] mb-2">Заявка на консультацию</h3>
          <p class="text-[var(--color-gray-500)] text-sm mb-6">Заполните форму — перезвоню в течение 15 минут</p>

          <form id="consultation-form" class="space-y-4" novalidate>
            <div>
              <input
                type="text"
                id="form-name"
                name="name"
                placeholder="Ваше имя"
                required
                minlength="2"
                maxlength="50"
                pattern="[А-Яа-яЁёA-Za-z\s\-]+"
                class="w-full px-4 py-4 bg-[var(--color-navy-dark)] border border-[var(--color-gray-600)]/20 rounded-lg text-[var(--color-white)] placeholder-[var(--color-gray-600)] focus:border-[var(--color-gold)] focus:outline-none transition-colors"
              />
              <span id="name-error" class="text-red-500 text-xs mt-1 hidden"></span>
            </div>
            <div>
              <input
                type="tel"
                id="form-phone"
                name="phone"
                placeholder="Телефон"
                required
                pattern="\+7 \(\d{3}\) \d{3}-\d{2}-\d{2}"
                class="w-full px-4 py-4 bg-[var(--color-navy-dark)] border border-[var(--color-gray-600)]/20 rounded-lg text-[var(--color-white)] placeholder-[var(--color-gray-600)] focus:border-[var(--color-gold)] focus:outline-none transition-colors"
              />
              <span id="phone-error" class="text-red-500 text-xs mt-1 hidden"></span>
            </div>
            <div>
              <select id="form-practice" name="practice" class="w-full px-4 py-4 bg-[var(--color-navy-dark)] border border-[var(--color-gray-600)]/20 rounded-lg text-[var(--color-gray-400)] focus:border-[var(--color-gold)] focus:outline-none transition-colors">
                <option value="">Выберите тип дела</option>
                <option value="civil">Гражданские дела</option>
                <option value="admin">Административные дела</option>
                <option value="family">Семейные дела</option>
                <option value="arbitration">Арбитражные дела</option>
                <option value="criminal">Уголовные дела</option>
                <option value="debt-protection">Защита должников</option>
                <option value="svo">Дела СВО</option>
                <option value="other">Другое</option>
              </select>
            </div>
            <div>
              <textarea
                id="form-message"
                name="message"
                placeholder="Краткое описание ситуации"
                rows="4"
                required
                minlength="10"
                maxlength="1000"
                class="w-full px-4 py-4 bg-[var(--color-navy-dark)] border border-[var(--color-gray-600)]/20 rounded-lg text-[var(--color-white)] placeholder-[var(--color-gray-600)] focus:border-[var(--color-gold)] focus:outline-none transition-colors resize-none"
              ></textarea>
              <div class="flex justify-between items-center mt-1">
                <span id="message-error" class="text-red-500 text-xs hidden"></span>
                <span id="char-count" class="text-xs text-[var(--color-gray-600)]">0 / 1000</span>
              </div>
            </div>

            <button
              type="submit"
              id="submit-btn"
              disabled
              class="w-full py-4 bg-[var(--color-gray-600)] text-[var(--color-gray-400)] font-bold rounded-lg transition-all cursor-not-allowed opacity-50"
              data-enabled-class="bg-[var(--color-gold)] hover:bg-[var(--color-gold-hover)] text-[var(--color-white)] font-bold rounded-lg transition-all hover:shadow-[0_0_30px_rgba(191,155,88,0.4)] flex items-center justify-center gap-3 group hover:cursor-pointer"
            >
              <span class="btn-text">Отправить заявку</span>
              <span class="btn-loading hidden">Отправка...</span>
            </button>

            <p class="text-xs text-[var(--color-gray-600)] text-center">
              Нажимая кнопку, вы соглашаетесь с политикой конфиденциальности
            </p>
          </form>
        </div>
      </div>
    </div>
  </div>
</section>

<script>
  import { loadAuthFromCookie } from '@lib/auth.ts';

  // Элементы
  const authRequiredBlock = document.getElementById('auth-required-block');
  const consultationFormBlock = document.getElementById('consultation-form-block');
  const consultationForm = document.getElementById('consultation-form');
  const submitBtn = document.getElementById('submit-btn');
  const btnText = submitBtn?.querySelector('.btn-text');
  const btnLoading = submitBtn?.querySelector('.btn-loading');

  // Проверка авторизации
  async function checkAuth() {
    try {
      const response = await fetch('/api/auth/me', {
        method: 'GET',
        credentials: 'include',
      });

      const data = await response.json();

      if (data.authenticated) {
        // Пользователь авторизован - показываем форму
        authRequiredBlock?.classList.add('hidden');
        consultationFormBlock?.classList.remove('hidden');
        initFormValidation();
      } else {
        // Пользователь не авторизован - показываем блок авторизации
        authRequiredBlock?.classList.remove('hidden');
        consultationFormBlock?.classList.add('hidden');
      }
    } catch (error) {
      console.error('[AuthorizedConsultationCTA] Ошибка проверки авторизации:', error);
      authRequiredBlock?.classList.remove('hidden');
      consultationFormBlock?.classList.add('hidden');
    }
  }

  // Инициализация при загрузке
  loadAuthFromCookie();
  checkAuth();

  // Добавляем redirectUrl к ссылкам авторизации
  const addRedirectToAuthLinks = () => {
    const currentPath = window.location.pathname;
    const loginLink = document.getElementById('login-link');
    const registerLink = document.getElementById('register-link');

    if (loginLink) {
      loginLink.href = `/auth/login?redirect=${encodeURIComponent(currentPath)}`;
    }
    if (registerLink) {
      registerLink.href = `/auth/register?redirect=${encodeURIComponent(currentPath)}`;
    }
  };

  addRedirectToAuthLinks();

  // Инициализация валидации формы
  function initFormValidation() {
    const nameInput = document.getElementById('form-name');
    const phoneInput = document.getElementById('form-phone');
    const messageInput = document.getElementById('form-message');
    const charCount = document.getElementById('char-count');

    const validationRules = {
      name: {
        required: true,
        minLength: 2,
        maxLength: 50,
        pattern: /^[А-Яа-яЁёA-Za-z\s\-]+$/,
      },
      phone: {
        required: true,
        pattern: /^\+7 \(\d{3}\) \d{3}-\d{2}-\d{2}$/,
      },
      message: {
        required: true,
        minLength: 10,
        maxLength: 1000,
      },
    };

    const touchedFields = new Set();

    function validateField(field, showError = false) {
      const name = field.name;
      const rules = validationRules[name];
      const errorEl = field.parentElement?.querySelector('.error-message') || document.getElementById(`${name}-error`);

      if (!rules) return true;

      let isValid = true;
      let errorMsg = '';

      if (rules.required && !field.value.trim()) {
        isValid = false;
        errorMsg = 'Обязательное поле';
      } else if (rules.minLength && field.value.length > 0 && field.value.length < rules.minLength) {
        isValid = false;
        errorMsg = `Минимум ${rules.minLength} символов`;
      } else if (rules.maxLength && field.value.length > rules.maxLength) {
        isValid = false;
        errorMsg = `Максимум ${rules.maxLength} символов`;
      } else if (rules.pattern && field.value.length > 0 && !rules.pattern.test(field.value)) {
        isValid = false;
        errorMsg = 'Некорректный формат';
      }

      if (errorEl && (showError || touchedFields.has(name))) {
        if (!isValid && (field.value.length > 0 || showError)) {
          errorEl.textContent = errorMsg;
          errorEl.classList.remove('hidden');
          field.classList.add('border-red-500');
          field.classList.remove('focus:border-[var(--color-gold)]');
        } else {
          errorEl.classList.add('hidden');
          field.classList.remove('border-red-500');
          field.classList.add('focus:border-[var(--color-gold)]');
        }
      }

      return isValid;
    }

    function checkFormValidity() {
      const fields = consultationForm.querySelectorAll('input[required], textarea[required]');
      let isValid = true;

      fields.forEach((field) => {
        if (!validateField(field, false)) isValid = false;
      });

      if (submitBtn) {
        submitBtn.disabled = !isValid;
        if (isValid) {
          submitBtn.classList.remove('bg-[var(--color-gray-600)]', 'text-[var(--color-gray-400)]', 'cursor-not-allowed', 'opacity-50');
          submitBtn.classList.add('bg-[var(--color-gold)]', 'hover:bg-[var(--color-gold-hover)]', 'text-[var(--color-white)]', 'hover:shadow-[0_0_30px_rgba(191,155,88,0.4)]', 'hover:cursor-pointer');
        } else {
          submitBtn.classList.add('bg-[var(--color-gray-600)]', 'text-[var(--color-gray-400)]', 'cursor-not-allowed', 'opacity-50');
          submitBtn.classList.remove('bg-[var(--color-gold)]', 'hover:bg-[var(--color-gold-hover)]', 'text-[var(--color-white)]', 'hover:shadow-[0_0_30px_rgba(191,155,88,0.4)]', 'hover:cursor-pointer');
        }
      }
      return isValid;
    }

    function showAllErrors() {
      const fields = consultationForm.querySelectorAll('input[required], textarea[required]');
      let isValid = true;

      fields.forEach((field) => {
        touchedFields.add(field.name);
        if (!validateField(field, true)) isValid = false;
      });

      return isValid;
    }

    // Маска телефона
    phoneInput?.addEventListener('input', (e) => {
      const target = e.target;
      let value = target.value.replace(/\D/g, '');

      if (value.length > 11) value = value.slice(0, 11);
      if (value.startsWith('7')) value = value.slice(1);
      if (value.startsWith('8')) value = value.slice(1);

      let formatted = '+7';
      if (value.length > 0) formatted += ' (' + value.slice(0, 3);
      if (value.length > 3) formatted += ') ' + value.slice(3, 6);
      if (value.length > 6) formatted += '-' + value.slice(6, 8);
      if (value.length > 8) formatted += '-' + value.slice(8, 10);

      target.value = formatted;
      validateField(target);
      checkFormValidity();
    });

    // Валидация имени
    nameInput?.addEventListener('input', () => {
      validateField(nameInput);
      checkFormValidity();
    });

    // Счетчик символов для сообщения
    messageInput?.addEventListener('input', () => {
      const length = messageInput.value.length;
      if (charCount) {
        charCount.textContent = `${length} / 1000`;
        charCount.classList.toggle('text-red-500', length > 1000);
      }
      validateField(messageInput);
      checkFormValidity();
    });

    // Отмечаем поле как "тронутое"
    consultationForm.querySelectorAll('input, textarea').forEach((field) => {
      field.addEventListener('focus', () => {
        touchedFields.add(field.name);
      });
      field.addEventListener('blur', () => {
        touchedFields.add(field.name);
        if (field.value.length > 0) {
          validateField(field, true);
        }
      });
    });

    // Отправка формы
    consultationForm?.addEventListener('submit', async (e) => {
      e.preventDefault();

      if (!showAllErrors()) return;

      if (submitBtn && btnText && btnLoading) {
        submitBtn.disabled = true;
        btnText.classList.add('hidden');
        btnLoading.classList.remove('hidden');
      }

      try {
        const formData = new FormData(consultationForm);
        const data = Object.fromEntries(formData);

        const response = await fetch('/api/contact', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data),
        });

        const result = await response.json();

        if (!response.ok) {
          throw new Error(result.error || 'Ошибка при отправке');
        }

        if (typeof window.showToast === 'function') {
          window.showToast('Заявка успешно отправлена! Мы свяжемся с вами в ближайшее время.', 'success', 5000);
        }

        consultationForm.reset();
        if (charCount) {
          charCount.textContent = '0 / 1000';
          charCount.classList.remove('text-red-500');
        }
        checkFormValidity();

      } catch (error) {
        console.error('[AuthorizedConsultationCTA] Ошибка:', error);
        const errorMessage = error instanceof Error ? error.message : 'Ошибка при отправке. Попробуйте позже.';
        if (typeof window.showToast === 'function') {
          window.showToast(errorMessage, 'error', 5000);
        }
      } finally {
        if (submitBtn && btnText && btnLoading) {
          submitBtn.disabled = false;
          btnText.classList.remove('hidden');
          btnLoading.classList.add('hidden');
        }
      }
    });

    checkFormValidity();
  }
</script>
