"use client"; import { ProductOption, ProductVariant } from "@/lib/store/types"; import clsx from "clsx"; interface VariantSelectorProps { options: ProductOption[]; variants: ProductVariant[]; selectedVariant: ProductVariant; onVariantChange: (variant: ProductVariant) => void; } export function VariantSelector({ options, variants, selectedVariant, onVariantChange, }: VariantSelectorProps) { const getSelectedOptionValue = (optionName: string) => { return selectedVariant.selectedOptions.find( (option) => option.name === optionName )?.value; }; const getVariantFromSelectedOptions = ( selectedOptions: Record ) => { return variants.find((variant) => variant.selectedOptions.every( (option) => selectedOptions[option.name] === option.value ) ); }; const handleOptionClick = (optionName: string, optionValue: string) => { const selectedOptions = { ...Object.fromEntries( selectedVariant.selectedOptions.map((option) => [ option.name, option.value, ]) ), }; selectedOptions[optionName] = optionValue; const newVariant = getVariantFromSelectedOptions(selectedOptions); if (newVariant) { onVariantChange(newVariant); } }; return (
{options.map((option) => (

{option.name}

{option.values.map((value) => { const isSelected = getSelectedOptionValue(option.name) === value; const variant = getVariantFromSelectedOptions({ ...Object.fromEntries( selectedVariant.selectedOptions.map((opt) => [ opt.name, opt.value, ]) ), [option.name]: value, }); const isAvailable = variant?.availableForSale || false; return ( ); })}
))}
); }