<template>
  <div class="members-page">
    <!-- Герой-секция -->
    <section class="hero-section">
      <div class="container">
        <div class="hero-content">
          <h1 class="hero-title">👥 Наша беговая семья</h1>
          <p class="hero-subtitle">Более 150 участников объединены любовью к бегу и стремлением к новым достижениям</p>
          <div class="hero-stats">
            <div class="stat">
              <div class="stat-number">{{ stats.totalMembers }}</div>
              <div class="stat-label">Участников</div>
            </div>
            <div class="stat">
              <div class="stat-number">{{ stats.activeMembers }}</div>
              <div class="stat-label">Активных</div>
            </div>
            <div class="stat">
              <div class="stat-number">{{ stats.citiesCount }}</div>
              <div class="stat-label">Городов</div>
            </div>
            <div class="stat">
              <div class="stat-number">{{ stats.totalDistance }}</div>
              <div class="stat-label">Км за год</div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Основной контент -->
    <section class="members-section">
      <div class="container">
        <div class="members-header">
          <h2 class="section-title">Знакомьтесь с нашей командой</h2>
          <p class="section-subtitle">Бегуны разных уровней, объединенные общей страстью</p>

          <div class="members-controls">
            <!-- Поиск -->
            <div class="search-box">
              <input v-model="searchQuery" type="text" placeholder="🔍 Поиск по имени, фамилии или email..."
                class="search-input" @input="handleSearch">
            </div>

            <!-- Фильтры -->
            <div class="filters-container">
              <div class="filter-group">
                <label for="experience">Опыт:</label>
                <select id="experience" v-model="filters.experience" @change="applyFilters">
                  <option value="all">Любой опыт</option>
                  <option value="beginner">Начинающий</option>
                  <option value="intermediate">Любитель</option>
                  <option value="advanced">Опытный</option>
                  <option value="professional">Профессионал</option>
                </select>
              </div>

              <div class="filter-group">
                <label for="goals">Цели:</label>
                <select id="goals" v-model="filters.goals" @change="applyFilters">
                  <option value="all">Все цели</option>
                  <option value="5км">5 км</option>
                  <option value="10км">10 км</option>
                  <option value="полумарафон">Полумарафон</option>
                  <option value="марафон">Марафон</option>
                  <option value="здоровье">Здоровье</option>
                  <option value="похудение">Похудение</option>
                </select>
              </div>

              <div class="view-toggle">
                <button :class="['view-btn', { 'active': viewMode === 'grid' }]" @click="viewMode = 'grid'"
                  title="Сетка">
                  ▦
                </button>
                <button :class="['view-btn', { 'active': viewMode === 'list' }]" @click="viewMode = 'list'"
                  title="Список">
                  ≡
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Статистика фильтров -->
        <div class="filter-stats" v-if="showFilterStats">
          <p>
            Показано {{ filteredMembers.length }} из {{ members.length }} участников
            <span v-if="searchQuery"> по запросу "{{ searchQuery }}"</span>
            <button class="clear-filters" @click="clearFilters">❌ Очистить фильтры</button>
          </p>
        </div>

        <!-- Загрузка -->
        <div class="loading-state" v-if="loading">
          <div class="loading-spinner"></div>
          <p>Загружаем участников...</p>
        </div>

        <!-- Ошибка -->
        <div class="error-state" v-else-if="error">
          <div class="error-icon">⚠️</div>
          <h3>Ошибка загрузки</h3>
          <p>{{ error }}</p>
          <button class="btn btn-primary" @click="loadMembers">
            🔄 Попробовать снова
          </button>
        </div>

        <!-- Сетка участников -->
        <div class="members-container" :class="viewMode" v-else-if="filteredMembers.length > 0">
          <div v-for="member in paginatedMembers" :key="member.id" class="member-card"
            :class="getExperienceClass(member.experience)">
            <div class="member-avatar">
              <img :src="getAvatarUrl(member.avatar)" :alt="member.firstName + ' ' + member.lastName" class="avatar-img"
                @error="handleImageError">
              <div class="level-badge" :class="getExperienceClass(member.experience)">
                {{ getExperienceLabel(member.experience) }}
              </div>
            </div>

            <div class="member-info">
              <h3 class="member-name">{{ member.firstName }} {{ member.lastName }}</h3>
              <p class="member-email">📧 {{ member.email }}</p>

              <div class="member-stats">
                <div class="stat-item" v-if="member.phone">
                  <span class="stat-icon">📱</span>
                  <span class="stat-value">{{ member.phone }}</span>
                </div>
                <div class="stat-item">
                  <span class="stat-icon">📅</span>
                  <span class="stat-value">Участник с {{ formatDate(member.createdAt) }}</span>
                </div>
              </div>

              <div class="member-achievements">
                <div class="achievement" v-if="member.experience">
                  <span class="achievement-icon">🎯</span>
                  <span class="achievement-text">Опыт: {{ getExperienceLabel(member.experience) }}</span>
                </div>
                <div class="achievement" v-if="member.goals">
                  <span class="achievement-icon">⭐</span>
                  <span class="achievement-text">Цели: {{ truncateText(member.goals, 30) }}</span>
                </div>
              </div>

              <div class="member-interests" v-if="member.goals || member.newsletter">
                <span class="interest-tag" v-if="member.goals">
                  {{ getGoalCategory(member.goals) }}
                </span>
                <span class="interest-tag" v-if="member.newsletter">
                  📰 Рассылка
                </span>
              </div>

              <div class="member-actions">
                <button class="btn-profile" @click="viewProfile(member)">
                  👤 Профиль
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Пустой результат -->
        <div class="empty-state" v-else-if="!loading && members.length === 0">
          <div class="empty-icon">👥</div>
          <h3>Пока нет участников</h3>
          <p>Будьте первым, кто присоединится к нашему клубу!</p>
          <router-link to="/register" class="btn btn-primary">
            👥 Вступить в клуб
          </router-link>
        </div>

        <!-- Пустой результат после фильтрации -->
        <div class="empty-state" v-else-if="!loading && filteredMembers.length === 0">
          <div class="empty-icon">🔍</div>
          <h3>Участники не найдены</h3>
          <p>Попробуйте изменить параметры поиска или фильтры</p>
          <button class="btn btn-primary" @click="clearFilters">
            🗑️ Сбросить фильтры
          </button>
        </div>

        <!-- Пагинация -->
        <div class="pagination" v-if="totalPages > 1 && !loading && !error">
          <button class="pagination-btn" :disabled="currentPage === 1" @click="changePage(currentPage - 1)">
            ‹
          </button>

          <button v-for="page in visiblePages" :key="page"
            :class="['pagination-btn', { 'active': currentPage === page }]" @click="changePage(page)">
            {{ page }}
          </button>

          <button class="pagination-btn" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">
            ›
          </button>
        </div>
      </div>
    </section>

    <!-- Статистика клуба -->
    <section class="stats-section">
      <div class="container">
        <h2 class="section-title">📊 Статистика клуба</h2>
        <div class="club-stats">
          <div class="stat-card">
            <div class="stat-icon">🏃‍♂️</div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalMembers }}</div>
              <div class="stat-label">Участников в клубе</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">🎯</div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.advancedMembers }}</div>
              <div class="stat-label">Опытных бегунов</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">👥</div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.newsletterSubscribers }}</div>
              <div class="stat-label">Подписчиков рассылки</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">📈</div>
            <div class="stat-content">
              <div class="stat-number">{{ stats.activeThisMonth }}</div>
              <div class="stat-label">Активных в этом месяце</div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Призыв к действию -->
    <section class="cta-section">
      <div class="container">
        <div class="cta-content">
          <h2>Стань частью нашей беговой семьи!</h2>
          <p>Присоединяйся к сообществу единомышленников и начни свой путь к новым достижениям</p>

          <div class="success-stories">
            <div class="story-card">
              <div class="story-avatar">
                <img src="https://via.placeholder.com/60/2e8b57/ffffff?text=А" alt="Анна">
              </div>
              <div class="story-content">
                <h4>Анна, участник 1 год</h4>
                <p>"Пришла с нулевым опытом, сейчас готовлюсь к марафону. Благодаря поддержке клуба нашла друзей и
                  полюбила бег!"</p>
                <div class="story-stats">
                  <span>🏃 10км за 48:15</span>
                  <span>📈 Улучшение +12 мин</span>
                </div>
              </div>
            </div>

            <div class="story-card">
              <div class="story-avatar">
                <img src="https://via.placeholder.com/60/26734a/ffffff?text=Д" alt="Данил">
              </div>
              <div class="story-content">
                <h4>Данил, участник 2 года</h4>
                <p>"От первых 5 км до ультрамарафона! В клубе нашел не только тренера, но и верных друзей для совместных
                  тренировок."</p>
                <div class="story-stats">
                  <span>🏔️ 120 км трейл</span>
                  <span>⭐ 5+ личных рекордов</span>
                </div>
              </div>
            </div>
          </div>

          <div class="cta-features">
            <div class="cta-feature">
              <div class="feature-icon">👨‍🏫</div>
              <div class="feature-text">
                <strong>Профессиональный тренер</strong>
                <span>Индивидуальный подход к каждому</span>
              </div>
            </div>
            <div class="cta-feature">
              <div class="feature-icon">👥</div>
              <div class="feature-text">
                <strong>Дружное сообщество</strong>
                <span>Поддержка и мотивация 24/7</span>
              </div>
            </div>
            <div class="cta-feature">
              <div class="feature-icon">📈</div>
              <div class="feature-text">
                <strong>Личный прогресс</strong>
                <span>Регулярное улучшение результатов</span>
              </div>
            </div>
            <div class="cta-feature">
              <div class="feature-icon">🎯</div>
              <div class="feature-text">
                <strong>Участие в забегах</strong>
                <span>От городских стартов до марафонов</span>
              </div>
            </div>
          </div>

          <div class="cta-actions">
            <router-link to="/training" class="btn btn-primary btn-large">
              🏃 Записаться на тренировку
            </router-link>
            <router-link to="/register" class="btn btn-secondary">
              👥 Вступить в клуб
            </router-link>
          </div>

          <div class="cta-note">
            <p>✅ Первая тренировка бесплатно • 💰 Гибкая система оплаты • 👋 Любой уровень подготовки</p>
          </div>
        </div>
      </div>
    </section>

    <!-- Модальное окно профиля -->
    <div class="modal-overlay" :class="{ 'active': showProfileModal }" v-if="showProfileModal">
      <div class="modal-content">
        <button class="modal-close" @click="closeProfileModal">×</button>

        <div class="profile-modal" v-if="selectedMember">
          <div class="profile-header">
            <div class="profile-avatar">
              <img :src="getAvatarUrl(selectedMember.avatar)"
                :alt="selectedMember.firstName + ' ' + selectedMember.lastName">
            </div>
            <div class="profile-info">
              <h2>{{ selectedMember.firstName }} {{ selectedMember.lastName }}</h2>
              <p class="profile-email">📧 {{ selectedMember.email }}</p>
              <div class="profile-badges">
                <span class="level-badge" :class="getExperienceClass(selectedMember.experience)">
                  {{ getExperienceLabel(selectedMember.experience) }}
                </span>
                <span class="member-since">Участник с {{ formatDate(selectedMember.createdAt) }}</span>
              </div>
            </div>
          </div>

          <div class="profile-stats">
            <div class="stat-item">
              <div class="stat-value">{{ selectedMember.experience ? getExperienceLabel(selectedMember.experience) :
                'Неуказан' }}</div>
              <div class="stat-label">Уровень опыта</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ selectedMember.newsletter ? 'Да' : 'Нет' }}</div>
              <div class="stat-label">Подписка на рассылку</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ selectedMember.role || 'user' }}</div>
              <div class="stat-label">Роль в клубе</div>
            </div>
          </div>

          <div class="profile-details">
            <div class="detail-section" v-if="selectedMember.phone">
              <h4>📱 Контакты</h4>
              <p class="contact-info">{{ selectedMember.phone }}</p>
            </div>

            <div class="detail-section" v-if="selectedMember.experience">
              <h4>🎯 Опыт в беге</h4>
              <p class="about-text">{{ selectedMember.experience }}</p>
            </div>

            <div class="detail-section" v-if="selectedMember.goals">
              <h4>⭐ Цели и планы</h4>
              <p class="about-text">{{ selectedMember.goals }}</p>
            </div>

            <div class="detail-section"
              v-if="!selectedMember.phone && !selectedMember.experience && !selectedMember.goals">
              <h4>📝 Информация</h4>
              <p class="about-text">Пользователь еще не заполнил информацию о себе</p>
            </div>
          </div>

          <div class="profile-actions">
            <button class="btn btn-outline" @click="suggestTraining(selectedMember)">
              🏃 Предложить тренировку
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { apiClient } from '../stores/helpers/api';

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Members',
  data() {
    return {
      searchQuery: '',
      filters: {
        experience: 'all',
        goals: 'all'
      },
      viewMode: 'grid',
      currentPage: 1,
      membersPerPage: 12,
      showProfileModal: false,
      selectedMember: null,
      searchTimeout: null,
      loading: false,
      error: '',
      members: [],
      stats: {
        totalMembers: 0,
        activeMembers: 0,
        citiesCount: 0,
        totalDistance: 0,
        advancedMembers: 0,
        newsletterSubscribers: 0,
        activeThisMonth: 0
      }
    }
  },
  computed: {
    filteredMembers() {
      let filtered = this.members

      // Поиск по имени, фамилии и email
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        filtered = filtered.filter(member =>
          member.firstName?.toLowerCase().includes(query) ||
          member.lastName?.toLowerCase().includes(query) ||
          member.email?.toLowerCase().includes(query)
        )
      }

      // Фильтрация по опыту
      if (this.filters.experience !== 'all') {
        filtered = filtered.filter(member => member.experience === this.filters.experience)
      }

      // Фильтрация по целям
      if (this.filters.goals !== 'all') {
        filtered = filtered.filter(member =>
          member.goals && member.goals.toLowerCase().includes(this.filters.goals.toLowerCase())
        )
      }

      return filtered
    },
    paginatedMembers() {
      const startIndex = (this.currentPage - 1) * this.membersPerPage
      return this.filteredMembers.slice(startIndex, startIndex + this.membersPerPage)
    },
    totalPages() {
      return Math.ceil(this.filteredMembers.length / this.membersPerPage)
    },
    visiblePages() {
      const pages = []
      const startPage = Math.max(1, this.currentPage - 2)
      const endPage = Math.min(this.totalPages, startPage + 4)

      for (let i = startPage; i <= endPage; i++) {
        pages.push(i)
      }
      return pages
    },
    showFilterStats() {
      return this.searchQuery ||
        this.filters.experience !== 'all' ||
        this.filters.goals !== 'all'
    }
  },
  methods: {
    handleFirstInteraction() {
      if (!this.hasInteracted) {
        this.hasInteracted = true
        this.showContent()
        clearTimeout(this.autoShowTimeout)
      }
    },
    showContent() {
      this.isContentVisible = true
      // Эмитим событие для показа хедера
      this.$emit('show-header')
    },
    getExperienceLabel(experience) {
      const labels = {
        'beginner': 'Начинающий',
        'intermediate': 'Любитель',
        'advanced': 'Опытный',
        'professional': 'Профессионал'
      }
      return labels[experience] || experience || 'Не указан'
    },

    getExperienceClass(experience) {
      return experience || 'beginner'
    },

    getGoalCategory(goals) {
      if (!goals) return 'Разные цели'

      const goal = goals.toLowerCase()
      if (goal.includes('5км') || goal.includes('5 км')) return '5 км'
      if (goal.includes('10км') || goal.includes('10 км')) return '10 км'
      if (goal.includes('полумарафон')) return 'Полумарафон'
      if (goal.includes('марафон')) return 'Марафон'
      if (goal.includes('ультра')) return 'Ультрамарафон'
      if (goal.includes('здор') || goal.includes('фитнес')) return 'Здоровье'
      if (goal.includes('вес') || goal.includes('похуд')) return 'Похудение'

      return 'Персональные цели'
    },

    getAvatarUrl(avatarPath) {
      if (!avatarPath) {
        return 'https://via.placeholder.com/120/666666/ffffff?text=🏃'
      }
      // Если avatarPath уже полный URL, возвращаем как есть
      if (avatarPath.startsWith('http')) {
        return avatarPath
      }
      // Извлекаем имя файла из пути
      const filename = avatarPath.trim('/').split('/').pop();

      // Используем API эндпоинт вместо прямого доступа
      const fullUrl = `https://begushiybashkir.ru/api/v1/user/avatars/${filename}`;
      // Иначе формируем полный URL к аватару через API
      return fullUrl
    },

    formatDate(dateString) {
      if (!dateString) return 'недавно'
      try {
        const date = new Date(dateString)
        return date.toLocaleDateString('ru-RU')
      } catch {
        return 'недавно'
      }
    },

    truncateText(text, maxLength) {
      if (!text) return ''
      return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
    },

    handleSearch() {
      clearTimeout(this.searchTimeout)
      this.searchTimeout = setTimeout(() => {
        this.currentPage = 1
      }, 300)
    },

    applyFilters() {
      this.currentPage = 1
    },

    clearFilters() {
      this.searchQuery = ''
      this.filters = {
        experience: 'all',
        goals: 'all'
      }
      this.currentPage = 1
    },

    changePage(page) {
      this.currentPage = page
      window.scrollTo({ top: 0, behavior: 'smooth' })
    },

    viewProfile(member) {
      this.selectedMember = member
      this.showProfileModal = true
      document.body.style.overflow = 'hidden'
    },

    closeProfileModal() {
      this.showProfileModal = false
      document.body.style.overflow = ''
    },

    suggestTraining(member) {
      alert(`Предложить совместную тренировку ${member.firstName} ${member.lastName}`)
    },

    handleImageError(event) {
      event.target.src = 'https://via.placeholder.com/120/666666/ffffff?text=🏃'
    },

    handleKeydown(event) {
      if (event.key === 'Escape' && this.showProfileModal) {
        this.closeProfileModal()
      }
    },

    async loadMembers() {
      this.loading = true
      this.error = ''

      try {
        // Используем правильный эндпойнт - /user вместо /users
        const response = await apiClient.get('/user')

        if (response.data && Array.isArray(response.data)) {
          this.members = response.data
          await this.loadStats()
        } else {
          throw new Error('Некорректный формат данных')
        }

      } catch (error) {
        console.error('Ошибка загрузки участников:', error)
        this.error = error.response?.data?.message || error.message || 'Не удалось загрузить список участников'

        // Используем демо-данные
        this.members = this.generateMockMembers()
        this.calculateStats()
      } finally {
        this.loading = false
      }
    },

    async loadStats() {
      try {
        // Пока используем расчетную статистику, так как эндпойнта /stats/members нет
        this.calculateStats()
      } catch (error) {
        console.warn('Не удалось загрузить статистику, используем расчетные значения:', error)
        this.calculateStats()
      }
    },

    calculateStats() {
      this.stats = {
        totalMembers: this.members.length,
        activeMembers: Math.floor(this.members.length * 0.7),
        citiesCount: this.calculateCitiesCount(),
        totalDistance: this.members.length * 250,
        advancedMembers: this.calculateAdvancedMembers(),
        newsletterSubscribers: this.calculateNewsletterSubscribers(),
        activeThisMonth: Math.floor(this.members.length * 0.6)
      }
    },

    calculateCitiesCount() {
      const domains = new Set(this.members.map(member => {
        const email = member.email || ''
        const domain = email.split('@')[1]
        return domain ? domain.split('.')[0] : 'unknown'
      }))
      return domains.size
    },

    calculateAdvancedMembers() {
      return this.members.filter(member =>
        member.experience && ['advanced', 'professional'].includes(member.experience)
      ).length
    },

    calculateNewsletterSubscribers() {
      return this.members.filter(member => member.newsletter).length
    },
  },
  mounted() {
    document.addEventListener('keydown', this.handleKeydown)
    this.loadMembers()
    window.addEventListener('scroll', this.handleFirstInteraction, { passive: true, once: true })
    window.addEventListener('click', this.handleFirstInteraction, { once: true })
    window.addEventListener('touchstart', this.handleFirstInteraction, { once: true })
    this.autoShowTimeout = setTimeout(() => {
      if (!this.hasInteracted) {
        this.showContent()
      }
    }, 3000)
  },
  beforeUnmount() {
    document.removeEventListener('keydown', this.handleKeydown)
    document.body.style.overflow = ''
    // Убираем обработчики при размонтировании
    window.removeEventListener('scroll', this.handleFirstInteraction)
    window.removeEventListener('click', this.handleFirstInteraction)
    window.removeEventListener('touchstart', this.handleFirstInteraction)
    clearTimeout(this.autoShowTimeout)
  }
}
</script>

<style scoped>
/* Добавляем стили для состояний загрузки и ошибки */
.loading-state {
  text-align: center;
  padding: 4rem 2rem;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #2e8b57;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.error-state {
  text-align: center;
  padding: 4rem 2rem;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
}

.error-icon {
  font-size: 4rem;
  margin-bottom: 1.5rem;
}

.error-state h3 {
  color: #e74c3c;
  margin-bottom: 1rem;
}

.error-state p {
  color: #666;
  margin-bottom: 2rem;
}

.contact-info {
  background: #f8f9fa;
  padding: 1rem;
  border-radius: 8px;
  border-left: 4px solid #2e8b57;
  font-family: monospace;
}

.members-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fff8 0%, #f0f8f0 100%);
}

/* Герой-секция */
.hero-section {
  background: linear-gradient(135deg, #2e8b57 0%, #26734a 100%);
  color: white;
  padding: 80px 0 60px;
  text-align: center;
}

.hero-title {
  font-size: 3rem;
  margin-bottom: 1rem;
  font-weight: 800;
}

.hero-subtitle {
  font-size: 1.3rem;
  opacity: 0.9;
  margin-bottom: 2rem;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

.hero-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 2rem;
  max-width: 600px;
  margin: 0 auto;
}

.stat {
  text-align: center;
}

.stat-number {
  font-size: 2.5rem;
  font-weight: 800;
  color: #ffd700;
  margin-bottom: 0.5rem;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.8;
}

/* Основные стили */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.section-title {
  font-size: 2.5rem;
  color: #2e8b57;
  margin-bottom: 1rem;
  font-weight: 700;
  text-align: center;
}

.section-subtitle {
  text-align: center;
  color: #666;
  font-size: 1.2rem;
  margin-bottom: 3rem;
}

/* Заголовок участников */
.members-section {
  padding: 4rem 0;
}

.members-controls {
  background: white;
  padding: 2rem;
  border-radius: 15px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 2rem;
}

.search-box {
  margin-bottom: 1.5rem;
}

.search-input {
  min-width: 70%;
  max-width: 95%;
  padding: 15px 20px;
  border: 2px solid #e9ecef;
  border-radius: 25px;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #2e8b57;
  box-shadow: 0 0 0 3px rgba(46, 139, 87, 0.1);
}

.filters-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  align-items: end;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.filter-group label {
  font-weight: 600;
  color: #333;
  font-size: 0.9rem;
}

.filter-group select {
  padding: 10px 12px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  background: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.filter-group select:focus {
  outline: none;
  border-color: #2e8b57;
}

.view-toggle {
  display: flex;
  gap: 0.5rem;
  align-self: end;
}

.view-btn {
  padding: 10px 15px;
  border: 2px solid #e9ecef;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1.2rem;
}

.view-btn:hover {
  border-color: #2e8b57;
}

.view-btn.active {
  background: #2e8b57;
  color: white;
  border-color: #2e8b57;
}

/* Статистика фильтров */
.filter-stats {
  background: #f8fff8;
  padding: 1rem 1.5rem;
  border-radius: 8px;
  margin-bottom: 2rem;
  border-left: 4px solid #2e8b57;
}

.clear-filters {
  background: none;
  border: none;
  color: #e74c3c;
  cursor: pointer;
  margin-left: 1rem;
  font-size: 0.9rem;
}

.clear-filters:hover {
  text-decoration: underline;
}

/* Контейнер участников */
.members-container.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 2rem;
  margin-bottom: 3rem;
}

.members-container.list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 3rem;
}

/* Карточка участника */
.member-card {
  background: white;
  border-radius: 15px;
  padding: 1.5rem;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.member-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.members-container.list .member-card {
  display: flex;
  gap: 1.5rem;
  align-items: flex-start;
}

.members-container.list .member-avatar {
  flex-shrink: 0;
}

.members-container.list .member-info {
  flex: 1;
}

/* Стили по уровням */
.member-card.beginner {
  border-color: #3498db;
  background: linear-gradient(135deg, #f0f8ff 0%, #e3f2fd 100%);
}

.member-card.intermediate {
  border-color: #2e8b57;
  background: linear-gradient(135deg, #f8fff8 0%, #f0f8f0 100%);
}

.member-card.advanced {
  border-color: #f39c12;
  background: linear-gradient(135deg, #fff9e6 0%, #fff3cc 100%);
}

.member-card.professional {
  border-color: #e74c3c;
  background: linear-gradient(135deg, #ffe6e6 0%, #ffcccc 100%);
}

/* Аватар */
.member-avatar {
  position: relative;
  margin-bottom: 1rem;
  text-align: center;
}

.members-container.list .member-avatar {
  margin-bottom: 0;
}

.avatar-img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid white;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.online-indicator {
  position: absolute;
  bottom: 5px;
  right: 5px;
  width: 12px;
  height: 12px;
  background: #27ae60;
  border: 2px solid white;
  border-radius: 50%;
}

.online-indicator.large {
  width: 16px;
  height: 16px;
  bottom: 8px;
  right: 8px;
}

.level-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #2e8b57;
  color: white;
  padding: 0.3rem 0.8rem;
  border-radius: 15px;
  font-size: 0.7rem;
  font-weight: 600;
  white-space: nowrap;
}

.level-badge.beginner {
  background: #3498db;
}

.level-badge.intermediate {
  background: #2e8b57;
}

.level-badge.advanced {
  background: #f39c12;
}

.level-badge.professional {
  background: #e74c3c;
}

/* Информация участника */
.member-info {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}

.member-name {
  color: #2e8b57;
  margin: 0 0 0.5rem 0;
  font-size: 1.3rem;
}

.member-city {
  color: #666;
  margin: 0 0 1rem 0;
  font-size: 0.9rem;
}

.member-stats {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  font-size: 0.8rem;
  color: #666;
}

.stat-icon {
  font-size: 0.9rem;
}

.stat-value {
  font-weight: 600;
}

.member-achievements {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.achievement {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.8rem;
}

.achievement-icon {
  font-size: 0.9rem;
}

.achievement-text {
  color: #333;
  font-weight: 500;
}

.member-interests {
  display: flex;
  flex-wrap: wrap;
  gap: 0.3rem;
  margin-bottom: 1.5rem;
}

.interest-tag {
  background: rgba(46, 139, 87, 0.1);
  color: #2e8b57;
  padding: 0.2rem 0.6rem;
  border-radius: 12px;
  font-size: 0.7rem;
  font-weight: 500;
}

.interest-more {
  background: rgba(153, 153, 153, 0.1);
  color: #666;
  padding: 0.2rem 0.6rem;
  border-radius: 12px;
  font-size: 0.7rem;
  cursor: help;
}

.member-actions {
  display: flex;
  gap: 0.5rem;
  justify-content: space-between;
}

.btn-profile {
  flex: 1;
  background: #2e8b57;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.8rem;
  font-weight: 600;
}

.btn-profile:hover {
  background: #26734a;
  transform: translateY(-1px);
}

.btn-contact {
  background: #0088cc;
  color: white;
  border: none;
  padding: 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
}

.btn-contact:hover {
  background: #0066a4;
  transform: scale(1.1);
}

/* Пагинация */
.pagination {
  display: flex;
  justify-content: center;
  gap: 0.5rem;
  margin: 3rem 0;
  flex-wrap: wrap;
}

.pagination-btn {
  padding: 10px 15px;
  border: 2px solid #e9ecef;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 600;
  min-width: 45px;
}

.pagination-btn:hover:not(:disabled) {
  border-color: #2e8b57;
  background: #f8fff8;
}

.pagination-btn.active {
  background: #2e8b57;
  color: white;
  border-color: #2e8b57;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* Пустое состояние */
.empty-state {
  text-align: center;
  padding: 4rem 2rem;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1.5rem;
  opacity: 0.5;
}

.empty-state h3 {
  color: #2e8b57;
  margin-bottom: 1rem;
}

.empty-state p {
  color: #666;
  margin-bottom: 2rem;
}

/* Статистика клуба */
.stats-section {
  background: white;
  padding: 4rem 0;
  border-top: 1px solid #e9ecef;
  border-bottom: 1px solid #e9ecef;
}

.club-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 2rem;
}

.stat-card {
  background: #f8fff8;
  padding: 2rem;
  border-radius: 15px;
  text-align: center;
  border: 2px solid #e9ecef;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-3px);
  border-color: #2e8b57;
}

.stat-card .stat-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.stat-card .stat-number {
  font-size: 2.5rem;
  font-weight: 800;
  color: #2e8b57;
  margin-bottom: 0.5rem;
}

.stat-card .stat-label {
  color: #666;
  font-size: 1rem;
}

/* CTA секция */
.cta-section {
  background: linear-gradient(135deg, #2e8b57 0%, #26734a 100%);
  color: white;
  padding: 80px 0;
  text-align: center;
}

.cta-content h2 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
}

.cta-content p {
  font-size: 1.2rem;
  opacity: 0.9;
  margin-bottom: 3rem;
}

.success-stories {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
  margin-bottom: 3rem;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.story-card {
  background: rgba(255, 255, 255, 0.1);
  padding: 2rem;
  border-radius: 15px;
  backdrop-filter: blur(10px);
  display: flex;
  gap: 1.5rem;
  align-items: flex-start;
  text-align: left;
}

.story-avatar img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: 3px solid rgba(255, 255, 255, 0.3);
}

.story-content h4 {
  margin: 0 0 1rem 0;
  color: #ffd700;
}

.story-content p {
  opacity: 0.9;
  margin: 0 0 1rem 0;
  line-height: 1.5;
  font-size: 0.95rem;
}

.story-stats {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.story-stats span {
  background: rgba(255, 255, 255, 0.2);
  padding: 0.3rem 0.8rem;
  border-radius: 15px;
  font-size: 0.8rem;
  font-weight: 600;
}

.cta-features {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 2rem;
  margin-bottom: 3rem;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
}

.cta-feature {
  display: flex;
  align-items: center;
  gap: 1rem;
  text-align: left;
}

.cta-feature .feature-icon {
  font-size: 2.5rem;
  flex-shrink: 0;
}

.cta-feature .feature-text {
  display: flex;
  flex-direction: column;
}

.cta-feature .feature-text strong {
  font-size: 1.1rem;
  margin-bottom: 0.3rem;
}

.cta-feature .feature-text span {
  opacity: 0.8;
  font-size: 0.9rem;
}

.cta-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
  flex-wrap: wrap;
  margin-bottom: 2rem;
}

.cta-note {
  opacity: 0.8;
  font-size: 0.9rem;
}

.cta-note p {
  margin: 0;
}

/* Модальное окно профиля */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  padding: 2rem;
}

.modal-overlay.active {
  opacity: 1;
  visibility: visible;
}

.modal-content {
  background: white;
  border-radius: 20px;
  max-width: 600px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
  transform: translateY(20px);
  transition: transform 0.3s ease;
}

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

.modal-close {
  position: absolute;
  top: 1rem;
  right: 1rem;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  font-size: 1.5rem;
  cursor: pointer;
  z-index: 10;
  transition: background 0.3s ease;
}

.modal-close:hover {
  background: rgba(0, 0, 0, 0.9);
}

.profile-modal {
  padding: 2rem;
}

.profile-header {
  display: flex;
  gap: 2rem;
  align-items: flex-start;
  margin-bottom: 2rem;
  padding-bottom: 2rem;
  border-bottom: 1px solid #e9ecef;
}

.profile-avatar {
  position: relative;
  flex-shrink: 0;
}

.profile-avatar img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #2e8b57;
}

.profile-info h2 {
  color: #2e8b57;
  margin: 0 0 0.5rem 0;
  font-size: 1.8rem;
}

.profile-city {
  color: #666;
  margin: 0 0 1rem 0;
  font-size: 1rem;
}

.profile-badges {
  display: flex;
  gap: 1rem;
  align-items: center;
  flex-wrap: wrap;
}

.member-since {
  background: #f8f9fa;
  color: #666;
  padding: 0.3rem 0.8rem;
  border-radius: 15px;
  font-size: 0.8rem;
}

.profile-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 1rem;
  margin-bottom: 2rem;
  padding: 1.5rem;
  background: #f8fff8;
  border-radius: 10px;
}

.profile-stats .stat-item {
  text-align: center;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.profile-stats .stat-value {
  font-size: 1.5rem;
  font-weight: 800;
  color: #2e8b57;
}

.profile-stats .stat-label {
  color: #666;
  font-size: 0.8rem;
}

.profile-details {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
  margin-bottom: 2rem;
}

.detail-section h4 {
  color: #2e8b57;
  margin: 0 0 1rem 0;
  font-size: 1.2rem;
}

.achievements-list {
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
}

.achievement-item {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  padding: 0.8rem;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #2e8b57;
}

.achievement-item .achievement-icon {
  font-size: 1.2rem;
}

.achievement-item .achievement-text {
  font-weight: 500;
  color: #333;
}

.interests-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.about-text {
  line-height: 1.6;
  color: #333;
  background: #f8f9fa;
  padding: 1rem;
  border-radius: 8px;
  border-left: 4px solid #2e8b57;
}

.profile-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
  flex-wrap: wrap;
  padding-top: 2rem;
  border-top: 1px solid #e9ecef;
}

/* Кнопки */
.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 12px 24px;
  border-radius: 50px;
  text-decoration: none;
  font-weight: 600;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  gap: 0.5rem;
  font-size: 1rem;
  cursor: pointer;
}

.btn-primary {
  background: #ffd700;
  color: #333;
}

.btn-primary:hover {
  background: #e6c200;
  transform: translateY(-2px);
}

.btn-secondary {
  background: transparent;
  color: white;
  border-color: white;
}

.btn-secondary:hover {
  background: white;
  color: #2e8b57;
  transform: translateY(-2px);
}

.btn-outline {
  background: transparent;
  color: #2e8b57;
  border-color: #2e8b57;
}

.btn-outline:hover {
  background: #2e8b57;
  color: white;
  transform: translateY(-2px);
}

.btn-large {
  padding: 15px 30px;
  font-size: 1.1rem;
}

/* Адаптивность */
@media (max-width: 768px) {
  .hero-title {
    font-size: 2.2rem;
  }

  .hero-stats {
    grid-template-columns: repeat(2, 1fr);
    gap: 1.5rem;
  }

  .stat-number {
    font-size: 2rem;
  }

  .filters-container {
    grid-template-columns: 1fr;
  }

  .members-container.grid {
    grid-template-columns: 1fr;
  }

  .members-container.list .member-card {
    flex-direction: column;
    text-align: center;
  }

  .club-stats {
    grid-template-columns: repeat(2, 1fr);
  }

  .success-stories {
    grid-template-columns: 1fr;
  }

  .cta-features {
    grid-template-columns: 1fr;
  }

  .cta-actions {
    flex-direction: column;
    align-items: center;
  }

  .btn {
    width: 100%;
    max-width: 300px;
  }

  .profile-header {
    flex-direction: column;
    text-align: center;
    gap: 1rem;
  }

  .profile-badges {
    justify-content: center;
  }

  .profile-actions {
    flex-direction: column;
  }

  .modal-content {
    margin: 1rem;
  }
}

@media (max-width: 480px) {
  .hero-section {
    padding: 60px 0 40px;
  }

  .hero-title {
    font-size: 1.8rem;
  }

  .section-title {
    font-size: 2rem;
  }

  .container {
    padding: 0 15px;
  }

  .club-stats {
    grid-template-columns: 1fr;
  }

  .members-controls {
    padding: 1.5rem;
  }

  .member-card {
    padding: 1.2rem;
  }
}

/* Анимации */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.member-card {
  animation: fadeInUp 0.6s ease;
}

/* Задержки для анимаций карточек */
.member-card:nth-child(odd) {
  animation-delay: 0.1s;
}

.member-card:nth-child(even) {
  animation-delay: 0.2s;
}

/* Улучшения доступности */
@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
  }
}

/* Фокус-стили */
button:focus-visible,
a:focus-visible,
select:focus-visible,
input:focus-visible {
  outline: 2px solid #2e8b57;
  outline-offset: 2px;
}

/* Темная тема */
@media (prefers-color-scheme: dark) {
  .members-page {
    background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
  }

  .member-card {
    background: #2d2d2d;
    color: #ffffff;
  }

  .search-input,
  .filter-group select {
    background: #3d3d3d;
    border-color: #555;
    color: white;
  }

  .members-controls {
    background: #2d2d2d;
  }
}

/* Кастомный скроллбар */
.modal-content::-webkit-scrollbar {
  width: 8px;
}

.modal-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 0 20px 20px 0;
}

.modal-content::-webkit-scrollbar-thumb {
  background: #2e8b57;
  border-radius: 4px;
}

.modal-content::-webkit-scrollbar-thumb:hover {
  background: #26734a;
}

/* Состояния загрузки */
.loading {
  opacity: 0.6;
  pointer-events: none;
}

/* Скелетон для загрузки */
.skeleton {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
}

@keyframes loading {
  0% {
    background-position: 200% 0;
  }

  100% {
    background-position: -200% 0;
  }
}

/* Утилитарные классы */
.text-center {
  text-align: center;
}

.mb-2 {
  margin-bottom: 2rem;
}

.mt-2 {
  margin-top: 2rem;
}

/* Адаптация для печати */
@media print {

  .hero-section,
  .cta-section,
  .member-actions,
  .pagination {
    display: none;
  }

  .member-card {
    break-inside: avoid;
    box-shadow: none;
    border: 1px solid #ddd;
  }
}
</style>