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

const cartItems = ref([]);
const isLoading = ref(false);

const removeFromCart = (id) => {
  cartItems.value = cartItems.value.filter(item => item.id !== id);
};

const updateQuantity = (id, newQuantity) => {
  const item = cartItems.value.find(item => item.id === id);
  if (item && newQuantity > 0) {
    item.quantity = newQuantity;
  }
};

const totalPrice = computed(() => {
  return cartItems.value.reduce((sum, item) => {
    return sum + (item.hourly_rate * item.quantity) + item.extraServices;
  }, 0);
});

const totalItems = computed(() => cartItems.value.length);

const handleCheckout = async () => {
  if (totalItems.value === 0) {
    alert('Корзина пуста!');
    return;
  }

  isLoading.value = true;
  try {
    const token = localStorage.getItem('jwt_token');
    if (!token) {
      alert('Пожалуйста, войдите в аккаунт для оформления бронирования');
      return;
    }

    const payload = JSON.parse(atob(token.split('.')[1]));
    
    // Создаем бронирование для каждого товара в корзине
    for (const item of cartItems.value) {
      const startTime = new Date();
      const endTime = new Date(startTime.getTime() + item.quantity * 60 * 60 * 1000);

      const response = await fetch('http://localhost:3000/api/booking', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          clientId: payload.id,
          hallId: item.hall_id,
          startTime: startTime.toISOString(),
          endTime: endTime.toISOString(),
          totalCost: (item.hourly_rate * item.quantity) + item.extraServices,
          status: 'pending'
        })
      });

      if (!response.ok) {
        throw new Error(`Ошибка бронирования ${item.hall_name}`);
      }
    }

    alert(`✅ Успешно забронировано! Сумма: ${totalPrice.value.toLocaleString()} ₽`);
    cartItems.value = [];
  } catch (error) {
    alert(`❌ Ошибка при оформлении заказа: ${error.message}`);
    console.error(error);
  } finally {
    isLoading.value = false;
  }
};

defineExpose({
  cartItems,
  totalPrice,
  totalItems,
  removeFromCart,
  updateQuantity
});
</script>

<template>
  <div class="tab-content">
    <h1 class="page-title">🛒 Корзина бронирования</h1>
    
    <div v-if="totalItems === 0" class="empty-cart-container">
      <div class="empty-state">
        <div class="empty-illustration">
          <span class="calendar-emoji">📅</span>
        </div>
        <h2 class="empty-title">Корзина пуста</h2>
        <p class="empty-description">Добавьте студии в корзину и забронируйте идеальное пространство для вашего проекта</p>
        <div class="empty-features">
          <div class="feature">
            <svg width="16" height="16" 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>
            Фиксированные цены без скрытых комиссий
          </div>
          <div class="feature">
            <svg width="16" height="16" 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>
            Быстрое подтверждение бронирования
          </div>
          <div class="feature">
            <svg width="16" height="16" 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>
            Гибкие условия отмены
          </div>
        </div>
        <button class="cta-button" @click="$root.$el.parentElement.parentElement.querySelector('.nav-btn[data-tab=catalog]')?.click() || alert('Перейдите в каталог через меню')">
          Открыть каталог студий →
        </button>
      </div>
    </div>

    <div v-else>
      <div v-for="item in cartItems" :key="item.id" class="cart-item">
        <img 
          :src="`http://localhost:3000/HallsImages/${item.imageURL}`" 
          class="cart-item-img"
          :alt="item.hall_name"
        />
        <div class="cart-item-info">
          <h3>{{ item.hall_name }}</h3>
          <p class="cart-date">📅 {{ item.bookingDate }}</p>
          <p class="cart-time">🕐 {{ item.bookingTime }}</p>
          <p class="cart-price">{{ (item.hourly_rate * item.quantity).toLocaleString() }} ₽</p>
        </div>
        <div class="cart-controls">
          <div class="quantity-control">
            <button @click="updateQuantity(item.id, item.quantity - 1)">−</button>
            <span>{{ item.quantity }}ч</span>
            <button @click="updateQuantity(item.id, item.quantity + 1)">+</button>
          </div>
          <button class="remove-btn" @click="removeFromCart(item.id)">✕</button>
        </div>
      </div>

      <div class="cart-summary">
        <div class="summary-row">
          <span>Количество товаров:</span>
          <span>{{ totalItems }}</span>
        </div>
        <div class="summary-row">
          <span>Подитог:</span>
          <span>{{ totalPrice.toLocaleString() }} ₽</span>
        </div>
        <div class="summary-row total">
          <span>Итого:</span>
          <span>{{ totalPrice.toLocaleString() }} ₽</span>
        </div>
      </div>

      <button class="checkout-btn" @click="handleCheckout" :disabled="isLoading">
        <template v-if="isLoading">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M6 4h12v7H6z"></path>
            <path d="M6 13h12v7H6z"></path>
            <path d="M9 9h6"></path>
            <path d="M9 18h6"></path>
          </svg>
          Обработка...
        </template>
        <template v-else>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
            <path d="M7 11V7a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v4"></path>
            <line x1="11" y1="16" x2="11" y2="20"></line>
          </svg>
          Перейти к оплате ({{ totalPrice.toLocaleString() }} ₽)
        </template>
      </button>
    </div>
  </div>
</template>

<style scoped>
.empty-cart-container {
  min-height: calc(100vh - 200px);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.empty-state {
  text-align: center;
  max-width: 420px;
}

.empty-illustration {
  font-size: 80px;
  margin-bottom: 24px;
  display: inline-block;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.calendar-emoji {
  display: inline-block;
  font-size: 80px;
}

.empty-title {
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 12px;
  letter-spacing: -0.5px;
}

.empty-description {
  font-size: 15px;
  color: var(--text-secondary);
  line-height: 1.6;
  margin-bottom: 28px;
}

.empty-features {
  background: var(--primary-light);
  border: 1px solid var(--primary-color);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 24px;
  text-align: left;
}

.feature {
  font-size: 13px;
  color: var(--text-primary);
  padding: 6px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.feature svg {
  flex-shrink: 0;
  color: var(--primary-color);
}

.feature:first-child {
  padding-top: 0;
}

.feature:last-child {
  padding-bottom: 0;
  margin-bottom: 0;
}

.cta-button {
  display: inline-block;
  background: var(--primary-color);
  color: white;
  border: none;
  padding: 14px 32px;
  border-radius: 8px;
  font-weight: 600;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(16, 163, 127, 0.25);
}

.cta-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(16, 163, 127, 0.35);
}

.cta-button:active {
  transform: translateY(0);
}

/* Cart items styling */

.cart-item { 
  display: flex; 
  gap: 12px;
  align-items: center;
  margin-bottom: 16px;
  background: white;
  padding: 12px;
  border-radius: 12px;
  border: 1px solid #eee;
  transition: all 0.2s ease;
}

.cart-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.cart-item-img { 
  width: 80px; 
  height: 80px; 
  border-radius: 8px; 
  object-fit: cover;
  flex-shrink: 0;
}

.cart-item-info { 
  flex: 1;
}

.cart-item-info h3 { 
  font-size: 14px;
  font-weight: 700;
  margin-bottom: 4px;
  line-height: 1.2;
}

.cart-date { 
  font-size: 11px; 
  color: #666; 
  margin-bottom: 2px;
}

.cart-time {
  font-size: 11px;
  color: #666;
  margin-bottom: 4px;
}

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

.cart-controls {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-shrink: 0;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 6px;
  background: #F5F5F5;
  border-radius: 6px;
  padding: 4px 8px;
}

.quantity-control button {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  font-weight: 700;
  color: #2BD84C;
  padding: 0 4px;
  transition: all 0.2s ease;
}

.quantity-control button:active {
  transform: scale(0.9);
}

.quantity-control span {
  font-size: 12px;
  font-weight: 600;
  min-width: 30px;
  text-align: center;
}

.remove-btn {
  background: #FFE0E0;
  border: none;
  color: #FF4B4B;
  width: 28px;
  height: 28px;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 700;
  transition: all 0.2s ease;
}

.remove-btn:hover {
  background: #FFD0D0;
}

.remove-btn:active {
  transform: scale(0.9);
}

.cart-summary { 
  background: #F5F5F5; 
  border-radius: 16px; 
  padding: 16px; 
  margin: 20px 0;
}

.summary-row { 
  display: flex; 
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px; 
  color: #666; 
  font-size: 14px;
  font-weight: 500;
}

.summary-row.total { 
  border-top: 1px solid #E0E0E0; 
  padding-top: 12px; 
  margin-bottom: 0; 
  color: #000; 
  font-size: 16px; 
  font-weight: 800;
}

.checkout-btn { 
  width: 100%; 
  background: linear-gradient(135deg, var(--primary-color), #0B7C60);
  color: white; 
  border: none; 
  padding: 14px; 
  border-radius: 12px; 
  font-size: 14px; 
  font-weight: 700; 
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(16, 163, 127, 0.2);
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.checkout-btn svg {
  flex-shrink: 0;
  color: white;
}

.checkout-btn:active {
  transform: scale(0.98);
}

.checkout-btn:hover {
  box-shadow: 0 6px 16px rgba(16, 163, 127, 0.3);
}

.checkout-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Планшет и ПК */
@media (min-width: 768px) {
  .cart-item {
    gap: 16px;
    padding: 16px;
    border-radius: 16px;
  }

  .cart-item-img {
    width: 120px;
    height: 120px;
    border-radius: 12px;
  }

  .cart-item-info h3 {
    font-size: 16px;
  }

  .cart-controls {
    gap: 12px;
  }

  .quantity-control {
    padding: 6px 12px;
  }

  .remove-btn {
    width: 32px;
    height: 32px;
  }

  .cart-summary {
    padding: 20px;
    border-radius: 20px;
    margin: 30px 0;
  }

  .summary-row {
    font-size: 15px;
    margin-bottom: 12px;
  }

  .summary-row.total {
    font-size: 18px;
  }

  .checkout-btn {
    padding: 16px;
    font-size: 16px;
    border-radius: 16px;
  }
}

/* Большие ПК */
@media (min-width: 1024px) {
  .cart-item {
    max-width: 600px;
  }

  .cart-summary {
    max-width: 600px;
  }

  .checkout-btn {
    max-width: 600px;
  }
}
</style>