<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useCouponStore } from '@/stores/coupon'
import type { Coupon } from '@/types'
import FavoriteButton from '@/components/FavoriteButton.vue'
import { getImageUrl as utilGetImageUrl } from '@/utils/imageUrl'
import AuthGuard from '@/components/common/AuthGuard.vue'
import { analyticsService } from '@/services/analyticsService'

const { t } = useI18n()
const couponStore = useCouponStore()

const showRedeemModal = ref(false)
const selectedCoupon = ref<Coupon | null>(null)

const searchQuery = ref('')
const selectedCategory = ref('Todas')
const showFilterSheet = ref(false)

const CATEGORIES = computed(() => [
  { label: t('discover.categories.all'), value: 'Todas' },
  { label: t('discover.categories.restaurant'), value: 'Restaurante' },
  { label: t('discover.categories.tourism'), value: 'Turismo' },
  { label: t('discover.categories.drinks'), value: 'Bebidas' },
  { label: t('discover.categories.commerce'), value: 'Comercio' }
])

onMounted(() => {
  couponStore.loadCoupons()
})

const filteredCoupons = computed(() => {
  return couponStore.coupons.filter(c => {
    const matchesSearch = c.title.toLowerCase().includes(searchQuery.value.toLowerCase()) || 
                         c.business?.name?.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesCategory = selectedCategory.value === 'Todas' || c.category === selectedCategory.value
    return matchesSearch && matchesCategory
  })
})

function getImageUrl(path: string | null | undefined) {
  return utilGetImageUrl(path, 'coupon')
}



function openCoupon(coupon: Coupon) {
  selectedCoupon.value = coupon
  showRedeemModal.value = true
  analyticsService.logEvent({
    event_name: 'promo_view',
    entity_type: 'coupon',
    entity_id: coupon.id,
    entity_name: coupon.title,
    properties: { business: coupon.business?.name }
  })
}

function handleDirections() {
  if (!selectedCoupon.value) return
  analyticsService.logEvent({
    event_name: 'location_click',
    entity_type: 'coupon',
    entity_id: selectedCoupon.value.id,
    entity_name: selectedCoupon.value.title,
    properties: { 
        action: 'get_directions',
        business: selectedCoupon.value.business?.name
    }
  })
  window.open(`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(selectedCoupon.value.business?.address || selectedCoupon.value.business?.name || '')}`, '_blank')
}

function getCategoryIcon(category?: string | null) {
  const cat = category?.toLowerCase() || ''
  if (cat.includes('restaurante')) return 'restaurant'
  if (cat.includes('turismo')) return 'landscape'
  if (cat.includes('bebida')) return 'local_bar'
  if (cat.includes('comercio')) return 'store'
  return 'local_offer'
}
</script>

<template>
  <div class="coupons-view">
    <header class="mobile-header">
      <button class="icon-btn-back" @click="$router.back()">
        <span class="material-icons">arrow_back</span>
      </button>
      <div class="header-center">
        <span class="material-icons brand-icon">local_offer</span>
        <h1>{{ t('coupons.title') }}</h1>
      </div>
      <div class="header-right"></div>
    </header>
    
    <div class="search-section">
      <div class="search-bar-rounded">
        <span class="material-icons search-icon">search</span>
        <input 
          v-model="searchQuery" 
          type="text" 
          :placeholder="t('coupons.searchPlaceholder')" 
          class="search-input"
        >
      </div>
      <button class="filter-btn-square" @click="showFilterSheet = true">
        <span class="material-icons">tune</span>
      </button>
    </div>

    <div class="offers-stats">
        <span class="stat-dot"></span>
        <span class="stat-label">{{ t('coupons.offersCount', { count: filteredCoupons.length }) }}</span>
    </div>
    
    <div v-if="couponStore.isLoading" class="loading-container">
      <span class="material-icons spin">refresh</span>
      <p>{{ t('coupons.loadingCoupons') }}</p>
    </div>
    
    <div v-else-if="couponStore.error" class="error-container">
      <span class="material-icons">error_outline</span>
      <p>{{ t('common.error') }}: {{ couponStore.error }}</p>
    </div>
    
    <div v-else-if="filteredCoupons.length === 0" class="empty-container">
      <span class="material-icons">search_off</span>
      <p>{{ t('coupons.noResults') }}</p>
    </div>
    
    <AuthGuard
      v-else
      :title="t('coupons.auth.title') || '¡Cupones exclusivos!'"
      :message="t('coupons.auth.message') || 'Regístrate para ver todos los descuentos y promociones en restaurantes y comercios locales.'"
    >
      <div class="coupons-grid-new">
        <div 
          v-for="coupon in filteredCoupons" 
          :key="coupon.id" 
          v-memo="[coupon.id]"
          class="offer-card-new"
          @click="openCoupon(coupon)"
        >
          <div class="offer-image-wrapper">
            <img :src="getImageUrl(coupon.image_url)" :alt="coupon.title" loading="lazy" decoding="async" class="offer-img">
            <div class="status-badge" :class="{ 'tmr': coupon.title.toLowerCase().includes('mañana') || (coupon.description?.toLowerCase().includes('mañana') ?? false) }">
              <span class="material-icons">schedule</span>
              {{ coupon.title.toLowerCase().includes('mañana') ? t('coupons.tomorrow') : t('coupons.active') }}
            </div>
            <div class="favorite-button-wrapper">
              <FavoriteButton 
                item-type="coupon" 
                :item-id="coupon.id" 
                :item-name="coupon.title"
                :item-image="coupon.image_url || undefined"
              />
            </div>
          </div>
          
          <div class="offer-content">
            <h3 class="offer-title">{{ coupon.business?.name || t('coupons.restaurant') }}</h3>
            <p class="offer-benefit">{{ coupon.title }}</p>
          </div>
        </div>
      </div>
    </AuthGuard>

    <!-- Category Filter Sheet -->
    <div v-if="showFilterSheet" class="bottom-sheet-overlay" @click.self="showFilterSheet = false">
        <div class="bottom-sheet">
            <div class="sheet-handle"></div>
            <div class="sheet-header">
                <h3>{{ t('coupons.filterByCategory') }}</h3>
            </div>
            <div class="sheet-body">
                <div v-for="cat in CATEGORIES" :key="cat.value" class="filter-option" @click="selectedCategory = cat.value; showFilterSheet = false">
                    <span class="material-icons">{{ getCategoryIcon(cat.value) }}</span>
                    <span>{{ cat.label }}</span>
                    <span v-if="selectedCategory === cat.value" class="material-icons check">check_circle</span>
                </div>
            </div>
            <div class="sheet-footer">
                <button class="apply-btn-full" @click="showFilterSheet = false">
                    {{ t('coupons.apply') }}
                </button>
            </div>
        </div>
    </div>

    <!-- Detail Modal -->
    <div v-if="showRedeemModal" class="modal-overlay-new" @click.self="showRedeemModal = false">
      <div class="detail-modal-new" v-if="selectedCoupon">
        <div class="modal-header-new">
            <h3>{{ t('coupons.offerDetails') }}</h3>
            <button class="close-btn-round" @click="showRedeemModal = false">
                <span class="material-icons">close</span>
            </button>
        </div>
        
        <div class="modal-scroll-body">
            <div class="modal-hero-image">
                <img :src="getImageUrl(selectedCoupon.image_url)" alt="Header Image">
            </div>
            
            <div class="modal-info-section">
                <h2 class="modal-business-title">{{ selectedCoupon.business?.name }}</h2>
                
                <div class="benefit-highlight-box">
                    <span class="material-icons icon-label">local_offer</span>
                    <span>{{ selectedCoupon.title }}</span>
                </div>

                <div class="info-block">
                    <div class="block-header">
                        <span class="material-icons icon-desc">description</span>
                        <h4>{{ t('coupons.description') }}</h4>
                    </div>
                    <p class="block-text">{{ selectedCoupon.description || t('coupons.noDescription') }}</p>
                </div>

                <div class="info-block">
                    <div class="block-header">
                        <span class="material-icons icon-date">calendar_today</span>
                        <h4>{{ t('coupons.validity') }}</h4>
                    </div>
                    <div class="validity-badge">
                        {{ t('coupons.validUntil') }} {{ selectedCoupon.valid_until || '31/1/2026' }}
                    </div>
                </div>

                <div v-if="selectedCoupon.category" class="info-block">
                    <div class="block-header">
                        <span class="material-icons icon-cat">category</span>
                        <h4>{{ t('coupons.category') }}</h4>
                    </div>
                    <div class="category-badge-simple">
                        {{ selectedCoupon.category.toLowerCase() }}
                    </div>
                </div>
            </div>
        </div>

        <div class="modal-footer-new">
            <button class="location-btn-green" @click="handleDirections">
              <span class="material-icons">place</span>
              {{ t('coupons.viewLocation') }}
            </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.coupons-view {
  padding: 0;
  background: var(--bg-primary);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* Mobile Header */
.mobile-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  background: var(--bg-primary);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-center {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-center h1 {
  font-size: 1.1rem;
  font-weight: 700;
  margin: 0;
}

.brand-icon {
  color: #fee715;
  font-size: 24px;
}

.icon-btn-back {
  background: none;
  border: none;
  color: var(--text-primary);
  cursor: pointer;
}

.header-right { width: 40px; }

/* Search and Filters */
.search-section {
  padding: 0 16px;
  display: flex;
  gap: 12px;
  margin-top: 10px;
}

.search-bar-rounded {
  flex: 1;
  background: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-bar-rounded:focus-within {
  border-color: #fee715;
}

.search-icon { color: var(--text-secondary); }
.search-input {
  border: none;
  background: transparent;
  width: 100%;
  color: var(--text-primary);
  font-size: 0.95rem;
  outline: none;
}

.filter-btn-square {
  background: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-primary);
  cursor: pointer;
}

/* Stats */
.offers-stats {
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.stat-dot {
    width: 8px;
    height: 8px;
    background: #fee715;
    border-radius: 50%;
}

.stat-label {
    font-size: 0.85rem;
    font-weight: 600;
    color: var(--text-secondary);
}

/* Grid and Cards */
.coupons-grid-new {
  padding: 0 16px 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 12px;
}

.offer-card-new {
  background: var(--card-bg);
  border-radius: 16px;
  overflow: hidden;
  border: 1px solid var(--border-color);
  box-shadow: 0 2px 8px var(--shadow);
}

.offer-image-wrapper {
  position: relative;
  aspect-ratio: 1/1;
  background: var(--bg-secondary);
}

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

.status-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  background: #166534;
  color: white;
  padding: 4px 8px;
  border-radius: 20px;
  font-size: 0.65rem;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 4px;
}

.status-badge.tmr { background: #f97316; }
.status-badge .material-icons { font-size: 10px; }

.favorite-button-wrapper {
  position: absolute;
  top: 8px;
  left: 8px;
  z-index: 5;
}

.offer-content {
  padding: 10px;
}

.offer-title {
  font-size: 0.85rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.offer-benefit {
  font-size: 0.75rem;
  color: var(--text-secondary);
  line-height: 1.2;
}

/* Bottom Sheet */
.bottom-sheet-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.5);
    z-index: 2000;
    display: flex;
    align-items: flex-end;
}

.bottom-sheet {
    background: var(--card-bg);
    width: 100%;
    border-radius: 24px 24px 0 0;
    padding: 12px 20px 30px;
    animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
    from { transform: translateY(100%); }
    to { transform: translateY(0); }
}

.sheet-handle {
    width: 40px;
    height: 4px;
    background: var(--border-color);
    border-radius: 2px;
    margin: 0 auto 16px;
}

.sheet-header h3 {
    font-size: 1.1rem;
    font-weight: 800;
    margin-bottom: 20px;
}

.filter-option {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 14px 0;
    border-bottom: 1px solid var(--border-color);
    cursor: pointer;
}

.filter-option .material-icons { color: var(--text-secondary); }
.filter-option span { font-weight: 600; color: var(--text-primary); }
.filter-option .check { color: #fee715; margin-left: auto; }

.sheet-footer { margin-top: 24px; }
.apply-btn-full {
    width: 100%;
    padding: 14px;
    background: #fee715;
    color: #101820;
    border: none;
    border-radius: 12px;
    font-weight: 800;
    cursor: pointer;
}

/* Detail Modal New */
.modal-overlay-new {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 3000;
    padding: 20px;
}

.detail-modal-new {
    background: var(--card-bg);
    width: 100%;
    max-width: 480px;
    height: 85vh;
    border-radius: 28px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
}

.modal-header-new {
    padding: 16px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid var(--border-color);
}

.modal-header-new h3 { font-size: 1rem; font-weight: 800; }
.close-btn-round {
    background: var(--bg-secondary);
    border: none;
    border-radius: 50%;
    width: 32px;
    height: 32px;
    cursor: pointer;
}

.modal-scroll-body {
    flex: 1;
    overflow-y: auto;
}

.modal-hero-image img {
    width: 100%;
    height: 220px;
    object-fit: cover;
}

.modal-info-section {
    padding: 20px;
}

.modal-business-title {
    font-size: 1.3rem;
    font-weight: 800;
    margin-bottom: 16px;
}

.benefit-highlight-box {
    background: #fefce8; /* Light yellow in light mode */
    border: 1px solid #fee715;
    padding: 12px 16px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 700;
    color: #854d0e;
    margin-bottom: 24px;
}

.dark .benefit-highlight-box {
    background: rgba(254, 231, 21, 0.1);
    color: #fee715;
}

.icon-label { color: #facc15; }

.info-block {
    margin-bottom: 20px;
}

.block-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
}

.block-header h4 { font-size: 0.9rem; font-weight: 700; color: var(--text-primary); }
.block-header .material-icons { font-size: 18px; color: var(--text-secondary); }

.block-text { font-size: 0.9rem; color: var(--text-secondary); line-height: 1.4; }

.validity-badge {
    display: inline-block;
    background: #dcfce7;
    color: #166534;
    padding: 6px 12px;
    border-radius: 8px;
    font-weight: 700;
    font-size: 0.85rem;
}

.dark .validity-badge { background: rgba(22, 101, 52, 0.2); color: #4ade80; }

.category-badge-simple {
    display: inline-block;
    background: #fefce8;
    color: #854d0e;
    padding: 6px 12px;
    border-radius: 8px;
    font-weight: 700;
    font-size: 0.85rem;
}

.modal-footer-new {
    padding: 20px;
    background: var(--card-bg);
}

.location-btn-green {
    width: 100%;
    padding: 16px;
    background: #10b981;
    color: white;
    border: none;
    border-radius: 16px;
    font-weight: 800;
    font-size: 1rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    cursor: pointer;
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.loading-container, .error-container, .empty-container {
  padding: 4rem 2rem;
  text-align: center;
  color: var(--text-secondary);
}

.spin { animation: spin 1s linear infinite; }
@keyframes spin { 100% { transform: rotate(360deg); } }
</style>
