<!-- Search.svelte -->
<script lang="ts">
    import { fly } from 'svelte/transition';
    import { flip } from 'svelte/animate';
    import { onMount } from 'svelte';
    
    let searchQuery = '';
    let showError = false;
    
    type FilterKeys = 'accommodation' | 'activities' | 'localGuides' | 'safetyTips' | 'meetups';
    type Filters = Record<FilterKeys, boolean>;
    const filterKeys: FilterKeys[] = ['accommodation', 'activities', 'localGuides', 'safetyTips', 'meetups'];
    
    let selectedFilters: Filters = {
      accommodation: false,
      activities: false,
      localGuides: false,
      safetyTips: false,
      meetups: false
    };
    
    let recentSearches: string[] = [];
  
    onMount(() => {
      const savedSearches = localStorage.getItem('recentSearches');
      recentSearches = savedSearches ? JSON.parse(savedSearches) : [
        'Local guides in Barcelona',
        'Safe hostels Tokyo',
        'Community meetups Paris'
      ];
    });

    function handleSearch() {
      if (!searchQuery.trim() && !Object.values(selectedFilters).some(v => v)) {
        showError = true;
        return;
      }
      showError = false;
      
      // Save search query to recent searches
      if (searchQuery.trim()) {
        const newSearch = searchQuery.trim();
        if (!recentSearches.includes(newSearch)) {
          recentSearches = [newSearch, ...recentSearches].slice(0, 3);
          localStorage.setItem('recentSearches', JSON.stringify(recentSearches));
        }
      }
      
      console.log('Searching:', searchQuery, selectedFilters);
    }
  
    function clearSearch() {
      searchQuery = '';
      showError = false;
    }
</script>
  
<div class="h-full  p-4 md:p-8">
    <!-- Hero Section -->
    <div class="hero bg-base-100 rounded-box mb-8 p-4 md:p-6" in:fly={{ y: 50, duration: 500 }}>
      <div class="hero-content text-center">
        <div>
          <h1 class="text-3xl md:text-4xl font-bold mb-4">Discover Your Community</h1>
          <p class="text-base md:text-lg opacity-80 max-w-md mx-auto">
            Connect with fellow travelers, find safe spaces, and create serendipitous moments
          </p>
        </div>
      </div>
    </div>
  
    <!-- Search Bar -->
    <div class="form-control mx-10 mb-4 ">
      <div class="input-group flex gap-4">
        <input
          type="text"
          bind:value={searchQuery}
          on:keydown={(e) => e.key === 'Enter' && handleSearch()}
          placeholder="Search for local guides, safe spaces, or community meetups..."
          class="input input-bordered w-full"
          aria-label="Search input"
        />
        {#if searchQuery}
          <button class="btn btn-square" on:click={clearSearch} aria-label="Clear search">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        {/if}
        <button class="btn btn-primary" on:click={handleSearch} aria-label="Search">
          Search
        </button>
      </div>
      {#if showError}
        <div class="text-error text-sm mt-2 text-center">
          Please enter a search term or select at least one filter
        </div>
      {/if}
    </div>
  
    <!-- Filter Tags -->
    <div class="flex flex-wrap gap-2 justify-center mb-6">
      {#each filterKeys as filter}
        <label class="cursor-pointer">
          <input
            type="checkbox"
            class="hidden"
            bind:checked={selectedFilters[filter]}
            aria-label={`Filter by ${filter}`}
          />
          <div
            class="badge badge-lg {selectedFilters[filter] ? 'badge-primary' : 'badge-outline'} p-4"
            role="checkbox"
            aria-checked={selectedFilters[filter]}
          >
            {filter.charAt(0).toUpperCase() + filter.slice(1)}
          </div>
        </label>
      {/each}
    </div>
  
    <!-- Recent Searches -->
    <div class="card bg-base-100 shadow-xl max-w-3xl mx-auto">
      <div class="card-body">
        <h2 class="card-title mb-4">Recent Community Searches</h2>
        <div class="space-y-2">
          {#each recentSearches as search (search)}
            <div
              animate:flip={{ duration: 300 }}
              class="flex items-center justify-between p-3 hover:bg-base-200 active:bg-base-300 rounded-lg cursor-pointer transition-colors"
              on:click={() => {
                searchQuery = search;
                handleSearch();
              }}
            >
              <span>{search}</span>
              <button class="btn btn-ghost btn-sm" aria-label="Apply search">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                </svg>
              </button>
            </div>
          {/each}
        </div>
      </div>
    </div>
</div>

<style>
    :global(.badge) {
      transition: all 0.2s ease-in-out;
    }
    
    :global(.badge:hover) {
      transform: scale(1.05);
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
</style>