'use client'; import { useRouter } from 'next/navigation'; type PantryItem = { id: number; product: { id: number; name: string; canonicalName: string | null; category: string | null }; }; type Props = { items: PantryItem[]; onDeleted?: () => void; }; export default function PantryList({ items, onDeleted }: Props) { const router = useRouter(); async function handleRemove(id: number, name: string) { if (!confirm(`Ta bort "${name}" från baslagret?`)) return; const res = await fetch(`/api/admin/pantry-item/${id}`, { method: 'DELETE' }); if (res.ok) { if (onDeleted) onDeleted(); else router.refresh(); } } 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; return (
{displayName}
); })}
))}
); } async function handleRemove(id: number, name: string) { if (!confirm(`Ta bort "${name}" från baslagret?`)) return; const res = await fetch(`/api/admin/pantry-item/${id}`, { method: 'DELETE' }); if (res.ok) { if (onDeleted) onDeleted(); else router.refresh(); } } 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 )}
); })}
))}
); }