"use client"; import { useCallback, useEffect, useState } from "react"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { HABIT_PET_DATA_UPDATED_EVENT } from "@/lib/app-events"; import { getShopState, purchaseShopItem, type ShopItem, } from "@/lib/shop-storage"; function formatItemType(type: string) { return type.charAt(0).toUpperCase() + type.slice(1); } export function ShopContent() { const [coins, setCoins] = useState(null); const [items, setItems] = useState([]); const [ownedItemIds, setOwnedItemIds] = useState([]); const [error, setError] = useState(null); const [purchaseError, setPurchaseError] = useState(null); const [isLoading, setIsLoading] = useState(true); const [pendingItemId, setPendingItemId] = useState(null); const refreshShop = useCallback(async () => { try { setError(null); const state = await getShopState(); setCoins(state.coins); setItems(state.items); setOwnedItemIds(state.ownedItemIds); } catch (refreshError) { setError( refreshError instanceof Error ? refreshError.message : "Could not load the shop.", ); setCoins(0); setItems([]); setOwnedItemIds([]); } finally { setIsLoading(false); } }, []); useEffect(() => { void refreshShop(); window.addEventListener(HABIT_PET_DATA_UPDATED_EVENT, refreshShop); return () => { window.removeEventListener(HABIT_PET_DATA_UPDATED_EVENT, refreshShop); }; }, [refreshShop]); const handlePurchase = async (item: ShopItem) => { if (pendingItemId) { return; } try { setPurchaseError(null); setPendingItemId(item.id); const remainingCoins = await purchaseShopItem(item.id); setCoins(remainingCoins); setOwnedItemIds((current) => current.includes(item.id) ? current : [...current, item.id], ); } catch (purchaseFailure) { setPurchaseError( purchaseFailure instanceof Error ? purchaseFailure.message : "Could not complete purchase.", ); } finally { setPendingItemId(null); } }; return ( <>
Your balance {coins === null ? "..." : `${coins} points`}
{error ?

{error}

: null} {purchaseError ? (

{purchaseError}

) : null} {isLoading ? (

Loading shop items...

) : items.length === 0 ? (

No items in the shop yet. Add rows to the shop_items table in Supabase.

) : (
{items.map((item) => { const isOwned = ownedItemIds.includes(item.id); const canAfford = coins !== null && coins >= item.price; const isPending = pendingItemId === item.id; return (
{item.name} {formatItemType(item.type)}
{item.price} pts
); })}
)} ); }