'use client' import { useState, useEffect } from 'react' import { useParams, useRouter } from 'next/navigation' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { Separator } from '@/components/ui/separator' import { ShoppingCart, Star, Truck, Shield, RefreshCw, ArrowLeft, Leaf, Clock, Award, MapPin, Thermometer, Package, Utensils, Heart, ChevronRight, Plus, Minus, Share2, Bookmark, Eye, TrendingUp, CheckCircle, Info, Zap } from 'lucide-react' import { motion, AnimatePresence } from 'framer-motion' import { toast } from 'sonner' import { cartManager } from '@/lib/cart' import { isFeatureEnabled } from '@/lib/business-config' import Link from 'next/link' import OptimizedImage from '@/components/ui/OptimizedImage' import ReviewsList from '@/components/reviews/ReviewsList' import B2BInquiryForm from '@/components/shop/B2BInquiryForm' import StructuredData, { MultipleStructuredData } from '@/components/StructuredData' import { generateProductJsonLd, generateBreadcrumbJsonLd } from '@/lib/structured-data' interface Product { id: string name: string description: string price: number discount: number images: string[] stock: number sku: string slug: string brand?: string origin?: string weight?: string category: { id: string name: string } } const getDiscountedPrice = (price: number, discount: number) => { return price - (price * discount / 100) } // Helper function to calculate per kg price const getPerKgPrice = (price: number, weight: string | undefined, discount: number = 0) => { if (!weight) return null // Extract numeric value from weight string (e.g., "1kg", "500g", "2.5 kg") const weightMatch = weight.toLowerCase().match(/(\d+(?:\.\d+)?)\s*(kg|g|gram|kilos?)/i) if (!weightMatch) return null const value = parseFloat(weightMatch[1]) const unit = weightMatch[2].toLowerCase() // Convert to kg let weightInKg = value if (unit.startsWith('g')) { weightInKg = value / 1000 } const finalPrice = discount > 0 ? getDiscountedPrice(price, discount) : price return Math.round(finalPrice / weightInKg) } export default function ProductDetailPage() { const params = useParams() const router = useRouter() const [product, setProduct] = useState(null) const [loading, setLoading] = useState(true) const [selectedImage, setSelectedImage] = useState(0) const [quantity, setQuantity] = useState(1) const [addingToCart, setAddingToCart] = useState(false) const [activeTab, setActiveTab] = useState('overview') const [isInquiryFormOpen, setIsInquiryFormOpen] = useState(false) useEffect(() => { if (params.slug && typeof params.slug === 'string') { // Decode the slug in case it's URL encoded const decodedSlug = decodeURIComponent(params.slug) fetchProduct(decodedSlug) } }, [params.slug]) const fetchProduct = async (slug: string) => { try { setLoading(true) const response = await fetch(`/api/products/${slug}`) if (!response.ok) { const errorData = await response.json().catch(() => ({ error: 'Unknown error' })) throw new Error(errorData.error || 'Product not found') } const data = await response.json() setProduct(data) } catch (error) { console.error('Error fetching product:', error) toast.error(error instanceof Error ? error.message : 'Failed to load product') } finally { setLoading(false) } } // Food information helper function const getFoodInfo = (category: string, productName: string) => { const categoryLower = category.toLowerCase() const productLower = productName.toLowerCase() if (categoryLower.includes('rice') || productLower.includes('rice')) { return { nutritionalInfo: [ { label: 'Calories', value: '130 per 100g', icon: '🔥' }, { label: 'Carbohydrates', value: '28g per 100g', icon: '🌾' }, { label: 'Protein', value: '2.7g per 100g', icon: '💪' }, { label: 'Fat', value: '0.3g per 100g', icon: '🫒' }, { label: 'Fiber', value: '0.4g per 100g', icon: '🌿' }, { label: 'Glycemic Index', value: 'Medium (56-69)', icon: '📊' } ], benefits: [ 'Rich in essential carbohydrates for energy', 'Naturally gluten-free grain', 'Contains important minerals like manganese', 'Low in fat and sodium', 'Easy to digest and suitable for all ages' ], cookingInstructions: [ 'Rinse rice thoroughly until water runs clear', 'Use 1:1.5 rice to water ratio for perfect texture', 'Bring to boil, then reduce heat and simmer for 18-20 minutes', 'Let it rest for 5 minutes before opening the lid', 'Fluff gently with a fork for best results' ], storage: 'Store in airtight container in cool, dry place away from direct sunlight. Best consumed within 12-18 months of packaging.', origin: 'Sourced from premium rice fields in Punjab and Haryana, known for their fertile soil and ideal climate conditions.', certification: ['FSSAI Approved', 'Organic Certified', 'Pesticide Free', 'Premium Grade A'] } } else if (categoryLower.includes('flour') || productLower.includes('flour') || productLower.includes('atta')) { return { nutritionalInfo: [ { label: 'Calories', value: '340 per 100g', icon: '🔥' }, { label: 'Carbohydrates', value: '72g per 100g', icon: '🌾' }, { label: 'Protein', value: '12g per 100g', icon: '💪' }, { label: 'Fat', value: '1.7g per 100g', icon: '🫒' }, { label: 'Fiber', value: '11g per 100g', icon: '🌿' }, { label: 'Iron', value: '4.6mg per 100g', icon: '⚡' } ], benefits: [ 'High fiber content supports digestive health', 'Rich in protein for muscle development', 'Contains essential B vitamins', 'Good source of minerals like iron and magnesium', 'Helps maintain stable blood sugar levels' ], cookingInstructions: [ 'Knead with warm water for soft, pliable dough', 'Add a pinch of salt and oil for better texture', 'Rest the dough for 15-20 minutes before rolling', 'Roll evenly for uniform cooking', 'Cook on medium heat for golden, soft rotis' ], storage: 'Store in cool, dry place in airtight containers. Use within 6-8 months for best quality and freshness.', origin: 'Milled from premium wheat grains sourced from the fertile plains of Punjab, Haryana, and Uttar Pradesh.', certification: ['FSSAI Approved', 'Whole Grain', 'Stone Ground', 'Chemical Free'] } } else if (categoryLower.includes('spice') || categoryLower.includes('masala') || productLower.includes('spice')) { return { nutritionalInfo: [ { label: 'Antioxidants', value: 'High', icon: '🛡️' }, { label: 'Vitamins', value: 'A, C, K', icon: '💊' }, { label: 'Minerals', value: 'Iron, Calcium', icon: '⚡' }, { label: 'Calories', value: '10-15 per tsp', icon: '🔥' }, { label: 'Sodium', value: 'Low', icon: '🧂' } ], benefits: [ 'Rich in antioxidants and anti-inflammatory compounds', 'Supports digestive health and metabolism', 'Natural antimicrobial and antibacterial properties', 'Enhances flavor without adding calories', 'May help regulate blood sugar and cholesterol levels' ], cookingInstructions: [ 'Dry roast whole spices for enhanced aroma and flavor', 'Add spices at the right time during cooking', 'Store ground spices in airtight containers', 'Use within 6-12 months for best potency', 'Combine with oil or ghee for better absorption' ], storage: 'Store in cool, dry place away from light and heat. Keep in airtight containers to preserve aroma and potency.', origin: 'Sourced from spice gardens of Kerala, Karnataka, Tamil Nadu, and Kashmir - regions known for their aromatic spices.', certification: ['FSSAI Approved', 'Pure & Natural', 'Chemical Free', 'Hand Picked'] } } else { return { nutritionalInfo: [ { label: 'Quality', value: 'Premium Grade', icon: '⭐' }, { label: 'Freshness', value: 'Farm Fresh', icon: '🌱' }, { label: 'Processing', value: 'Minimal', icon: '🏭' }, { label: 'Shelf Life', value: '12 months', icon: '📅' } ], benefits: [ 'High nutritional value with natural goodness', 'Carefully processed to retain nutrients', 'Free from artificial preservatives', 'Supports healthy lifestyle and balanced diet', 'Trusted quality from Padmaaja Rasooi' ], cookingInstructions: [ 'Follow traditional cooking methods for best results', 'Use fresh ingredients for enhanced taste', 'Store properly after opening to maintain quality', 'Cook as per package instructions', 'Enjoy fresh preparations for optimal nutrition' ], storage: 'Store in cool, dry place away from direct sunlight and moisture. Keep in original packaging or airtight containers.', origin: 'Sourced from trusted farmers and suppliers across India, ensuring authenticity and quality.', certification: ['FSSAI Approved', 'Quality Assured', 'Safe for Consumption', 'Hygienically Processed'] } } } const handleAddToCart = () => { if (!product) return setAddingToCart(true) if (product.stock === 0) { toast.error('Product is out of stock') setAddingToCart(false) return } if (quantity > product.stock) { toast.error('Not enough stock available') setAddingToCart(false) return } try { const success = cartManager.addToCart(product, quantity) if (success) { toast.success(`${product.name} added to cart!`) } else { toast.error('Failed to add to cart') } } catch (error) { console.error('Error adding to cart:', error) toast.error('Failed to add to cart') } finally { setAddingToCart(false) } } const handleShare = async () => { const url = window.location.href const title = `${product?.name} - Padmaaja Rasooi` const text = `Check out this premium ${product?.name} from Padmaaja Rasooi!` if (navigator.share) { try { await navigator.share({ title, text, url, }) toast.success('Shared successfully!') } catch (error) { console.error('Error sharing:', error) // Fallback to copy URL handleCopyUrl() } } else { // Fallback to copy URL handleCopyUrl() } } const handleCopyUrl = async () => { try { await navigator.clipboard.writeText(window.location.href) toast.success('URL copied to clipboard!') } catch (error) { console.error('Error copying URL:', error) toast.error('Failed to copy URL') } } if (loading) { return (
{[1, 2, 3, 4].map((i) => (
))}
) } if (!product) { return (

Product Not Found

The product you're looking for doesn't exist or has been moved.

) } // Generate JSON-LD structured data for SEO const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || (typeof window !== 'undefined' ? window.location.origin : 'https://padmaajarasooi.com') const productJsonLd = generateProductJsonLd(product as any, baseUrl) const breadcrumbJsonLd = generateBreadcrumbJsonLd([ { name: 'Home', url: '/' }, { name: 'Products', url: '/products' }, { name: product.category.name, url: `/products?category=${product.category.id}` }, { name: product.name, url: `/products/${product.slug}` } ], baseUrl) return (
{/* SEO: Product & Breadcrumb Schema - Critical for Google indexing */} {/* Premium Navigation Bar */} {/* Main Product Section */}
{/* Product Gallery */} {/* Main Image */}
{/* Floating Badges */}
{product.discount > 0 && ( -{product.discount}% OFF )} {product.stock < 10 && product.stock > 0 && ( Only {product.stock} left )}
{/* Image Counter */} {product.images.length > 1 && (
{selectedImage + 1} / {product.images.length}
)}
{/* Thumbnail Gallery */} {product.images.length > 1 && (
{product.images.map((image, index) => ( ))}
)}
{/* Product Information */} {/* Header Section */}
{/* Category & Stock Status */}
{product.category.name}
{product.stock > 0 ? (
In Stock
) : (
Out of Stock
)}
{/* Product Name */}

{product.name}

{/* Rating & Reviews */}
{[1, 2, 3, 4, 5].map((star) => ( ))}
4.8 (2,547 reviews)
{/* Description */}

{product.description || `Premium quality ${product.name} sourced directly from trusted suppliers. Experience the authentic taste and exceptional quality that Padmaaja is known for.`}

{/* Pricing Section */}
{/*
{product.discount > 0 ? ( <> ₹{getDiscountedPrice(product.price, product.discount).toFixed(2)} ₹{product.price.toFixed(2)} ) : ( ₹{product.price.toFixed(2)} )}
*/} {/* Per kg price display */} {getPerKgPrice(product.price, product.weight, product.discount) && (
₹{getPerKgPrice(product.price, product.weight, product.discount)}/kg
)} {product.discount > 0 && (
Save ₹{(product.price * product.discount / 100).toFixed(2)} ({product.discount}% off)
)}
{/* Stock Indicator */} {/*
{product.stock} available
*/}
{/* Purchase Section - B2B/B2C Mode */} {product.stock > 0 ? (
{/* B2C Feature - Quantity & Cart (Disabled for B2B mode) */} {isFeatureEnabled('cart') ? ( <> {/* Quantity Selector */}
{quantity}
{product.stock} available
{/* Action Buttons */}
) : ( /* B2B Mode - Quote Request */

Bulk Orders & Wholesale

Get competitive pricing for bulk orders. Contact us for custom quotes and wholesale rates.

Minimum Order: 1+ ton
Delivery: PAN India
{/* B2B Quantity Selector - In Tons */}
{quantity} {quantity === 1 ? 'Ton' : 'Tons'}
= {(quantity * 1000).toLocaleString()} kg

Bulk pricing available for orders above 5 tons. Contact us for volume discounts.

{/* B2B Action Buttons */}
)}
) : (

Out of Stock

This product is currently unavailable

)} {/* Trust Indicators */}

Free Delivery

Orders above ₹500

Quality Assured

Premium products

Fresh & Pure

No additives

{/* Modern Product Information Tabs */} {/* Tab Navigation */}
{/* Tab Content */}
{(() => { const foodInfo = getFoodInfo(product.category.name, product.name) switch (activeTab) { case 'overview': return (

Product Description

{product.description || `Experience the finest quality ${product.name} from Padmaaja. Our products are carefully sourced and processed to maintain their natural goodness and authentic flavor. Perfect for your daily cooking needs with guaranteed freshness and purity.`}

Quality Promise

  • 100% authentic and pure
  • No artificial preservatives
  • Hygienically processed
  • Quality tested

Product Details

SKU

{product.sku}

Category

{product.category.name}

{product.brand && (

Brand

{product.brand}

)} {product.weight && (

Weight

{product.weight}

)} {product.origin && (

Origin

{product.origin}

)}

Shipping Information

  • • Free delivery on orders above ₹500
  • • Standard delivery: 2-4 business days
  • • Express delivery available
  • • Secure packaging guaranteed
) case 'nutrition': return (

Nutritional Information

Discover the nutritional value and health benefits of our premium {product.name.toLowerCase()}.

{foodInfo.nutritionalInfo.map((info, index) => (
{info.icon}

{info.label}

{info.value}

))}
) case 'benefits': return (

Health Benefits

Discover why {product.name.toLowerCase()} is an excellent choice for your health and wellness.

{foodInfo.benefits.map((benefit, index) => (

{benefit}

))}
) case 'instructions': return (
{/* Cooking Instructions */}

Cooking Instructions

{foodInfo.cookingInstructions.map((instruction, index) => (
{index + 1}

{instruction}

))}
{/* Storage Instructions */}

Storage Guidelines

{foodInfo.storage}

Storage Tips

  • Keep away from direct sunlight
  • Store in cool, dry place
  • Use airtight containers
  • Check expiry dates regularly
{/* Origin & Certification */}

Origin & Quality

{foodInfo.origin}

{foodInfo.certification.map((cert, index) => ( {cert} ))}
) case 'specifications': return (

Product Specifications

Detailed specifications and technical information about {product.name.toLowerCase()}.

SKU

{product.sku}

Category

{product.category.name}

{product.weight && (

Weight

{product.weight}

)} {product.brand && (

Brand

{product.brand}

)} {product.origin && (

Origin

{product.origin}

)}

Quality

Premium Grade

) default: return null } })()}
{/* Reviews Section */}

Customer Reviews

See what our customers are saying about {product.name}

{/* B2B Inquiry Form */} {product && ( )}
) }