'use client'; import { useState, useEffect, useCallback } from 'react'; import type { Product } from '../../../../features/inventory/types'; import AddToPantryForm from '../../../baslager/AddToPantryForm'; import PantryList from '../../../baslager/PantryList'; import { useAuthFetch } from '../../../../lib/use-auth-fetch'; type PantryItem = { id: number; productId: number; createdAt: string; updatedAt: string; product: Product; }; type InventoryItem = { productId: number; quantity: string; unit: string; }; export default function PantryView() { const [pantryItems, setPantryItems] = useState([]); const [products, setProducts] = useState([]); const [inventoryByProductId, setInventoryByProductId] = useState>({}); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const authFetch = useAuthFetch(); const load = useCallback(async () => { setLoading(true); setError(null); try { const [pantryRes, prodRes, invRes] = await Promise.all([ authFetch('/api/pantry'), fetch('/api/products'), authFetch('/api/inventory').catch(() => null), ]); if (!pantryRes.ok) throw new Error('Kunde inte hämta baslager'); if (!prodRes.ok) throw new Error('Kunde inte hämta produkter'); const [pantry, prods] = await Promise.all([pantryRes.json(), prodRes.json()]); const inv: InventoryItem[] = invRes?.ok ? await invRes.json() : []; setPantryItems(pantry); setProducts(prods); const byProd = inv.reduce>((acc, item) => { if (!acc[item.productId]) acc[item.productId] = []; acc[item.productId].push(item); return acc; }, {}); setInventoryByProductId(byProd); } catch (e) { setError(e instanceof Error ? e.message : 'Okänt fel'); } finally { setLoading(false); } }, [authFetch]); useEffect(() => { load(); }, [load]); if (loading) return

Laddar baslager…

; if (error) return

{error}

; const pantryProductIds = new Set(pantryItems.map((i) => i.productId)); return (

Produkter du alltid räknar med att ha hemma. Lägg till och ta bort varor i ditt baslager.

Lägg till produkt

{pantryItems.length} {pantryItems.length === 1 ? 'produkt' : 'produkter'} i baslagret

); }