<script setup lang="ts">
import { ref, computed } from 'vue'
import Fuse from 'fuse.js'
import DirectoryCard from './DirectoryCard.vue'
import { type DirectoryItem } from '@/types/directory'
import DirectoryFilter from './DirectoryFilter.vue'

const selectedCategory = ref<string>('all')
const searchQuery = ref('')

const props = defineProps<{
  items: DirectoryItem[]
}>()

// Configure Fuse.js options
const fuseOptions = {
  keys: [
    'name',
    'description',
    'town',
    'address',
    'contact',
    'lightning'
  ],
  threshold: 0.3, // Lower threshold means more strict matching
  ignoreLocation: true,
  shouldSort: true
}

const fuse = new Fuse(props.items, fuseOptions)

const filteredItems = computed(() => {
  let results = props.items

  // Apply search if query exists
  if (searchQuery.value) {
    results = fuse.search(searchQuery.value).map(result => result.item)
  }

  // Apply category filter
  if (selectedCategory.value !== 'all') {
    results = results.filter(item => item.category === selectedCategory.value)
  }

  return results
})
</script>

<template>
  <div class="container mx-auto px-4 py-8">
    <!-- Filters -->
    <div class="mb-8 space-y-4 md:space-y-0 md:flex md:items-center md:justify-between">
      <DirectoryFilter 
        v-model:category="selectedCategory"
        v-model:search="searchQuery"
      />
    </div>

    <!-- Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      <DirectoryCard
        v-for="item in filteredItems"
        :key="item.id"
        :item="item"
      />
    </div>

    <!-- Empty State -->
    <div 
      v-if="filteredItems.length === 0"
      class="text-center py-12"
    >
      <p class="text-lg text-muted-foreground">
        No results found. Try adjusting your filters.
      </p>
    </div>
  </div>
</template>
