"use client"; import { motion } from "framer-motion"; import { useTranslations } from "next-intl"; import type { Product } from "@/types/saleor"; import { getProductPrice, formatPrice } from "@/lib/saleor"; interface BundleSelectorProps { baseProduct: Product; bundleProducts: Product[]; selectedVariantId: string | null; onSelectVariant: (variantId: string, quantity: number, price: number) => void; locale: string; } interface BundleOption { product: Product; quantity: number; price: number; pricePerUnit: number; savings: number; isBase: boolean; } export default function BundleSelector({ baseProduct, bundleProducts, selectedVariantId, onSelectVariant, locale, }: BundleSelectorProps) { const t = useTranslations("Bundle"); if (bundleProducts.length === 0) { return null; } const baseVariant = baseProduct.variants?.[0]; const basePrice = baseVariant?.pricing?.price?.gross?.amount || 0; const options: BundleOption[] = []; options.push({ product: baseProduct, quantity: 1, price: basePrice, pricePerUnit: basePrice, savings: 0, isBase: true, }); bundleProducts.forEach((bundle) => { const variant = bundle.variants?.[0]; if (!variant?.pricing?.price?.gross?.amount) return; const price = variant.pricing.price.gross.amount; const quantityMatch = bundle.name.match(/(\d+)x/i); const quantity = quantityMatch ? parseInt(quantityMatch[1], 10) : 1; const pricePerUnit = price / quantity; const savings = (basePrice * quantity) - price; options.push({ product: bundle, quantity, price, pricePerUnit, savings, isBase: false, }); }); options.sort((a, b) => a.quantity - b.quantity); const formatPriceWithLocale = (amount: number, currency: string = "RSD") => { const localeMap: Record = { sr: "sr-RS", en: "en-US", de: "de-DE", fr: "fr-FR", }; const numLocale = localeMap[locale] || "sr-RS"; return new Intl.NumberFormat(numLocale, { style: "currency", currency, minimumFractionDigits: 0, maximumFractionDigits: 0, }).format(amount); }; return (
{t("selectBundle")}
{options.map((option) => { const variantId = option.isBase ? baseVariant?.id : option.product.variants?.[0]?.id; const isSelected = selectedVariantId === variantId; return ( variantId && onSelectVariant(variantId, option.quantity, option.price)} className={`w-full p-4 border-2 transition-all text-left ${ isSelected ? "border-black bg-black text-white" : "border-[#e5e5e5] hover:border-[#999999]" }`} whileHover={{ scale: 1.01 }} whileTap={{ scale: 0.99 }} >
{isSelected && ( )}
{option.isBase ? t("singleUnit") : t("xSet", { count: option.quantity })} {!option.isBase && option.savings > 0 && ( {t("save", { amount: formatPriceWithLocale(option.savings) })} )}
{formatPriceWithLocale(option.price)}
{!option.isBase && (
{formatPriceWithLocale(option.pricePerUnit)} {t("perUnit")}
)}
); })}
); }