"use client"; import { useMemo, useState, useEffect } from "react"; import Link from "next/link"; import { useSearchParams, useRouter } from "next/navigation"; import { CATEGORIES } from "@/data/gunbuilderParts"; import { BUILDER_SLOTS, isSlotSatisfied } from "@/data/builderSlots"; import type { CategoryId, Part } from "@/types/gunbuilder"; import { PART_ROLE_TO_CATEGORY } from "@/data/partRoleMappings"; import { Pencil, Link2, Square, CheckSquare } from "lucide-react"; type GunbuilderProductFromApi = { id: number; // backend numeric id name: string; brand: string; platform: string; partRole: string; price: number | null; mainImageUrl: string | null; buyUrl: string | null; }; const PLATFORMS = ["AR-15", "AR-10", "AR-9"] as const; const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080"; type BuildState = Partial>; // categoryId -> partId const STORAGE_KEY = "gunbuilder-build-state"; // Categories that should NOT be filtered by platform (universal accessories / gear) const UNIVERSAL_CATEGORIES = new Set([ "magazine", "weapon-light", "foregrip", "bipod", "sling", "rail-accessory", "tools", // Optics & sights are intentionally treated as universal "optic", "sights", ]); // Category groups for the main grid const CATEGORY_GROUPS: { id: string; label: string; description?: string; categoryIds: CategoryId[]; }[] = [ { id: "lower-group", label: "Lower Receiver Parts", description: "Everything from the serialized lower to small parts, fire control, and core controls.", categoryIds: [ "lower", "complete-lower", "lower-parts", "trigger", "grip", "safety", "buffer", "stock", ], }, { id: "upper-group", label: "Upper Receiver Parts", description: "Barrel, upper, gas system, and the parts that keep the rifle cycling.", categoryIds: [ "upper", "complete-upper", "bcg", "barrel", "gas-block", "gas-tube", "muzzle-device", "suppressor", "handguard", "charging-handle", "sights", "optic", ], }, { id: "accessories-group", label: "Accessories & Gear", description: "Universal add-ons that work across platforms — mags, lights, slings, tools, and more.", categoryIds: [ "magazine", "weapon-light", "foregrip", "bipod", "sling", "rail-accessory", "tools", ], }, ]; export default function GunbuilderPage() { const searchParams = useSearchParams(); const router = useRouter(); const [parts, setParts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const isValidPlatform = ( value: string | null ): value is (typeof PLATFORMS)[number] => !!value && (PLATFORMS as readonly string[]).includes(value); const [platform, setPlatform] = useState<(typeof PLATFORMS)[number]>(() => { if (typeof window === "undefined") return "AR-15"; const initial = new URLSearchParams(window.location.search).get("platform"); return isValidPlatform(initial) ? initial : "AR-15"; }); const [build, setBuild] = useState(() => { if (typeof window !== "undefined") { const stored = localStorage.getItem(STORAGE_KEY); if (stored) { try { return JSON.parse(stored); } catch { return {}; } } } return {}; }); const [shareStatus, setShareStatus] = useState(null); const [shareUrl, setShareUrl] = useState(""); useEffect(() => { const controller = new AbortController(); async function fetchProducts() { try { setLoading(true); setError(null); // 1) Platform-scoped products const scopedUrl = `${API_BASE_URL}/api/products?platform=${encodeURIComponent( platform )}`; // 2) Universal products (no platform filter) // NOTE: This assumes your backend supports /api/products with no platform param. // If it doesn't yet, this call will fail quietly and you'll still see scoped results. const universalUrl = `${API_BASE_URL}/api/products`; const [scopedRes, universalRes] = await Promise.all([ fetch(scopedUrl, { signal: controller.signal }), fetch(universalUrl, { signal: controller.signal }).catch( () => null as any ), ]); if (!scopedRes || !scopedRes.ok) { const status = scopedRes?.status ?? ""; throw new Error(`Failed to load products (${status})`); } const scopedData: GunbuilderProductFromApi[] = await scopedRes.json(); let universalData: GunbuilderProductFromApi[] = []; if (universalRes && universalRes.ok) { universalData = await universalRes.json(); } // Normalize both lists const normalize = (data: GunbuilderProductFromApi[]): Part[] => data .map((p): Part | null => { const normalizedRole = (p.partRole ?? "") .trim() .toLowerCase() .replace(/_/g, "-"); const categoryId = PART_ROLE_TO_CATEGORY[normalizedRole]; if (!categoryId) return null; // Only keep truly-universal categories from the universal feed // so we don't accidentally mix platforms for platform-scoped parts. if ( data === universalData && !UNIVERSAL_CATEGORIES.has(categoryId) ) { return null; } const buyUrl = p.buyUrl ?? undefined; return { id: String(p.id), categoryId, name: p.name, brand: p.brand, price: p.price ?? 0, imageUrl: p.mainImageUrl ?? undefined, affiliateUrl: buyUrl, url: buyUrl, notes: undefined, }; }) .filter((p): p is Part => p !== null); const scopedParts = normalize(scopedData); const universalParts = normalize(universalData); // Merge + de-dupe by (categoryId + id) const seen = new Set(); const merged: Part[] = []; for (const p of [...scopedParts, ...universalParts]) { const key = `${p.categoryId}:${p.id}`; if (seen.has(key)) continue; seen.add(key); merged.push(p); } setParts(merged); } catch (err: any) { if (err?.name === "AbortError") return; setError(err?.message ?? "Failed to load products"); } finally { setLoading(false); } } fetchProducts(); return () => controller.abort(); }, [platform]); useEffect(() => { // When the platform changes, clear ONLY platform-scoped selections. // Keep universal accessories (optic/light/sling/etc) so the user doesn't lose them. setBuild((prev) => { const next: BuildState = {}; for (const [categoryId, partId] of Object.entries(prev)) { const cid = categoryId as CategoryId; if (UNIVERSAL_CATEGORIES.has(cid)) { next[cid] = partId; } } return next; }); }, [platform]); // Handle URL query parameter for part selection (?select=upper:165) useEffect(() => { const selectParam = searchParams.get("select"); if (selectParam) { const [categoryId, partId] = selectParam.split(":"); if (categoryId && partId && CATEGORIES.some((c) => c.id === categoryId)) { setBuild((prev) => { const updated = { ...prev, [categoryId as CategoryId]: partId, }; if (typeof window !== "undefined") { localStorage.setItem(STORAGE_KEY, JSON.stringify(updated)); } return updated; }); const qp = searchParams.get("platform"); const nextPlatform = isValidPlatform(qp) ? qp : platform; router.replace( `/builder?platform=${encodeURIComponent(nextPlatform)}`, { scroll: false, } ); } } }, [searchParams, router]); useEffect(() => { const qp = searchParams.get("platform"); if (isValidPlatform(qp) && qp !== platform) { setPlatform(qp); } }, [searchParams, platform]); // Persist build state to localStorage whenever it changes useEffect(() => { if (typeof window !== "undefined") { localStorage.setItem(STORAGE_KEY, JSON.stringify(build)); } }, [build]); const partsByCategory: Record = useMemo(() => { const grouped = {} as Record; for (const category of CATEGORIES) { grouped[category.id] = parts.filter((p) => p.categoryId === category.id); } return grouped; }, [parts]); const selectedParts: Part[] = useMemo(() => { return Object.entries(build) .map(([categoryId, partId]) => parts.find((p) => p.id === partId && p.categoryId === categoryId) ) .filter(Boolean) as Part[]; }, [build, parts]); const selectedByCategory: Record = useMemo( () => Object.fromEntries( Object.entries(build).map(([categoryId, partId]) => [ categoryId as CategoryId, partId ? true : false, ]) ) as Record, [build] ); const totalPrice = useMemo( () => selectedParts.reduce((sum, p) => sum + p.price, 0), [selectedParts] ); useEffect(() => { if (typeof window === "undefined") return; // If no parts selected, clear the share URL if (Object.keys(build).length === 0) { setShareUrl(""); return; } try { const payload = JSON.stringify(build); const encoded = window.btoa(payload); const origin = window.location?.origin ?? ""; const url = `${origin}/builder/build?build=${encodeURIComponent( encoded )}`; setShareUrl(url); } catch { setShareUrl(""); } }, [build]); const handleSelectPart = (categoryId: CategoryId, partId: string) => { setBuild((prev) => { const updated = { ...prev, [categoryId]: partId, }; if (typeof window !== "undefined") { localStorage.setItem(STORAGE_KEY, JSON.stringify(updated)); } return updated; }); }; // Use group ordering for the summary as well const summaryCategoryOrder: CategoryId[] = useMemo( () => CATEGORY_GROUPS.flatMap((group) => group.categoryIds).filter((id) => CATEGORIES.some((c) => c.id === id) ), [] ); const handleShare = async () => { if (selectedParts.length === 0) { setShareStatus("Add a few parts before sharing your build."); return; } const lines: string[] = []; lines.push("B Build"); lines.push(""); lines.push(`Total: $${totalPrice.toFixed(2)}`); lines.push(""); summaryCategoryOrder.forEach((categoryId) => { const cat = CATEGORIES.find((c) => c.id === categoryId); if (!cat) return; const selectedPartId = build[cat.id]; const part = parts.find( (p) => p.id === selectedPartId && p.categoryId === cat.id ); if (part) { lines.push( `${cat.name}: ${part.brand} — ${part.name} ($${part.price.toFixed( 2 )})` ); } else { lines.push(`${cat.name}: [Not selected]`); } }); const text = lines.join("\n"); try { await navigator.clipboard.writeText(text); setShareStatus("Build summary copied to clipboard."); } catch { setShareStatus( "Could not access clipboard. You can copy from the build summary page." ); } }; const handleCopyLink = async () => { if (!shareUrl) { setShareStatus("No shareable link available yet."); return; } try { await navigator.clipboard.writeText(shareUrl); setShareStatus("Shareable link copied to clipboard."); } catch { setShareStatus("Could not copy link to clipboard."); } }; const handleNativeShare = async () => { if (!shareUrl) { setShareStatus("No shareable link available yet."); return; } if (navigator.share) { try { await navigator.share({ title: "Shadow Standard — The Armory Build", text: "Check out my Shadow Standard Armory build.", url: shareUrl, }); setShareStatus("Share dialog opened."); } catch { // User canceled or share failed; keep it quiet but let them know setShareStatus( "Share canceled or unavailable. You can copy the link instead." ); } } else { // Fallback to copying the link await handleCopyLink(); } }; return (
{/* Header */}

BATTL BUILDERS

BattlBuilder Early Access

Explore components from trusted brands, choose one part per category, track live prices, and watch your total build cost update as you go. This early-access builder keeps your setup saved locally so you can come back and refine it anytime.

Parts list updates automatically when you change platforms.

{/* Build summary panel */}
{/* Left: title + totals + primary actions */}

My Build Breakdown

Current build total
${totalPrice.toFixed(2)}
{selectedParts.length} / {CATEGORIES.length} categories filled
{/* Primary actions now live under the total */}
Build Summary
{/* Right: Share Your Build */}
{selectedParts.length > 0 && shareUrl && (

Share Your Build

Share this link to let others view your build or bookmark it to come back later.

Shareable URL
)} {shareStatus && (

{shareStatus}

)}
{/* Build status strip */}

Build Status (Needs Refined)

{BUILDER_SLOTS.map((slot) => { const satisfied = isSlotSatisfied(slot, selectedByCategory); return (
{satisfied ? ( ) : ( )} {slot.label}
); })}
{/* Layout */}

Work top-down through the major sections. Each row shows your current pick for that part type, with price and a direct buy link—or a quick way to choose a part if you haven't picked one yet.

{loading && (

Loading parts from backend…

)} {error && !loading && (

{error} — check that the Ballistic API is running and CORS is configured.

)} {!loading && !error && (
{CATEGORY_GROUPS.map((group) => { const groupCategories = CATEGORIES.filter((c) => group.categoryIds.includes(c.id as CategoryId) ); if (groupCategories.length === 0) { return null; } return (

{group.label}

{group.description && (

{group.description}

)}
{groupCategories.map((category) => { const categoryParts = partsByCategory[category.id] ?? []; const selectedPartId = build[category.id]; const selectedPart = categoryParts.find( (p) => p.id === selectedPartId ); const hasParts = categoryParts.length > 0; return ( {/* Component / Part Type */} {/* Brand */} {/* Price */} {/* Sale Price (placeholder until we wire through sale/original) */} {/* Caliber (placeholder for now) */} {/* Buy / Choose */} ); })}
Component / Part Type Brand Price Sale Price Caliber Buy / Choose
{category.name}
{selectedPart ? (
{selectedPart.name}
) : hasParts ? (
No part selected
) : (
No parts available yet
)}
{selectedPart ? selectedPart.brand : "—"} {selectedPart ? `$${selectedPart.price.toFixed(2)}` : "—"} {/* TODO: wire in sale/original prices from backend */} {selectedPart ? "—" : "—"} {/* TODO: wire in caliber from ProductSummaryDto when available */} —
{selectedPart && selectedPart.url ? ( <> ) : hasParts ? ( Choose a Part ) : ( )}
); })}
)}
{/* What's New */}

What's New in Early Access

  • • Live parts and pricing pulled from multiple merchants.
  • • Grouped layout for lower and upper receiver parts so you can see at a glance which sections of your build are still missing.
  • • Running build total that updates automatically as you add or swap components.
  • • Local build persistence so your selections stick around between visits on this device.
{/* Roadmap */}

What's on our roadmap

  • • Platform filters (AR-15, AR-9, AR-10)
  • • More part categories and furniture
  • • Richer pricing/stock sync
  • • Smarter compatibility checks between components
  • • AR9/AR10 support and more
); }