ifixkart-storefront/components/ShopMegaMenu.tsx

91 lines
2.4 KiB
TypeScript

'use client';
import React, { useEffect, useState } from 'react';
import {
CmsMegaMenuPanel,
hasCmsMegaGroups,
} from '@/components/CmsMegaMenuPanel';
import type { MegaMenuData } from '@/services/api/storefrontService';
import { storefrontService } from '@/services/api/storefrontService';
import { catalogService, CategoryResponse } from '@/services/api/catalogService';
interface ShopMegaMenuProps {
cms?: MegaMenuData | null;
}
export const ShopMegaMenu: React.FC<ShopMegaMenuProps> = ({ cms }) => {
const [remote, setRemote] = useState<MegaMenuData | null>(cms ?? null);
const [categories, setCategories] = useState<CategoryResponse[]>([]);
useEffect(() => {
if (hasCmsMegaGroups(cms)) {
setRemote(cms ?? null);
return;
}
let cancelled = false;
storefrontService.getMegaMenu().then((menus) => {
if (cancelled) return;
if (hasCmsMegaGroups(menus.shop)) {
setRemote(menus.shop || null);
}
});
catalogService.getCategories().then((res) => {
if (cancelled) return;
if (Array.isArray(res)) {
setCategories(res);
}
});
return () => {
cancelled = true;
};
}, [cms]);
if (hasCmsMegaGroups(remote)) {
return <CmsMegaMenuPanel menu={remote!} />;
}
// Dynamic menu constructed 100% from DB categories
const categoryLinks = categories
.filter((c) => !c.parent_category_id || categories.length <= 8)
.slice(0, 10)
.map((c) => ({
label: c.name,
href: `/shop?category=${encodeURIComponent(c.slug)}`,
}));
const dynamicMenu: MegaMenuData = {
nav_key: 'shop',
groups: [
{
title: 'Shop by Category',
links:
categoryLinks.length > 0
? categoryLinks
: [{ label: 'All Products', href: '/shop' }],
},
{
title: 'Quick Links',
links: [
{ label: 'All Products', href: '/shop' },
{ label: 'Browse Categories', href: '/categories' },
{ label: 'Shopping Cart', href: '/cart' },
{ label: 'Wishlist', href: '/wishlist' },
{ label: 'Compare Products', href: '/compare' },
{ label: 'My Account', href: '/account' },
{ label: 'Checkout', href: '/checkout' },
],
},
],
promo: null,
};
return <CmsMegaMenuPanel menu={dynamicMenu} />;
};
export function isShopNavLabel(label: string): boolean {
const n = label.toLowerCase().trim();
return n === 'shop' || n === 'store';
}