iamfebin's picture
feat: player economy, item catalog, vault inventory, and companion gifting
aa1fcca
Raw History Blame Contribute Delete
21.5 kB
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<StoreWindowProps> = ({ 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<MainTab>('storefront');
const [storeCategory, setStoreCategory] = useState<FilterCategory>('all');
const [vaultCategory, setVaultCategory] = useState<FilterCategory>('all');
const [loadingItemId, setLoadingItemId] = useState<string | null>(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<ToastNotification[]>([]);
// 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 (
<div className="w-full h-full bg-[#fbf7ee] flex flex-col overflow-hidden text-ink-black select-none">
{/* Top Banner & Header Bar */}
<div className="bg-[#FFFDF0] border-b-[3px] border-ink-black px-4 py-3 shrink-0 flex flex-wrap items-center justify-between gap-3 shadow-[0_2px_4px_rgba(0,0,0,0.05)]">
{/* Navigation Tabs */}
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setActiveTab('storefront')}
className={`font-arcade text-xs px-3.5 py-2 border-[2px] border-ink-black rounded shadow-[2px_2px_0px_0px_#1E293B] active:translate-y-0.5 active:shadow-none transition-all flex items-center gap-2 cursor-pointer uppercase font-bold ${activeTab === 'storefront'
? 'bg-amber-400 text-ink-black ring-2 ring-amber-500/50'
: 'bg-paper-white text-slate-700 hover:bg-amber-100/60'
}`}
>
<Store className="w-4 h-4 text-amber-800" />
<span>Store</span>
</button>
<button
type="button"
onClick={() => setActiveTab('vault')}
className={`font-arcade text-xs px-3.5 py-2 border-[2px] border-ink-black rounded shadow-[2px_2px_0px_0px_#1E293B] active:translate-y-0.5 active:shadow-none transition-all flex items-center gap-2 cursor-pointer uppercase font-bold ${activeTab === 'vault'
? 'bg-amber-400 text-ink-black ring-2 ring-amber-500/50'
: 'bg-paper-white text-slate-700 hover:bg-amber-100/60'
}`}
>
<Package className="w-4 h-4 text-amber-800" />
<span>Adventurer&apos;s Vault</span>
{totalInventoryCount > 0 && (
<span className="font-arcade text-[9px] bg-ink-black text-amber-300 px-1.5 py-0.5 rounded font-extrabold ml-0.5">
{totalInventoryCount}
</span>
)}
</button>
</div>
{/* Live Gold Counter Widget */}
<div
className="flex items-center gap-3 bg-amber-100/70 border-[2px] border-ink-black px-3.5 py-1.5 rounded shadow-[2px_2px_0px_0px_#1E293B]"
title={`Gold: ${gold} (Lifetime: ${lifetimeEarned})`}
>
<div className="flex items-center gap-1.5 font-arcade text-xs font-bold text-amber-900">
<Coins className="w-4 h-4 text-amber-500 fill-amber-500" />
<span>{gold}g</span>
</div>
<div className="h-3 w-[1px] bg-amber-300" />
<span className="font-arcade text-[8px] text-amber-800 uppercase font-semibold">
Lifetime: {lifetimeEarned}g
</span>
</div>
</div>
{/* Main Content Area */}
<div className="flex-1 overflow-y-auto custom-scrollbar p-4 md:p-6 flex flex-col gap-5">
{/* Storefront View */}
{activeTab === 'storefront' && (
<div className="flex flex-col gap-4">
{/* Category Filter Pills */}
<div className="flex items-center gap-2 flex-wrap pb-1 border-b border-ink-black/10">
<span className="font-arcade text-[9px] text-slate-600 uppercase font-bold mr-1">
Filter:
</span>
<button
type="button"
onClick={() => setStoreCategory('all')}
className={`font-arcade text-[10px] px-3 py-1 border-[2px] border-ink-black rounded cursor-pointer transition-all uppercase font-bold ${storeCategory === 'all'
? 'bg-ink-black text-amber-300 shadow-[2px_2px_0px_0px_#1E293B]'
: 'bg-white text-slate-700 hover:bg-amber-100/50'
}`}
>
All Goods (12)
</button>
<button
type="button"
onClick={() => setStoreCategory('consumable')}
className={`font-arcade text-[10px] px-3 py-1 border-[2px] border-ink-black rounded cursor-pointer transition-all uppercase font-bold ${storeCategory === 'consumable'
? 'bg-emerald-700 text-white shadow-[2px_2px_0px_0px_#1E293B]'
: 'bg-white text-emerald-800 hover:bg-emerald-50'
}`}
>
Consumables (4)
</button>
<button
type="button"
onClick={() => setStoreCategory('cosmetic')}
className={`font-arcade text-[10px] px-3 py-1 border-[2px] border-ink-black rounded cursor-pointer transition-all uppercase font-bold ${storeCategory === 'cosmetic'
? 'bg-purple-700 text-white shadow-[2px_2px_0px_0px_#1E293B]'
: 'bg-white text-purple-800 hover:bg-purple-50'
}`}
>
Cosmetics (4)
</button>
<button
type="button"
onClick={() => setStoreCategory('companion_gift')}
className={`font-arcade text-[10px] px-3 py-1 border-[2px] border-ink-black rounded cursor-pointer transition-all uppercase font-bold ${storeCategory === 'companion_gift'
? 'bg-amber-600 text-white shadow-[2px_2px_0px_0px_#1E293B]'
: 'bg-white text-amber-900 hover:bg-amber-50'
}`}
>
Gifts for Aurelia (4)
</button>
</div>
{/* Catalog Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filteredCatalog.map(item => (
<StoreItemCard
key={item.id}
item={item}
playerGold={gold}
isPurchasing={loadingItemId === item.id}
onPurchase={handlePurchase}
onInspect={it => setInspectItem({ item: it })}
/>
))}
</div>
</div>
)}
{/* Adventurer's Vault View */}
{activeTab === 'vault' && (
<div className="flex flex-col gap-4">
{/* Category Filter Pills */}
<div className="flex items-center gap-2 flex-wrap pb-1 border-b border-ink-black/10">
<span className="font-arcade text-[9px] text-slate-600 uppercase font-bold mr-1">
Filter:
</span>
<button
type="button"
onClick={() => setVaultCategory('all')}
className={`font-arcade text-[10px] px-3 py-1 border-[2px] border-ink-black rounded cursor-pointer transition-all uppercase font-bold ${vaultCategory === 'all'
? 'bg-ink-black text-amber-300 shadow-[2px_2px_0px_0px_#1E293B]'
: 'bg-white text-slate-700 hover:bg-amber-100/50'
}`}
>
All Satchel
</button>
<button
type="button"
onClick={() => setVaultCategory('consumable')}
className={`font-arcade text-[10px] px-3 py-1 border-[2px] border-ink-black rounded cursor-pointer transition-all uppercase font-bold ${vaultCategory === 'consumable'
? 'bg-emerald-700 text-white shadow-[2px_2px_0px_0px_#1E293B]'
: 'bg-white text-emerald-800 hover:bg-emerald-50'
}`}
>
Consumables
</button>
<button
type="button"
onClick={() => setVaultCategory('cosmetic')}
className={`font-arcade text-[10px] px-3 py-1 border-[2px] border-ink-black rounded cursor-pointer transition-all uppercase font-bold ${vaultCategory === 'cosmetic'
? 'bg-purple-700 text-white shadow-[2px_2px_0px_0px_#1E293B]'
: 'bg-white text-purple-800 hover:bg-purple-50'
}`}
>
Cosmetics
</button>
<button
type="button"
onClick={() => setVaultCategory('companion_gift')}
className={`font-arcade text-[10px] px-3 py-1 border-[2px] border-ink-black rounded cursor-pointer transition-all uppercase font-bold ${vaultCategory === 'companion_gift'
? 'bg-amber-600 text-white shadow-[2px_2px_0px_0px_#1E293B]'
: 'bg-white text-amber-900 hover:bg-amber-50'
}`}
>
Gifts
</button>
</div>
{/* Empty State */}
{filteredInventory.length === 0 ? (
<div className="bg-[#FFFDF0] border-[3px] border-dashed border-ink-black/40 rounded-xl p-8 flex flex-col items-center justify-center text-center gap-3 my-6">
<div className="w-16 h-16 bg-amber-100/80 border-[2px] border-ink-black rounded-full flex items-center justify-center text-amber-800 mb-1">
<ShoppingBag className="w-8 h-8" />
</div>
<h4 className="font-headline-md font-bold text-lg text-ink-black">
Your satchel is empty. Visit the store to acquire items!
</h4>
<p className="font-serif italic text-sm text-slate-600 max-w-sm">
Complete daily reviews and coding challenges to earn gold coins, then browse the store.
</p>
<button
type="button"
onClick={() => setActiveTab('storefront')}
className="mt-2 font-arcade text-xs px-4 py-2.5 bg-amber-400 hover:bg-amber-300 text-ink-black border-[2px] border-ink-black rounded shadow-[2px_2px_0px_0px_#1E293B] active:translate-y-0.5 active:shadow-none cursor-pointer uppercase font-bold tracking-wider"
>
Browse Emporium
</button>
</div>
) : (
/* Vault Grid */
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{filteredInventory.map(({ invItem, catalog }) => (
<VaultItemCard
key={invItem.item_id}
inventoryItem={invItem}
catalogItem={catalog}
isLoading={loadingItemId === catalog.id}
onConsume={handleConsume}
onEquip={handleEquip}
onPresentGift={handlePresentGift}
onInspect={(cat, inv) => setInspectItem({ item: cat, inventoryItem: inv })}
/>
))}
</div>
)}
</div>
)}
</div>
{/* Floating Toast Alerts */}
{toasts.length > 0 && (
<div className="absolute bottom-4 right-4 z-40 flex flex-col gap-2 max-w-sm w-full pointer-events-none">
{toasts.map(toast => (
<div
key={toast.id}
className={`pointer-events-auto p-3 border-[2px] border-ink-black rounded shadow-[3px_3px_0px_0px_#1E293B] flex items-start justify-between gap-2 text-xs font-sans animate-in slide-in-from-bottom-2 duration-150 ${toast.type === 'success'
? 'bg-emerald-100 text-emerald-950 border-emerald-900'
: toast.type === 'error'
? 'bg-rose-100 text-rose-950 border-rose-900'
: 'bg-amber-100 text-amber-950 border-amber-900'
}`}
>
<div className="flex items-center gap-2">
{toast.type === 'success' ? (
<CheckCircle2 className="w-4 h-4 text-emerald-700 shrink-0" />
) : toast.type === 'error' ? (
<AlertCircle className="w-4 h-4 text-rose-700 shrink-0" />
) : (
<Sparkles className="w-4 h-4 text-amber-700 shrink-0" />
)}
<span className="font-semibold">{toast.message}</span>
</div>
<button
type="button"
onClick={() => removeToast(toast.id)}
className="p-0.5 hover:bg-black/10 rounded cursor-pointer shrink-0"
>
<X className="w-3.5 h-3.5" />
</button>
</div>
))}
</div>
)}
{/* Item Lore Inspection Modal */}
{inspectItem && (
<ItemLoreModal
item={inspectItem.item}
ownedQuantity={inspectItem.inventoryItem?.quantity}
playerGold={gold}
isEquipped={inspectItem.inventoryItem?.is_equipped}
isActionLoading={loadingItemId === inspectItem.item.id}
onClose={() => 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 && (
<GiftPresentationModal
giftItem={giftCelebration.item}
reaction={giftCelebration.reaction}
onClose={() => setGiftCelebration(null)}
onOpenCompanion={onOpenCompanion}
/>
)}
</div>
);
};
export default StoreWindow;