<template class="m-0 p-0">
  <Layout>
    <FBWProductFilter :category="category" />

    <div class="max-w-screen-xl mx-auto px-4 py-2 dark:bg-gray-200">
      <div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
        <template v-for="product in products" :key="product.id">
          <FBWProductCard
            :product="product"
            :wishlist="wishlist"
            @onToggleWishlist="toggleWishlist"
          />
        </template>
      </div>
    </div>
    <br /><br />
  </Layout>
</template>
  
  <script setup>
    import { ref, onMounted, watch } from 'vue';
    import { useRoute } from 'vue-router'; // Import Vue Router
    import Layout from '../layout/defaultLayout.vue';
    import FBWProductCard from '../components/FBWProductCard.vue';
    import FBWProductFilter from '../components/FBWProductFilter.vue';

    const products = ref([]);
    const wishlist = ref([]);

  const route = useRoute();
  const category = ref(route.params.category || ''); 

  const fetchProducts = async (category) => {
    try {
      const response = await fetch(`/products/${category}.json`); // Adjust URL to use the new naming convention
      const data = await response.json();
      products.value = data;
    } catch (error) {
      console.error('Error fetching products:', error);
    }
  };

    // Watch for changes in category from route params
    watch(() => route.params.category, (newCategory) => {
      category.value = newCategory;
      fetchProducts(category.value);
    }, { immediate: true });

        
    const toggleWishlist = ({productId}) => {
    event.preventDefault(); // Prevent the default link behavior

    // Toggle the heart icon and add/remove from wishlist
    if (wishlist.value.includes(productId)) {
        wishlist.value = wishlist.value.filter(item => item !== productId);
    } else {
        wishlist.value.push(productId);
    }
    };

    onMounted(() => {
      fetchProducts(category.value);
    });
  </script>


  <style>
  .add-to-cart {
    background-color: #f0e8d7; 
    border: 2px solid #cbac71; 
    color: black;
    padding: 0.5rem 1rem; 
    width: 50%; 
    text-align: center; 
    font-weight: bold; 
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem; 
  }

  .add-to-cart:hover {
    background-color: #cbac71; 
  }


  .add-to-cart .fa-shopping-cart {
    color: black;
  }

  .buy-now {
    background-color: #91b1d5; 
    color: white;
    padding: 0.5rem 1rem; 
    width: 50%; 
    text-align: center; 
    font-weight: bold; 
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem; 
  }

  .buy-now:hover {
    background-color: #5780b0; 

  }

  </style>





  