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

const userName = ref('Загрузка...');
const userAvatar = ref('Images/AvatarPlaceholder.png');
const userBookings = ref([]);
const activeSection = ref('overview');

onMounted(async () => {
  const token = localStorage.getItem('jwt_token');
  
  if (token) {
    try {
      const payloadBase64 = token.split('.')[1];
      const binaryString = atob(payloadBase64);
      const bytes = new Uint8Array(binaryString.length);
      for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
      const decodedText = new TextDecoder().decode(bytes);
      const decodedPayload = JSON.parse(decodedText);
      userName.value = decodedPayload.firstName || 'Пользователь';

      // Загружаем бронирования пользователя
      try {
        const bookingsResponse = await fetch('http://localhost:3000/api/booking');
        if (bookingsResponse.ok) {
          const allBookings = await bookingsResponse.json();
          userBookings.value = allBookings.filter(b => b.client_id === decodedPayload.id);
        }
      } catch (error) {
        console.error('Ошибка загрузки бронирований:', error);
      }
    } catch (e) {
      console.error('Ошибка при расшифровке токена:', e);
      userName.value = 'Гость';
    }
  } else {
    userName.value = 'Гость';
  }
});

const handleLogout = () => {
  if (confirm('Вы уверены, что хотите выйти из аккаунта?')) {
    localStorage.removeItem('jwt_token');
    alert('Выход выполнен 🚪');
    location.reload(); 
  }
};

const getStatusBadge = (status) => {
  const badges = {
    pending: 'Ожидание',
    confirmed: 'Подтверждено',
    completed: 'Завершено',
    cancelled: 'Отменено'
  };
  return badges[status] || status;
};

const formatDate = (dateString) => {
  try {
    return new Date(dateString).toLocaleString('ru-RU');
  } catch {
    return dateString;
  }
};
</script>

<template>
  <div class="tab-content">
    <!-- Profile Header -->
    <div class="profile-header-compact">
      <img :src="userAvatar" class="profile-avatar-small" alt="Аватар пользователя" />
      <div class="profile-info-compact">
        <h1 class="page-title">{{ userName }}</h1>
        <p class="profile-subtitle">Профиль пользователя</p>
      </div>
    </div>

    <!-- Tabs Navigation -->
    <div class="tabs-navigation">
      <button 
        class="tab-item" 
        :class="{ active: activeSection === 'overview' }"
        @click="activeSection = 'overview'"
      >
        👤 Профиль
        <span class="tab-underline"></span>
      </button>
      <button 
        class="tab-item" 
        :class="{ active: activeSection === 'bookings' }"
        @click="activeSection = 'bookings'"
      >
        <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="4" width="18" height="18" rx="2" ry="2"></rect>
          <line x1="16" y1="2" x2="16" y2="6"></line>
          <line x1="8" y1="2" x2="8" y2="6"></line>
          <line x1="3" y1="10" x2="21" y2="10"></line>
        </svg>
        Бронирования
        <span class="tab-underline"></span>
      </button>
    </div>

    <!-- Profile Section -->
    <div v-if="activeSection === 'overview'" class="profile-section">
      <div class="menu-list">
        <div class="menu-item" @click="activeSection = 'bookings'">
          <svg class="menu-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
            <line x1="16" y1="2" x2="16" y2="6"></line>
            <line x1="8" y1="2" x2="8" y2="6"></line>
            <line x1="3" y1="10" x2="21" y2="10"></line>
          </svg>
          <div class="menu-content">
            <span class="menu-text">Мои бронирования</span>
            <span class="menu-count">{{ userBookings.length }}</span>
          </div>
          <span class="menu-arrow">›</span>
        </div>
        <div class="menu-item" @click="() => alert('Раздел находится в разработке 🚧')">
          <svg class="menu-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect>
            <line x1="1" y1="10" x2="23" y2="10"></line>
          </svg>
          <span class="menu-text">Способы оплаты</span>
          <span class="menu-arrow">›</span>
        </div>
        <div class="menu-item" @click="() => alert('Раздел находится в разработке 🚧')">
          <svg class="menu-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="12" cy="12" r="3"></circle>
            <path d="M12 1v6m0 6v6M4.22 4.22l4.24 4.24m5.08 5.08l4.24 4.24M1 12h6m6 0h6M4.22 19.78l4.24-4.24m5.08-5.08l4.24-4.24"></path>
          </svg>
          <span class="menu-text">Настройки</span>
          <span class="menu-arrow">›</span>
        </div>
        <div class="menu-item logout" @click="handleLogout">
          <svg class="menu-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M10 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h4"></path>
            <polyline points="17 16 21 12 17 8"></polyline>
            <line x1="21" y1="12" x2="9" y2="12"></line>
          </svg>
          <span class="menu-text">Выйти из аккаунта</span>
        </div>
      </div>
    </div>

    <!-- Bookings Section -->
    <div v-else-if="activeSection === 'bookings'" class="bookings-section">
      <div v-if="userBookings.length === 0" class="empty-bookings">
        <svg class="empty-icon" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"></path>
          <path d="M2 6h20"></path>
        </svg>
        <p class="empty-text">У вас нет бронирований</p>
        <p class="empty-hint">Забронируйте студию из каталога</p>
      </div>

      <div v-else class="bookings-list">
        <div class="booking-card" v-for="booking in userBookings" :key="booking.booking_id">
          <div class="booking-status">
            <span class="status-badge" :class="booking.status">
              <svg v-if="booking.status === 'pending'" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="10"></circle>
                <polyline points="12 6 12 12 16 14"></polyline>
              </svg>
              <svg v-else-if="booking.status === 'confirmed'" 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>
              <svg v-else-if="booking.status === 'completed'" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="10"></circle>
                <polygon points="12 7 15 17 9 13 15 13 9 17l3-10z" fill="currentColor"></polygon>
              </svg>
              <svg v-else-if="booking.status === 'cancelled'" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
              {{ getStatusBadge(booking.status) }}
            </span>
          </div>
          <div class="booking-body">
            <h3 class="booking-title">Зал #{{ booking.hall_id }}</h3>
            <div class="booking-time">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                <line x1="16" y1="2" x2="16" y2="6"></line>
                <line x1="8" y1="2" x2="8" y2="6"></line>
                <line x1="3" y1="10" x2="21" y2="10"></line>
              </svg>
              <span class="time-item">{{ formatDate(booking.start_time) }}</span>
            </div>
            <div class="booking-footer">
              <span class="booking-cost">{{ booking.total_cost }} ₽</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* Profile Header */
.profile-header-compact {
  display: flex;
  align-items: center;
  gap: 14px;
  margin-bottom: 28px;
  padding-bottom: 16px;
}

.profile-avatar-small {
  width: 80px;
  height: 80px;
  border-radius: 12px;
  object-fit: cover;
  border: 2px solid var(--primary-light);
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.profile-info-compact {
  flex: 1;
}

.profile-subtitle {
  font-size: 13px;
  color: var(--text-secondary);
  margin-top: 4px;
}

/* Tabs Navigation */
.tabs-navigation {
  display: flex;
  gap: 0;
  margin-bottom: 24px;
  border-bottom: 1px solid var(--border-color);
}

.tab-item {
  background: none;
  border: none;
  color: var(--text-secondary);
  font-weight: 600;
  font-size: 15px;
  padding: 12px 16px 10px;
  cursor: pointer;
  position: relative;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.tab-item svg {
  flex-shrink: 0;
  width: 18px;
  height: 18px;
  color: var(--text-secondary);
}

.tab-item.active svg {
  color: var(--primary-color);
}

.tab-item:hover {
  color: var(--text-primary);
}

.tab-item.active {
  color: var(--primary-color);
}

.tab-underline {
  position: absolute;
  bottom: -1px;
  left: 16px;
  right: 16px;
  height: 2px;
  background: var(--primary-color);
  transform: scaleX(0);
  transform-origin: center;
  transition: transform 0.3s ease;
}

.tab-item.active .tab-underline {
  transform: scaleX(1);
}

/* Profile Section */
.profile-section {
  margin-top: 16px;
}

.menu-list {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  cursor: pointer;
  transition: all 0.3s ease;
  background: var(--bg-primary);
}

.menu-item:first-child {
  border-radius: var(--border-radius) var(--border-radius) 0 0;
}

.menu-item:last-child {
  border-radius: 0 0 var(--border-radius) var(--border-radius);
  border-bottom: none;
}

.menu-item:hover {
  background: var(--primary-light);
  border-color: var(--primary-color);
  transform: translateX(4px);
}

.menu-item.logout:hover {
  background: rgba(220, 38, 38, 0.1);
  border-color: #DC2626;
}

.menu-icon {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  color: var(--text-secondary);
}

.menu-item:hover .menu-icon {
  color: var(--primary-color);
}

.menu-item.logout:hover .menu-icon {
  color: #DC2626;
}

.menu-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.menu-text {
  font-size: 15px;
  color: var(--text-primary);
  font-weight: 500;
}

.menu-count {
  background: var(--primary-color);
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 700;
}

.menu-arrow {
  color: var(--text-tertiary);
  font-size: 18px;
  font-weight: 700;
}

/* Bookings Section */
.bookings-section {
  margin-top: 16px;
}

.empty-bookings {
  text-align: center;
  padding: 48px 20px;
  background: var(--bg-primary);
  border-radius: var(--border-radius);
  border: 1px dashed var(--border-color);
}

.empty-icon {
  width: 48px;
  height: 48px;
  margin: 0 auto 16px;
  display: block;
  color: var(--text-secondary);
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.empty-hint {
  font-size: 13px;
  color: var(--text-secondary);
}

.bookings-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.booking-card {
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  padding: 16px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-sm);
}

.booking-card:hover {
  border-color: var(--primary-color);
  box-shadow: 0 6px 16px rgba(16, 163, 127, 0.1);
  transform: translateY(-2px);
}

.booking-status {
  flex-shrink: 0;
}

.status-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.3px;
}

.status-badge svg {
  flex-shrink: 0;
  width: 14px;
  height: 14px;
}

.status-badge.pending {
  background: rgba(255, 193, 7, 0.15);
  color: #F59E0B;
}

.status-badge.confirmed {
  background: rgba(34, 197, 94, 0.15);
  color: #22C55E;
}

.status-badge.completed {
  background: rgba(59, 130, 246, 0.15);
  color: #3B82F6;
}

.status-badge.cancelled {
  background: rgba(220, 38, 38, 0.15);
  color: #DC2626;
}

.booking-body {
  flex: 1;
  min-width: 0;
}

.booking-title {
  font-size: 15px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px 0;
}

.booking-time {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
}

.booking-time svg {
  flex-shrink: 0;
  width: 14px;
  height: 14px;
  color: var(--primary-color);
}

.time-item {
  font-size: 12px;
  color: var(--text-secondary);
}

.booking-footer {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 8px;
  padding-top: 8px;
  border-top: 1px solid var(--border-color);
}

.booking-cost {
  font-size: 15px;
  font-weight: 700;
  color: var(--primary-color);
}

/* Responsive */
@media (min-width: 768px) {
  .profile-header-compact {
    margin-bottom: 32px;
  }

  .profile-avatar-small {
    width: 100px;
    height: 100px;
  }

  .tabs-navigation {
    margin-bottom: 28px;
  }

  .tab-item {
    padding: 14px 20px 12px;
    font-size: 16px;
  }

  .menu-item {
    padding: 18px 20px;
  }

  .bookings-list {
    gap: 14px;
  }

  .booking-card {
    padding: 18px 20px;
  }
}

@media (min-width: 1024px) {
  .profile-header-compact {
    margin-bottom: 40px;
  }

  .profile-avatar-small {
    width: 120px;
    height: 120px;
  }
}
</style>