Spaces:
Running
Running
File size: 21,537 Bytes
aa1fcca | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | 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'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;
|