<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { businessService } from '@/services/businessService';
import { API_URL } from '@/services/apiClient';
import type { Business } from '@/types';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import FavoriteButton from '@/components/FavoriteButton.vue';

const { t } = useI18n();
const router = useRouter();
const businesses = ref<Business[]>([]);
const isLoading = ref(true);
const selectedArea = ref('Todas');
const selectedCategory = ref('Todas');

import { analyticsService } from '@/services/analyticsService';

onMounted(async () => {
  analyticsService.logEvent({ event_name: 'screen_view', screen_name: 'Discover' });
  try {
    businesses.value = await businessService.getAllBusinesses();
  } catch (error) {
    console.error('Error loading tourist spots:', error);
  } finally {
    isLoading.value = false;
  }
});

function handleExplore(biz: Business) {
  analyticsService.logEvent({ 
    event_name: 'promo_click', 
    item_id: biz.name,
    properties: { business_id: biz.id }
  });
  router.push('/business/' + biz.id);
}

const filteredBusinesses = computed(() => {
  let filtered = businesses.value;
  
  if (selectedArea.value !== 'Todas') {
    filtered = filtered.filter(b => b.area === selectedArea.value);
  }
  
  if (selectedCategory.value !== 'Todas') {
    filtered = filtered.filter(b => b.category === selectedCategory.value);
  }
  
  return filtered;
});

const categories = computed<string[]>(() => {
  const cats = new Set(businesses.value.map(b => b.category).filter(Boolean) as string[]);
  return ['Todas', ...Array.from(cats)];
});

function getImageUrl(path: string | null | undefined) {
  if (!path) return '/default-business.jpg';
  if (path.startsWith('http')) return path;
  return `${API_URL}${path.startsWith('/') ? '' : '/'}${path}`;
}

function getCategoryIcon(category: string) {
  const icons: Record<string, string> = {
    'Restaurante': 'restaurant',
    'Turismo': 'landscape',
    'Bebidas': 'local_bar',
    'Comercio': 'store',
    'Hotel': 'hotel',
    'Café': 'local_cafe'
  };
  return icons[category] || 'place';
}
</script>

<template>
  <div class="discover-view">
    <!-- Compact Glass Header -->
    <header class="premium-header">
      <div class="header-glass-card">
        <div class="header-icon-box">
          <span class="material-icons">explore</span>
          <div class="icon-pulse"></div>
        </div>
        <div class="header-text-box">
          <h1 class="gradient-text">{{ t('discover.title') }}</h1>
          <p class="subtitle">{{ t('discover.subtitle') }}</p>
        </div>
      </div>
    </header>

    <!-- Integrated High-Tech Filters -->
    <div class="filters-panel">
      <div class="glass-filters">
        <div class="filter-item">
          <div class="filter-label">
            <span class="material-icons">location_on</span>
            <span>Región</span>
          </div>
          <div class="custom-select-box">
            <select v-model="selectedArea" class="modern-select">
              <option value="Todas">{{ t('discover.allAreas') }}</option>
              <option value="Boquete">Boquete</option>
              <option value="Dolega">Dolega</option>
              <option value="David">David</option>
            </select>
            <span class="material-icons">expand_more</span>
          </div>
        </div>

        <div class="filter-divider"></div>

        <div class="filter-item">
          <div class="filter-label">
            <span class="material-icons">category</span>
            <span>Categoría</span>
          </div>
          <div class="custom-select-box">
            <select v-model="selectedCategory" class="modern-select">
              <option v-for="cat in categories" :key="cat" :value="cat">
                {{ cat }}
              </option>
            </select>
            <span class="material-icons">expand_more</span>
          </div>
        </div>
      </div>
    </div>

    <!-- Main Content Area -->
    <main class="discover-main">
      <!-- Loading Experience -->
      <div v-if="isLoading" class="loading-container">
        <div class="nexus-loader">
          <div class="nexus-dot"></div>
          <div class="nexus-ring"></div>
        </div>
        <p class="loading-text">Sincronizando con SIBU...</p>
      </div>

      <!-- Empty State -->
      <div v-else-if="filteredBusinesses.length === 0" class="empty-nexus">
        <div class="empty-nexus-box">
          <span class="material-icons">search_off</span>
          <h3>Sin resultados</h3>
          <p>La búsqueda no devolvió datos en esta frecuencia.</p>
          <button class="reboot-btn" @click="selectedArea = 'Todas'; selectedCategory = 'Todas'">
            REINICIAR SENSORES
          </button>
        </div>
      </div>

      <!-- Business Grid Premium -->
      <TransitionGroup 
        v-else 
        name="stagger-list" 
        tag="div" 
        class="premium-business-grid"
      >
        <div v-for="(biz, index) in filteredBusinesses" 
             :key="biz.id" 
             class="nexus-card"
             @click="handleExplore(biz)"
             :style="{ '--order': index }"
        >
          <div class="nexus-card-inner">
            <div class="nexus-image-container">
              <img :src="getImageUrl(biz.image_url)" alt="" class="nexus-img">
              <div class="nexus-overlay-gradient"></div>
              
              <!-- Floating Badges -->
              <div class="nexus-badge category">
                <span class="material-icons">{{ getCategoryIcon(biz.category || '') }}</span>
              </div>
              
              <div class="nexus-fav">
                <FavoriteButton 
                  item-type="business" 
                  :item-id="biz.id" 
                  :item-name="biz.name"
                  :item-image="biz.image_url || undefined"
                />
              </div>
            </div>

            <div class="nexus-card-details">
              <h3 class="nexus-biz-name">{{ biz.name }}</h3>
              <div class="nexus-biz-meta">
                <span class="area"><span class="material-icons">near_me</span>{{ biz.area }}</span>
              </div>
            </div>
          </div>
        </div>
      </TransitionGroup>
    </main>
  </div>
</template>

<style scoped>
.discover-view {
  min-height: 100vh;
  position: relative;
  padding: 20px 16px 150px;
  overflow-x: hidden;
}

/* Contenido directo */
.premium-header, 
.filters-panel, 
.discover-main {
  position: relative;
  z-index: 1;
}

/* Tarjetas nitidas */
.header-glass-card, 
.glass-filters,
.nexus-card-inner {
  background: var(--card-bg) !important;
  backdrop-filter: none !important;
  border: 1px solid var(--border-color) !important;
}

/* Premium Header */
.premium-header {
  margin-bottom: 24px;
}

.header-glass-card {
  background: var(--card-bg);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border: 1px solid var(--border-color);
  border-radius: 24px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

.header-icon-box {
  width: 56px;
  height: 56px;
  background: var(--active-bg);
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.header-icon-box .material-icons {
  color: var(--active-color);
  font-size: 28px;
  z-index: 1;
}

.icon-pulse {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 18px;
  border: 2px solid var(--active-color);
  animation: pulse-out 2s infinite;
}

@keyframes pulse-out {
  0% { transform: scale(1); opacity: 0.5; }
  100% { transform: scale(1.5); opacity: 0; }
}

.header-text-box h1 {
  font-size: 1.5rem;
  font-weight: 900;
  margin: 0;
  letter-spacing: -0.02em;
}

.subtitle {
  margin: 4px 0 0;
  font-size: 0.85rem;
  color: var(--text-secondary);
  font-weight: 500;
}

/* Unified Filters */
.filters-panel {
  margin-bottom: 24px;
}

.glass-filters {
  background: var(--glass-bg);
  backdrop-filter: blur(12px);
  border: 1px solid var(--glass-border);
  border-radius: 20px;
  display: flex;
  padding: 8px;
  gap: 8px;
}

.filter-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 8px 12px;
}

.filter-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.75rem;
  font-weight: 700;
  color: var(--text-secondary);
  margin-bottom: 4px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.filter-label .material-icons {
  font-size: 14px;
  color: var(--active-color);
}

.custom-select-box {
  position: relative;
  display: flex;
  align-items: center;
}

.modern-select {
  width: 100%;
  background: transparent;
  border: none;
  color: var(--text-primary);
  font-size: 0.95rem;
  font-weight: 700;
  padding-right: 24px;
  cursor: pointer;
  outline: none;
  appearance: none;
}

.custom-select-box .material-icons {
  position: absolute;
  right: 0;
  pointer-events: none;
  color: var(--text-secondary);
  font-size: 18px;
}

.filter-divider {
  width: 1px;
  background: var(--border-color);
  margin: 10px 0;
}

/* Premium Grid */
.premium-business-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

@media (max-width: 1024px) {
  .premium-business-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 600px) {
  .premium-business-grid {
    grid-template-columns: repeat(2, 1fr); /* Mantenemos 2 en móvil para aprovechar el espacio nexus */
    gap: 10px;
  }
}

.nexus-card {
  perspective: 1000px;
}

.nexus-card-inner {
  background: var(--card-bg);
  border-radius: 24px;
  overflow: hidden;
  border: 1px solid var(--border-color);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.nexus-card:hover .nexus-card-inner {
  transform: translateY(-8px);
  border-color: var(--active-color);
  box-shadow: 0 15px 30px rgba(0,0,0,0.3);
}

.nexus-image-container {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
}

.nexus-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.6s cubic-bezier(0.4, 0, 0.2, 1);
}

.nexus-card:hover .nexus-img {
  transform: scale(1.1);
}

.nexus-overlay-gradient {
  position: absolute;
  inset: 0;
  background: linear-gradient(to top, rgba(15, 23, 42, 0.8) 0%, transparent 60%);
}

.nexus-badge {
  position: absolute;
  top: 12px;
  left: 12px;
  width: 36px;
  height: 36px;
  background: var(--active-bg);
  backdrop-filter: blur(8px);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--active-color);
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}

.nexus-fav {
  position: absolute;
  top: 12px;
  right: 12px;
}

.nexus-card-details {
  padding: 16px;
  background: var(--card-bg);
}

.nexus-biz-name {
  margin: 0;
  font-size: 1rem;
  font-weight: 800;
  color: var(--text-primary);
  line-height: 1.2;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-clamp: 2;
  overflow: hidden;
}

.nexus-biz-meta {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.area {
  font-size: 0.75rem;
  color: var(--text-secondary);
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 4px;
}

.area .material-icons {
  font-size: 14px;
  color: var(--active-color);
}

/* Loading & Empty States */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 0;
}

.nexus-loader {
  position: relative;
  width: 60px;
  height: 60px;
}

.nexus-dot {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 12px;
  height: 12px;
  background: var(--active-color);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 0 20px var(--active-color);
}

.nexus-ring {
  width: 60px;
  height: 60px;
  border: 4px solid var(--active-bg);
  border-top-color: var(--active-color);
  border-radius: 50%;
  animation: spin 1s infinite linear;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  margin-top: 24px;
  font-weight: 700;
  color: var(--text-secondary);
  letter-spacing: 1px;
}

.empty-nexus {
  padding: 60px 0;
  text-align: center;
}

.empty-nexus-box {
  background: var(--card-bg);
  border-radius: 30px;
  padding: 40px;
  border: 1px dashed var(--border-color);
}

.empty-nexus-box .material-icons {
  font-size: 48px;
  color: var(--text-secondary);
  margin-bottom: 20px;
}

.reboot-btn {
  margin-top: 24px;
  background: var(--active-color);
  color: #101820;
  border: none;
  padding: 12px 24px;
  border-radius: 12px;
  font-weight: 800;
  cursor: pointer;
}

/* Animations */
.stagger-list-enter-active {
  transition: all 0.5s ease;
  transition-delay: calc(0.1s * var(--order));
}

.stagger-list-enter-from {
  opacity: 0;
  transform: translateY(30px);
}

@media (max-width: 480px) {
  .header-glass-card {
    padding: 16px;
    gap: 16px;
  }
  
  .header-icon-box {
    width: 44px;
    height: 44px;
  }
  
  .header-text-box h1 {
    font-size: 1.2rem;
  }
}
</style>
