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

const props = defineProps({
  studios: Array
});

const emit = defineEmits(['addToCart']);

const sortBy = ref('name');
const filterPrice = ref(10000);
const favorites = ref([]);

const sortedAndFilteredStudios = computed(() => {
  if (!Array.isArray(props.studios)) return [];
  
  let result = props.studios.filter(s => s.hourly_rate <= filterPrice.value);
  
  if (sortBy.value === 'price_low') {
    result.sort((a, b) => a.hourly_rate - b.hourly_rate);
  } else if (sortBy.value === 'price_high') {
    result.sort((a, b) => b.hourly_rate - a.hourly_rate);
  } else {
    result.sort((a, b) => a.hall_name.localeCompare(b.hall_name, 'ru'));
  }
  
  return result;
});

const handleAddToCart = (studio) => {
  const bookingDate = prompt('Введите дату (например: 25 Октября):');
  if (!bookingDate) return;

  const bookingTime = prompt('Введите время (например: 14:00 - 16:00):');
  if (!bookingTime) return;

  const quantity = parseInt(prompt('Количество часов:', '2')) || 2;
  const extraServices = parseInt(prompt('Доп. услуги (₽):', '0')) || 0;

  const item = {
    id: Date.now(),
    ...studio,
    bookingDate,
    bookingTime,
    quantity,
    extraServices,
    imageURL: studio.imageURL
  };

  emit('addToCart', item);
  alert('Добавлено в корзину!');
};

const isFavorite = (hallId) => {
  return favorites.value.some(fav => fav.hall_id === hallId);
};

const toggleFavorite = async (studio) => {
  const token = localStorage.getItem('jwt_token');
  if (!token) {
    alert('Пожалуйста, войдите для добавления в избранное');
    return;
  }

  try {
    const response = await fetch('http://localhost:3000/api/favorites', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        hall_id: studio.hall_id,
        photographer_id: null
      })
    });

    if (response.ok) {
      if (!isFavorite(studio.hall_id)) {
        favorites.value.push({ hall_id: studio.hall_id, hall_name: studio.hall_name });
        alert('✅ Добавлено в избранное');
      }
    } else {
      alert('Ошибка при добавлении в избранное');
    }
  } catch (error) {
    console.error('Ошибка:', error);
  }
};

onMounted(async () => {
  const token = localStorage.getItem('jwt_token');
  if (token) {
    try {
      const response = await fetch('http://localhost:3000/api/favorites', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      if (response.ok) {
        favorites.value = await response.json();
      }
    } catch (error) {
      console.error('Ошибка загрузки избранного:', error);
    }
  }
});
</script>

<template>
  <div class="tab-content">
    <header class="location-header">
      <svg class="location-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
        <circle cx="12" cy="10" r="3"></circle>
      </svg>
      <span class="city">Йошкар-Ола</span>
    </header>

    <div class="filters">
      <div class="filter-group">
        <label>Сортировка:</label>
        <select v-model="sortBy" class="filter-select">
          <option value="name">По названию</option>
          <option value="price_low">Дешевле</option>
          <option value="price_high">Дороже</option>
        </select>
      </div>
      <div class="filter-group">
        <label>Макс. цена: {{ filterPrice }} ₽/час</label>
        <input v-model.number="filterPrice" type="range" min="0" max="10000" step="100" class="filter-range" />
      </div>
    </div>

    <div class="studios-grid">
      <div v-if="sortedAndFilteredStudios.length === 0" class="no-results">
        <p>Студии не найдены с указанными фильтрами</p>
      </div>
      
      <div class="studio-card" v-for="studio in sortedAndFilteredStudios" :key="studio.hall_id">
        <div class="image-container">
          <img 
            :src="`http://localhost:3000/HallsImages/${studio.imageURL}`"
            class="studio-image" 
            :alt="studio.hall_name"
            @error="(e) => e.target.src = 'https://via.placeholder.com/280x200'"
          />
          <!-- Top left badge -->
          <div class="badge-top-left">
            <span class="badge recommend-badge">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="20 6 9 17 4 12"></polyline>
              </svg>
              Рекомендуем
            </span>
          </div>
          
          <!-- Favorite button -->
          <button 
            class="favorite-btn"
            :class="{ active: isFavorite(studio.hall_id) }"
            @click.stop="toggleFavorite(studio)"
            title="Добавить в избранное"
          >
            <svg v-if="!isFavorite(studio.hall_id)" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
            </svg>
            <svg v-else width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
              <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
            </svg>
          </button>
          
          <!-- CTA overlay -->
          <div class="card-overlay">
            <button class="add-to-cart-btn" @click.stop="handleAddToCart(studio)">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M7.5 18C8.32843 18 9 18.6716 9 19.5C9 20.3284 8.32843 21 7.5 21C6.67157 21 6 20.3284 6 19.5C6 18.6716 6.67157 18 7.5 18Z"/>
                <path d="M16.5 18.0001C17.3284 18.0001 18 18.6716 18 19.5001C18 20.3285 17.3284 21.0001 16.5 21.0001C15.6716 21.0001 15 20.3285 15 19.5001C15 18.6716 15.6716 18.0001 16.5 18.0001Z"/>
                <path stroke-linecap="round" d="M2 3L2.26121 3.09184C3.5628 3.54945 4.2136 3.77826 4.58584 4.32298C4.95808 4.86771 4.95808 5.59126 4.95808 7.03836V9.76C4.95808 12.7016 5.02132 13.6723 5.88772 14.5862C6.75412 15.5 8.14857 15.5 10.9375 15.5H12M16.2404 15.5C17.8014 15.5 18.5819 15.5 19.1336 15.0504C19.6853 14.6008 19.8429 13.8364 20.158 12.3075L20.6578 9.88275C21.0049 8.14369 21.1784 7.27417 20.7345 6.69708C20.2906 6.12 18.7738 6.12 17.0888 6.12H11.0235M4.95808 6.12H7"/>
              </svg>
              Забронировать
            </button>
          </div>
        </div>
        
        <div class="card-content">
          <h2 class="studio-name">{{ studio.hall_name }}</h2>
          <p class="studio-description">{{ studio.description }}</p>
          <div class="price-section">
            <span class="price">{{ studio.hourly_rate }} ₽<span class="price-period">/час</span></span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.location-header { 
  display: flex; 
  align-items: center; 
  gap: 8px; 
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-color);
}

.location-icon {
  color: var(--primary-color);
  flex-shrink: 0;
}

.city { 
  font-size: 18px; 
  font-weight: 600; 
  color: var(--text-primary);
  letter-spacing: -0.3px;
}

.filters {
  display: flex;
  gap: 14px;
  margin-bottom: 24px;
  padding: 16px;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  flex-wrap: wrap;
  box-shadow: var(--shadow-sm);
}

.filter-group {
  flex: 1;
  min-width: 140px;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.filter-group label {
  font-size: 12px;
  font-weight: 600;
  color: var(--text-secondary);
  text-transform: uppercase;
  letter-spacing: 0.3px;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  font-size: 13px;
  background: white;
  color: var(--text-primary);
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.filter-select:hover {
  border-color: var(--primary-color);
}

.filter-select:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px var(--primary-light);
}

.filter-range {
  width: 100%;
  cursor: pointer;
  height: 5px;
  border-radius: 3px;
  background: var(--border-color);
  -webkit-appearance: none;
  appearance: none;
}

.filter-range::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: var(--primary-color);
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(16, 163, 127, 0.25);
  transition: all 0.2s ease;
}

.filter-range::-webkit-slider-thumb:hover {
  transform: scale(1.15);
}

.filter-range::-moz-range-thumb {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: var(--primary-color);
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(16, 163, 127, 0.25);
  border: none;
}

.no-results {
  grid-column: 1 / -1;
  text-align: center;
  padding: 48px 20px;
  color: var(--text-tertiary);
}

.no-results p {
  font-size: 16px;
  color: var(--text-secondary);
}

.studios-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  width: 100%;
}

.studio-card { 
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: var(--border-radius);
  overflow: hidden;
  background: var(--bg-primary);
  display: flex;
  flex-direction: column;
  border: 1px solid var(--border-color);
  box-shadow: var(--shadow-sm);
}

.studio-card:hover {
  border-color: var(--primary-color);
  box-shadow: 0 8px 24px rgba(16, 163, 127, 0.12);
  transform: translateY(-4px);
}

.studio-card:active {
  transform: translateY(-2px);
}

.image-container {
  position: relative;
  overflow: hidden;
  border-radius: var(--border-radius) var(--border-radius) 0 0;
  height: 240px;
  background: var(--bg-tertiary);
}

.studio-image { 
  width: 100%; 
  height: 100%; 
  object-fit: cover; 
  display: block;
  transition: transform 0.4s ease;
}

.studio-card:hover .studio-image {
  transform: scale(1.08);
}

/* Badge on top-left */
.badge-top-left {
  position: absolute;
  top: 12px;
  left: 12px;
  z-index: 4;
}

.recommend-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  background: rgba(16, 163, 127, 0.9);
  backdrop-filter: blur(8px);
  color: white;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 11px;
  font-weight: 600;
  letter-spacing: 0.3px;
  text-transform: uppercase;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.recommend-badge svg {
  flex-shrink: 0;
  color: white;
}

/* Favorite button */
.favorite-btn {
  position: absolute;
  top: 12px;
  right: 12px;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  border: 2px solid white;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(4px);
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  z-index: 5;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.favorite-btn svg {
  width: 24px;
  height: 24px;
  color: #666;
  transition: all 0.3s ease;
}

.favorite-btn.active svg {
  color: #FF6B6B;
}

.favorite-btn:hover {
  background: white;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.25);
  transform: scale(1.15);
}

.favorite-btn:active {
  transform: scale(0.95);
}

/* CTA Overlay */
.card-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  transition: all 0.3s ease;
}

.studio-card:hover .card-overlay {
  background: rgba(0, 0, 0, 0.35);
}

.add-to-cart-btn {
  background: var(--primary-color);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  box-shadow: 0 4px 12px rgba(16, 163, 127, 0.3);
  opacity: 0;
  transform: translateY(10px);
}

.add-to-cart-btn svg {
  flex-shrink: 0;
  color: white;
}

.studio-card:hover .add-to-cart-btn {
  opacity: 1;
  transform: translateY(0);
}

.add-to-cart-btn:hover {
  background: #0B7C60;
  box-shadow: 0 6px 16px rgba(16, 163, 127, 0.4);
  transform: translateY(-2px);
}

.add-to-cart-btn:active {
  transform: translateY(0);
}

.card-content {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.studio-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
  line-height: 1.3;
}

.studio-description {
  font-size: 13px;
  color: var(--text-secondary);
  line-height: 1.4;
  margin: 0;
  flex: 1;
}

.price-section {
  display: flex;
  align-items: baseline;
  gap: 6px;
  margin-top: 4px;
  padding-top: 8px;
  border-top: 1px solid var(--border-color);
}

.price {
  font-size: 18px;
  font-weight: 700;
  color: var(--primary-color);
}

.price-period {
  font-size: 12px;
  font-weight: 500;
  color: var(--text-secondary);
}

/* Responsive: Tablet */
@media (min-width: 768px) {
  .studios-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }

  .image-container {
    height: 260px;
  }

  .studio-name {
    font-size: 17px;
  }

  .price {
    font-size: 20px;
  }
}

/* Responsive: Desktop */
@media (min-width: 1024px) {
  .studios-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 24px;
  }

  .image-container {
    height: 280px;
  }

  .studio-name {
    font-size: 18px;
  }

  .price {
    font-size: 22px;
  }

  .add-to-cart-btn {
    padding: 14px 28px;
    font-size: 15px;
  }
}
</style>