"use client"; import React, { useState, useEffect, useRef, useMemo } from "react"; import CatalogPageSpread, { CategoryMeta } from "./CatalogPageSpread"; import { Product } from "../../lib/data/products"; import { ChevronRight, ChevronLeft, Printer, Maximize2, Minimize2, BookOpen, Search, Sparkles, Activity, ShieldCheck, Zap, Baby, X } from "lucide-react"; interface FlipbookCatalogProps { products: Product[]; } // Normalize Persian / Arabic strings for accurate search const normalizeSearchText = (str: string) => { return (str || "") .toLowerCase() .replace(/ي/g, "ی") .replace(/ك/g, "ک") .replace(/[\u200B-\u200D\uFEFF]/g, "") // zero-width spaces .trim(); }; export default function FlipbookCatalog({ products }: FlipbookCatalogProps) { const [currentPage, setCurrentPage] = useState(1); const [searchQuery, setSearchQuery] = useState(""); const [isFullscreen, setIsFullscreen] = useState(false); // 3D Flipping animation state const [isFlipping, setIsFlipping] = useState(false); const [flipDirection, setFlipDirection] = useState<"next" | "prev" | null>(null); const containerRef = useRef(null); // 1. Build Category Metadata with dynamic starting pages const categoryMetaList: CategoryMeta[] = useMemo(() => { let currentStartPage = 3; // Page 1 = Cover, Page 2 = TOC const cats: { id: string; name: string; color: string; lightBg: string; borderBg: string; icon: React.ElementType; tagline: string; filterKey: string }[] = [ { id: "joints", name: "مفاصل، استخوان و اسکلت", color: "#0284C7", lightBg: "bg-sky-50", borderBg: "border-sky-200", icon: Activity, tagline: "بازسازی غضروف، هیدروکسی آپاتیت طبیعی و تراکم استخوان", filterKey: "مفاصل و استخوان" }, { id: "special-care", name: "پوست، مو و بهداشت تخصصی", color: "#0D9488", lightBg: "bg-teal-50", borderBg: "border-teal-200", icon: Sparkles, tagline: "تکنولوژی نقره میکروسیلور، اسیدهای چرب امگا و ترمیم بیولوژیک", filterKey: "مراقبت‌های ویژه (پوست، دندان و چشم)" }, { id: "immune", name: "سیستم ایمنی و گوارش", color: "#16A34A", lightBg: "bg-emerald-50", borderBg: "border-emerald-200", icon: ShieldCheck, tagline: "خمیر آغوز متمرکز (Colostrum) و تقویت فوری ایمونوگلوبولین‌ها", filterKey: "تقویت سیستم ایمنی و گوارش" }, { id: "vitamins", name: "ویتامین‌ها و انرژی‌بخش‌ها", color: "#D97706", lightBg: "bg-amber-50", borderBg: "border-amber-200", icon: Zap, tagline: "تامین عناصر کمیاب، هموگلوبین و توان فیزیکی پت‌ها", filterKey: "ویتامین‌ها و انرژی‌بخش‌ها" }, { id: "nutrition", name: "تغذیه تخصصی و رشد توله‌ها", color: "#8B5CF6", lightBg: "bg-purple-50", borderBg: "border-purple-200", icon: Baby, tagline: "شیرهای جایگزین مادر با پروتئین بالا و فرنی‌های تغذیه تکمیلی", filterKey: "تغذیه تخصصی" } ]; return cats.map(cat => { const count = products.filter(p => p.category === cat.filterKey || (cat.id === "vitamins" && p.category === "تقویت عمومی")).length; const meta: CategoryMeta = { ...cat, startPage: currentStartPage }; currentStartPage += Math.max(count, 1); return meta; }); }, [products]); // 2. Build Full Ordered List of Product Pages const orderedProducts = useMemo(() => { const list: { product: Product; categoryMeta: CategoryMeta; pageNum: number }[] = []; let pageCounter = 3; categoryMetaList.forEach(cat => { const catProds = products.filter(p => p.category === (cat.id === "joints" ? "مفاصل و استخوان" : cat.id === "special-care" ? "مراقبت‌های ویژه (پوست، دندان و چشم)" : cat.id === "immune" ? "تقویت سیستم ایمنی و گوارش" : cat.id === "vitamins" ? (p.category === "ویتامین‌ها و انرژی‌بخش‌ها" || p.category === "تقویت عمومی") : p.category === "تغذیه تخصصی") ); catProds.forEach(prod => { list.push({ product: prod, categoryMeta: cat, pageNum: pageCounter++ }); }); }); return list; }, [products, categoryMetaList]); // Total pages: Cover (1) + TOC (2) + All Products (N) + Back Cover const TOTAL_PAGES = useMemo(() => { const rawTotal = 2 + orderedProducts.length + 1; return rawTotal % 2 === 0 ? rawTotal : rawTotal + 1; }, [orderedProducts.length]); // 3D Page Flip Forward in Persian (Left page turns over to the right!) const handleNext = () => { if (currentPage < TOTAL_PAGES && !isFlipping) { setIsFlipping(true); setFlipDirection("next"); setTimeout(() => { setCurrentPage(prev => { if (prev === 1) return 2; // From cover (1) to spread (2-3) return Math.min(prev + 2, TOTAL_PAGES); }); setIsFlipping(false); setFlipDirection(null); }, 650); } }; // 3D Page Flip Backward in Persian (Right page turns back over to the left!) const handlePrev = () => { if (currentPage > 1 && !isFlipping) { setIsFlipping(true); setFlipDirection("prev"); setTimeout(() => { setCurrentPage(prev => { if (prev <= 3) return 1; // Back to cover return Math.max(prev - 2, 1); }); setIsFlipping(false); setFlipDirection(null); }, 650); } }; // Direct Jump const handleJumpToPage = (pageNum: number) => { if (pageNum >= 1 && pageNum <= TOTAL_PAGES) { if (pageNum === 1) { setCurrentPage(1); } else { setCurrentPage(pageNum % 2 === 0 ? pageNum : pageNum - 1); } } }; // Keyboard navigation (RTL: Left Arrow advances forward, Right Arrow goes back) useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { // Don't trigger if focus is on search input if (document.activeElement?.tagName === "INPUT") return; if (e.key === "ArrowLeft") handleNext(); if (e.key === "ArrowRight") handlePrev(); }; window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); }, [currentPage, isFlipping, TOTAL_PAGES]); // Enhanced Search with multi-field matching & Persian normalization const searchResults = useMemo(() => { const query = normalizeSearchText(searchQuery); if (!query) return []; return orderedProducts.filter(item => { const name = normalizeSearchText(item.product.name); const nameEn = normalizeSearchText(item.product.nameEn || ""); const artNo = normalizeSearchText(item.product.artNo); const tagline = normalizeSearchText(item.product.scientificTagline || ""); const desc = normalizeSearchText(item.product.description || ""); const category = normalizeSearchText(item.product.category || ""); const ingredients = item.product.main_ingredients?.map(normalizeSearchText).join(" ") || ""; const symptoms = item.product.symptoms?.map(normalizeSearchText).join(" ") || ""; return name.includes(query) || nameEn.includes(query) || artNo.includes(query) || tagline.includes(query) || desc.includes(query) || category.includes(query) || ingredients.includes(query) || symptoms.includes(query); }); }, [searchQuery, orderedProducts]); const toggleFullscreen = () => { if (!containerRef.current) return; if (!document.fullscreenElement) { containerRef.current.requestFullscreen().catch(err => console.error(err)); setIsFullscreen(true); } else { document.exitFullscreen().catch(err => console.error(err)); setIsFullscreen(false); } }; const handlePrint = () => { window.print(); }; // Helper to render a specific page number content for on-screen viewing const renderSinglePage = (pageNum: number) => { if (pageNum < 1 || pageNum > TOTAL_PAGES) { return (
); } if (pageNum === 1) { return ; } if (pageNum === 2) { return ( ); } if (pageNum === TOTAL_PAGES) { return ; } // Product pages: pageNum 3 corresponds to index 0 of orderedProducts const productItem = orderedProducts[pageNum - 3]; if (productItem) { return ( ); } return ; }; // Current page numbers on spread const rightPageNum = currentPage === 1 ? 1 : currentPage; const leftPageNum = currentPage === 1 ? 0 : currentPage + 1; // Next spread page numbers (for upcoming pages during forward flip) const nextRightPageNum = currentPage === 1 ? 2 : currentPage + 2; const nextLeftPageNum = currentPage === 1 ? 3 : currentPage + 3; // Prev spread page numbers (for upcoming pages during backward flip) const prevRightPageNum = currentPage <= 3 ? 1 : currentPage - 2; const prevLeftPageNum = currentPage <= 3 ? 0 : currentPage - 1; return (
{/* ========================================================================= */} {/* 1. TOP TOOLBAR (Controls, Search, Print, Fullscreen) - Fixed Height */} {/* ========================================================================= */}
{/* Brand Title Badge */}
CP

کاتالوگ دیجیتال Canina Pharma

شبیه‌ساز ۳D ورق‌زن کتاب دارویی • ۳۰ صفحه اختصاصی A4
{/* Quick Search with Instant Jump & Dropdown */}
setSearchQuery(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && searchResults.length > 0) { handleJumpToPage(searchResults[0].pageNum); setSearchQuery(""); } }} className="w-full bg-slate-950 border border-slate-800 rounded-xl py-1.5 pr-8 pl-7 text-[11px] font-bold text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-amber-400/40" /> {searchQuery && ( )} {/* Search Dropdown Results */} {searchQuery && (
{searchResults.length === 0 ? (
محصولی با عبارت «{searchQuery}» یافت نشد.
) : ( searchResults.map(item => (
{ handleJumpToPage(item.pageNum); setSearchQuery(""); }} className="p-1.5 hover:bg-slate-800 rounded-lg flex items-center justify-between cursor-pointer group transition-colors" >
{item.product.name}
کد: {item.product.artNo} • {item.product.category}
صفحه {item.pageNum}
)) )}
)}
{/* Action Buttons */}
{/* ========================================================================= */} {/* 2. MAIN 3D FLIPBOOK STAGE (Auto-scaled within available height) */} {/* ========================================================================= */}
{/* Navigation Arrow - Previous (Right side in RTL: flips back to earlier pages) */} {/* 3D Book Stage Container */}
{/* Desktop 3D Double Spread Book (Strict A4 Aspect Ratio & Height Bound) */}
{/* Center Spine Depth & Crease */}
{/* LEFT HALF OF SCREEN (Physical Left Page) */}
handleNext()} className="w-1/2 h-full bg-white rounded-l-3xl overflow-hidden relative cursor-pointer group shadow-2xl border-l border-slate-800" style={{ direction: "rtl" }} > {currentPage === 1 ? ( // Inside Front Flyleaf when on Cover
CANINA PHARMA GERMANY EST. 1984
CP

کاتالوگ تخصصی کانینا آلمان

جهت باز کردن کاتالوگ و شروع مطالعه، روی صفحه چپ یا کلید ← کیبورد را بزنید.

Official Veterinary Guide 2026
) : isFlipping && flipDirection === "next" ? ( // Underneath left page during next flip (shows upcoming left page) renderSinglePage(nextLeftPageNum) ) : ( renderSinglePage(leftPageNum) )} {/* Dynamic Spine Curvature Shadow */}
{/* Corner Curl Hover Hint */}
{/* RIGHT HALF OF SCREEN (Physical Right Page) */}
handlePrev()} className="w-1/2 h-full bg-white rounded-r-3xl overflow-hidden relative cursor-pointer group shadow-2xl border-r border-slate-800" style={{ direction: "rtl" }} > {isFlipping && flipDirection === "prev" ? ( // Underneath right page during prev flip renderSinglePage(prevRightPageNum) ) : ( renderSinglePage(rightPageNum) )} {/* Dynamic Spine Curvature Shadow */}
{/* Corner Curl Hover Hint */}
{/* 3D FLIPPING LEAF (NEXT / FORWARD: LEFT PAGE FLIPS OVER THE SPINE TO THE RIGHT!) */} {isFlipping && flipDirection === "next" && (
{/* Front Face (Current Left Page turning to the right) */}
{currentPage === 1 ? (
CANINA PHARMA
Canina Germany
2026
) : ( renderSinglePage(leftPageNum) )} {/* Dynamic Light Shadow during rotation */}
{/* Back Face (Upcoming Right Page landing on the right) */}
{renderSinglePage(nextRightPageNum)} {/* Dynamic Light Shadow during landing */}
)} {/* 3D FLIPPING LEAF (PREV / BACKWARD: RIGHT PAGE FLIPS OVER THE SPINE TO THE LEFT!) */} {isFlipping && flipDirection === "prev" && (
{/* Front Face (Current Right Page turning back to the left) */}
{renderSinglePage(rightPageNum)}
{/* Back Face (Previous Left Page landing on the left) */}
{renderSinglePage(prevLeftPageNum === 0 ? 1 : prevLeftPageNum)}
)}
{/* Mobile Single Page View with 3D Flip */}
handleNext()} className="w-full h-full" > {renderSinglePage(currentPage)}
{/* Navigation Arrow - Next (Left side in RTL: flips forward) */}
{/* ========================================================================= */} {/* 3. BOTTOM SLIDER & CATEGORY JUMP BAR - Fixed Height */} {/* ========================================================================= */}
{/* Page Slider */}
{currentPage === 1 ? "جلد ۱" : `صفحه ${currentPage}-${Math.min(currentPage + 1, TOTAL_PAGES)}`} handleJumpToPage(parseInt(e.target.value))} className="w-full h-1.5 bg-slate-800 rounded-lg appearance-none cursor-pointer accent-amber-400" /> /{TOTAL_PAGES}
{/* Category Jump Pills */}
{categoryMetaList.map((cat) => ( ))}
{/* ========================================================================= */} {/* 4. COMPLETE PRINT-ONLY A4 MULTI-PAGE DOCUMENT (Export ALL products to PDF) */} {/* ========================================================================= */}
{/* Page 1: Cover */}
{/* Page 2: Table of Contents */}
{/* Pages 3 to N: All Dedicated Product Pages in Order */} {orderedProducts.map((item) => (
))} {/* Final Page: Back Cover */}
{/* 3D Keyframe CSS Animations & Print Stylesheet */}
); }