'use client'
// contexts/FilterContext.js
import React, { createContext, useContext, useState } from 'react';

// Create the context
const FilterContext = createContext();

// Create a provider component
export const FilterProvider = ({ children }) => {
  const [filters, setFilters] = useState({
    search: '',
    size: [],
    brand: [],
    label: [],
    min_price: null, // Initialize as null or default value
    max_price: null, // Initialize as null or default value
  });

  // Toggle functions to update filter state
  const toggleSize = (sizeKey) => {
    setFilters((prev) => ({
      ...prev,
      size: prev.size.includes(sizeKey)
        ? prev.size.filter((key) => key !== sizeKey)
        : [...prev.size, sizeKey],
    }));
  };

  const toggleBrand = (brandId) => {
    setFilters((prev) => ({
      ...prev,
      brand: prev.brand.includes(brandId)
        ? prev.brand.filter((id) => id !== brandId)
        : [...prev.brand, brandId],
    }));
  };

  const toggleLabel = (labelId) => {
    setFilters((prev) => ({
      ...prev,
      label: prev.label.includes(labelId)
        ? prev.label.filter((id) => id !== labelId)
        : [...prev.label, labelId],
    }));
  };

  // Adjusted function to set min and max price separately
  const setPriceRange = (minPrice, maxPrice) => {
    setFilters((prev) => ({
      ...prev,
      min_price: minPrice,
      max_price: maxPrice,
    }));
  };

  const setSearch = (searchText) => {
    setFilters((prev) => ({
      ...prev,
      search: searchText,
    }));
  };

  return (
    <FilterContext.Provider
      value={{
        filters,
        toggleSize,
        toggleBrand,
        toggleLabel,
        setPriceRange,
        setSearch,
      }}
    >
      {children}
    </FilterContext.Provider>
  );
};

// Custom hook for easy context access
export const useFilter = () => useContext(FilterContext);
