"use client"; import React, { useEffect, useRef } from "react"; import { useRouter, useSearchParams, usePathname } from "next/navigation"; import PrimaryButton from "./primaryButton"; import Select from "./select"; import { useVehicleData } from "@/hooks/useVehicleData"; import { useYmmStore } from "@/store/useYmmStore"; interface SelectInputProps { onSearch?: (fitment: string) => void; className?: string; AddClearButton?: boolean; } export const SearchByVehicle = ({ onSearch, className, AddClearButton = false, }: SelectInputProps) => { const params = useSearchParams(); const router = useRouter(); const pathname = usePathname(); const isYmmActive = useYmmStore((state) => state.isYmmActive); const previousPairsRef = useRef(null); const isSearchPage = pathname === "/search"; const { rootTypes, selectedRootType, dropdownLevels, handleRootTypeChange, handleValueChange, isComplete, getSelectedPairs, initializeFromPairs, resetInitialization, } = useVehicleData(); const initialPairs = params.get("fitment_pairs"); useEffect(() => { if ( rootTypes.length > 0 && selectedRootType === 0 && dropdownLevels.length === 0 && !initialPairs ) { handleRootTypeChange(rootTypes[0].id); } }, [rootTypes]); useEffect(() => { // Only initialize if we're on the search page AND we have fitment_pairs if (!isSearchPage || !initialPairs) { return; } // Prevent re-initialization if pairs haven't changed if (previousPairsRef.current === initialPairs) { return; } if (rootTypes.length === 0) { return; } previousPairsRef.current = initialPairs; initializeFromPairs(initialPairs); }, [initialPairs, isSearchPage, rootTypes]); // Reset when leaving the search page or pairs are cleared useEffect(() => { return () => { if (isSearchPage) { resetInitialization(); previousPairsRef.current = null; } }; }, [isSearchPage]); const handleSearch = () => { const pairs = getSelectedPairs(); if (onSearch) { onSearch(pairs); } else { router.push(`/search?fitment_pairs=${pairs}`); } }; const handleClear = () => { resetInitialization(); previousPairsRef.current = null; // Only navigate if we're on the search page if (isSearchPage) { router.push(`/search`); } if (rootTypes.length > 0) { setTimeout(() => { handleRootTypeChange(rootTypes[0].id); }, 100); } }; // Check if any filter is selected const hasSelectedFilters = dropdownLevels.some( (level) => level.selectedValue !== "" ); if (!isYmmActive) { return null; } return (

SEARCH BY VEHICLE

{/* Dynamic Dropdown Levels */} {dropdownLevels.length > 0 ? ( dropdownLevels.map((level, index) => { const selectId = `vehicle-${level.typeName.toLowerCase()}-${index}`; return (