<template>
  <div class="news-page">
    <!-- Герой-секция -->
    <section class="hero-section">
      <div class="container">
        <div class="hero-content">
          <h1 class="hero-title">📰 Новости клуба</h1>
          <p class="hero-subtitle">Будьте в курсе всех событий, забегов и достижений нашего бегового сообщества</p>
          <div class="hero-stats">
            <div class="stat">
              <div class="stat-number">{{ totalNews }}</div>
              <div class="stat-label">Новостей</div>
            </div>
            <div class="stat">
              <div class="stat-number">{{ upcomingEvents }}</div>
              <div class="stat-label">Предстоящих событий</div>
            </div>
            <div class="stat">
              <div class="stat-number">{{ totalComments }}</div>
              <div class="stat-label">Комментариев</div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Основной контент -->
    <section class="news-section">
      <div class="container">
        <div class="news-header">
          <h2 class="section-title">Последние новости</h2>
          <div class="news-controls">
            <div class="news-filters">
              <button v-for="filter in filters" :key="filter.value"
                :class="['filter-btn', { 'active': activeFilter === filter.value }]" @click="setFilter(filter.value)">
                {{ filter.label }}
              </button>
            </div>
            <button v-if="isAuthenticated" class="btn btn-primary" @click="openCreateNewsModal">
              ✏️ Добавить новость
            </button>
          </div>
        </div>

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

        <!-- Сообщение об ошибке -->
        <div v-else-if="error" class="error-state">
          <p>❌ {{ error }}</p>
          <button class="btn btn-outline" @click="fetchNews">Попробовать снова</button>
        </div>

        <!-- Сетка новостей -->
        <div v-else class="news-grid">
          <article v-for="item in filteredNews" :key="item.id" class="news-card" :class="item.category">
            <div class="news-image">
              <img :src="getImageUrl(item.image)" :alt="item.title" class="news-img">
              <div class="news-category">{{ getCategoryLabel(item.category) }}</div>
              <div class="news-date">{{ formatDate(item.created_at) }}</div>
            </div>

            <div class="news-content">
              <h3 class="news-title">{{ item.title }}</h3>
              <p class="news-excerpt">{{ item.excerpt }}</p>

              <div class="news-meta">
                <div class="meta-item">
                  <span class="meta-icon">👁️</span>
                  {{ item.views }} просмотров
                </div>
                <div class="meta-item">
                  <span class="meta-icon">💬</span>
                  {{ item.comments_count || 0 }} комментариев
                </div>
                <div class="meta-item">
                  <span class="meta-icon">👤</span>
                  {{ item.author.first_name }} {{ item.author.last_name }}
                </div>
              </div>

              <div class="news-actions">
                <button class="btn-read-more" @click="openNewsModal(item)">
                  📖 Читать подробнее
                </button>
                <div v-if="isAuthenticated && isAuthor(item.author_id)" class="news-owner-actions">
                  <button class="btn-edit" @click="editNews(item)" title="Редактировать">
                    ✏️
                  </button>
                  <button class="btn-delete" @click="deleteNews(item.id)" title="Удалить">
                    🗑️
                  </button>
                </div>
              </div>
            </div>
          </article>
        </div>

        <!-- Кнопка загрузки еще -->
        <div class="load-more" v-if="!loading && !error && visibleNews < filteredNews.length">
          <button class="btn btn-outline" @click="loadMore">
            📰 Загрузить еще новости
          </button>
        </div>

        <!-- Сообщение если новостей нет -->
        <div v-if="!loading && !error && filteredNews.length === 0" class="empty-state">
          <p>📭 Новостей пока нет</p>
          <button v-if="isAuthenticated" class="btn btn-primary" @click="openCreateNewsModal">
            Создать первую новость
          </button>
        </div>
      </div>
    </section>

    <!-- Модальное окно новости -->
    <div class="news-modal-overlay" :class="{ 'active': showNewsModal }" v-if="showNewsModal">
      <div class="news-modal">
        <button class="modal-close" @click="closeNewsModal">×</button>

        <article class="modal-content" v-if="selectedNews">
          <div class="modal-header">
            <div class="modal-meta">
              <span class="modal-category">{{ getCategoryLabel(selectedNews.category) }}</span>
              <span class="modal-date">{{ formatDate(selectedNews.created_at) }}</span>
              <span class="modal-views">👁️ {{ selectedNews.views }} просмотров</span>
            </div>
            <h2 class="modal-title">{{ selectedNews.title }}</h2>
            <div class="modal-author">
              <span class="author-avatar" v-if="selectedNews.author.avatar">
                <img :src="getImageUrl(selectedNews.author.avatar)" :alt="selectedNews.author.first_name">
              </span>
              <span class="author-name">{{ selectedNews.author.first_name }} {{ selectedNews.author.last_name }}</span>
            </div>
          </div>

          <div class="modal-image" v-if="selectedNews.image">
            <img :src="getImageUrl(selectedNews.image)" :alt="selectedNews.title">
          </div>

          <div class="modal-body">
            <div class="news-content-full" v-html="formatContent(selectedNews.content)"></div>

            <div class="modal-actions">
              <button class="btn-share-modal" @click="shareNews(selectedNews)">
                📤 Поделиться новостью
              </button>
              <div v-if="isAuthenticated && isAuthor(selectedNews.author_id)" class="modal-owner-actions">
                <button class="btn btn-outline" @click="editNews(selectedNews)">
                  ✏️ Редактировать
                </button>
                <button class="btn btn-danger" @click="deleteNews(selectedNews.id)">
                  🗑️ Удалить
                </button>
              </div>
            </div>

            <!-- Секция комментариев -->
            <div class="news-comments">
              <h4>💬 Комментарии ({{ comments.length }})</h4>

              <!-- Форма добавления комментария -->
              <div v-if="isAuthenticated" class="comment-form">
                <textarea v-model="newComment" placeholder="Напишите ваш комментарий..." class="comment-input"
                  rows="3"></textarea>
                <button class="btn btn-primary" @click="addComment" :disabled="!newComment.trim() || commentLoading">
                  {{ commentLoading ? 'Отправка...' : '💬 Отправить комментарий' }}
                </button>
              </div>
              <div v-else class="auth-prompt">
                <p>🔐 Войдите, чтобы оставить комментарий</p>
                <router-link to="/login" class="btn btn-outline">
                  Войти
                </router-link>
              </div>

              <!-- Список комментариев -->
              <div class="comments-list" v-if="comments.length > 0">
                <div v-for="comment in comments" :key="comment.id" class="comment-item">
                  <div class="comment-header">
                    <div class="comment-author">
                      <span class="author-avatar" v-if="comment.author.avatar">
                        <img :src="getImageUrl(comment.author.avatar)" :alt="comment.author.first_name">
                      </span>
                      <span class="author-name">{{ comment.author.first_name }} {{ comment.author.last_name }}</span>
                      <span class="comment-date">{{ formatDate(comment.created_at) }}</span>
                    </div>
                    <button v-if="isAuthenticated && isCommentAuthor(comment.author_id)" class="btn-delete-comment"
                      @click="deleteComment(comment.id)" title="Удалить комментарий">
                      🗑️
                    </button>
                  </div>
                  <div class="comment-content">{{ comment.content }}</div>
                </div>
              </div>
              <div v-else class="no-comments">
                <p>Пока нет комментариев. Будьте первым!</p>
              </div>
            </div>
          </div>
        </article>
      </div>
    </div>

    <!-- Модальное окно создания/редактирования новости -->
    <div class="news-modal-overlay" :class="{ 'active': showNewsFormModal }" v-if="showNewsFormModal">
      <div class="news-modal">
        <button class="modal-close" @click="closeNewsFormModal">×</button>

        <div class="modal-content">
          <h2 class="modal-title">{{ editingNews ? '✏️ Редактировать новость' : '📝 Создать новость' }}</h2>

          <form @submit.prevent="submitNewsForm" class="news-form">
            <div class="form-group">
              <label>Заголовок *</label>
              <input v-model="newsForm.title" 
                     type="text" 
                     required 
                     placeholder="Введите заголовок новости (минимум 5 символов)"
                     class="form-input"
                     :class="{ 'error': formErrors.title }"
                     @input="clearFieldError('title')">
              <div v-if="formErrors.title" class="error-message">{{ formErrors.title }}</div>
              <div class="char-count" :class="{ 'error': newsForm.title.length < 5 }">
                {{ newsForm.title.length }}/255
                <span v-if="newsForm.title.length < 5" class="min-length-warning">
                  (минимум 5 символов)
                </span>
              </div>
            </div>

            <div class="form-group">
              <label>Краткое описание *</label>
              <textarea v-model="newsForm.excerpt" 
                        required
                        placeholder="Краткое описание новости (минимум 10 символов, максимум 500)"
                        class="form-textarea" 
                        rows="3"
                        maxlength="500"
                        :class="{ 'error': formErrors.excerpt }"
                        @input="clearFieldError('excerpt')"></textarea>
              <div v-if="formErrors.excerpt" class="error-message">{{ formErrors.excerpt }}</div>
              <div class="char-count" :class="{ 'error': newsForm.excerpt.length < 10 }">
                {{ newsForm.excerpt.length }}/500
                <span v-if="newsForm.excerpt.length < 10" class="min-length-warning">
                  (минимум 10 символов)
                </span>
              </div>
            </div>

            <div class="form-group">
              <label>Содержание *</label>
              <textarea v-model="newsForm.content" 
                        required 
                        placeholder="Полное содержание новости (минимум 50 символов)"
                        class="form-textarea" 
                        rows="6"
                        :class="{ 'error': formErrors.content }"
                        @input="clearFieldError('content')"></textarea>
              <div v-if="formErrors.content" class="error-message">{{ formErrors.content }}</div>
              <div class="char-count" :class="{ 'error': newsForm.content.length < 50 }">
                {{ newsForm.content.length }} символов
                <span v-if="newsForm.content.length < 50" class="min-length-warning">
                  (минимум 50 символов)
                </span>
              </div>
            </div>

            <div class="form-group">
              <label>Категория *</label>
              <select v-model="newsForm.category" 
                      required 
                      class="form-select"
                      :class="{ 'error': formErrors.category }"
                      @change="clearFieldError('category')">
                <option value="">Выберите категорию</option>
                <option value="events">События</option>
                <option value="training">Тренировки</option>
                <option value="achievements">Достижения</option>
                <option value="community">Сообщество</option>
              </select>
              <div v-if="formErrors.category" class="error-message">{{ formErrors.category }}</div>
            </div>

            <div class="form-group">
              <label>Изображение (URL)</label>
              <input v-model="newsForm.image" 
                     type="url" 
                     placeholder="https://example.com/image.jpg" 
                     class="form-input">
              <small>Оставьте пустым для изображения по умолчанию</small>
            </div>

            <div class="form-actions">
              <button type="button" class="btn btn-outline" @click="closeNewsFormModal">
                Отмена
              </button>
              <button type="submit" 
                      class="btn btn-primary" 
                      :disabled="newsLoading || !isFormValid">
                {{ newsLoading ? 'Сохранение...' : (editingNews ? '💾 Сохранить изменения' : '📝 Создать новость') }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'pinia'
import { useAuthStore } from '../stores/auth'
import { apiClient } from '../stores/helpers/api';

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'News',
  data() {
    return {
      activeFilter: 'all',
      visibleNews: 6,
      showNewsModal: false,
      showNewsFormModal: false,
      selectedNews: null,
      editingNews: null,
      newsLoading: false,
      commentLoading: false,
      loading: false,
      error: '',
      newComment: '',
      news: [],
      comments: [],
      newsForm: {
        title: '',
        excerpt: '',
        content: '',
        category: '',
        image: ''
      },
      formErrors: {
        title: '',
        excerpt: '',
        content: '',
        category: ''
      },
      filters: [
        { value: 'all', label: 'Все новости' },
        { value: 'events', label: 'События' },
        { value: 'training', label: 'Тренировки' },
        { value: 'achievements', label: 'Достижения' },
        { value: 'community', label: 'Сообщество' }
      ]
    }
  },
  computed: {
    ...mapState(useAuthStore, ['user', 'isAuthenticated']),
    totalNews() {
      return this.news.length
    },
    upcomingEvents() {
      return this.news.filter(item => item.category === 'events').length
    },
    totalComments() {
      return this.news.reduce((total, news) => total + (news.comments_count || 0), 0)
    },
    filteredNews() {
      let filtered = this.news
      if (this.activeFilter !== 'all') {
        filtered = this.news.filter(item => item.category === this.activeFilter)
      }
      return filtered.slice(0, this.visibleNews)
    },
    // Проверка валидности формы
    isFormValid() {
      return this.newsForm.title.length >= 5 && 
             this.newsForm.title.length <= 255 &&
             this.newsForm.excerpt.length >= 10 && 
             this.newsForm.excerpt.length <= 500 &&
             this.newsForm.content.length >= 50 &&
             this.newsForm.category !== ''
    }
  },
  methods: {
    ...mapActions(useAuthStore, ['fetchProfile']),

    handleFirstInteraction() {
      if (!this.hasInteracted) {
        this.hasInteracted = true
        this.showContent()
        clearTimeout(this.autoShowTimeout)
      }
    },
    
    showContent() {
      this.isContentVisible = true
      // Эмитим событие для показа хедера
      this.$emit('show-header')
    },

    // Валидация формы
    validateForm() {
      this.clearAllErrors()
      let isValid = true

      // Валидация заголовка
      if (this.newsForm.title.length < 5) {
        this.formErrors.title = 'Заголовок должен содержать минимум 5 символов'
        isValid = false
      } else if (this.newsForm.title.length > 255) {
        this.formErrors.title = 'Заголовок не должен превышать 255 символов'
        isValid = false
      }

      // Валидация краткого описания
      if (this.newsForm.excerpt.length < 10) {
        this.formErrors.excerpt = 'Краткое описание должно содержать минимум 10 символов'
        isValid = false
      } else if (this.newsForm.excerpt.length > 500) {
        this.formErrors.excerpt = 'Краткое описание не должно превышать 500 символов'
        isValid = false
      }

      // Валидация содержания
      if (this.newsForm.content.length < 50) {
        this.formErrors.content = 'Содержание должно содержать минимум 50 символов'
        isValid = false
      }

      // Валидация категории
      if (!this.newsForm.category) {
        this.formErrors.category = 'Выберите категорию'
        isValid = false
      }

      return isValid
    },

    // Очистка ошибок
    clearAllErrors() {
      this.formErrors = {
        title: '',
        excerpt: '',
        content: '',
        category: ''
      }
    },

    clearFieldError(field) {
      if (this.formErrors[field]) {
        this.formErrors[field] = ''
      }
    },

    async fetchNews() {
      this.loading = true
      this.error = ''
      try {
        const response = await apiClient.get('/news')
        this.news = response.data.news || response.data
      } catch (error) {
        console.error('Failed to fetch news:', error)
        this.error = 'Не удалось загрузить новости. Попробуйте позже.'
      } finally {
        this.loading = false
      }
    },

    async fetchComments(newsId) {
      try {
        const response = await apiClient.get(`/news/${newsId}/comments`)
        this.comments = response.data.comments || response.data
      } catch (error) {
        console.error('Failed to fetch comments:', error)
        this.comments = []
      }
    },

    async openNewsModal(newsItem) {
      try {
        const response = await apiClient.get(`/news/${newsItem.id}`)
        this.selectedNews = response.data
        await this.fetchComments(newsItem.id)
      } catch (error) {
        console.error('Failed to fetch news details:', error)
        this.selectedNews = newsItem
      }

      this.showNewsModal = true
      document.body.style.overflow = 'hidden'
    },

    async addComment() {
      if (!this.newComment.trim() || !this.selectedNews) return

      this.commentLoading = true
      try {
        await apiClient.post(`/news/${this.selectedNews.id}/comments`, {
          content: this.newComment
        })

        this.newComment = ''
        await this.fetchComments(this.selectedNews.id)
        await this.fetchNews() // Обновляем счетчик комментариев
      } catch (error) {
        console.error('Failed to add comment:', error)
        alert('Не удалось добавить комментарий. Попробуйте позже.')
      } finally {
        this.commentLoading = false
      }
    },

    async deleteComment(commentId) {
      if (!confirm('Удалить этот комментарий?')) return

      try {
        await apiClient.delete(`/news/comments/${commentId}`)
        await this.fetchComments(this.selectedNews.id)
        await this.fetchNews()
      } catch (error) {
        console.error('Failed to delete comment:', error)
        alert('Не удалось удалить комментарий.')
      }
    },

    openCreateNewsModal() {
      this.editingNews = null
      this.newsForm = {
        title: '',
        excerpt: '',
        content: '',
        category: '',
        image: ''
      }
      this.clearAllErrors()
      this.showNewsFormModal = true
    },

    editNews(newsItem) {
      this.editingNews = newsItem
      this.newsForm = {
        title: newsItem.title,
        excerpt: newsItem.excerpt,
        content: newsItem.content,
        category: newsItem.category,
        image: newsItem.image || ''
      }
      this.clearAllErrors()
      this.showNewsFormModal = true
      if (this.showNewsModal) {
        this.closeNewsModal()
      }
    },

    async checkAuth() {
      try {
        const token = localStorage.getItem('auth_token')
        if (token) {
          try {
            // Пытаемся получить профиль пользователя для проверки авторизации
            const response = await apiClient.get('/user/profile')
            this.isAuthenticated = true
            this.currentUser = response.data
          } catch (error) {
            console.error('Токен невалиден:', error)
            this.handleAuthError()
          }
        } else {
          this.isAuthenticated = false
          this.currentUser = null
        }
      } catch (error) {
        console.error('Ошибка проверки авторизации:', error)
        this.handleAuthError()
      }
    },

    async submitNewsForm() {
      // Предварительная валидация на фронтенде
      if (!this.validateForm()) {
        alert('Пожалуйста, исправьте ошибки в форме перед отправкой.')
        return
      }

      this.newsLoading = true
      try {
        if (this.editingNews) {
          await apiClient.put(`/news/${this.editingNews.id}`, this.newsForm)
        } else {
          console.log('News form data:', this.newsForm)
          await apiClient.post('/news', this.newsForm)
        }

        this.closeNewsFormModal()
        await this.fetchNews()
      } catch (error) {
        console.error('Failed to save news:', error)
        // Обработка ошибок валидации с бэкенда
        if (error.response && error.response.status === 400) {
          const errorData = error.response.data
          if (typeof errorData === 'string' && errorData.includes('Validation failed')) {
            alert('Ошибка валидации: проверьте, что все поля соответствуют требованиям (заголовок - минимум 5 символов, описание - минимум 10 символов, содержание - минимум 50 символов).')
          } else {
            alert('Ошибка при сохранении: ' + (errorData.message || errorData))
          }
        } else {
          alert('Не удалось сохранить новость. Проверьте все поля и попробуйте снова.')
        }
      } finally {
        this.newsLoading = false
      }
    },

    async deleteNews(newsId) {
      if (!confirm('Удалить эту новость? Это действие нельзя отменить.')) return

      try {
        await apiClient.delete(`/news/${newsId}`)
        await this.fetchNews()
        if (this.showNewsModal) {
          this.closeNewsModal()
        }
      } catch (error) {
        console.error('Failed to delete news:', error)
        alert('Не удалось удалить новость.')
      }
    },

    isAuthor(authorId) {
      return this.user && this.user.id === authorId
    },

    isCommentAuthor(authorId) {
      return this.user && this.user.id === authorId
    },

    setFilter(filter) {
      this.activeFilter = filter
      this.visibleNews = 6
    },

    loadMore() {
      this.visibleNews += 3
    },

    closeNewsModal() {
      this.showNewsModal = false
      this.selectedNews = null
      this.comments = []
      this.newComment = ''
      document.body.style.overflow = ''
    },

    closeNewsFormModal() {
      this.showNewsFormModal = false
      this.editingNews = null
      this.clearAllErrors()
    },

    shareNews(newsItem) {
      if (navigator.share) {
        navigator.share({
          title: newsItem.title,
          text: newsItem.excerpt,
          url: window.location.href
        })
      } else {
        navigator.clipboard.writeText(window.location.href)
        alert('Ссылка скопирована в буфер обмена!')
      }
    },

    getCategoryLabel(category) {
      const labels = {
        'events': 'События',
        'training': 'Тренировки',
        'achievements': 'Достижения',
        'community': 'Сообщество'
      }
      return labels[category] || 'Новости'
    },

    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleDateString('ru-RU', {
        day: 'numeric',
        month: 'long',
        year: 'numeric'
      })
    },

    getImageUrl(imagePath) {
      if (!imagePath) return '/images/default-news.jpg'
      if (imagePath.startsWith('http')) return imagePath
      return `https://begushiybashkir.ru${imagePath}`
    },

    formatContent(content) {
      return content.replace(/\n/g, '<br>')
    },

    handleKeydown(event) {
      if (event.key === 'Escape') {
        if (this.showNewsModal) this.closeNewsModal()
        if (this.showNewsFormModal) this.closeNewsFormModal()
      }
    },

    handleAuthError() {
      localStorage.removeItem('auth_token')
      this.isAuthenticated = false
      this.currentUser = null
    }
  },
  async mounted() {
    document.addEventListener('keydown', this.handleKeydown)
    await this.fetchNews()
    if (this.isAuthenticated) {
      await this.fetchProfile()
    }
    this.checkAuth()
    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>
/* Существующие стили остаются без изменений, добавляем только новые для валидации */

.form-input.error,
.form-textarea.error,
.form-select.error {
  border-color: #f44336;
  background-color: #fff5f5;
}

.error-message {
  color: #f44336;
  font-size: 0.8rem;
  margin-top: 0.25rem;
  font-weight: 500;
}

.char-count.error {
  color: #f44336;
}

.min-length-warning {
  color: #f44336;
  font-size: 0.8rem;
  font-weight: 500;
}

.char-count {
  text-align: right;
  font-size: 0.8rem;
  color: #666;
  margin-top: 0.25rem;
}

.char-count.error .min-length-warning {
  color: #f44336;
}

/* Остальные стили остаются без изменений */
.news-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 2rem;
  flex-wrap: wrap;
}

.news-owner-actions {
  display: flex;
  gap: 0.5rem;
}

.btn-edit,
.btn-delete,
.btn-delete-comment {
  background: none;
  border: none;
  padding: 5px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1.1rem;
  transition: all 0.3s ease;
}

.btn-edit:hover {
  background: #e3f2fd;
  transform: scale(1.1);
}

.btn-delete:hover,
.btn-delete-comment:hover {
  background: #ffebee;
  transform: scale(1.1);
}

.btn-danger {
  background: #f44336;
  color: white;
}

.btn-danger:hover {
  background: #d32f2f;
}

.loading-state,
.error-state,
.empty-state {
  text-align: center;
  padding: 3rem;
  color: #666;
}

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

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

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

.error-state {
  color: #f44336;
}

/* Стили для комментариев */
.comment-form {
  margin-bottom: 2rem;
}

.comment-input {
  width: 100%;
  padding: 1rem;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-family: inherit;
  font-size: 1rem;
  resize: vertical;
  margin-bottom: 1rem;
}

.comment-input:focus {
  outline: none;
  border-color: #2e8b57;
}

.auth-prompt {
  text-align: center;
  padding: 1.5rem;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 2rem;
}

.comments-list {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}

.comment-item {
  background: #f8f9fa;
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1rem;
}

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

.comment-author {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.author-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  overflow: hidden;
}

.author-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.author-name {
  font-weight: 600;
  color: #2e8b57;
}

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

.comment-content {
  line-height: 1.5;
  color: #333;
}

.no-comments {
  text-align: center;
  padding: 2rem;
  color: #666;
}

/* Стили для формы новости */
.news-form {
  display: grid;
  grid-template-columns: 1fr;
  gap: 1rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 600;
  color: #333;
}

.form-input,
.form-textarea,
.form-select {
  width: 100%;
  padding: 0.75rem;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-family: inherit;
  font-size: 1rem;
}

.form-input:focus,
.form-textarea:focus,
.form-select:focus {
  outline: none;
  border-color: #2e8b57;
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

.form-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 2rem;
}

.modal-owner-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.modal-author {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-top: 0.5rem;
  color: #666;
}

/* Адаптивность */
@media (max-width: 768px) {
  .news-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .news-owner-actions {
    justify-content: center;
  }

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

  .modal-owner-actions {
    flex-direction: column;
    width: 100%;
  }

  .modal-owner-actions .btn {
    width: 100%;
  }
}

/* Остальные стили из предыдущей версии остаются без изменений */
.news-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: flex;
  justify-content: center;
  gap: 3rem;
  flex-wrap: wrap;
}

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

.news-header {
  margin-bottom: 3rem;
}

.news-filters {
  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;
}

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

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

.news-section {
  padding: 4rem 0;
}

.news-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 2rem;
  margin-bottom: 3rem;
}

.news-card {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

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

.news-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.news-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.news-card:hover .news-img {
  transform: scale(1.05);
}

.news-category {
  position: absolute;
  top: 1rem;
  left: 1rem;
  background: rgba(255, 255, 255, 0.9);
  padding: 0.5rem 1rem;
  border-radius: 15px;
  font-size: 0.8rem;
  font-weight: 600;
  color: #2e8b57;
}

.news-date {
  position: absolute;
  bottom: 1rem;
  right: 1rem;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 15px;
  font-size: 0.8rem;
}

.news-content {
  padding: 1.5rem;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.news-title {
  color: #2e8b57;
  margin-bottom: 1rem;
  font-size: 1.3rem;
  line-height: 1.4;
}

.news-excerpt {
  color: #666;
  line-height: 1.5;
  margin-bottom: 1.5rem;
  flex: 1;
}

.news-meta {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  font-size: 0.8rem;
  color: #999;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 0.3rem;
}

.news-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

.btn-read-more {
  background: #2e8b57;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 600;
  flex: 1;
}

.btn-read-more:hover {
  background: #26734a;
  transform: translateY(-2px);
}

.load-more {
  text-align: center;
  margin-top: 2rem;
}

.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-outline {
  background: transparent;
  color: #2e8b57;
  border-color: #2e8b57;
}

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

.news-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
  padding: 2rem;
}

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

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

.news-modal-overlay.active .news-modal {
  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);
}

.modal-content {
  padding: 3rem;
}

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

.modal-meta {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
  flex-wrap: wrap;
}

.modal-category {
  background: #2e8b57;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 15px;
  font-size: 0.8rem;
  font-weight: 600;
}

.modal-date,
.modal-views {
  color: #666;
  font-size: 0.9rem;
}

.modal-title {
  color: #2e8b57;
  font-size: 2rem;
  line-height: 1.3;
  margin-bottom: 0;
}

.modal-image {
  margin-bottom: 2rem;
  border-radius: 10px;
  overflow: hidden;
}

.modal-image img {
  width: 100%;
  height: 300px;
  object-fit: cover;
}

.news-content-full {
  line-height: 1.6;
  margin-bottom: 2rem;
}

.modal-actions {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
  flex-wrap: wrap;
  align-items: center;
}

.btn-share-modal {
  background: #6c757d;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 600;
}

.btn-share-modal:hover {
  background: #5a6268;
  transform: translateY(-2px);
}

.news-comments {
  border-top: 1px solid #e9ecef;
  padding-top: 2rem;
}

.news-comments h4 {
  color: #2e8b57;
  margin-bottom: 1rem;
}

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

  .hero-stats {
    gap: 2rem;
  }

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

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

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

  .modal-content {
    padding: 2rem;
  }

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

  .news-modal-overlay {
    padding: 1rem;
  }
}

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

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

  .hero-subtitle {
    font-size: 1.1rem;
  }

  .hero-stats {
    gap: 1.5rem;
  }

  .stat {
    flex: 1;
  }

  .news-section {
    padding: 2rem 0;
  }

  .news-filters {
    justify-content: center;
  }

  .news-controls {
    flex-direction: column;
    gap: 1rem;
  }
}
</style>