import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import type { MegaMenuPayload, MenuColumn, MenuLink } from '../store/menuStore'; import { X, ChevronRight, ChevronLeft, Globe } from 'lucide-react'; import { useAuthStore } from '../store/authStore'; import { loginLiff, logoutLiff } from '../lib/liff'; import { useTranslation } from 'react-i18next'; interface MobileDrawerProps { isOpen: boolean; onClose: () => void; items: MegaMenuPayload[]; onOpenLang: () => void; } const getLocalizedText = (textObj: Record | string | undefined, lang: string) => { if (typeof textObj === 'string') return textObj; if (!textObj) return ''; return textObj[lang] || textObj['en'] || Object.values(textObj)[0] || ''; }; type MenuNode = | { type: 'root'; data: MegaMenuPayload[]; title: string | Record } | { type: 'mega'; data: MenuColumn[]; title: string | Record } | { type: 'links'; data: MenuLink[]; title: string | Record }; export function MobileDrawer({ isOpen, onClose, items, onOpenLang }: MobileDrawerProps) { const { customer } = useAuthStore(); const navigate = useNavigate(); const { i18n } = useTranslation(); const lang = i18n.language ? i18n.language.substring(0, 2) : 'en'; const [stack, setStack] = useState([{ type: 'root', data: items, title: 'Menu' }]); useEffect(() => { if (!isOpen) { setTimeout(() => { setStack([{ type: 'root', data: items, title: 'Menu' }]); }, 300); } else { if (stack.length === 1 && stack[0].data !== items) { setStack([{ type: 'root', data: items, title: 'Menu' }]); } } }, [isOpen, items]); const handleLinkClick = (url: string) => { navigate(url); onClose(); }; const pushView = (node: MenuNode) => { setStack((prev) => [...prev, node]); }; const popView = () => { setStack((prev) => (prev.length > 1 ? prev.slice(0, -1) : prev)); }; const renderView = (view: MenuNode) => { if (view.type === 'root') { return (
{view.data.map((item, index) => (
{item.columns && item.columns.length > 0 ? ( ) : ( )}
))} {customer && (
)}
); } if (view.type === 'mega') { return (
{view.data.map((col, idx) => (

{getLocalizedText(col.title, lang)}

{col.links.map((link, lIdx) => (
{link.links && link.links.length > 0 ? ( ) : ( )}
))}
))}
); } if (view.type === 'links') { return (
{view.data.map((link, lIdx) => (
{link.links && link.links.length > 0 ? ( ) : ( )}
))}
); } return null; }; return (
{/* Static Top Header */}
Menu
{/* Sliding Views Container */}
{stack.map((view, index) => { const isCurrent = index === stack.length - 1; const isPast = index < stack.length - 1; return (
{/* Back Button for nested views */} {index > 0 && ( )} {/* Optional View Title Header for nested views to emphasize context */} {index > 0 && (

{getLocalizedText(view.title, lang)}

)} {/* View Content */}
{renderView(view)}
); })}
{/* Static Bottom Footer */}
{customer ? ( ) : ( )}
); }