<script setup>
import { ref, computed } from 'vue';

const studios = ref([]);
const categories = ref(['Фотосессия', 'Видеосъемка', 'Лофт', 'Подкаст', 'Минимализм', 'Цветной свет']);
const searchQuery = ref('');
const selectedCategory = ref(null);

const filteredStudios = computed(() => {
  if (!Array.isArray(studios.value)) return [];
  
  return studios.value.filter(studio => {
    const matchesQuery = studio.hall_name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
                        (studio.description && studio.description.toLowerCase().includes(searchQuery.value.toLowerCase()));
    const matchesCategory = !selectedCategory.value || 
                           (studio.description && studio.description.includes(selectedCategory.value));
    return matchesQuery && matchesCategory;
  });
});

const loadStudios = async () => {
  try {
    const response = await fetch('http://localhost:3000/api/halls');
    if (response.ok) {
      studios.value = await response.json();
    }
  } catch (e) {
    console.error('Ошибка загрузки залов:', e);
  }
};

const toggleCategory = (cat) => {
  selectedCategory.value = selectedCategory.value === cat ? null : cat;
};

// Загружаем студии при монтировании
import { onMounted } from 'vue';
onMounted(() => {
  loadStudios();
});
</script>

<template>
  <div class="tab-content">
    <h1 class="page-title">Поиск</h1>
    
    <div class="search-bar">
      <svg class="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><path d="m21 21-4.35-4.35"></path></svg>
      <input 
        v-model="searchQuery" 
        type="text" 
        placeholder="Название, описание, стиль..." 
        class="search-input" 
      />
    </div>

    <h2 class="section-title">Популярные категории</h2>
    <div class="categories-wrapper">
      <button 
        class="category-chip"
        :class="{ active: selectedCategory === cat }"
        v-for="cat in categories" 
        :key="cat"
        @click="toggleCategory(cat)"
      >
        {{ cat }}
      </button>
    </div>

    <div v-if="filteredStudios.length > 0" class="search-results">
      <h2 class="section-title">Результаты поиска ({{ filteredStudios.length }})</h2>
      <div class="results-grid">
        <div class="result-card" v-for="studio in filteredStudios" :key="studio.hall_id">
          <img 
            :src="`http://localhost:3000/HallsImages/${studio.imageURL}`"
            :alt="studio.hall_name"
            class="result-image"
            @error="(e) => e.target.src = 'https://via.placeholder.com/80'"
          />
          <div class="result-content">
            <h3>{{ studio.hall_name }}</h3>
            <p class="desc">{{ studio.description }}</p>
            <p class="price">{{ studio.hourly_rate }} ₽/час</p>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else-if="studios.length > 0 && searchQuery" class="no-results">
      <p>🔍 Ничего не найдено по запросу "{{ searchQuery }}"</p>
    </div>
  </div>
</template>

<style scoped>
.search-bar { 
  display: flex; 
  align-items: center; 
  background: #F5F5F5; 
  border-radius: 20px; 
  padding: 15px 20px; 
  margin-bottom: 20px;
  transition: all 0.2s ease;
}

.search-bar:focus-within {
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #2BD84C;
}

.search-icon { 
  color: #999;
  flex-shrink: 0;
}

.search-input { 
  border: none !important; 
  background: transparent; 
  font-size: 16px; 
  width: 100%; 
  outline: none !important;
  font-family: inherit;
  margin-left: 12px;
}

.categories-wrapper { 
  display: flex; 
  flex-wrap: wrap; 
  gap: 10px;
}

.category-chip { 
  background: white; 
  border: 2px solid #F0F0F0; 
  padding: 10px 20px; 
  border-radius: 20px; 
  font-size: 14px; 
  font-weight: 600; 
  color: #333; 
  cursor: pointer; 
  transition: all 0.2s ease;
  white-space: nowrap;
}

.category-chip:active {
  transform: scale(0.95);
}

.category-chip:hover { 
  border-color: #2BD84C; 
  color: #2BD84C;
  background: rgba(43, 216, 76, 0.05);
}

.category-chip.active {
  background: #2BD84C;
  border-color: #2BD84C;
  color: white;
}

.search-results {
  margin-top: 40px;
}

.results-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

.result-card {
  display: flex;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 12px;
  border: 1px solid #eee;
  transition: all 0.2s ease;
  cursor: pointer;
}

.result-card:hover {
  border-color: #2BD84C;
  box-shadow: 0 4px 12px rgba(43, 216, 76, 0.15);
}

.result-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  flex-shrink: 0;
}

.result-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.result-content h3 {
  font-size: 14px;
  font-weight: 700;
  margin-bottom: 4px;
}

.result-content .desc {
  font-size: 12px;
  color: #999;
  margin-bottom: 6px;
  line-height: 1.3;
}

.result-content .price {
  font-size: 14px;
  font-weight: 700;
  color: #2BD84C;
}

.no-results {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 16px;
}

/* Планшет и ПК */
@media (min-width: 768px) {
  .search-bar {
    padding: 18px 24px;
    border-radius: 24px;
    margin-bottom: 30px;
  }

  .search-icon {
    width: 22px;
    height: 22px;
  }

  .search-input {
    font-size: 18px;
  }

  .category-chip {
    padding: 12px 24px;
    font-size: 15px;
    border-radius: 24px;
    gap: 12px;
  }

  .category-chip:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(43, 216, 76, 0.15);
  }
}

/* Большие ПК */
@media (min-width: 1024px) {
  .search-bar {
    padding: 20px 28px;
    margin-bottom: 40px;
  }

  .search-input {
    font-size: 18px;
  }

  .category-chip {
    padding: 14px 28px;
    font-size: 16px;
  }
}
</style>