"use client"; import { useMemo, useState, useEffect, useCallback, useRef } 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 "@/lib/catalogMappings"; import { Pencil, X, Link2, Square, CheckSquare } from "lucide-react"; // ✅ Centralized overlap rules + helpers import OverlapChip from "@/components/builder/OverlapChip"; import { getOverlapChipsForCategory, getSelectionHints, type BuildState, } from "@/lib/buildOverlaps"; type GunbuilderProductFromApi = { id: number; // backend numeric id name: string; brand: string; platform: string; partRole: string; price: number | null; imageUrl: 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"; 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-receiver", "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-receiver", "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(""); // Guards so “platform change clears build” does NOT run on initial hydration / URL sync. const didHydrateRef = useRef(false); const lastPlatformRef = useRef(platform); // ✅ Guard to prevent infinite loops when processing ?select / ?remove const processedActionKeyRef = useRef(""); // ---------- Derived ---------- 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(() => { const seen = new Set(); const resolved = Object.values(build) .map((partId) => partId ? parts.find((p) => p.id === partId) : undefined ) .filter(Boolean) as Part[]; return resolved.filter((p) => { if (seen.has(p.id)) return false; seen.add(p.id); return true; }); }, [build, parts]); // Role -> Category resolver // NOTE: defensive while backend roles/mappings evolve const resolveCategoryId = (normalizedRole: string): CategoryId | null => { if (normalizedRole === "upper-receiver") return "upper-receiver"; if (normalizedRole.includes("complete-upper")) return "complete-upper"; if (normalizedRole === "lower-receiver") return "lower-receiver"; if (normalizedRole.includes("complete-lower")) return "complete-lower"; if (normalizedRole === "upper") return "upper-receiver"; if (normalizedRole === "lower") return "lower-receiver"; if (normalizedRole.includes("charging")) return "charging-handle"; if ( normalizedRole.includes("handguard") || (normalizedRole.includes("rail") && !normalizedRole.includes("rail-accessory")) ) return "handguard"; if ( normalizedRole.includes("bcg") || normalizedRole.includes("bolt-carrier") ) return "bcg"; if (normalizedRole.includes("barrel")) return "barrel"; if ( normalizedRole.includes("gas-block") || normalizedRole.includes("gasblock") ) return "gas-block"; if ( normalizedRole.includes("gas-tube") || normalizedRole.includes("gastube") ) return "gas-tube"; if ( normalizedRole.includes("muzzle") || normalizedRole.includes("flash") || normalizedRole.includes("brake") || normalizedRole.includes("comp") ) return "muzzle-device"; if (normalizedRole.includes("suppress")) return "suppressor"; if ( normalizedRole.includes("lower-parts") || normalizedRole.includes("lpk") ) return "lower-parts"; if (normalizedRole.includes("trigger")) return "trigger"; if (normalizedRole.includes("grip")) return "grip"; if (normalizedRole.includes("safety")) return "safety"; if (normalizedRole.includes("buffer")) return "buffer"; if (normalizedRole.includes("stock")) return "stock"; if (normalizedRole.includes("optic") || normalizedRole.includes("scope")) return "optic"; if (normalizedRole.includes("sight")) return "sights"; if (normalizedRole.includes("mag")) return "magazine"; if ( normalizedRole.includes("weapon-light") || (normalizedRole.includes("light") && !normalizedRole.includes("flight")) ) return "weapon-light"; if ( normalizedRole.includes("foregrip") || normalizedRole.includes("grip-vertical") ) return "foregrip"; if (normalizedRole.includes("bipod")) return "bipod"; if (normalizedRole.includes("sling")) return "sling"; if ( normalizedRole.includes("rail-accessory") || normalizedRole.includes("rail-attachment") ) return "rail-accessory"; if (normalizedRole.includes("tool")) return "tools"; return (PART_ROLE_TO_CATEGORY as any)[normalizedRole] ?? null; }; 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] ); const handleSelectPart = useCallback( (categoryId: CategoryId, partId: string, _opts?: { confirm?: boolean }) => { // NOTE: // - We DO NOT auto-remove any existing selections. // - We show subtle overlap guidance (chips + an optional “heads up” toast). const warn = (msg: string) => { setShareStatus(msg); window.setTimeout(() => setShareStatus(null), 4000); }; const hints = getSelectionHints(categoryId, build); if (hints.length > 0) warn(hints[0]); // ✅ Only set the selection. No deletes. No clearing. setBuild((prev) => ({ ...prev, [categoryId]: partId, })); }, [build] ); // ---------- Fetch products ---------- useEffect(() => { const controller = new AbortController(); async function fetchProducts() { try { setLoading(true); setError(null); const scopedUrl = `${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent( platform )}`; const universalUrl = `${API_BASE_URL}/api/v1/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(); } const normalize = (data: GunbuilderProductFromApi[]): Part[] => data .map((p): Part | null => { const normalizedRole = (p.partRole ?? "") .trim() .toLowerCase() .replace(/_/g, "-"); const categoryId = resolveCategoryId(normalizedRole); if (!categoryId) return null; 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 as any).imageUrl ?? (p as any).mainImageUrl ?? undefined, affiliateUrl: buyUrl, url: buyUrl, notes: undefined, }; }) .filter((p): p is Part => p !== null); const scopedParts = normalize(scopedData); const universalParts = normalize(universalData); 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]); // ✅ Persist build state whenever it changes useEffect(() => { if (typeof window === "undefined") return; try { localStorage.setItem(STORAGE_KEY, JSON.stringify(build)); } catch { // ignore } }, [build]); // When the platform changes, clear ONLY platform-scoped selections. useEffect(() => { const prev = lastPlatformRef.current; lastPlatformRef.current = platform; if (!didHydrateRef.current) { didHydrateRef.current = true; return; } if (prev === platform) return; setBuild((prevBuild) => { const next: BuildState = {}; for (const [categoryId, partId] of Object.entries(prevBuild)) { const cid = categoryId as CategoryId; if (UNIVERSAL_CATEGORIES.has(cid)) { next[cid] = partId; } } return next; }); }, [platform]); // Handle URL query parameters: // - ?select=categoryId:partId // - ?remove=categoryId useEffect(() => { const selectParam = searchParams.get("select"); const removeParam = searchParams.get("remove"); const qpPlatform = searchParams.get("platform"); const actionKey = `${selectParam ?? ""}|${removeParam ?? ""}|${ qpPlatform ?? "" }`; if (!selectParam && !removeParam) { processedActionKeyRef.current = ""; return; } if (processedActionKeyRef.current === actionKey) return; processedActionKeyRef.current = actionKey; if (selectParam) { const [categoryIdRaw, partId] = selectParam.split(":"); const requestedCategoryId = categoryIdRaw as CategoryId; if (requestedCategoryId && partId) { handleSelectPart(requestedCategoryId, partId, { confirm: false }); } } if (removeParam) { if (CATEGORIES.some((c) => c.id === removeParam)) { setBuild((prev) => { const next: BuildState = { ...prev }; delete next[removeParam as CategoryId]; return next; }); } } const nextPlatform = isValidPlatform(qpPlatform) ? qpPlatform : platform; const nextUrl = `/builder?platform=${encodeURIComponent(nextPlatform)}`; if (typeof window !== "undefined") { const current = `${window.location.pathname}${window.location.search}`; if (current !== nextUrl) { router.replace(nextUrl, { scroll: false }); } } else { router.replace(nextUrl, { scroll: false }); } }, [searchParams, router, platform, handleSelectPart]); // Keep platform in sync w/ URL useEffect(() => { const qp = searchParams.get("platform"); if (isValidPlatform(qp) && qp !== platform) { setPlatform(qp); } }, [searchParams, platform]); // Build share URL whenever build changes useEffect(() => { if (typeof window === "undefined") return; 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 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 { setShareStatus( "Share canceled or unavailable. You can copy the link instead." ); } } else { 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 */}

My Build Breakdown

Current build total
${totalPrice.toFixed(2)}
{selectedParts.length} / {CATEGORIES.length} categories filled
Build Summary
{/* Right */}
{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 = selectedPartId ? categoryParts.find( (p) => p.id === selectedPartId ) ?? parts.find((p) => p.id === selectedPartId) : undefined; const hasParts = categoryParts.length > 0; return ( {/* Component */} {/* Brand */} {/* Price */} {/* Sale price placeholder */} {/* Caliber placeholder */} {/* Actions */} ); })}
Component / Part Type Brand Price Sale Price Caliber Buy / Choose
{category.name}
{selectedPart ? ( <>
{selectedPart.name}
{/* ✅ Category overlap chips */}
{getOverlapChipsForCategory( category.id as CategoryId, build ).map((c) => ( ))}
) : hasParts ? (
No part selected
) : (
No parts available yet
)}
{selectedPart ? selectedPart.brand : "—"} {selectedPart ? `$${selectedPart.price.toFixed(2)}` : "—"}
{selectedPart && selectedPart.url ? ( <> ) : hasParts ? ( Choose ) : ( )}
); })}
)}
); }