"use client"; import React, { useState, useRef, useEffect } from "react"; import { Search, ChevronDown, Menu, X, Pill, ShieldCheck, HeartPulse, Sparkles, ShoppingBag, User, Check, Building2, LogIn, LogOut, FileHeart, Dog, BookOpen, FileText, Video, Award, PhoneCall, Activity } from "lucide-react"; import { motion, AnimatePresence } from "motion/react"; import Link from "next/link"; import { useCartStore } from "../lib/store/cartStore"; import { usePetStore } from "../lib/store/usePetStore"; import { useUserStore } from "../lib/store/userStore"; import { useSettingsStore } from "../lib/store/settingsStore"; import { toast } from "sonner"; import AuthModal from "./AuthModal"; import PrescriptionUploadModal from "./PrescriptionUploadModal"; import TickerBanner from "./TickerBanner"; import BrandLogo from "./BrandLogo"; import { cn } from "../lib/utils"; import { productService } from "../lib/services/productService"; const MENU_ICONS: Record = { joints: , immune: , energy: , "special-care": , }; import { NavigationTarget } from "../lib/types"; export default function Header({ onCartOpen = () => {}, onSearch = () => {}, onB2BOpen = () => {} }: { onNavigate?: (v: NavigationTarget) => void; onShopNavigate?: (c?: string, s?: string) => void; currentView?: string; onCartOpen?: () => void; onSearch?: (q: string) => void; onB2BOpen?: () => void; }) { const [isMegaMenuOpen, setIsMegaMenuOpen] = useState(false); const [activeDropdown, setActiveDropdown] = useState(null); const [isAuthModalOpen, setIsAuthModalOpen] = useState(false); const [isPrescriptionModalOpen, setIsPrescriptionModalOpen] = useState(false); const [isProfileMenuOpen, setIsProfileMenuOpen] = useState(false); const userProfileRef = useRef(null); const [searchQuery, setSearchQuery] = useState(""); const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); const isB2BEnabled = useSettingsStore((s) => s.getBoolean('b2bRegistrationOpen', true) && s.getBoolean('b2b_enabled', true)); const [menuItems, setMenuItems] = useState<{ id: string; title: string; icon: React.ReactNode; solutions: string[]; }[]>([ { id: "joints", title: "مفاصل و استخوان", icon: MENU_ICONS["joints"], solutions: ["لنگیدن", "سختی در بلند شدن", "درد مفاصل", "رشد سریع توله‌سگ", "پاهای پرانتزی", "ضعف تاندون"] }, { id: "immune", title: "تقویت سیستم ایمنی و گوارش", icon: MENU_ICONS["immune"], solutions: ["ضعف بعد از بیماری", "بی‌اشتهایی", "بعد از زایمان", "اسهال", "مشکلات گوارشی"] }, { id: "energy", title: "ویتامین‌ها و انرژی‌بخش‌ها", icon: MENU_ICONS["energy"], solutions: ["نفس‌نفس زدن", "خستگی", "سن بالا", "بی‌حالی"] }, { id: "special-care", title: "مراقبت‌های ویژه (پوست، دندان و چشم)", icon: MENU_ICONS["special-care"], solutions: ["ریزش مو", "خشکی پوست", "خارش", "جرم دندان", "سوزش چشم"] } ]); interface HeaderMenuItem { id: string; label: string; href: string; icon?: string | null; badge?: string | null; children?: { id: string; label: string; href: string; icon?: string | null }[]; } const [headerNavItems, setHeaderNavItems] = useState([ { id: 'symptoms', label: 'راهکارهای درمانی', href: '/shop?view=symptoms', icon: 'Pill', }, { id: 'products', label: 'محصولات تخصصی', href: '/shop', icon: 'ShoppingBag', children: [ { id: 'shop-all', label: 'فروشگاه تخصصی محصولات کنینا', href: '/shop' }, { id: 'catalog', label: 'کاتالوگ دیجیتال و راهنمای بالینی', href: '/catalog' }, ], }, { id: 'science', label: 'دانشنامه علمی', href: '/wiki', icon: 'BookOpen', children: [ { id: 'wiki', label: 'دانشنامه علمی ترکیبات', href: '/wiki' }, { id: 'blog', label: 'مجله سلامت پت (وبلاگ)', href: '/blog' }, ], }, { id: 'blog-mag', label: 'مجله سلامت پت', href: '/blog', icon: 'FileText', }, { id: 'pets', label: 'شناسنامه پت‌ها', href: '/dashboard/pets', icon: 'Dog', }, { id: 'videos', label: 'ویدیوها', href: '/videos', icon: 'Video', }, ]); const [isMounted, setIsMounted] = useState(false); useEffect(() => { Promise.resolve().then(() => setIsMounted(true)); }, []); const { getTotalItems } = useCartStore(); const { pets, activePetId, setActivePet } = usePetStore(); const { isLoggedIn, logout, profile } = useUserStore(); const getText = useSettingsStore(state => state.getText); const isCatalogMode = getText('catalog_mode', 'false') === 'true'; const isCatalogDisableCart = getText('catalog_disable_cart', 'false') === 'true'; const isCartDisabled = isCatalogMode || isCatalogDisableCart; useEffect(() => { const loadDynamicNav = async () => { try { const [filtersRes, menuRes] = await Promise.allSettled([ productService.getNavigationFilters(), fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/menu/type/HEADER`).then((r) => r.json()), ]); if (filtersRes.status === 'fulfilled' && filtersRes.value && filtersRes.value.length > 0) { setMenuItems( filtersRes.value.map((item) => ({ id: item.slug, title: item.name, icon: MENU_ICONS[item.slug] || , solutions: item.symptoms || [], })) ); } if (menuRes.status === 'fulfilled' && Array.isArray(menuRes.value) && menuRes.value.length > 0) { setHeaderNavItems(menuRes.value); } } catch (err) { console.error('Failed to load navigation data:', err); } }; loadDynamicNav(); }, []); useEffect(() => { function handleClickOutside(event: MouseEvent) { if (userProfileRef.current && !userProfileRef.current.contains(event.target as Node)) { setIsProfileMenuOpen(false); } } document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, []); const handleSearch = (e: React.FormEvent) => { e.preventDefault(); if (searchQuery.trim()) { onSearch(searchQuery); } }; return ( <> setIsAuthModalOpen(false)} /> setIsPrescriptionModalOpen(false)} />
{/* Sliding Announcement Ticker Banner */}
{/* TOP ROW: Logo + Search + Primary Actions */}
{/* Mobile Menu Toggle & Logo */}
{/* Center Search Input (Desktop) */}
setSearchQuery(e.target.value)} className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl py-2.5 pr-10 pl-4 text-xs font-bold text-medical-gray-900 focus:outline-none focus:ring-2 focus:ring-canina-blue/20 focus:bg-white transition-all" />
{/* Left Action Buttons */}
{/* Prescription Upload Button (Desktop & Mobile) */} {/* User Account Button with Dropdown & Pets List */} {isLoggedIn ? (
{isProfileMenuOpen && ( {/* User info header */}

{profile.firstName ? `${profile.firstName} ${profile.lastName || ''}` : 'کاربر عزیز'}

{profile.mobile || profile.email}

{/* Pets List Section */}
پت‌های من ({pets.length}) setIsProfileMenuOpen(false)} className="text-canina-blue hover:underline text-[10px]"> مدیریت
{pets.length > 0 ? (
{pets.map((p) => ( ))}
) : (

پتی ثبت نشده است

)}
{/* Direct Navigation Links */} setIsProfileMenuOpen(false)} className="flex items-center gap-2 px-3 py-2 hover:bg-medical-gray-50 text-medical-gray-700 rounded-xl font-bold transition-colors" > داشبورد کاربری )}
) : ( )} {/* Shopping Cart Button */} {!isCartDisabled && ( )}
{/* BOTTOM ROW: Clean Organized Dropdown Navigation Bar (Desktop) */}
{headerNavItems.map((navItem) => { const hasChildren = Array.isArray(navItem.children) && navItem.children.length > 0; const isMega = navItem.href?.includes('view=symptoms') || navItem.id === 'category-mega' || navItem.id === 'symptoms'; if (isMega) { return (
setIsMegaMenuOpen(true)} onMouseLeave={() => setIsMegaMenuOpen(false)} > {navItem.label} {isMegaMenuOpen && ( {menuItems.map((item, idx) => (
setIsMegaMenuOpen(false)} className="flex items-center gap-3 mb-3 cursor-pointer" >
{item.icon}

{item.title}

{item.solutions.slice(0, 6).map((sol, sIdx) => ( setIsMegaMenuOpen(false)} > {sol} ))}
))}
)}
); } if (hasChildren) { return (
setActiveDropdown(navItem.id)} onMouseLeave={() => setActiveDropdown(null)} > {navItem.label} {activeDropdown === navItem.id && (
{navItem.children!.map((child) => ( {child.label} ))}
)}
); } return ( {navItem.label} {navItem.badge && ( {navItem.badge} )} ); })}
{/* Mobile Navigation Drawer & Backdrop */} {isMobileMenuOpen && ( <> setIsMobileMenuOpen(false)} className="lg:hidden fixed inset-0 bg-black/50 z-40 backdrop-blur-xs" />
setSearchQuery(e.target.value)} className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-2.5 pr-10 pl-4 text-xs font-bold focus:ring-2 focus:ring-canina-blue/20 outline-none font-vazir placeholder:font-vazir" /> {/* Direct Prescription CTA in Mobile Drawer */} {/* Dynamic Menu Groups in Mobile Drawer */} {headerNavItems.map((navGroup) => { const hasChildren = Array.isArray(navGroup.children) && navGroup.children.length > 0; const isMega = navGroup.href?.includes('view=symptoms') || navGroup.id === 'category-mega' || navGroup.id === 'symptoms'; if (isMega) { return (
{navGroup.label}
{menuItems.map((item, idx) => ( setIsMobileMenuOpen(false)} className="flex items-center gap-2 p-2.5 rounded-xl border border-medical-gray-100 bg-white hover:border-canina-blue/30 text-medical-gray-800 text-[11px] font-bold" > {item.icon} {item.title} ))}
); } if (hasChildren) { return (
{navGroup.label}
{navGroup.children!.map((child) => ( setIsMobileMenuOpen(false)} className="flex items-center gap-3 p-2.5 rounded-xl hover:bg-medical-gray-50 text-medical-gray-800 font-bold text-xs transition-all" > {child.label} ))}
); } return (
setIsMobileMenuOpen(false)} className="flex items-center justify-between p-3 rounded-xl bg-medical-gray-50/70 hover:bg-canina-blue/10 hover:text-canina-blue text-medical-gray-900 font-black text-xs transition-all" > {navGroup.label} {navGroup.badge && ( {navGroup.badge} )}
); })} {/* Additional Company & Support links if needed */}
پشتیبانی و اطلاعات
setIsMobileMenuOpen(false)} className="flex items-center gap-3 p-2.5 rounded-xl hover:bg-medical-gray-50 text-emerald-600 font-bold text-xs transition-all" > نمادهای اعتماد و مجوزهای رسمی {isB2BEnabled && ( setIsMobileMenuOpen(false)} className="flex items-center gap-3 p-2.5 rounded-xl hover:bg-medical-gray-50 text-medical-gray-800 font-bold text-xs transition-all" > درخواست نمایندگی و خرید عمده (B2B) )} setIsMobileMenuOpen(false)} className="flex items-center gap-3 p-2.5 rounded-xl hover:bg-medical-gray-50 text-medical-gray-800 font-bold text-xs transition-all" > تماس با مرکز پشتیبانی
)}
); }