/* eslint-disable @next/next/no-img-element */ "use client"; import { useState, useMemo, useEffect } from "react"; import { motion, AnimatePresence } from "motion/react"; import { ArrowRight, ChevronLeft, ShieldCheck, CheckCircle2, Clock, FlaskConical, Stethoscope, Info, CalendarDays, X, Plus, Minus, Bell, Sparkles, ChevronRight, ChevronDown, Activity, Heart, Zap, Star, ShoppingBag, Thermometer, AlertTriangle, Share2, Phone } from "lucide-react"; const ICON_MAP: Record> = { Sparkles, Activity, ShieldCheck, Heart, Zap, Star }; import { toPersian } from "../lib/utils"; import { Product } from "../lib/data/products"; import { productService } from "../lib/services/productService"; import { SCIENTIFIC_TERMS } from "../lib/data/scientificTerms"; import { useSettingsStore } from "../lib/store/settingsStore"; import { create } from "zustand"; import { useCartStore } from "../lib/store/cartStore"; import { usePetStore } from "../lib/store/usePetStore"; import { toast } from "sonner"; import api from "../lib/services/api"; import { DosageConfig } from "../lib/types"; interface CalculatorState { petType: "young" | "adult"; weight: number; setPetType: (type: "young" | "adult") => void; setWeight: (weight: number) => void; } const useCalculatorStore = create((set) => ({ petType: "young", weight: 10, setPetType: (petType) => set({ petType }), setWeight: (weight) => set({ weight }), })); import Tooltip from "./Tooltip"; import SafeImage from "./SafeImage"; import ProductReviews from "./ProductReviews"; import { useRouter } from 'next/navigation'; export default function ProductPage({ productSlug }: { productSlug: string }) { const router = useRouter(); const [product, setProduct] = useState(null); const [allProducts, setAllProducts] = useState([]); const [isLoading, setIsLoading] = useState(true); const [itemQuantity, setItemQuantity] = useState(1); const [showRefillModal, setShowRefillModal] = useState(false); const [isMounted, setIsMounted] = useState(false); const [dosageConfig, setDosageConfig] = useState(null); useEffect(() => { Promise.resolve().then(() => setIsMounted(true)); }, []); useEffect(() => { productService.getProductBySlug(productSlug) .then(p => { setProduct(p); return productService.getProducts({ limit: 50 }); }) .then(res => { if (res && res.data) setAllProducts(res.data); }) .catch(err => console.error("Error fetching products in ProductPage:", err)) .finally(() => setIsLoading(false)); }, [productSlug]); useEffect(() => { if (product && product.id) { api.get(`/products/${product.id}/dosage-config`) .then(res => { if (res.data) { setDosageConfig(res.data); } }) .catch(err => console.error('[ProductPage] Dosage config fetch error:', err)); } }, [product]); const { pets, getActivePet } = usePetStore(); const activePet = getActivePet(); const { petType, weight, setPetType, setWeight } = useCalculatorStore(); const { addItem } = useCartStore(); const getText = useSettingsStore((state) => state.getText); const isCatalogMode = getText('catalog_mode', 'false') === 'true'; const isCatalogHidePrices = getText('catalog_hide_prices', 'false') === 'true'; const isCatalogDisableCart = getText('catalog_disable_cart', 'false') === 'true'; const isCartDisabled = isCatalogMode || isCatalogDisableCart; const scientificTerms = useSettingsStore(state => state.scientificTerms); const termKeys = useMemo(() => { return Array.from(new Set([ ...Object.keys(scientificTerms), ...Object.keys(SCIENTIFIC_TERMS) ])); }, [scientificTerms]); // Re-hydrate product const fullProduct = useMemo(() => { if (!product) return null; const apiProduct = allProducts.find(p => p.id === product.id) || product; if (!apiProduct) return null; return { ...apiProduct, packageSize: apiProduct.packageSize || 100, }; }, [product, allProducts]); useEffect(() => { if (activePet && activePet.weight > 0) { setWeight(activePet.weight); setPetType(activePet.age <= 1 ? "young" : "adult"); } }, [activePet, setPetType, setWeight]); const calculation = useMemo(() => { if (!fullProduct) return null; let dailyDose = 1; let unit = fullProduct.unit?.includes('ml') ? "میلی‌لیتر" : fullProduct.unit?.includes('g') ? "گرم" : "قرص"; let description = petType === "young" ? "دوز رشد روزانه" : "دوز نگهداری روزانه"; if (dosageConfig) { const baseW = dosageConfig.baseWeightKg || 10; const baseD = dosageConfig.baseDose || 1; const calculated = Math.round((weight / baseW) * baseD); dailyDose = Math.max(1, calculated); if (dosageConfig.maxDailyDose && dosageConfig.maxDailyDose > 0) { dailyDose = Math.min(dailyDose, dosageConfig.maxDailyDose); } if (dosageConfig.unit) { unit = dosageConfig.unit; } if (dosageConfig.instructions) { description = dosageConfig.instructions; } } else if (typeof fullProduct.calculateDosage === 'function') { const result = fullProduct.calculateDosage(weight, petType === "young"); dailyDose = result.quantity; unit = result.unit; description = result.description; } else { const factor = petType === "young" ? 0.2 : 0.1; dailyDose = Math.max(1, Math.round(weight * factor)); } const packageSize = fullProduct.packageSize || 100; const duration = Math.max(1, Math.floor(packageSize / (dailyDose || 1))); return { dailyDose, duration: duration || 0, unit, description }; }, [fullProduct, dosageConfig, petType, weight]); // Suggest quantity inside useEffect to avoid render-phase state update useEffect(() => { const duration = calculation?.duration ?? 0; const suggestedQty = (duration < 30 && duration > 0) ? 2 : 1; Promise.resolve().then(() => setItemQuantity(suggestedQty)); }, [calculation?.duration]); if (isLoading) return (
); if (!product || !fullProduct || !calculation) return
محصول یافت نشد
; return (
{/* Standard Breadcrumb Navigation & Integrated Back Button */}
router.push('/')}>خانه router.push('/shop')}>فروشگاه {product.nameFa || product.name}
{/* Global Single Grid Layout - Aligns Sticky Buy Box at the Top */}
{/* Right/Main Content Column (lg:col-span-8) */}
{/* Above the Fold Grid */}
{/* Right Column: Product Image Frame (md:col-span-5) */}
موجود در انبار
گرید دارویی اختصاصی
{/* Left Column: Product Title & Description (md:col-span-7) */}
استاندارد صنعتی آلمان
کاتالوگ رسمی Canina
{product.specialBadge && (
{product.specialBadge}
)}

{product.nameFa || product.name}

{product.nameEn && (

{product.nameEn}

)}

{isMounted && pets.length > 0 ? ( product.optimisticTemplate?.replace("[PetName]", activePet?.name || "").replace("[OnSet]", product.onSetOfAction || "به زودی") ) : ( product.scientificTagline )}

{fullProduct.shortDescription && (

{fullProduct.shortDescription}

)}
{/* ─── Symptoms / Therapeutic Indications Section ─── */} {fullProduct.symptoms && fullProduct.symptoms.length > 0 && (

علائم و موارد درمانی مرتبط

این محصول برای رفع علائم زیر توسط دامپزشکان توصیه می‌شود:

{fullProduct.symptoms.map((symptom: string, idx: number) => ( {symptom} ))}
)} {/* Key Benefits Section */} {fullProduct.keyBenefits && fullProduct.keyBenefits.length > 0 && (

چرا {fullProduct.name}؟

{fullProduct.keyBenefits.map((benefit, i) => { const Icon = ICON_MAP[benefit.icon] || CheckCircle2; return (

{benefit.title}

{benefit.description}

); })}
)} {/* Comprehensive Product Description Section (Below the fold) */} {fullProduct.description && (

توضیحات و معرفی محصول

{fullProduct.description.split('\n').filter(Boolean).map((para, pIdx) => (

{para.trim()}

))}
)} {/* Smart Dosage Calculator Utility Section / Topical Usage Notice */} {fullProduct.categorySlug === 'special-care' || fullProduct.name.toLowerCase().includes('pfotenpflege') || fullProduct.name.toLowerCase().includes('augenpflege') || fullProduct.unit?.includes('ml Lotion') || fullProduct.unit?.includes('Balsam') || fullProduct.nameFa?.includes('کرم') || fullProduct.nameFa?.includes('قطره تمیزکننده') || fullProduct.nameFa?.includes('اسپری') ? (

نحوه استفاده موضعی و کاربرد

محصولات بهداشتی و بهداشت موضعی نیاز به دوزبندی بر اساس وزن ندارند

ℹ️

راهنمای مصرف موضعی

این محصول یک فرآورده موضعی/بهداشتی است و مقدار مصرف آن به صورت موضعی (روی پوست، چشم یا پنجه) اعمال می‌شود و وابسته به وزن بدن حیوان نمی‌باشد. ماندگاری بسته بسته به میزان و تکرار مصرف روزانه شما متفاوت خواهد بود.

) : (

ماشین حساب هوشمند مصرف

تخمین دقیق دوز روزانه و ماندگاری هر بسته بر اساس مشخصات پت شما

{/* Manual Slider Inputs */}
وزن پت (کیلوگرم) {toPersian(weight)} ک‌گ
setWeight(parseInt(e.target.value))} className="w-full h-2 bg-medical-gray-200 rounded-lg appearance-none cursor-pointer accent-canina-blue [&::-webkit-slider-thumb]:w-6 [&::-webkit-slider-thumb]:h-6 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-canina-blue [&::-webkit-slider-thumb]:appearance-none" />
سن حیوان
{/* Calculation Results Output */}
محاسبه‌گر دوره درمانی (AI Calculator)
پیشنهاد: {toPersian(itemQuantity)} بسته
{toPersian(calculation.duration)} روز
مدت تامین یک بسته
{toPersian(calculation.dailyDose)}
دوز روزانه ({calculation.unit === 'g' ? 'گرم' : calculation.unit})
تخمین هزینه دوره ۳۰ روزه: {toPersian((Math.ceil(30 / (calculation.duration || 30)) * (product.priceValue || 0)).toLocaleString())} تومان

* دوز دقیق بر اساس وزن پت محاسبه شده است؛ برای ماندگاری کامل دوره، خرید تعداد بسته‌های پیشنهادی توصیه می‌شود.

)} {/* Ingredients Section */}

ترکیبات و آنالیز علمی

{/* Ingredients Cards */}

مواد تشکیل‌دهنده برتر

{product.main_ingredients.map((ing, idx) => { const termKey = termKeys.find(key => { const termObj = scientificTerms[key] || SCIENTIFIC_TERMS[key]; const termName = termObj?.term || key; const ingClean = ing.toLowerCase(); const keyClean = key.toLowerCase(); const termNameClean = termName.toLowerCase(); return ingClean.includes(keyClean) || keyClean.includes(ingClean) || ingClean.includes(termNameClean) || termNameClean.includes(ingClean); }); return (
{termKey ? ( router.push(`/wiki?term=${id}`)}> {ing} ) : ing}
); })}
{/* Analysis Cards Grid */} {Object.keys(product.analysis).length > 0 && (
تخمین اتمام بسته (هوش مصنوعی)
{Object.entries(product.analysis).map(([key, value]) => (
{key}
{toPersian(value)}
))}
)}
{/* Feeding / Usage Instructions Section (Dynamic Header based on product category) */}

{product.categorySlug === 'special-care' || product.name.toLowerCase().includes('pfotenpflege') || product.name.toLowerCase().includes('augenpflege') ? 'دستورالعمل و نحوه استفاده موضعی' : 'توصیه غذایی و نحوه مصرف'}

{product.feedingAdvice}

{/* Storage & Precautions Bar */}
شرایط نگهداری کاتالوگ آلمان

{product.storage || "در جای خشک، خنک (زیر ۲۵ درجه سانتی‌گراد) و دور از تابش مستقیم نور خورشید نگهداری شود."}

احتیاط و منع مصرف (Contraindications)

{product.contraindications?.join(" • ") || "دور از دسترس کودکان نگهداری شود. پس از هربار مصرف درب قوطی را محکم ببندید."}

{/* Specialist Note */} {product.specialist && (
{product.specialist.name}
مورد تأیید دامپزشکان

{product.specialist.name}

{product.specialist.title}

"{product.specialist.message}"

)} {/* Specialized Landing Banner */}
toast.info("بزودی: صفحه فرود تخصصی این محصول در حال آماده‌سازی است")} >

مشاهده بررسی تخصصی و نتایج درمانی

گزارش‌های علمی، ویدیوهای آموزشی و تجربیات واقعی دیگر صاحبان پت در لندینگ‌پیج اختصاصی این محصول.

ورود به آزمایشگاه علمی
{/* FAQ Section */} {product.faqs && product.faqs.length > 0 && (

پاسخ به ابهامات شما

{product.faqs.map((faq, i) => (
{faq.question}
{faq.answer}
))}
)} {/* Customer Reviews & Ratings Section */} {product && (
)}
{/* Sticky Sidebar (Clean Buy Box) - Hidden on mobile as mobile floating buy bar is active */}
قیمت نهایی محصول
{isCatalogHidePrices ? "استعلام قیمت" : toPersian(product.price)}
{isCartDisabled ? (
مشاوره و استعلام خرید ({getText('contact_phone', '۰۲۱-۸۸۸۸۴۴۴۴')})

خرید آنلاین در حالت کاتالوگ موقتاً غیرفعال است

) : (
{/* Quantity Selector - 40% Width */}
{toPersian(itemQuantity)}
{/* Add to Cart / Preorder / Stock Notify Button - 60% Width */} {(product as unknown as { isPreorder?: boolean; preorderDeposit?: number }).isPreorder ? ( ) : (product.packageSize || 0) <= 0 ? ( ) : ( )}
)}
ضمانت اصالت محصول (Made in Germany)
آماده ارسال (تحویل حداکثر ۴۸ ساعت)
{/* expected results box */} {product.expectedResults && product.expectedResults.length > 0 && (

تغییرات قابل انتظار

{product.expectedResults.map((res, i) => { const Icon = ICON_MAP[res.icon] || Sparkles; return (
{res.text}
); })}
)}
{/* Smart Cross-sell: Recommended Combinations */} {product.relatedProducts && product.relatedProducts.length > 0 && (
فرمولاسیون ترکیبی هم‌افزا (Synergy Blend)

اثربخشی دوبرابر با ترکیب هوشمند

{product.relatedProducts.map(relId => { const relProduct = allProducts.find(p => p.id === relId); if (!relProduct) return null; return ( router.push(`/shop/${relProduct.id}`)} >

{relProduct.name}

{relProduct.description}

{relProduct.price}
مشاهده محصول مکمل
); })}
)}
{/* Refill Automation Popup */} {showRefillModal && (
setShowRefillModal(false)} className="absolute inset-0 bg-medical-gray-900/60 backdrop-blur-md" />

سیستم یادآوری هوشمند

بر اساس وزن {toPersian(weight)} کیلوگرمی {activePet ? `برای ${activePet.name}` : 'سگ شما'}، این بسته {toPersian(product.packageSize)} تایی دقیقاً {toPersian(calculation.duration)} روز دیگر تمام می‌شود.

آیا مایلید سیستم ۵ روز قبل از اتمام، به شما پیامک یادآوری ارسال کند؟
)} {/* Mobile Floating Sticky Bottom Buy Bar */}
قیمت نهایی {isCatalogHidePrices ? "استعلام قیمت" : toPersian(product.price)}
{isCartDisabled ? ( استعلام و مشاوره ) : ( <>
{toPersian(itemQuantity)}
)}
); }