<template>
  <div class="achievements-page">
    <!-- Герой-секция -->
    <section class="hero-section">
      <div class="container">
        <h1 class="hero-title">🏆 Наши достижения</h1>
        <p class="hero-subtitle">Гордимся каждым участником и каждым результатом!</p>
        <div class="hero-stats">
          <div class="stat">
            <div class="stat-number">{{ totalAchievements }}</div>
            <div class="stat-label">Достижений</div>
          </div>
          <div class="stat">
            <div class="stat-number">{{ activeMembers }}</div>
            <div class="stat-label">Активных участников</div>
          </div>
          <div class="stat">
            <div class="stat-number">{{ personalBests }}</div>
            <div class="stat-label">Личных рекордов</div>
          </div>
        </div>
      </div>
    </section>

    <!-- Фильтры и поиск -->
    <section class="filters-section">
      <div class="container">
        <div class="filters-container">
          <div class="search-box">
            <input v-model="searchQuery" type="text" placeholder="🔍 Поиск по имени или дистанции..."
              class="search-input">
          </div>
          <div class="filter-buttons">
            <button v-for="filter in filters" :key="filter.value"
              :class="['filter-btn', { 'active': activeFilter === filter.value }]" @click="setFilter(filter.value)">
              {{ filter.label }}
            </button>
          </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>
    </section>

    <!-- Достижения -->
    <section class="achievements-section">
      <div class="container">
        <!-- Командные достижения -->
        <div class="category-section">
          <h2 class="category-title">🏆 Командные достижения</h2>
          <div class="achievements-grid" :class="viewMode">
            <div v-for="achievement in teamAchievements" :key="achievement.id" class="achievement-card team-card">
              <div class="achievement-icon">🏅</div>
              <h3>{{ achievement.title }}</h3>
              <p>{{ achievement.description }}</p>
              <div class="achievement-meta">
                <span class="year">{{ achievement.year }}</span>
                <span class="type">{{ achievement.type }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Личные достижения по дистанциям -->
        <div v-for="category in filteredCategories" :key="category.id" class="category-section">
          <h2 class="category-title">{{ category.icon }} {{ category.title }}</h2>
          <div class="achievements-grid" :class="viewMode">
            <div v-for="achievement in category.achievements" :key="achievement.id" class="achievement-card"
              :class="getAchievementClass(achievement)">
              <div class="achievement-header">
                <h3>{{ achievement.name }}</h3>
                <span class="result">{{ achievement.result }}</span>
              </div>

              <div class="achievement-details">
                <p class="pace" v-if="achievement.pace">Темп: {{ achievement.pace }}</p>
                <p class="note" v-if="achievement.note">{{ achievement.note }}</p>

                <div class="achievement-links" v-if="achievement.telegram">
                  <a :href="achievement.telegram" target="_blank" class="telegram-link" title="Написать в Telegram">
                    📱 @{{ getTelegramUsername(achievement.telegram) }}
                  </a>
                </div>

                <div class="achievement-meta">
                  <span v-if="achievement.pb" class="badge pb-badge" title="Личный рекорд">
                    PB
                  </span>
                  <span class="distance">{{ category.distance }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Статистика -->
        <div class="stats-section">
          <h2 class="section-title">📊 Статистика клуба</h2>
          <div class="stats-grid">
            <div class="stat-card">
              <div class="stat-icon">🚀</div>
              <div class="stat-content">
                <h3>Самый быстрый марафон</h3>
                <p class="stat-value">3:27:49</p>
                <p class="stat-person">Сергей</p>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">🏔️</div>
              <div class="stat-content">
                <h3>Самая длинная дистанция</h3>
                <p class="stat-value">120 км</p>
                <p class="stat-person">Даниил Хайбуллин</p>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">⭐</div>
              <div class="stat-content">
                <h3>Больше всего PB</h3>
                <p class="stat-value">5 рекордов</p>
                <p class="stat-person">Ғаяз</p>
              </div>
            </div>
          </div>
        </div>

        <!-- Призыв к действию -->
        <div class="cta-section">
          <div class="cta-content">
            <h2>Хочешь попасть в этот список?</h2>
            <p>Присоединяйся к нашему клубу и начни свой путь к новым достижениям!</p>
            <div class="cta-buttons">
              <router-link to="/training" class="btn btn-primary">
                📅 Начать тренироваться
              </router-link>
              <router-link to="/register" class="btn btn-secondary">
                🏃 Вступить в клуб
              </router-link>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Achievements',
  mounted() {
    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() {
    // Убираем обработчики при размонтировании
    window.removeEventListener('scroll', this.handleFirstInteraction)
    window.removeEventListener('click', this.handleFirstInteraction)
    window.removeEventListener('touchstart', this.handleFirstInteraction)
    clearTimeout(this.autoShowTimeout)
  },
  data() {
    return {
      searchQuery: '',
      activeFilter: 'all',
      viewMode: 'grid',
      filters: [
        { value: 'all', label: 'Все' },
        { value: 'marathon', label: 'Марафон' },
        { value: 'half', label: 'Полумарафон' },
        { value: 'short', label: 'Короткие' },
        { value: 'trail', label: 'Трейл' }
      ],
      teamAchievements: [
        {
          id: 1,
          title: 'Эстафета 4×400м',
          description: 'III место среди беговых клубов',
          year: '2024, 2025',
          type: 'Командное'
        }
      ],
      achievementCategories: [
        {
          id: 'marathon',
          title: 'Марафон 42.2 км',
          icon: '🏃',
          distance: '42.2 км',
          achievements: [
            {
              id: 1,
              name: 'Сергей',
              result: '3:27:49',
              telegram: 'https://t.me/Sergeicortess',
              pb: true
            },
            {
              id: 2,
              name: 'Ғаяз',
              result: '3:34:33',
              telegram: 'https://t.me/GeniusUfa',
              pb: true
            }
          ]
        },
        {
          id: 'half',
          title: 'Полумарафон 21.1 км',
          icon: '🎯',
          distance: '21.1 км',
          achievements: [
            {
              id: 1,
              name: 'Ильгам',
              result: '1:23:33',
              telegram: 'https://t.me/Ilgam25883',
              pb: true
            },
            {
              id: 2,
              name: 'Данил',
              result: '1:30:40',
              pace: "4'16",
              telegram: 'https://t.me/Khaybullin_D',
              note: 'PB',
              pb: true
            },
            {
              id: 3,
              name: 'Ғаяз',
              result: '1:31:40',
              pace: "4'20",
              telegram: 'https://t.me/GeniusUfa',
              note: 'PB',
              pb: true
            },
            {
              id: 4,
              name: 'Булат',
              result: '1:45:48',
              pace: "5'00",
              telegram: 'https://t.me/Bulat_Vakhitov',
              note: 'PB',
              pb: true
            },
            {
              id: 5,
              name: 'Ильвира',
              result: '1:45:48',
              pace: "5'00",
              telegram: 'https://t.me/Yahina_Ilvira',
              note: 'PB',
              pb: true
            },
            {
              id: 6,
              name: 'Булат',
              result: '2:08:30',
              pace: "6'05",
              telegram: 'https://t.me/Bulatiwe',
              note: 'PB',
              pb: true
            }
          ]
        },
        {
          id: 'ten',
          title: '10 км',
          icon: '⚡',
          distance: '10 км',
          achievements: [
            {
              id: 1,
              name: 'Эдуард',
              result: '36:52',
              pace: "3'41"
            },
            {
              id: 2,
              name: 'Илһам',
              result: '37:59',
              pace: "3'47",
              telegram: 'https://t.me/Ilgam25883'
            },
            {
              id: 3,
              name: 'Арыҫлан',
              result: '38:25',
              pace: "3'50",
              telegram: 'https://t.me/Just_Aryslan'
            },
            {
              id: 4,
              name: 'Ибрагимов Ринат',
              result: '38:49'
            },
            {
              id: 5,
              name: 'Гүзәл Гузель Ахмадуллина',
              result: '53:25',
              pace: "5'20"
            },
            {
              id: 6,
              name: 'Финат Гайфуллин',
              result: '56:46',
              pace: "5'40"
            },
            {
              id: 7,
              name: 'Регина',
              result: '59:43',
              pace: "5'58",
              telegram: 'https://t.me/massageregina'
            }
          ]
        },
        {
          id: 'five',
          title: '5 км',
          icon: '🎽',
          distance: '5 км',
          achievements: [
            {
              id: 1,
              name: 'Ғәзиз',
              result: '25:13',
              pace: "5'02",
              telegram: 'https://t.me/valitovgaziz',
              note: 'PB',
              pb: true
            },
            {
              id: 2,
              name: 'Зарема',
              result: '28:22',
              pace: "5'40",
              telegram: 'https://t.me/am1neva',
              note: 'PB',
              pb: true
            },
            {
              id: 3,
              name: 'Камила',
              result: '32:23',
              pace: "6'28",
              telegram: 'https://t.me/khayrutdinova_kamila'
            },
            {
              id: 4,
              name: 'Айгөл',
              result: '37:23',
              pace: "7'28",
              telegram: 'https://t.me/Aigulika_Elis'
            }
          ]
        },
        {
          id: 'trail',
          title: 'Трейловые дистанции',
          icon: '🏔️',
          distance: 'Разные дистанции',
          achievements: [
            {
              id: 1,
              name: 'Хайбуллин Даниил',
              result: '120 км',
              note: 'III место на Batyr BackYard Ultra',
              pb: true
            },
            {
              id: 2,
              name: 'Ибрагимов Ринат',
              result: '22 км',
              note: 'III место на ультрамарафоне «Мир!Труд! Май!»',
              pb: true
            },
            {
              id: 3,
              name: 'Хайбуллин Азамат',
              result: '6 км',
              note: 'III место на Karst trail',
              pb: true
            }
          ]
        }
      ]
    }
  },
  computed: {
    totalAchievements() {
      return this.achievementCategories.reduce((total, category) => {
        return total + category.achievements.length
      }, 0) + this.teamAchievements.length
    },
    activeMembers() {
      const members = new Set()
      this.achievementCategories.forEach(category => {
        category.achievements.forEach(achievement => {
          members.add(achievement.name)
        })
      })
      return members.size
    },
    personalBests() {
      let count = 0
      this.achievementCategories.forEach(category => {
        category.achievements.forEach(achievement => {
          if (achievement.pb) count++
        })
      })
      return count
    },
    filteredCategories() {
      if (this.activeFilter === 'all' && !this.searchQuery) {
        return this.achievementCategories
      }

      return this.achievementCategories
        .filter(category => {
          if (this.activeFilter === 'all') return true
          if (this.activeFilter === 'short') {
            return category.id === 'five' || category.id === 'ten'
          }
          return category.id === this.activeFilter
        })
        .map(category => ({
          ...category,
          achievements: category.achievements.filter(achievement => {
            if (!this.searchQuery) return true
            const query = this.searchQuery.toLowerCase()
            return (
              achievement.name.toLowerCase().includes(query) ||
              category.title.toLowerCase().includes(query) ||
              (achievement.note && achievement.note.toLowerCase().includes(query))
            )
          })
        }))
        .filter(category => category.achievements.length > 0)
    }
  },
  methods: {
    handleFirstInteraction() {
      if (!this.hasInteracted) {
        this.hasInteracted = true
        this.showContent()
        clearTimeout(this.autoShowTimeout)
      }
    },
    showContent() {
      this.isContentVisible = true
      // Эмитим событие для показа хедера
      this.$emit('show-header')
    },
    setFilter(filter) {
      this.activeFilter = filter
    },
    getTelegramUsername(url) {
      return url.split('/').pop()
    },
    getAchievementClass(achievement) {
      const classes = []
      if (achievement.pb) classes.push('pb-achievement')
      if (achievement.telegram) classes.push('has-contact')
      return classes
    }
  }
}
</script>

<style scoped>
.achievements-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;
}

.hero-stats {
  display: flex;
  justify-content: center;
  gap: 3rem;
  flex-wrap: wrap;
  margin-top: 2rem;
}

.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;
}

/* Фильтры */
.filters-section {
  background: white;
  padding: 2rem 0;
  border-bottom: 1px solid #e9ecef;
  position: sticky;
  top: 80px;
  z-index: 100;
}

.filters-container {
  display: flex;
  gap: 1.5rem;
  align-items: center;
  flex-wrap: wrap;
}

.search-box {
  flex: 1;
  min-width: 250px;
}

.search-input {
  width: 100%;
  padding: 12px 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);
}

.filter-buttons {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.filter-btn {
  padding: 10px 20px;
  border: 2px solid #e9ecef;
  background: white;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
  white-space: nowrap;
}

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

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

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

.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;
}

/* Достижения */
.achievements-section {
  padding: 3rem 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.category-section {
  margin-bottom: 4rem;
}

.category-title {
  font-size: 2rem;
  color: #2e8b57;
  margin-bottom: 2rem;
  padding-bottom: 0.5rem;
  border-bottom: 3px solid #ffd700;
}

/* Сетка достижений */
.achievements-grid {
  display: grid;
  gap: 1.5rem;
}

.achievements-grid.grid {
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.achievements-grid.list {
  grid-template-columns: 1fr;
}

.achievement-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-left: 4px solid #2e8b57;
  position: relative;
  overflow: hidden;
}

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

.achievement-card.team-card {
  border-left-color: #ffd700;
  background: linear-gradient(135deg, #fff9e6 0%, #fff3cc 100%);
}

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

.achievement-icon {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  text-align: center;
}

.achievement-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.achievement-header h3 {
  color: #2e8b57;
  margin: 0;
  font-size: 1.3rem;
  flex: 1;
}

.result {
  background: #2e8b57;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-weight: bold;
  font-size: 1.1rem;
  margin-left: 1rem;
}

.achievement-details {
  display: flex;
  flex-direction: column;
  gap: 1.5rem; /* Современный способ для Flexbox */
}

.pace {
  color: #666;
  font-size: 0.9rem;
  margin: 0.5rem 0;
}

.note {
  color: #e74c3c;
  font-weight: 600;
  font-size: 0.9rem;
  margin: 0.5rem 0;
}

.achievement-links {
  margin: 1rem 0;
}

.telegram-link {
  color: #0088cc;
  text-decoration: none;
  font-size: 0.9rem;
  transition: color 0.3s ease;
}

.telegram-link:hover {
  color: #005580;
  text-decoration: underline;
}

.achievement-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #f0f0f0;
}

.badge {
  padding: 0.3rem 0.8rem;
  border-radius: 15px;
  font-size: 0.8rem;
  font-weight: bold;
}

.pb-badge {
  background: #e74c3c;
  color: white;
}

.distance {
  color: #666;
  font-size: 0.8rem;
}

/* Статистика */
.stats-section {
  margin: 4rem 0;
}

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

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

.stat-card {
  background: white;
  padding: 2rem;
  border-radius: 15px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  text-align: center;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-3px);
}

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

.stat-value {
  font-size: 2rem;
  font-weight: 800;
  color: #2e8b57;
  margin: 0.5rem 0;
}

.stat-person {
  color: #666;
  font-style: italic;
}

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

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

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

.cta-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
  flex-wrap: wrap;
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 15px 30px;
  border-radius: 50px;
  text-decoration: none;
  font-weight: 600;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  gap: 0.5rem;
  font-size: 1.1rem;
}

.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);
}

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

  .hero-stats {
    gap: 2rem;
  }

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

  .filters-container {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box {
    min-width: auto;
  }

  .filter-buttons {
    justify-content: center;
  }

  .view-toggle {
    align-self: center;
  }

  .achievements-grid.grid {
    grid-template-columns: 1fr;
  }

  .achievement-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .result {
    margin-left: 0;
    margin-top: 0.5rem;
    align-self: flex-start;
  }

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

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

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

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

  .category-title {
    font-size: 1.5rem;
  }

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

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

  .container {
    padding: 0 15px;
  }
}

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

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

.achievement-card {
  animation: fadeInUp 0.6s ease;
}
</style>