import React, { useState, useMemo, useCallback } from 'react'; import { Store, Package, Coins, Sparkles, ShoppingBag, CheckCircle2, AlertCircle, X } from 'lucide-react'; import confetti from 'canvas-confetti'; import { useEconomyStore } from '../../stores/useEconomyStore'; import { STORE_CATALOG, STORE_CATALOG_MAP } from '../../data/storeCatalog'; import type { StoreItem, StoreItemCategory, InventoryItem } from '../../types/storeTypes'; import { playPopupChime, playLevelUpFanfare } from '../../utils/rpgAudio'; import { companionStore } from '../../features/companion/store/useCompanionStore'; import { StoreItemCard } from './StoreItemCard'; import { VaultItemCard } from './VaultItemCard'; import { ItemLoreModal } from './ItemLoreModal'; import { GiftPresentationModal } from './GiftPresentationModal'; import { AURELIA_GIFT_REACTIONS, DEFAULT_GIFT_REACTION, type GiftReactionData } from './giftReactions'; export interface StoreWindowProps { onClose?: () => void; onOpenCompanion?: () => void; } type MainTab = 'storefront' | 'vault'; type FilterCategory = 'all' | StoreItemCategory; interface ToastNotification { id: string; type: 'success' | 'error' | 'info'; message: string; } export const StoreWindow: React.FC = ({ onClose: _onClose, onOpenCompanion }) => { // Store subscriptions const gold = useEconomyStore(s => Math.max(0, s.gold ?? 0)); const lifetimeEarned = useEconomyStore(s => Math.max(0, s.lifetimeEarned ?? 0)); const inventory = useEconomyStore(s => s.inventory ?? []); const purchaseItem = useEconomyStore(s => s.purchaseItem); const consumeItem = useEconomyStore(s => s.consumeItem); const equipItem = useEconomyStore(s => s.equipItem); // Local UI state const [activeTab, setActiveTab] = useState('storefront'); const [storeCategory, setStoreCategory] = useState('all'); const [vaultCategory, setVaultCategory] = useState('all'); const [loadingItemId, setLoadingItemId] = useState(null); const [inspectItem, setInspectItem] = useState<{ item: StoreItem; inventoryItem?: InventoryItem; } | null>(null); const [giftCelebration, setGiftCelebration] = useState<{ item: StoreItem; reaction: GiftReactionData; } | null>(null); const [toasts, setToasts] = useState([]); // Toast notification helper const addToast = useCallback((message: string, type: 'success' | 'error' | 'info' = 'info') => { const id = `toast_${Date.now()}_${Math.random().toString(36).substring(2, 6)}`; setToasts(prev => [...prev.slice(-2), { id, message, type }]); setTimeout(() => { setToasts(prev => prev.filter(t => t.id !== id)); }, 4000); }, []); const removeToast = useCallback((id: string) => { setToasts(prev => prev.filter(t => t.id !== id)); }, []); // Filtered Catalog Items for Storefront const filteredCatalog = useMemo(() => { if (storeCategory === 'all') return STORE_CATALOG; return STORE_CATALOG.filter(item => item.category === storeCategory); }, [storeCategory]); // Enriched Inventory Items for Vault const enrichedInventory = useMemo(() => { return inventory .map(invItem => ({ invItem, catalog: STORE_CATALOG_MAP[invItem.item_id] })) .filter((entry): entry is { invItem: InventoryItem; catalog: StoreItem } => !!entry.catalog); }, [inventory]); // Filtered Inventory Items for Vault const filteredInventory = useMemo(() => { if (vaultCategory === 'all') return enrichedInventory; return enrichedInventory.filter(entry => entry.catalog.category === vaultCategory); }, [enrichedInventory, vaultCategory]); // Total items count in inventory const totalInventoryCount = useMemo(() => { return inventory.reduce((acc, curr) => acc + (curr.quantity || 0), 0); }, [inventory]); // Purchase Handler const handlePurchase = useCallback( async (item: StoreItem) => { if (gold < item.price) { addToast(`Insufficient Gold. You need ${item.price - gold} more gold to acquire this item.`, 'error'); return; } setLoadingItemId(item.id); try { await purchaseItem(item.id, 1); // Celebratory feedback playPopupChime(); try { confetti({ particleCount: 45, spread: 60, origin: { y: 0.65 } }); } catch { // safe fallback if canvas is unavailable } addToast(`Acquired ${item.name}! Added to Adventurer's Vault.`, 'success'); if (inspectItem?.item.id === item.id) { setInspectItem(null); } } catch (err) { const msg = err instanceof Error ? err.message : 'Purchase failed. Your gold balance remains intact.'; addToast(msg, 'error'); } finally { setLoadingItemId(null); } }, [gold, purchaseItem, addToast, inspectItem] ); // Consume Handler const handleConsume = useCallback( async (item: StoreItem) => { setLoadingItemId(item.id); try { const res = await consumeItem(item.id); playPopupChime(); addToast(`Consumed ${item.name}! Effect active. (Remaining: x${res.remaining_quantity})`, 'success'); if (inspectItem?.item.id === item.id) { setInspectItem(null); } } catch (err) { const msg = err instanceof Error ? err.message : `Failed to consume ${item.name}.`; addToast(msg, 'error'); } finally { setLoadingItemId(null); } }, [consumeItem, addToast, inspectItem] ); // Equip / Unequip Cosmetic Handler const handleEquip = useCallback( async (item: StoreItem, isEquipping: boolean) => { setLoadingItemId(item.id); try { await equipItem(item.id, isEquipping); playPopupChime(); addToast( isEquipping ? `Equipped ${item.name}!` : `Unequipped ${item.name}.`, 'success' ); if (inspectItem?.item.id === item.id) { setInspectItem(null); } } catch (err) { const msg = err instanceof Error ? err.message : `Failed to update cosmetic state.`; addToast(msg, 'error'); } finally { setLoadingItemId(null); } }, [equipItem, addToast, inspectItem] ); // Present Gift to Aurelia Handler const handlePresentGift = useCallback( async (item: StoreItem) => { setLoadingItemId(item.id); try { // Consume 1 unit from inventory await consumeItem(item.id); const reaction = AURELIA_GIFT_REACTIONS[item.id] || DEFAULT_GIFT_REACTION; // Update Princess Companion state via genuine companionStore.presentGift companionStore.presentGift({ id: item.id, name: item.name, price: item.price, effect_payload: item.effect_payload }); // Audio & Visual Fanfare playLevelUpFanfare(); try { confetti({ particleCount: 60, spread: 70, origin: { y: 0.6 } }); } catch { // safe fallback } // Display celebration dialogue modal setGiftCelebration({ item, reaction }); if (inspectItem?.item.id === item.id) { setInspectItem(null); } } catch (err) { const msg = err instanceof Error ? err.message : `Failed to present ${item.name} to Aurelia.`; addToast(msg, 'error'); } finally { setLoadingItemId(null); } }, [consumeItem, addToast, inspectItem] ); return (
{/* Top Banner & Header Bar */}
{/* Navigation Tabs */}
{/* Live Gold Counter Widget */}
{gold}g
Lifetime: {lifetimeEarned}g
{/* Main Content Area */}
{/* Storefront View */} {activeTab === 'storefront' && (
{/* Category Filter Pills */}
Filter:
{/* Catalog Grid */}
{filteredCatalog.map(item => ( setInspectItem({ item: it })} /> ))}
)} {/* Adventurer's Vault View */} {activeTab === 'vault' && (
{/* Category Filter Pills */}
Filter:
{/* Empty State */} {filteredInventory.length === 0 ? (

Your satchel is empty. Visit the store to acquire items!

Complete daily reviews and coding challenges to earn gold coins, then browse the store.

) : ( /* Vault Grid */
{filteredInventory.map(({ invItem, catalog }) => ( setInspectItem({ item: cat, inventoryItem: inv })} /> ))}
)}
)}
{/* Floating Toast Alerts */} {toasts.length > 0 && (
{toasts.map(toast => (
{toast.type === 'success' ? ( ) : toast.type === 'error' ? ( ) : ( )} {toast.message}
))}
)} {/* Item Lore Inspection Modal */} {inspectItem && ( setInspectItem(null)} onPurchase={activeTab === 'storefront' ? handlePurchase : undefined} onAction={ activeTab === 'vault' && inspectItem.inventoryItem ? it => { if (it.category === 'consumable') handleConsume(it); else if (it.category === 'cosmetic') handleEquip(it, !inspectItem.inventoryItem?.is_equipped); else if (it.category === 'companion_gift') handlePresentGift(it); } : undefined } actionLabel={ inspectItem.item.category === 'consumable' ? 'Consume' : inspectItem.item.category === 'cosmetic' ? inspectItem.inventoryItem?.is_equipped ? 'Unequip' : 'Equip' : 'Present Gift' } /> )} {/* Gift Celebration Dialogue Modal */} {giftCelebration && ( setGiftCelebration(null)} onOpenCompanion={onOpenCompanion} /> )}
); }; export default StoreWindow;