'use client'; import { Button } from '@/components/ui/Button'; import { Heading } from '@/components/ui/Typography'; import { useTranslation } from '@/lib/hooks/useTranslation'; import { useAppDispatch } from '@/lib/redux/hooks'; import { loadBoxForEditing } from '@/lib/redux/slices/boxSlice'; import Price from 'components/price'; import { CartItem } from 'lib/shopify/types'; import { ChevronDown, ChevronUp, Pencil, Trash2 } from 'lucide-react'; import Image from 'next/image'; import { useRouter } from 'next/navigation'; import { useState } from 'react'; import { CartProductItem } from './CartProductItem'; import { getUniqueItemKey } from './processCartItems'; interface CartBoxItemProps { boxItem: CartItem; boxProducts: CartItem[]; onUpdate: (merchandiseId: string, updateType: 'plus' | 'minus' | 'delete', itemId?: string) => void; isPending: boolean; } export function CartBoxItem({ boxItem, boxProducts, onUpdate, isPending }: CartBoxItemProps) { const { t } = useTranslation(); const [isExpanded, setIsExpanded] = useState(true); const router = useRouter(); const dispatch = useAppDispatch(); // Get box attributes if any const boxGroupId = boxItem.attributes?.find(attr => attr.key === '_box_group_id')?.value || 'box'; // Handle box deletion - delete box and all products inside it const handleBoxDelete = () => { // First update localStorage to reflect the box deletion try { const boxStateString = localStorage.getItem('lastBoxState'); if (boxStateString) { const boxState = JSON.parse(boxStateString); // Check if this is the box that's currently saved for editing if (boxState.originalBoxGroupId === boxGroupId) { // Remove the box from localStorage localStorage.removeItem('lastBoxState'); } } } catch (error) { console.error('Error updating box state in localStorage on delete', error); } // First delete the box container onUpdate(boxItem.merchandise.id, 'delete', boxItem.id); // Then delete all products inside the box boxProducts.forEach(product => { if (product.id) { onUpdate(product.merchandise.id, 'delete', product.id); } }); }; // Handle box editing const handleEditBox = () => { // Prvo pokušaj direktno spremiti trenutni boxGroupId u lokalno stanje try { const currentBoxState = localStorage.getItem('lastBoxState'); let boxStateObject = currentBoxState ? JSON.parse(currentBoxState) : {}; // Dodaj originalni boxGroupId da kasnije znamo što trebamo obrisati boxStateObject.originalBoxGroupId = boxGroupId; localStorage.setItem('lastBoxState', JSON.stringify(boxStateObject)); } catch (error) { console.error('Failed to save original box group ID', error); } // Attempt to load box state for editing from localStorage dispatch(loadBoxForEditing()); // Redirect to build-box page router.push('/build-box'); }; return (