'use client'; import { useTransition } from 'react'; import { removePantryItem } from './actions'; type PantryItem = { id: number; product: { id: number; name: string; canonicalName: string | null; category: string | null }; }; type InventoryItem = { productId: number; quantity: string; unit: string; }; type Props = { items: PantryItem[]; inventoryByProductId: Record; }; export default function PantryList({ items, inventoryByProductId }: Props) { const [isPending, startTransition] = useTransition(); function handleRemove(id: number, name: string) { if (!confirm(`Ta bort "${name}" från baslagret?`)) return; startTransition(async () => { await removePantryItem(id); }); } if (items.length === 0) { return (

Baslagret är tomt. Lägg till produkter ovan.

); } // Gruppera per kategori const grouped = items.reduce>((acc, item) => { const cat = item.product.category || 'Övrigt'; if (!acc[cat]) acc[cat] = []; acc[cat].push(item); return acc; }, {}); const sortedCategories = Object.keys(grouped).sort((a, b) => { if (a === 'Övrigt') return 1; if (b === 'Övrigt') return -1; return a.localeCompare(b, 'sv'); }); return (
{sortedCategories.map((category) => (

{category}

{grouped[category].map((item) => { const displayName = item.product.canonicalName || item.product.name; const invItems = inventoryByProductId[item.product.id] || []; const hasInventory = invItems.length > 0; // Summera per enhet för visning const unitSummary = invItems.reduce>((acc, inv) => { const u = inv.unit || '?'; acc[u] = (acc[u] || 0) + parseFloat(inv.quantity || '0'); return acc; }, {}); const inventoryText = Object.entries(unitSummary) .map(([u, q]) => `${q % 1 === 0 ? q : q.toFixed(1)} ${u}`) .join(', '); return (
{hasInventory ? '✓' : '○'} {displayName} {hasInventory ? ( {inventoryText} ) : ( Saknas i inventariet )}
); })}
))}
); }