'use client'; import { useEffect, useState } from 'react'; import Link from 'next/link'; import { MessageCircle } from 'lucide-react'; import { buildDeliveryInquiryMessage, buildPickupInquiryMessage, } from '@/application/messaging/whatsapp-message-builder'; import type { FulfillmentMode } from '@/domain/cart/inquiry'; import type { DeliveryInquiryDetails, PickupInquiryDetails } from '@/domain/cart/inquiry'; import { calculateLineTotal, formatLineQuantityLabel, } from '@/domain/shared/order-line'; import { RESTAURANT_CONTACT } from '@/domain/shared/constants'; import { container } from '@/infrastructure/di/container'; import { useCart } from '@/presentation/providers/cart-provider'; import { useLanguage } from '@/presentation/providers/language-provider'; import { getTranslation } from '@/presentation/i18n/translations'; import { getMenuItemName } from '@/application/i18n/menu-localization'; import { useMenu } from '@/presentation/providers/menu-provider'; import CartInquiryModal from '@/components/CartInquiryModal'; import { buildCartInquiryCopy, getWhatsAppInquiryLanguage, getWhatsAppInquiryTranslation, } from '@/application/messaging/inquiry-language'; import { useCustomerAuth } from '@/presentation/providers/customer-auth-provider'; const CART_INQUIRY_INTENT_KEY = 'shahi-cart-inquiry-intent'; function GoogleIcon({ className }: { className?: string }) { return ( ); } export default function CartDrawer() { const { items, isOpen, closeCart, openCart, totalPrice, removeFromCart, updateQuantity, clearCart, } = useCart(); const { language, isRtl } = useLanguage(); const { getItemById } = useMenu(); const { email: customerEmail, name: customerName, isAuthenticated, isLoading: isAuthLoading, } = useCustomerAuth(); const t = getTranslation(language); const [inquiryMode, setInquiryMode] = useState(null); const [authGateMode, setAuthGateMode] = useState(null); useEffect(() => { if (isAuthLoading || !isAuthenticated) return; const intent = sessionStorage.getItem(CART_INQUIRY_INTENT_KEY) as FulfillmentMode | null; if (intent !== 'pickup' && intent !== 'delivery') return; sessionStorage.removeItem(CART_INQUIRY_INTENT_KEY); openCart(); setAuthGateMode(null); setInquiryMode(intent); }, [isAuthenticated, isAuthLoading, openCart]); const openWhatsApp = (message: string | null) => { if (!message) return; container.messagingGateway.openWhatsApp(message); setInquiryMode(null); }; const startInquiry = (mode: FulfillmentMode) => { if (isAuthLoading) return; if (!isAuthenticated) { setAuthGateMode(mode); setInquiryMode(null); return; } setAuthGateMode(null); setInquiryMode(mode); }; const handleGoogleSignInForInquiry = () => { if (!authGateMode) return; try { sessionStorage.setItem(CART_INQUIRY_INTENT_KEY, authGateMode); } catch { // Ignore storage errors. } const returnTo = encodeURIComponent(`${window.location.pathname}${window.location.search}`); window.location.href = `/api/auth/google?returnTo=${returnTo}`; }; const handlePickupSubmit = (details: PickupInquiryDetails) => { const inquiryLang = getWhatsAppInquiryLanguage(language); const inquiryCopy = buildCartInquiryCopy(getWhatsAppInquiryTranslation(language)); openWhatsApp(buildPickupInquiryMessage(items, details, inquiryCopy, inquiryLang)); }; const handleDeliverySubmit = (details: DeliveryInquiryDetails) => { const inquiryLang = getWhatsAppInquiryLanguage(language); const inquiryCopy = buildCartInquiryCopy(getWhatsAppInquiryTranslation(language)); openWhatsApp(buildDeliveryInquiryMessage(items, details, inquiryCopy, inquiryLang)); }; if (!isOpen) return null; return ( <> {t.cartDrawer.title} {items.length > 0 && ( {items.length} {items.length === 1 ? t.cartDrawer.item : t.cartDrawer.items} )} {items.length > 0 && ( {t.cartDrawer.clear} )} × {items.length === 0 ? ( 🛒 {t.cartDrawer.empty} {t.cartDrawer.browseMenu} ) : ( {items.map((item) => ( {getMenuItemName(language, { id: item.id, name: getItemById(item.id)?.name ?? item.name, })} {item.pricingMode === 'weight' ? `${item.pricePerHalfKg ?? item.price} kr / ½ kg` : `${item.price} kr × ${item.quantity}`} {calculateLineTotal(item)} kr updateQuantity(item.id, item.quantity - 1)} className="w-11 h-11 flex items-center justify-center border border-[#EDE6D9] rounded hover:bg-white transition touch-manipulation" > − {formatLineQuantityLabel(item)} updateQuantity(item.id, item.quantity + 1)} className="w-11 h-11 flex items-center justify-center border border-[#EDE6D9] rounded hover:bg-white transition touch-manipulation" > + removeFromCart(item.id)} className="ml-auto text-xs text-[#B38B4D] hover:underline" > {t.cartDrawer.remove} ))} )} {items.length > 0 && ( {t.cartDrawer.clearBasket} {t.cartDrawer.total} {totalPrice.toFixed(0)} kr {authGateMode ? ( {t.cartDrawer.signInRequiredTitle} {t.cartDrawer.signInRequiredSubtitle} {t.auth.customer.signInWithGoogle} setAuthGateMode(null)} className="inline-flex min-h-[44px] w-full items-center justify-center text-sm font-medium text-[#6B665F] hover:text-[#101724] active:underline touch-manipulation" > {t.cartDrawer.inquiryCancel} ) : ( <> {t.cartDrawer.inquiryHint} startInquiry('pickup')} disabled={isAuthLoading} className="btn-primary mb-2 flex w-full min-h-[52px] items-center justify-center gap-2 rounded-full py-4 text-base font-medium tracking-[0.5px] touch-manipulation active:scale-[0.985] disabled:opacity-60" > {t.cartDrawer.pickupInquiry} startInquiry('delivery')} disabled={isAuthLoading} className="btn-outline mb-2 flex w-full min-h-[52px] items-center justify-center gap-2 rounded-full border-[#25D366] py-4 text-base font-medium tracking-[0.5px] text-[#128C7E] hover:bg-[#25D366]/10 touch-manipulation active:scale-[0.985] disabled:opacity-60" > {t.cartDrawer.deliveryInquiry} > )} window.open(`tel:${RESTAURANT_CONTACT.phonePrimary}`, '_self')} className="btn-outline w-full py-3 rounded-full text-sm tracking-[0.5px] font-medium mb-3" > {t.cartDrawer.call} {t.cartDrawer.continueBrowsing} )} {inquiryMode && isAuthenticated && ( setInquiryMode(null)} onSubmitPickup={handlePickupSubmit} onSubmitDelivery={handleDeliverySubmit} labels={{ titlePickup: t.cartDrawer.inquiryModalTitlePickup, titleDelivery: t.cartDrawer.inquiryModalTitleDelivery, signedInAs: t.cartDrawer.signedInAs, nameLabel: t.cartDrawer.nameLabel, namePlaceholder: t.cartDrawer.namePlaceholder, emailLabel: t.cartDrawer.emailLabel, emailPlaceholder: t.cartDrawer.emailPlaceholder, emailRequired: t.cartDrawer.emailRequired, branchLabel: t.cartDrawer.branchLabel, branchAskim: t.cartDrawer.branchAskim, branchBackaplan: t.cartDrawer.branchBackaplan, askimOnlineUnavailable: t.cartDrawer.askimOnlineUnavailable, addressLabel: t.cartDrawer.addressLabel, addressPlaceholder: t.cartDrawer.addressPlaceholder, addressHint: (t.cartDrawer as { addressHint?: string }).addressHint ?? 'Only Gothenburg addresses can be selected. Pick one from the suggestions.', addressFallbackPlaceholder: (t.cartDrawer as { addressFallbackPlaceholder?: string }).addressFallbackPlaceholder ?? 'Street, postcode, city…', addressFallbackHint: (t.cartDrawer as { addressFallbackHint?: string }).addressFallbackHint ?? 'Address search is temporarily unavailable. Type your full delivery address manually.', addressSearching: (t.cartDrawer as { addressSearching?: string }).addressSearching ?? 'Searching addresses…', addressNoResults: (t.cartDrawer as { addressNoResults?: string }).addressNoResults ?? 'No matching addresses. Try street name and number.', addressOutsideGothenburg: (t.cartDrawer as { addressOutsideGothenburg?: string }).addressOutsideGothenburg ?? 'This address is outside Gothenburg. We only deliver within the city.', addressSelectSuggestion: (t.cartDrawer as { addressSelectSuggestion?: string }).addressSelectSuggestion ?? 'Please pick an address from the suggestions.', addressInvalid: (t.cartDrawer as { addressInvalid?: string }).addressInvalid ?? 'Select a valid Gothenburg address from the list.', preferredDateLabel: t.cartDrawer.preferredDateLabel, preferredDatePlaceholder: t.cartDrawer.preferredDatePlaceholder, dateToday: t.cartDrawer.dateToday, dateTomorrow: t.cartDrawer.dateTomorrow, preferredTimeLabel: t.cartDrawer.preferredTimeLabel, scheduleOptionalHint: t.cartDrawer.scheduleOptionalHint, submitPickup: t.cartDrawer.submitPickup, submitDelivery: t.cartDrawer.submitDelivery, cancel: t.cartDrawer.inquiryCancel, close: t.cartDrawer.inquiryClose, nameRequired: t.cartDrawer.nameRequired, branchRequired: t.cartDrawer.branchRequired, scheduleIncomplete: t.cartDrawer.scheduleIncomplete, scheduleTooSoon: t.cartDrawer.scheduleTooSoon, }} /> )} > ); }
{t.cartDrawer.empty}
{item.pricingMode === 'weight' ? `${item.pricePerHalfKg ?? item.price} kr / ½ kg` : `${item.price} kr × ${item.quantity}`}
{t.cartDrawer.signInRequiredSubtitle}
{t.cartDrawer.inquiryHint}