generated from google-gemini/aistudio-repository-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
868 lines (782 loc) · 43.6 KB
/
App.tsx
File metadata and controls
868 lines (782 loc) · 43.6 KB
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
import React, { useState, useEffect, useRef } from 'react';
import { Navbar } from './components/Navbar';
import { Button } from './components/Button';
import { SwapModal } from './components/SwapModal';
import { NegotiationChat } from './components/NegotiationChat';
import { DeliveryCalculator } from './components/DeliveryCalculator';
import { UserProfile } from './components/UserProfile';
import { TechSwapGuide } from './components/TechSwapGuide';
import { MOCK_PRODUCTS, MOCK_USER_HISTORY } from './constants';
import { Product, ViewState } from './types';
import { generateListingDetails, semanticSearchProducts, compareProducts, getPersonalizedRecommendations, ComparisonResult, visualSearchProducts, getMarketBadges } from './services/geminiService';
import { Plus, Tag, RefreshCcw, MapPin, DollarSign, CheckCircle, Search, Trash2, Upload, X, Sparkles, Loader2, Filter, Scale, Trophy, Bot, Star, Camera } from 'lucide-react';
// Utility for Fuzzy Search
const getLevenshteinDistance = (a: string, b: string): number => {
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
const matrix = [];
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1,
matrix[i][j - 1] + 1,
matrix[i - 1][j] + 1
);
}
}
}
return matrix[b.length][a.length];
};
const App: React.FC = () => {
const [currentView, setCurrentView] = useState<ViewState>('market');
const [activeSwapProduct, setActiveSwapProduct] = useState<Product | null>(null);
const [activeNegotiationProduct, setActiveNegotiationProduct] = useState<Product | null>(null);
// Cart state now includes optional deliveryFee
const [cart, setCart] = useState<{product: Product, price: number, isSwap: boolean, deliveryFee?: number}[]>([]);
const [searchTerm, setSearchTerm] = useState('');
const [selectedCategory, setSelectedCategory] = useState('All');
// New AI Search State
const [isAiSearchMode, setIsAiSearchMode] = useState(false);
const [isSearchingAi, setIsSearchingAi] = useState(false);
const [aiSearchResults, setAiSearchResults] = useState<string[] | null>(null); // List of IDs
// Visual Search State
const [isVisualSearching, setIsVisualSearching] = useState(false);
const visualSearchInputRef = useRef<HTMLInputElement>(null);
// AI Recommendations State
const [recommendedIds, setRecommendedIds] = useState<string[]>([]);
const [loadingRecommendations, setLoadingRecommendations] = useState(false);
// Market Badges State
const [productBadges, setProductBadges] = useState<Record<string, string>>({});
// Comparison State
const [selectedForCompare, setSelectedForCompare] = useState<string[]>([]);
const [isComparing, setIsComparing] = useState(false);
const [comparisonResult, setComparisonResult] = useState<ComparisonResult | null>(null);
const [showComparisonModal, setShowComparisonModal] = useState(false);
// Sell View State
const [listingImages, setListingImages] = useState<string[]>([]);
const [isAiAnalyzing, setIsAiAnalyzing] = useState(false);
// Controlled Form State
const [listingForm, setListingForm] = useState({
name: '',
category: 'Phone',
description: '',
price: '',
condition: 'Good'
});
// Load recommendations and badges on mount
useEffect(() => {
const initData = async () => {
setLoadingRecommendations(true);
const [recIds, badges] = await Promise.all([
getPersonalizedRecommendations(MOCK_USER_HISTORY, MOCK_PRODUCTS),
getMarketBadges(MOCK_PRODUCTS)
]);
setRecommendedIds(recIds);
setProductBadges(badges);
setLoadingRecommendations(false);
};
initData();
}, []);
const handleSearch = async () => {
if (isAiSearchMode && searchTerm.trim().length > 2) {
setIsSearchingAi(true);
const ids = await semanticSearchProducts(searchTerm, MOCK_PRODUCTS);
setAiSearchResults(ids);
setIsSearchingAi(false);
} else {
// Standard search clears AI results
setAiSearchResults(null);
}
};
const handleVisualSearch = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsVisualSearching(true);
setSearchTerm("Analyzing image...");
const reader = new FileReader();
reader.onloadend = async () => {
const base64 = (reader.result as string).split(',')[1];
const ids = await visualSearchProducts(base64, MOCK_PRODUCTS);
setAiSearchResults(ids);
setIsAiSearchMode(true); // Switch to AI mode to display these results
setSearchTerm("📸 Visual Search Results");
setIsVisualSearching(false);
};
reader.readAsDataURL(file);
};
const filteredProducts = MOCK_PRODUCTS.filter(p => {
// 0. AI Search Filter (Higher Priority)
if (isAiSearchMode && aiSearchResults) {
return aiSearchResults.includes(p.id);
}
// 1. Category Filter
if (selectedCategory !== 'All' && p.category !== selectedCategory) return false;
// 2. Standard Search Filter
if (!searchTerm || isAiSearchMode) return true; // If AI mode is on but no results yet, show all
const term = searchTerm.toLowerCase();
const name = p.name.toLowerCase();
const desc = p.description.toLowerCase();
const cat = p.category.toLowerCase();
// Direct match
if (name.includes(term) || desc.includes(term) || cat.includes(term)) return true;
// Fuzzy match on Name words
if (term.length > 2) {
const words = name.split(' ');
return words.some(word => {
if (Math.abs(word.length - term.length) > 2) return false;
return getLevenshteinDistance(word, term) <= 2;
});
}
return false;
}).sort((a, b) => {
// Sort by AI result order if applicable
if (isAiSearchMode && aiSearchResults) {
return aiSearchResults.indexOf(a.id) - aiSearchResults.indexOf(b.id);
}
return 0;
});
const toggleCompare = (productId: string) => {
setSelectedForCompare(prev => {
if (prev.includes(productId)) return prev.filter(id => id !== productId);
if (prev.length >= 2) return [prev[1], productId]; // Keep max 2
return [...prev, productId];
});
};
const runComparison = async () => {
if (selectedForCompare.length !== 2) return;
setIsComparing(true);
setShowComparisonModal(true);
const p1 = MOCK_PRODUCTS.find(p => p.id === selectedForCompare[0]);
const p2 = MOCK_PRODUCTS.find(p => p.id === selectedForCompare[1]);
if (p1 && p2) {
const result = await compareProducts(p1, p2);
setComparisonResult(result);
}
setIsComparing(false);
};
const handleAddToCart = (product: Product, finalPrice: number, isSwap: boolean = false) => {
setCart([...cart, { product, price: finalPrice, isSwap }]);
setActiveSwapProduct(null);
setActiveNegotiationProduct(null);
setCurrentView('cart');
};
const updateDeliveryFee = (index: number, fee: number) => {
setCart(prevCart => {
const newCart = [...prevCart];
if (newCart[index]) {
newCart[index] = { ...newCart[index], deliveryFee: fee };
}
return newCart;
});
};
const removeFromCart = (index: number) => {
setCart(prev => prev.filter((_, i) => i !== index));
};
const handleListingImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length > 0) {
const files = Array.from(e.target.files) as File[];
const filePromises = files.map(file => {
return new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onloadend = () => {
resolve(reader.result as string);
};
reader.readAsDataURL(file);
});
});
Promise.all(filePromises).then(newImages => {
setListingImages(prev => [...prev, ...newImages]);
});
}
};
const removeListingImage = (indexToRemove: number) => {
setListingImages(prev => prev.filter((_, index) => index !== indexToRemove));
};
const handleAiAutoFill = async () => {
if (listingImages.length === 0) {
alert("Please upload an image first for AI analysis.");
return;
}
setIsAiAnalyzing(true);
// Get base64 of first image without header
const base64 = listingImages[0].split(',')[1];
const data = await generateListingDetails(base64);
setListingForm({
name: data.name,
category: data.category,
description: data.description,
price: data.price.toString(),
condition: data.condition
});
setIsAiAnalyzing(false);
};
const handleCreateListing = (e: React.FormEvent) => {
e.preventDefault();
alert(`Listing created for ${listingForm.name}! (Demo)`);
setListingImages([]);
setListingForm({ name: '', category: 'Phone', description: '', price: '', condition: 'Good' });
setCurrentView('market');
};
// Calculate totals
const subtotal = cart.reduce((acc, item) => acc + item.price, 0);
const totalDelivery = cart.reduce((acc, item) => acc + (item.deliveryFee || 0), 0);
const total = subtotal + totalDelivery;
return (
<div className="min-h-screen bg-[#0f172a] bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-indigo-900 via-slate-900 to-black text-slate-100 font-sans pb-20 selection:bg-indigo-500 selection:text-white">
<Navbar
currentView={currentView}
setView={setCurrentView}
cartCount={cart.length}
/>
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-24">
{/* MARKET VIEW */}
{currentView === 'market' && (
<div className="space-y-8 animate-in fade-in duration-500">
<div className="flex flex-col md:flex-row justify-between items-end md:items-center gap-4">
<div>
<h1 className="text-3xl font-bold text-white tracking-tight">Marketplace</h1>
<p className="text-slate-400 mt-1">Buy, Sell, or Swap certified devices.</p>
</div>
<div className="flex flex-col md:flex-row gap-3 w-full md:w-auto items-end md:items-center">
{/* Category Filter */}
<div className="relative min-w-[160px]">
<Filter className="absolute left-3 top-3 w-4 h-4 text-slate-400 pointer-events-none" />
<select
value={selectedCategory}
onChange={(e) => setSelectedCategory(e.target.value)}
className="w-full pl-9 pr-4 py-2.5 rounded-xl bg-slate-800/80 border border-slate-700 text-slate-300 focus:ring-2 focus:ring-indigo-500 focus:outline-none focus:border-transparent backdrop-blur-sm appearance-none cursor-pointer hover:bg-slate-800"
>
<option value="All">All Categories</option>
<option value="Phone">Phones</option>
<option value="Laptop">Laptops</option>
<option value="Tablet">Tablets</option>
<option value="Watch">Watches</option>
<option value="Audio">Audio</option>
<option value="Gaming">Gaming</option>
<option value="Camera">Cameras</option>
<option value="Drone">Drones</option>
<option value="Smart Home">Smart Home</option>
</select>
</div>
{/* Search Bar */}
<div className="relative w-full md:w-96 group flex gap-2">
<div className="relative flex-1">
<div className={`absolute -inset-0.5 rounded-xl blur opacity-25 transition duration-1000 ${isAiSearchMode ? 'bg-gradient-to-r from-purple-500 to-pink-500 opacity-50' : 'bg-gradient-to-r from-indigo-500 to-teal-500'}`}></div>
<div className="relative">
{isAiSearchMode ? (
<Sparkles className="absolute left-3 top-3 w-5 h-5 text-purple-400 animate-pulse" />
) : (
<Search className="absolute left-3 top-3 w-5 h-5 text-slate-400" />
)}
<input
type="text"
placeholder={isAiSearchMode ? "Ask AI: 'Best laptop for coding under $900'..." : "Search devices..."}
className={`w-full pl-10 pr-24 py-2.5 rounded-xl border text-white focus:ring-2 focus:outline-none focus:border-transparent backdrop-blur-sm transition-all ${isAiSearchMode ? 'bg-purple-900/40 border-purple-500/50 focus:ring-purple-500 placeholder-purple-300' : 'bg-slate-800/80 border-slate-700 placeholder-slate-400 focus:ring-indigo-500'}`}
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
/>
<div className="absolute right-2 top-1.5 flex gap-1">
{/* Visual Search Button */}
<button
onClick={() => visualSearchInputRef.current?.click()}
className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 transition-colors"
title="Visual Search (Snap to Find)"
>
{isVisualSearching ? <Loader2 className="w-4 h-4 animate-spin" /> : <Camera className="w-4 h-4" />}
</button>
<input
type="file"
ref={visualSearchInputRef}
className="hidden"
accept="image/*"
onChange={handleVisualSearch}
/>
{/* Toggle AI Button */}
<button
onClick={() => { setIsAiSearchMode(!isAiSearchMode); setAiSearchResults(null); }}
className={`p-1.5 rounded-lg transition-all ${isAiSearchMode ? 'bg-purple-500 text-white' : 'text-slate-400 hover:text-white hover:bg-slate-700'}`}
title="Toggle AI Semantic Search"
>
<Sparkles className="w-4 h-4" />
</button>
</div>
</div>
</div>
{isAiSearchMode && (
<Button onClick={handleSearch} disabled={isSearchingAi || searchTerm.length < 3} className="bg-purple-600 hover:bg-purple-700">
{isSearchingAi ? <Loader2 className="w-4 h-4 animate-spin" /> : "Ask"}
</Button>
)}
</div>
</div>
</div>
{/* Recommendations Section */}
{!searchTerm && selectedCategory === 'All' && !isAiSearchMode && (
<div className="bg-gradient-to-br from-indigo-900/50 to-purple-900/50 border border-white/5 rounded-2xl p-6 mb-8 backdrop-blur-sm">
<h3 className="flex items-center gap-2 text-xl font-bold text-white mb-4">
<Sparkles className="w-5 h-5 text-yellow-400" />
Recommended for You
</h3>
{loadingRecommendations ? (
<div className="flex items-center justify-center py-8 text-slate-400 gap-2">
<Loader2 className="w-5 h-5 animate-spin" /> AI is personalizing your feed...
</div>
) : recommendedIds.length > 0 ? (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{MOCK_PRODUCTS.filter(p => recommendedIds.includes(p.id)).map(product => (
<div key={product.id} className="bg-white/10 rounded-xl p-4 flex gap-4 hover:bg-white/15 transition-colors cursor-pointer border border-white/5">
<img src={product.image} className="w-20 h-20 object-cover rounded-lg" alt={product.name} />
<div>
<div className="text-xs font-bold text-purple-300 uppercase tracking-wider mb-1 flex items-center gap-1">
<Star className="w-3 h-3 fill-purple-300" /> Best Match
</div>
<h4 className="font-bold text-white">{product.name}</h4>
<p className="text-indigo-300 font-bold">${product.price}</p>
<button
onClick={() => handleAddToCart(product, product.price)}
className="text-xs text-white bg-indigo-600 hover:bg-indigo-500 px-3 py-1.5 rounded mt-2 transition-colors"
>
View Deal
</button>
</div>
</div>
))}
</div>
) : (
<p className="text-slate-400">Browse more items to see personalized recommendations!</p>
)}
</div>
)}
{filteredProducts.length === 0 ? (
<div className="text-center py-20 bg-white/5 rounded-2xl border border-white/5">
{isAiSearchMode ? <Sparkles className="w-12 h-12 text-purple-400 mx-auto mb-4" /> : <Search className="w-12 h-12 text-slate-600 mx-auto mb-4" />}
<h3 className="text-xl font-bold text-white">No matches found</h3>
<p className="text-slate-400">Try adjusting your {isAiSearchMode ? 'AI prompt' : 'search'} or category filter.</p>
<button
onClick={() => {setSearchTerm(''); setSelectedCategory('All'); setAiSearchResults(null);}}
className="mt-4 text-indigo-400 hover:text-indigo-300 font-medium"
>
Clear all filters
</button>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
{filteredProducts.map((product) => (
<div key={product.id} className={`bg-white rounded-2xl shadow-xl hover:shadow-2xl transition-all duration-300 overflow-hidden group border relative ${selectedForCompare.includes(product.id) ? 'ring-2 ring-indigo-500 border-indigo-500 transform scale-[1.02]' : 'border-white/5 hover:shadow-indigo-500/10'}`}>
{/* Market Badge (AI Generated) */}
{productBadges[product.id] && (
<div className="absolute top-3 left-3 z-10">
<span className="bg-amber-400 text-slate-900 text-xs font-bold px-2 py-1 rounded shadow-md flex items-center gap-1">
<Tag className="w-3 h-3" /> {productBadges[product.id]}
</span>
</div>
)}
{/* Compare Checkbox */}
<div className="absolute top-3 right-3 z-10">
<button
onClick={(e) => { e.stopPropagation(); toggleCompare(product.id); }}
className={`p-1.5 rounded-full backdrop-blur-md transition-all ${selectedForCompare.includes(product.id) ? 'bg-indigo-600 text-white shadow-lg' : 'bg-white/30 text-slate-800 hover:bg-white'}`}
>
<Scale className="w-4 h-4" />
</button>
</div>
<div className="relative h-64 overflow-hidden bg-slate-100">
<img
src={product.image}
alt={product.name}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
/>
<div className="absolute bottom-3 left-3 bg-white/90 backdrop-blur-md px-2 py-1 rounded-md text-xs font-semibold text-slate-900 shadow-sm">
{product.condition}
</div>
</div>
<div className="p-5">
<div className="flex justify-between items-start mb-2">
<div>
<h3 className="font-bold text-lg text-slate-900 leading-tight mb-1">{product.name}</h3>
<p className="text-sm text-slate-500 flex items-center">
<MapPin className="w-3 h-3 mr-1" /> {product.location}
</p>
</div>
<div className="text-right">
<span className="block text-xl font-bold text-indigo-600">${product.price}</span>
</div>
</div>
<p className="text-slate-600 text-sm line-clamp-2 mb-4 h-10">{product.description}</p>
<div className="grid grid-cols-2 gap-2 mt-4">
<Button
variant="secondary"
onClick={() => setActiveSwapProduct(product)}
className="flex items-center justify-center text-sm"
>
<RefreshCcw className="w-4 h-4 mr-1.5" /> Swap
</Button>
<Button
variant="primary"
onClick={() => handleAddToCart(product, product.price)}
className="flex items-center justify-center text-sm"
>
Buy Now
</Button>
</div>
<div className="mt-2">
<button
onClick={() => setActiveNegotiationProduct(product)}
className="w-full py-2 text-xs font-medium text-slate-500 hover:text-indigo-600 transition-colors flex items-center justify-center gap-1"
>
<DollarSign className="w-3 h-3" /> Negotiate Price
</button>
</div>
</div>
</div>
))}
</div>
)}
</div>
)}
{/* Floating Compare Button */}
{selectedForCompare.length > 0 && currentView === 'market' && (
<div className="fixed bottom-8 left-1/2 transform -translate-x-1/2 z-40 animate-in slide-in-from-bottom-4">
<div className="bg-slate-900 text-white px-6 py-3 rounded-full shadow-2xl flex items-center gap-4 border border-slate-700">
<span className="text-sm font-medium">{selectedForCompare.length} selected</span>
<div className="h-4 w-px bg-slate-700"></div>
{selectedForCompare.length === 2 ? (
<button
onClick={runComparison}
className="flex items-center gap-2 font-bold text-indigo-400 hover:text-indigo-300 transition-colors"
>
<Sparkles className="w-4 h-4" /> Compare with AI
</button>
) : (
<span className="text-xs text-slate-400">Select 2 to compare</span>
)}
<button onClick={() => setSelectedForCompare([])} className="ml-2 hover:bg-slate-800 p-1 rounded-full">
<X className="w-4 h-4 text-slate-400" />
</button>
</div>
</div>
)}
{/* SELL VIEW */}
{currentView === 'sell' && (
<div className="max-w-2xl mx-auto bg-white/5 backdrop-blur-xl rounded-3xl shadow-2xl border border-white/10 p-8 animate-in slide-in-from-bottom-4 duration-500">
<div className="text-center mb-8">
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-full mb-4 shadow-lg shadow-indigo-500/30">
<Plus className="w-8 h-8 text-white" />
</div>
<h2 className="text-2xl font-bold text-white">List Your Device</h2>
<p className="text-slate-400">Get the best value for your gadgets instantly.</p>
</div>
<form className="space-y-6" onSubmit={handleCreateListing}>
{/* Image Upload Area */}
<div className="space-y-4">
<label className="block text-sm font-medium text-slate-300">Device Photos</label>
<div className="relative border-2 border-dashed border-slate-600 bg-slate-800/50 rounded-xl p-8 text-center hover:bg-slate-800 hover:border-indigo-400 transition-all duration-300 group">
<input
type="file"
multiple
accept="image/*"
onChange={handleListingImageUpload}
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"
/>
<div className="pointer-events-none">
<Upload className="w-10 h-10 mx-auto text-slate-400 mb-3 group-hover:text-indigo-400 transition-colors" />
<span className="text-sm text-slate-300 font-medium">Click to upload photos</span>
<p className="text-xs text-slate-500 mt-1">PNG, JPG up to 5MB</p>
</div>
</div>
{/* Image Previews & AI Button */}
{listingImages.length > 0 && (
<div className="space-y-4">
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{listingImages.map((img, index) => (
<div key={index} className="relative group aspect-square rounded-lg overflow-hidden bg-slate-800 border border-slate-600">
<img src={img} alt={`Preview ${index}`} className="w-full h-full object-cover" />
<button
type="button"
onClick={() => removeListingImage(index)}
className="absolute top-1 right-1 bg-red-500 text-white p-1 rounded-full opacity-90 hover:opacity-100 transition-opacity"
>
<X className="w-4 h-4" />
</button>
</div>
))}
</div>
<button
type="button"
onClick={handleAiAutoFill}
disabled={isAiAnalyzing}
className="w-full py-3 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 text-white rounded-xl font-bold flex items-center justify-center gap-2 transition-all shadow-lg shadow-indigo-500/20 disabled:opacity-50 disabled:cursor-wait"
>
{isAiAnalyzing ? (
<>
<Loader2 className="w-5 h-5 animate-spin" /> Analyzing Image...
</>
) : (
<>
<Sparkles className="w-5 h-5" /> AI Auto-Fill Details
</>
)}
</button>
</div>
)}
</div>
<div className="grid md:grid-cols-2 gap-6">
<div>
<label className="block text-sm font-medium text-slate-300 mb-1">Product Name</label>
<input
type="text"
required
className="w-full p-3 bg-slate-800/50 border border-slate-600 text-white rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent placeholder-slate-500"
placeholder="e.g. iPhone 14 Pro"
value={listingForm.name}
onChange={(e) => setListingForm({...listingForm, name: e.target.value})}
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-300 mb-1">Category</label>
<select
className="w-full p-3 bg-slate-800/50 border border-slate-600 text-white rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
value={listingForm.category}
onChange={(e) => setListingForm({...listingForm, category: e.target.value})}
>
<option>Phone</option>
<option>Laptop</option>
<option>Tablet</option>
<option>Smartwatch</option>
</select>
</div>
</div>
<div>
<label className="block text-sm font-medium text-slate-300 mb-1">Description</label>
<textarea
rows={4}
required
className="w-full p-3 bg-slate-800/50 border border-slate-600 text-white rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent placeholder-slate-500"
placeholder="Condition, accessories included..."
value={listingForm.description}
onChange={(e) => setListingForm({...listingForm, description: e.target.value})}
/>
</div>
<div className="grid md:grid-cols-2 gap-6">
<div>
<label className="block text-sm font-medium text-slate-300 mb-1">Price ($)</label>
<input
type="number"
required
className="w-full p-3 bg-slate-800/50 border border-slate-600 text-white rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent placeholder-slate-500"
placeholder="0.00"
value={listingForm.price}
onChange={(e) => setListingForm({...listingForm, price: e.target.value})}
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-300 mb-1">Condition</label>
<select
className="w-full p-3 bg-slate-800/50 border border-slate-600 text-white rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
value={listingForm.condition}
onChange={(e) => setListingForm({...listingForm, condition: e.target.value})}
>
<option>Mint</option>
<option>Good</option>
<option>Fair</option>
<option>Poor</option>
</select>
</div>
</div>
<Button type="submit" className="w-full py-4 text-lg bg-indigo-600 hover:bg-indigo-500 border-0 shadow-xl shadow-indigo-900/50" disabled={listingImages.length === 0}>
Post Listing
</Button>
</form>
</div>
)}
{/* NEGOTIATIONS VIEW */}
{currentView === 'negotiations' && (
<div className="text-center py-20">
<div className="bg-white/10 backdrop-blur-md p-8 rounded-2xl shadow-xl border border-white/10 inline-block max-w-md">
<CheckCircle className="w-16 h-16 text-emerald-400 mx-auto mb-4" />
<h2 className="text-2xl font-bold text-white mb-2">No Active Negotiations</h2>
<p className="text-slate-300 mb-6">Start bargaining on the market page to see chats here.</p>
<Button onClick={() => setCurrentView('market')}>Go to Market</Button>
</div>
</div>
)}
{/* CART VIEW */}
{currentView === 'cart' && (
<div className="max-w-4xl mx-auto animate-in fade-in duration-300">
<h1 className="text-3xl font-bold mb-8 text-white">Your Cart</h1>
{cart.length === 0 ? (
<div className="text-center py-12 bg-white/5 backdrop-blur-md rounded-xl border border-white/10">
<p className="text-slate-400 mb-4">Your cart is empty.</p>
<Button onClick={() => setCurrentView('market')}>Continue Shopping</Button>
</div>
) : (
<div className="grid md:grid-cols-3 gap-8">
<div className="md:col-span-2 space-y-4">
{cart.map((item, index) => (
<div key={index} className="bg-white p-4 rounded-xl shadow-lg border border-slate-100 flex flex-col gap-4 relative">
<button
onClick={() => removeFromCart(index)}
className="absolute top-4 right-4 text-slate-300 hover:text-red-500"
>
<Trash2 className="w-5 h-5" />
</button>
<div className="flex gap-4">
<img src={item.product.image} className="w-24 h-24 object-cover rounded-lg" alt={item.product.name} />
<div className="flex-1 pr-8">
<h3 className="font-bold text-lg text-slate-900">{item.product.name}</h3>
<p className="text-sm text-slate-500 mb-1">{item.product.condition}</p>
{item.isSwap && <span className="text-xs bg-indigo-100 text-indigo-700 px-2 py-0.5 rounded font-medium">Swap Deal</span>}
<div className="mt-2 font-bold text-xl text-slate-900">${item.price}</div>
</div>
</div>
<div className="border-t border-slate-100 pt-3">
<DeliveryCalculator
sellerLocation={item.product.location}
onFeeCalculated={(fee) => updateDeliveryFee(index, fee)}
/>
</div>
</div>
))}
</div>
<div className="bg-white/10 backdrop-blur-md p-6 rounded-xl shadow-lg border border-white/10 h-fit sticky top-24 text-white">
<h3 className="font-bold text-lg mb-4">Summary</h3>
<div className="space-y-2 mb-4 text-sm">
<div className="flex justify-between">
<span className="text-slate-300">Subtotal</span>
<span className="font-medium">${subtotal.toFixed(2)}</span>
</div>
<div className="flex justify-between">
<span className="text-slate-300">Delivery</span>
<span className="font-medium">${totalDelivery.toFixed(2)}</span>
</div>
</div>
<div className="border-t border-white/10 pt-4 mb-6">
<div className="flex justify-between font-bold text-lg">
<span>Total</span>
<span>${total.toFixed(2)}</span>
</div>
</div>
<Button className="w-full bg-emerald-500 hover:bg-emerald-600 border-0">Proceed to Checkout</Button>
</div>
</div>
)}
</div>
)}
{/* PROFILE VIEW */}
{currentView === 'profile' && <UserProfile />}
</main>
{/* Global TechSwap Guide */}
<TechSwapGuide products={MOCK_PRODUCTS} />
{/* Comparison Modal */}
{showComparisonModal && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden">
<div className="p-4 border-b border-slate-100 flex justify-between items-center bg-slate-900 text-white">
<div className="flex items-center gap-2">
<Sparkles className="w-5 h-5 text-indigo-400" />
<h2 className="font-bold text-lg">AI Device Comparison</h2>
</div>
<button onClick={() => {setShowComparisonModal(false); setComparisonResult(null);}} className="p-1 hover:bg-slate-700 rounded-full">
<X className="w-6 h-6" />
</button>
</div>
<div className="p-6 overflow-y-auto">
{isComparing || !comparisonResult ? (
<div className="flex flex-col items-center justify-center py-16 text-slate-500">
<Loader2 className="w-12 h-12 animate-spin text-indigo-600 mb-4" />
<p>AI is analyzing specs and value...</p>
</div>
) : (
<div className="space-y-8">
{/* Header Products */}
<div className="grid grid-cols-2 gap-8 text-center">
{[selectedForCompare[0], selectedForCompare[1]].map((id, idx) => {
const p = MOCK_PRODUCTS.find(i => i.id === id);
if (!p) return null;
const isWinner = comparisonResult.winnerId === p.id;
return (
<div key={id} className={`p-4 rounded-xl border ${isWinner ? 'border-indigo-500 bg-indigo-50/50' : 'border-slate-200'}`}>
{isWinner && (
<div className="inline-flex items-center gap-1 bg-indigo-100 text-indigo-700 px-3 py-1 rounded-full text-xs font-bold uppercase mb-3">
<Trophy className="w-3 h-3" /> Best Value
</div>
)}
<img src={p.image} className="w-32 h-32 object-cover rounded-lg mx-auto mb-3 shadow-sm" alt={p.name} />
<h3 className="font-bold text-slate-900">{p.name}</h3>
<p className="text-lg font-bold text-slate-600">${p.price}</p>
<p className="text-sm text-slate-500">{p.condition}</p>
</div>
)
})}
</div>
{/* AI Summary */}
<div className="bg-slate-50 p-6 rounded-xl border border-slate-200">
<h4 className="font-bold text-slate-800 mb-2 flex items-center gap-2">
<Bot className="w-4 h-4 text-indigo-600" /> AI Summary
</h4>
<p className="text-slate-600 leading-relaxed text-sm">
{comparisonResult.summary}
</p>
</div>
{/* Comparison Table */}
<div>
<table className="w-full text-sm">
<thead>
<tr className="border-b border-slate-200">
<th className="text-left py-2 font-medium text-slate-400 w-1/3">Feature</th>
<th className="text-left py-2 font-bold text-slate-800 w-1/3">Item 1</th>
<th className="text-left py-2 font-bold text-slate-800 w-1/3">Item 2</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{comparisonResult.specs.map((spec, i) => (
<tr key={i}>
<td className="py-3 text-slate-500 font-medium">{spec.label}</td>
<td className="py-3 text-slate-700">{spec.item1Value}</td>
<td className="py-3 text-slate-700">{spec.item2Value}</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="flex justify-end pt-4 border-t border-slate-100">
<Button onClick={() => setShowComparisonModal(false)}>Close</Button>
</div>
</div>
)}
</div>
</div>
</div>
)}
{/* Modals */}
{activeSwapProduct && (
<SwapModal
targetProduct={activeSwapProduct}
onClose={() => setActiveSwapProduct(null)}
onAddToCart={(finalPrice, isSwap) => handleAddToCart(activeSwapProduct, finalPrice, isSwap)}
/>
)}
{activeNegotiationProduct && (
<NegotiationChat
product={activeNegotiationProduct}
onClose={() => setActiveNegotiationProduct(null)}
onSuccess={(finalPrice) => {
alert(`Offer accepted! Added to cart at $${finalPrice}`);
handleAddToCart(activeNegotiationProduct, finalPrice);
}}
/>
)}
</div>
);
};
export default App;