<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';
import { analyticsService } from '@/services/analyticsService';

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

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);
  }

  if (searchQuery.value.trim() !== '') {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(b => 
      b.name.toLowerCase().includes(query) || 
      (b.area && b.area.toLowerCase().includes(query)) ||
      (b.category && b.category.toLowerCase().includes(query))
    );
  }
  
  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)];
});

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

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">

    <!-- Barra de búsqueda -->
    <div class="search-section">
      <div class="search-bar">
        <span class="material-icons search-icon-inner">search</span>
        <input 
          v-model="searchQuery"
          class="search-input"
          :placeholder="t('discover.searchPlaceholder')"
          type="text"
        />
        <button v-if="searchQuery" class="clear-search-btn" @click="searchQuery = ''">
          <span class="material-icons">close</span>
        </button>
      </div>
    </div>

    <!-- Filtros de Región y Categoría -->
    <div class="filters-row">
      <div class="filter-card">
        <div class="filter-label-row">
          <span class="material-icons filter-icon">location_on</span>
          <span class="filter-label-text">REGIÓN</span>
        </div>
        <select v-model="selectedArea" class="filter-select">
          <option value="Todas">{{ t('discover.allAreas') }}</option>
          <option v-for="area in areas" :key="area" :value="area">{{ area }}</option>
        </select>
      </div>

      <div class="filter-card">
        <div class="filter-label-row">
          <span class="material-icons filter-icon">category</span>
          <span class="filter-label-text">CATEGORÍA</span>
        </div>
        <select v-model="selectedCategory" class="filter-select">
          <option v-for="cat in categories" :key="cat" :value="cat">{{ cat }}</option>
        </select>
      </div>
    </div>

    <main class="discover-main">
      <!-- Loading -->
      <div v-if="isLoading" class="state-container">
        <div class="spinner"></div>
        <p class="state-text">Sincronizando con SIBU...</p>
      </div>

      <!-- Vacío -->
      <div v-else-if="filteredBusinesses.length === 0" class="state-container">
        <div class="empty-box">
          <span class="material-icons empty-icon">search_off</span>
          <h3 class="empty-title">Sin resultados</h3>
          <p class="empty-desc">La búsqueda no devolvió resultados.</p>
          <button 
            @click="selectedArea = 'Todas'; selectedCategory = 'Todas'; searchQuery = ''" 
            class="reset-btn"
          >
            REINICIAR FILTROS
          </button>
        </div>
      </div>

      <!-- Grid de negocios -->
      <TransitionGroup 
        v-else 
        name="fade" 
        tag="div" 
        class="business-grid"
      >
        <div 
          v-for="biz in filteredBusinesses" 
          :key="biz.id" 
          class="business-card"
          @click="handleExplore(biz)"
        >
          <div class="card-image-wrapper">
            <img :src="getImageUrl(biz.image_url)" :alt="biz.name" class="card-img" />
            <div class="card-gradient"></div>
            <div class="card-category-badge">
              <span class="material-icons category-badge-icon">
                {{ getCategoryIcon(biz.category || '') }}
              </span>
            </div>
            <div class="card-favorite-btn">
              <FavoriteButton 
                item-type="business" 
                :item-id="biz.id" 
                :item-name="biz.name"
                :item-image="biz.image_url || undefined"
              />
            </div>
          </div>
          <div class="card-body">
            <h3 class="card-name">{{ biz.name }}</h3>
            <div class="card-meta">
              <span class="material-icons card-meta-icon">near_me</span>
              <span class="card-area">{{ biz.area }}</span>
            </div>
          </div>
        </div>
      </TransitionGroup>
    </main>
  </div>
</template>

<style scoped>
.discover-view {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  background: var(--bg-primary);
  color: var(--text-primary);
  padding-bottom: 6rem;
}

/* ─── Búsqueda ─── */
.search-section {
  padding: 1rem 1.25rem 0.5rem;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 1rem;
  padding: 0.5rem 0.75rem;
  transition: border-color 0.2s;
}

.search-bar:focus-within {
  border-color: var(--active-color);
}

.search-icon-inner {
  color: var(--text-secondary);
  font-size: 1.25rem;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  background: transparent;
  border: none;
  outline: none;
  color: var(--text-primary);
  font-size: 0.9375rem;
  font-weight: 500;
  font-family: inherit;
}

.search-input::placeholder {
  color: var(--text-secondary);
}

.clear-search-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--text-secondary);
  display: flex;
  align-items: center;
  padding: 0;
}

/* ─── Filtros ─── */
.filters-row {
  display: flex;
  gap: 0.75rem;
  padding: 0.75rem 1.25rem;
}

.filter-card {
  flex: 1;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 1rem;
  padding: 0.875rem 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  cursor: pointer;
}

.filter-label-row {
  display: flex;
  align-items: center;
  gap: 0.375rem;
}

.filter-icon {
  font-size: 1rem;
  color: var(--active-color);
}

.filter-label-text {
  font-size: 0.625rem;
  font-weight: 800;
  color: var(--text-secondary);
  letter-spacing: 0.1em;
  text-transform: uppercase;
}

.filter-select {
  background: transparent;
  border: none;
  outline: none;
  color: var(--text-primary);
  font-size: 0.875rem;
  font-weight: 700;
  font-family: inherit;
  cursor: pointer;
  padding: 0;
  width: 100%;
}

.filter-select option {
  background: var(--bg-secondary);
  color: var(--text-primary);
}

/* ─── Estados ─── */
.discover-main {
  flex: 1;
  padding: 0 1.25rem;
}

.state-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 5rem 1rem;
  gap: 1rem;
}

.spinner {
  width: 2.5rem;
  height: 2.5rem;
  border: 3px solid var(--border-color);
  border-top-color: var(--active-color);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

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

.state-text {
  color: var(--text-secondary);
  font-weight: 700;
  font-size: 0.75rem;
  letter-spacing: 0.1em;
  text-transform: uppercase;
}

.empty-box {
  background: var(--bg-secondary);
  border: 1.5px dashed var(--border-color);
  border-radius: 1.5rem;
  padding: 2.5rem;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
}

.empty-icon {
  font-size: 3rem;
  color: var(--text-secondary);
  opacity: 0.4;
  margin-bottom: 0.5rem;
}

.empty-title {
  font-size: 1.125rem;
  font-weight: 800;
  color: var(--text-primary);
  margin: 0;
}

.empty-desc {
  color: var(--text-secondary);
  font-size: 0.875rem;
  margin: 0;
}

.reset-btn {
  margin-top: 0.75rem;
  background: var(--active-color);
  color: #101820;
  border: none;
  border-radius: 0.75rem;
  padding: 0.625rem 1.5rem;
  font-weight: 900;
  font-size: 0.75rem;
  letter-spacing: 0.1em;
  cursor: pointer;
  transition: transform 0.15s;
}

.reset-btn:active { transform: scale(0.97); }

/* ─── Grid ─── */
.business-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.875rem;
  padding-bottom: 1rem;
}

.business-card {
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 1.25rem;
  overflow: hidden;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  transition: transform 0.15s, box-shadow 0.15s;
}

.business-card:active {
  transform: scale(0.97);
}

.card-image-wrapper {
  position: relative;
  height: 10rem;
}

.card-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card-gradient {
  position: absolute;
  inset: 0;
  background: linear-gradient(to bottom, rgba(0,0,0,0.35) 0%, transparent 50%);
}

.card-category-badge {
  position: absolute;
  top: 0.625rem;
  left: 0.625rem;
  background: rgba(0,0,0,0.55);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(255,255,255,0.1);
  border-radius: 0.625rem;
  padding: 0.3rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.category-badge-icon {
  font-size: 1rem;
  color: var(--active-color);
}

.card-favorite-btn {
  position: absolute;
  top: 0.625rem;
  right: 0.625rem;
}

.card-body {
  padding: 0.75rem;
  display: flex;
  flex-direction: column;
  gap: 0.375rem;
  flex: 1;
}

.card-name {
  font-size: 0.9rem;
  font-weight: 800;
  color: var(--text-primary);
  margin: 0;
  line-height: 1.3;
}

.card-meta {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  margin-top: auto;
}

.card-meta-icon {
  font-size: 0.875rem;
  color: var(--active-color);
}

.card-area {
  font-size: 0.75rem;
  font-weight: 600;
  color: var(--text-secondary);
}

/* ─── Transiciones ─── */
.fade-move,
.fade-enter-active,
.fade-leave-active {
  transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(16px);
}

.fade-leave-active {
  position: absolute;
}
</style>
