<template>
  <div class="recipe-search">
    <!-- Category Carousel (full-width image slides) -->
    <div class="cat-wrap" v-if="categories.length && !selectedCategory">
      <div class="cat-track" :style="{ transform: `translateX(-${catIdx * 100}%)` }">
        <div
          v-for="cat in categories"
          :key="cat.name"
          class="cat-card"
          :style="{ backgroundImage: cat.bg_image ? `url(${cat.bg_image})` : `linear-gradient(135deg, ${cat.color_from || '#7a9e7e'}, ${cat.color_to || '#5a7d5e'})` }"
          @click="selectCategory(cat)"
        >
          <div class="cat-inner">
            <div class="cat-icon">{{ cat.icon || '🌿' }}</div>
            <div class="cat-name">{{ cat.name }}</div>
            <div v-if="cat.subtitle" class="cat-sub">{{ cat.subtitle }}</div>
          </div>
        </div>
      </div>
      <button class="cat-arrow left" @click="slideCat(-1)">‹</button>
      <button class="cat-arrow right" @click="slideCat(1)">›</button>
    </div>
    <div class="cat-dots" v-if="categories.length > 1 && !selectedCategory">
      <span
        v-for="(cat, i) in categories"
        :key="i"
        class="cat-dot"
        :class="{ active: catIdx === i }"
        @click="catIdx = i"
      ></span>
    </div>
    <!-- Category filter active banner -->
    <div v-if="selectedCategory" class="cat-filter-bar">
      <span>📂 {{ selectedCategory }}</span>
      <button @click="selectedCategory = null; catIdx = 0" class="btn-sm btn-outline">✕ 返回全部</button>
    </div>

    <!-- Search Box -->
    <div class="search-box">
      <input
        class="search-input"
        v-model="searchQuery"
        placeholder="搜索配方名、精油、标签..."
        @input="onSearch"
      />
      <button v-if="searchQuery" class="search-clear-btn" @click="clearSearch">✕</button>
      <button class="search-btn" @click="onSearch">🔍</button>
    </div>

    <!-- Personal Section (logged in) -->
    <div v-if="auth.isLoggedIn" class="personal-section">
      <div class="section-header" @click="showMyRecipes = !showMyRecipes">
        <span>📖 我的配方</span>
        <span class="toggle-icon">{{ showMyRecipes ? '▾' : '▸' }}</span>
      </div>
      <div v-if="showMyRecipes" class="recipe-grid">
        <RecipeCard
          v-for="(r, i) in myRecipesPreview"
          :key="r._id"
          :recipe="r"
          :index="findGlobalIndex(r)"
          @click="openDetail(findGlobalIndex(r))"
          @toggle-fav="handleToggleFav(r)"
        />
        <div v-if="myRecipesPreview.length === 0" class="empty-hint">暂无个人配方</div>
      </div>

      <div class="section-header" @click="showFavorites = !showFavorites">
        <span>⭐ 收藏配方</span>
        <span class="toggle-icon">{{ showFavorites ? '▾' : '▸' }}</span>
      </div>
      <div v-if="showFavorites" class="recipe-grid">
        <RecipeCard
          v-for="(r, i) in favoritesPreview"
          :key="r._id"
          :recipe="r"
          :index="findGlobalIndex(r)"
          @click="openDetail(findGlobalIndex(r))"
          @toggle-fav="handleToggleFav(r)"
        />
        <div v-if="favoritesPreview.length === 0" class="empty-hint">暂无收藏配方</div>
      </div>
    </div>

    <!-- Fuzzy Search Results -->
    <div v-if="searchQuery && fuzzyResults.length" class="search-results-section">
      <div class="section-label">🔍 搜索结果 ({{ fuzzyResults.length }})</div>
      <div class="recipe-grid">
        <RecipeCard
          v-for="(r, i) in fuzzyResults"
          :key="r._id"
          :recipe="r"
          :index="findGlobalIndex(r)"
          @click="openDetail(findGlobalIndex(r))"
          @toggle-fav="handleToggleFav(r)"
        />
      </div>
    </div>

    <!-- Public Recipe Grid -->
    <div v-if="!searchQuery || fuzzyResults.length === 0">
      <div class="section-label">🌿 公共配方库 ({{ filteredRecipes.length }})</div>
      <div class="recipe-grid">
        <RecipeCard
          v-for="(r, i) in filteredRecipes"
          :key="r._id"
          :recipe="r"
          :index="findGlobalIndex(r)"
          @click="openDetail(findGlobalIndex(r))"
          @toggle-fav="handleToggleFav(r)"
        />
        <div v-if="filteredRecipes.length === 0" class="empty-hint">暂无配方</div>
      </div>
    </div>

    <!-- Recipe Detail Overlay -->
    <RecipeDetailOverlay
      v-if="selectedRecipeIndex !== null"
      :recipeIndex="selectedRecipeIndex"
      @close="selectedRecipeIndex = null"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useAuthStore } from '../stores/auth'
import { useOilsStore } from '../stores/oils'
import { useRecipesStore } from '../stores/recipes'
import { useUiStore } from '../stores/ui'
import { api } from '../composables/useApi'
import RecipeCard from '../components/RecipeCard.vue'
import RecipeDetailOverlay from '../components/RecipeDetailOverlay.vue'

const auth = useAuthStore()
const oils = useOilsStore()
const recipeStore = useRecipesStore()
const ui = useUiStore()

const searchQuery = ref('')
const selectedCategory = ref(null)
const categories = ref([])
const selectedRecipeIndex = ref(null)
const showMyRecipes = ref(true)
const showFavorites = ref(true)
const catIdx = ref(0)

onMounted(async () => {
  try {
    const res = await api('/api/categories')
    if (res.ok) {
      categories.value = await res.json()
    }
  } catch {
    // category modules are optional
  }
})

function selectCategory(cat) {
  selectedCategory.value = cat.tag_name || cat.name
}

function slideCat(dir) {
  const len = categories.value.length
  catIdx.value = (catIdx.value + dir + len) % len
}

const filteredRecipes = computed(() => {
  let list = recipeStore.recipes
  if (selectedCategory.value) {
    list = list.filter(r => r.tags && r.tags.includes(selectedCategory.value))
  }
  return list
})

const fuzzyResults = computed(() => {
  if (!searchQuery.value.trim()) return []
  const q = searchQuery.value.trim().toLowerCase()
  return recipeStore.recipes.filter(r => {
    const nameMatch = r.name.toLowerCase().includes(q)
    const oilMatch = r.ingredients.some(ing => ing.oil.toLowerCase().includes(q))
    const tagMatch = r.tags && r.tags.some(t => t.toLowerCase().includes(q))
    return nameMatch || oilMatch || tagMatch
  })
})

const myRecipesPreview = computed(() => {
  if (!auth.isLoggedIn) return []
  return recipeStore.recipes
    .filter(r => r._owner_id === auth.user.id)
    .slice(0, 6)
})

const favoritesPreview = computed(() => {
  if (!auth.isLoggedIn) return []
  return recipeStore.recipes
    .filter(r => recipeStore.isFavorite(r))
    .slice(0, 6)
})

function findGlobalIndex(recipe) {
  return recipeStore.recipes.findIndex(r => r._id === recipe._id)
}

function openDetail(index) {
  if (index >= 0) {
    selectedRecipeIndex.value = index
  }
}

async function handleToggleFav(recipe) {
  if (!auth.isLoggedIn) {
    ui.openLogin()
    return
  }
  await recipeStore.toggleFavorite(recipe._id)
}

function onSearch() {
  // fuzzyResults computed handles the filtering reactively
}

function clearSearch() {
  searchQuery.value = ''
  selectedCategory.value = null
}
</script>

<style scoped>
.recipe-search {
  padding: 0 12px 24px;
}

.cat-wrap {
  position: relative;
  margin: 0 -12px 20px;
  overflow: hidden;
}

.cat-track {
  display: flex;
  transition: transform 0.4s ease;
  will-change: transform;
}

.cat-card {
  flex: 0 0 100%;
  min-height: 200px;
  position: relative;
  overflow: hidden;
  cursor: pointer;
  background-size: cover;
  background-position: center;
}

.cat-card::after {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(135deg, rgba(0,0,0,0.45), rgba(0,0,0,0.25));
}

.cat-inner {
  position: relative;
  z-index: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 36px 24px;
  color: white;
  text-align: center;
}

.cat-icon {
  font-size: 48px;
  margin-bottom: 10px;
  filter: drop-shadow(0 2px 6px rgba(0,0,0,0.3));
}

.cat-name {
  font-family: 'Noto Serif SC', serif;
  font-size: 24px;
  font-weight: 700;
  letter-spacing: 3px;
  text-shadow: 0 2px 8px rgba(0,0,0,0.5);
}

.cat-sub {
  font-size: 13px;
  margin-top: 6px;
  opacity: 0.9;
  letter-spacing: 1px;
}

.cat-arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 2;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: rgba(255,255,255,0.25);
  border: none;
  color: white;
  font-size: 18px;
  cursor: pointer;
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
}
.cat-arrow:hover { background: rgba(255,255,255,0.45); }
.cat-arrow.left { left: 12px; }
.cat-arrow.right { right: 12px; }

.cat-dots {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-bottom: 14px;
}
.cat-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--border, #e0d4c0);
  cursor: pointer;
  transition: all 0.25s;
}
.cat-dot.active {
  background: var(--sage, #7a9e7e);
  width: 22px;
  border-radius: 4px;
}

.cat-filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--sage-mist, #eef4ee);
  border-radius: 10px;
  padding: 10px 16px;
  margin-bottom: 16px;
  font-size: 14px;
  font-weight: 600;
  color: var(--sage-dark, #5a7d5e);
}

.cat-label {
  font-size: 12px;
}

.search-box {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  background: #f8f7f5;
  border-radius: 12px;
  padding: 4px 8px;
  border: 1.5px solid #e5e4e7;
}

.search-input {
  flex: 1;
  border: none;
  background: transparent;
  padding: 10px 8px;
  font-size: 14px;
  outline: none;
  font-family: inherit;
  color: #3e3a44;
}

.search-input::placeholder {
  color: #b0aab5;
}

.search-btn,
.search-clear-btn {
  border: none;
  background: transparent;
  cursor: pointer;
  font-size: 16px;
  padding: 6px 8px;
  border-radius: 8px;
  color: #6b6375;
}

.search-clear-btn:hover,
.search-btn:hover {
  background: #eae8e5;
}

.personal-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  background: #f8f7f5;
  border-radius: 10px;
  cursor: pointer;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: 600;
  color: #3e3a44;
}

.section-header:hover {
  background: #f0eeeb;
}

.toggle-icon {
  font-size: 12px;
  color: #999;
}

.section-label {
  font-size: 14px;
  font-weight: 600;
  color: #3e3a44;
  padding: 8px 4px;
  margin-bottom: 8px;
}

.search-results-section {
  margin-bottom: 20px;
}

.recipe-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.empty-hint {
  grid-column: 1 / -1;
  text-align: center;
  color: #b0aab5;
  font-size: 13px;
  padding: 24px 0;
}

@media (max-width: 600px) {
  .recipe-grid {
    grid-template-columns: 1fr;
  }
}
</style>
