"use client" import React, { useState, useEffect } from "react" import Link from "next/link" import { Button } from "@/components/ui/button" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { Alert, AlertDescription } from "@/components/ui/alert" import { swal } from "@/lib/sweetalert" import { Cpu, ArrowLeft, Search, Plus, X, TrendingUp, TrendingDown, Minus, Equal, BarChart3, DollarSign, Zap, Monitor, HardDrive, MemoryStick, Fan, Clapperboard as Motherboard, Settings, Star, Eye, Heart, Share, AlertTriangle, CheckCircle, Info, } from "lucide-react" import { mockBuilds, mockComponents, type Build, type Component } from "@/lib/mock-data" import { formatCurrency } from "@/lib/currency" const categoryIcons = { cpu: Cpu, motherboard: Motherboard, memory: MemoryStick, storage: HardDrive, gpu: Monitor, psu: Zap, case: Settings, cooling: Fan, } const categoryNames = { cpu: "Processor", motherboard: "Motherboard", memory: "Memory (RAM)", storage: "Storage", gpu: "Graphics Card", psu: "Power Supply", case: "Case", cooling: "Cooling", } interface ComparisonBuild extends Build { components: Record } export default function ComparePage() { const [selectedBuilds, setSelectedBuilds] = useState([]) const [searchTerm, setSearchTerm] = useState("") const [filteredBuilds, setFilteredBuilds] = useState([]) const [activeTab, setActiveTab] = useState("overview") const [currentUserBuild, setCurrentUserBuild] = useState(null) // Check for current user build from localStorage or API useEffect(() => { if (typeof window !== 'undefined') { const savedBuild = localStorage.getItem('buildmate-current-build') if (savedBuild) { try { const build = JSON.parse(savedBuild) // Only set if it has valid components if (build && build.components && Object.keys(build.components).length > 0) { setCurrentUserBuild(build) } } catch (e) { console.error('Error parsing current build:', e) } } } }, []) useEffect(() => { // Filter builds based on search term const filtered = mockBuilds.filter(build => build.name.toLowerCase().includes(searchTerm.toLowerCase()) || build.description.toLowerCase().includes(searchTerm.toLowerCase()) || build.tags.some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase())) ) setFilteredBuilds(filtered) }, [searchTerm]) const addBuildToComparison = (build: Build) => { if (selectedBuilds.length >= 3) { swal.info("Limit reached", "You can compare up to 3 builds at once") return } if (selectedBuilds.some(b => b.id === build.id)) { swal.info("Already added", "This build is already in the comparison") return } // Convert build to comparison build with mock components const comparisonBuild: ComparisonBuild = { ...build, components: { cpu: mockComponents.find(c => c.category === "cpu" && Math.random() > 0.5) || null, motherboard: mockComponents.find(c => c.category === "motherboard" && Math.random() > 0.5) || null, memory: mockComponents.find(c => c.category === "memory" && Math.random() > 0.5) || null, storage: mockComponents.find(c => c.category === "storage" && Math.random() > 0.5) || null, gpu: mockComponents.find(c => c.category === "gpu" && Math.random() > 0.5) || null, psu: mockComponents.find(c => c.category === "psu" && Math.random() > 0.5) || null, case: mockComponents.find(c => c.category === "case" && Math.random() > 0.5) || null, cooling: mockComponents.find(c => c.category === "cooling" && Math.random() > 0.5) || null, } } setSelectedBuilds([...selectedBuilds, comparisonBuild]) } const removeBuildFromComparison = (buildId: string) => { setSelectedBuilds(selectedBuilds.filter(build => build.id !== buildId)) } const getComparisonValue = (builds: ComparisonBuild[], category: string, spec: string) => { return builds.map(build => { const component = build.components[category] if (!component) return null return component.specifications[spec] || "N/A" }) } const getPriceComparison = (builds: ComparisonBuild[]) => { const prices = builds.map(build => build.totalPrice) const min = Math.min(...prices) const max = Math.max(...prices) const avg = prices.reduce((sum, price) => sum + price, 0) / prices.length return { min, max, avg, prices } } const getPerformanceScore = (build: ComparisonBuild) => { // Mock performance calculation based on components let score = 0 Object.values(build.components).forEach(component => { if (component) { score += component.rating * 20 // Convert 5-star rating to 100-point scale } }) return Math.round(score / Object.keys(build.components).length) } const getValueScore = (build: ComparisonBuild) => { const performanceScore = getPerformanceScore(build) const pricePerPerformance = build.totalPrice / performanceScore return Math.round(100 - (pricePerPerformance / 20)) // Higher score = better value } const allBuilds = currentUserBuild ? [currentUserBuild, ...selectedBuilds] : selectedBuilds return (
{/* Page Header */}

Build Comparison

{allBuilds.length === 0 || (!currentUserBuild && selectedBuilds.length === 0) ? ( // Build Selection View
Select Builds to Compare Choose up to 3 builds to compare with your current build
setSearchTerm(e.target.value)} className="flex-1" />
{filteredBuilds.map((build) => (

{build.name}

{build.description}

{formatCurrency(build.totalPrice)}
{build.tags.map((tag) => ( {tag} ))}
{build.likes}
1.2k
))}
) : ( // Comparison View
{/* Build Selection Header */}
Comparing {allBuilds.length} Builds Analyze differences in specs, performance, and cost
{allBuilds.map((build, index) => (
{index === 0 ? "Your Build" : `Build ${index}`} {build.name} {index > 0 && ( )}
))}
Overview Components Performance Value Analysis {/* Overview Tab */}
{allBuilds.map((build, index) => (
{build.name} {index === 0 ? "Your Build" : `Build ${index}`}
{build.description}
Total Price {formatCurrency(build.totalPrice)}
Performance Score
{getPerformanceScore(build)}/100
Value Score
{getValueScore(build)}/100
{build.tags.map((tag) => ( {tag} ))}
))}
{/* Price Comparison Chart */} Price Comparison
{(() => { const priceData = getPriceComparison(allBuilds) return ( <>

Lowest

{formatCurrency(priceData.min)}

Average

{formatCurrency(Math.round(priceData.avg))}

Highest

{formatCurrency(priceData.max)}

{allBuilds.map((build, index) => (
{build.name}
{formatCurrency(build.totalPrice)}
))}
) })()}
{/* Components Tab */} Component Comparison Compare individual components across builds
{allBuilds.map((build, index) => ( ))} {Object.entries(categoryNames).map(([category, name]) => ( {allBuilds.map((build) => { const component = build.components[category] return ( ) })} ))}
Component {index === 0 ? "Your Build" : `Build ${index}`}
{React.createElement(categoryIcons[category as keyof typeof categoryIcons], { className: "h-4 w-4 text-slate-600" })} {name}
{component ? (

{component.name}

{formatCurrency(component.price)}

{[...Array(5)].map((_, i) => ( ))}
) : ( Not selected )}
{/* Performance Tab */}
Performance Scores
{allBuilds.map((build, index) => (
{build.name} {getPerformanceScore(build)}/100
))}
Performance Breakdown
{allBuilds.map((build, index) => (
{build.name} {index === 0 ? "Your Build" : `Build ${index}`}
CPU Score: {build.components.cpu ? Math.round(build.components.cpu.rating * 20) : "N/A"}
GPU Score: {build.components.gpu ? Math.round(build.components.gpu.rating * 20) : "N/A"}
RAM Score: {build.components.memory ? Math.round(build.components.memory.rating * 20) : "N/A"}
Storage Score: {build.components.storage ? Math.round(build.components.storage.rating * 20) : "N/A"}
))}
{/* Value Analysis Tab */} Value Analysis Compare performance per dollar spent
{allBuilds.map((build, index) => { const performanceScore = getPerformanceScore(build) const valueScore = getValueScore(build) const pricePerPerformance = build.totalPrice / performanceScore return (

{build.name}

{formatCurrency(build.totalPrice)} • {performanceScore}/100 Performance

{index === 0 ? "Your Build" : `Build ${index}`}

Value Score

{valueScore}/100

Price per Performance

{formatCurrency(Math.round(pricePerPerformance))}

per performance point

Efficiency

{valueScore > 80 ? "Excellent" : valueScore > 60 ? "Good" : valueScore > 40 ? "Fair" : "Poor"}

value rating

) })}
{/* Recommendations */} Recommendations
Best Value: The build with the highest value score offers the best performance per dollar spent. Performance Leader: The build with the highest performance score is best for demanding tasks. Budget Option: The lowest-priced build is ideal for budget-conscious users.
)}
) }