"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 type { CategoryId, Part } from "@/types/gunbuilder"; import { PART_ROLE_TO_CATEGORY } from "@/data/partRoleMappings"; import { Pencil, Link2 } 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 API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080"; type BuildState = Partial>; // categoryId -> partId const STORAGE_KEY = "gunbuilder-build-state"; // 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", "completeLower", "lowerParts", "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", "completeUpper", "bcg", "barrel", "gasBlock", "gasTube", "muzzleDevice", "suppressor", "handguard", "chargingHandle", "sights", "optic", ], }, // Optional: future group for accessories/furniture if needed // { // id: "accessories-group", // label: "Accessories & Furniture", // description: "Optics, lights, slings, and other supporting gear.", // categoryIds: ["optic", "sights", ...] as CategoryId[], // }, ]; 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 [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); const res = await fetch( `${API_BASE_URL}/api/products/gunbuilder?platform=AR-15`, { signal: controller.signal }, ); if (!res.ok) { throw new Error(`Failed to load products (${res.status})`); } const data: GunbuilderProductFromApi[] = await res.json(); const normalized: Part[] = data .map((p): Part | null => { const categoryId = PART_ROLE_TO_CATEGORY[p.partRole]; if (!categoryId) { // Skip any parts we don't know how to map yet return null; } const buyUrl = p.buyUrl ?? undefined; return { id: String(p.id), // ALWAYS string categoryId, name: p.name, brand: p.brand, price: p.price ?? 0, imageUrl: p.mainImageUrl ?? undefined, affiliateUrl: buyUrl, // main link url: buyUrl, // 👈optional alias if you still reference .url. maybe pretty url? notes: undefined, }; }) .filter((p): p is Part => p !== null); setParts(normalized); } catch (err: any) { if (err.name === "AbortError") return; setError(err.message ?? "Failed to load products"); } finally { setLoading(false); } } fetchProducts(); return () => controller.abort(); }, []); // 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; }); router.replace("/builder", { scroll: false }); } } }, [searchParams, router]); // 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 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) => ({ ...prev, [categoryId]: partId, })); }; // 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("Shadow Standard — The Armory 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 */}

Shadow Standard Co.

The Build Bench: 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.

{/* 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}

)}
{/* 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 ? ( { // If you want to pre-select something later, you can handle here. }} > 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
); }