// app/(builder)/builder/page.tsx "use client"; /** * Battl Builder - Main builder page * * Key flows: * 1) Build selections are stored locally (localStorage) so users can come back. * 2) "Save As…" creates a NEW saved build in the user's Vault (server-side). * 3) Vault -> Builder loads builds via ?load= (also supports legacy ?build=). * * Notes for devs: * - We intentionally keep ONE save-to-vault handler: handleSaveAs() * - Toast is used for clear user feedback (save success/fail) * * Auth note: * - /api/v1/builds/me/* requires JWT. * - The builder can render before AuthContext hydrates from localStorage, so we * guard “load build” calls until auth is ready to avoid a 401. */ import { useMemo, useState, useEffect, useCallback, useRef } from "react"; import Link from "next/link"; import { useSearchParams, useRouter } from "next/navigation"; import { X, Link2, Square, CheckSquare } from "lucide-react"; import { useApi } from "@/lib/api"; import { useAuth } from "@/context/AuthContext"; import { CATEGORIES } from "@/data/gunbuilderParts"; import { BUILDER_SLOTS, isSlotSatisfied } from "@/data/builderSlots"; import type { BuilderSlotKey, Part } from "@/types/builderSlots"; import { PART_ROLE_TO_CATEGORY } from "@/lib/catalogMappings"; // ✅ 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 isUuid = (v: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test( v ); 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: BuilderSlotKey[]; }[] = [ { 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-kit", "trigger", "grip", "safety-selector", "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 api = useApi(); // ✅ Auth: we need the token ready before calling /builds/me/* const { token, loading: authLoading, getAuthHeaders } = useAuth(); // ----------------------------- // Save As… modal state (Vault variants) // ----------------------------- const [saveAsOpen, setSaveAsOpen] = useState(false); const [saveAsTitle, setSaveAsTitle] = useState(""); const [saveAsDesc, setSaveAsDesc] = useState(""); const [saveAsSaving, setSaveAsSaving] = useState(false); // prevents double-submit // ----------------------------- // Parts data state // ----------------------------- const [parts, setParts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // ----------------------------- // Platform state (AR-15/AR-10/AR-9) // ----------------------------- 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"; }); // ----------------------------- // Build state (categoryId -> productId), persisted locally // ----------------------------- const [build, setBuild] = useState(() => { if (typeof window !== "undefined") { const stored = localStorage.getItem(STORAGE_KEY); if (stored) { try { return JSON.parse(stored); } catch { return {}; } } } return {}; }); type PageResponse = { content: T[]; totalElements?: number; totalPages?: number; number?: number; size?: number; }; function unwrapPage(json: any): T[] { if (!json) return []; if (Array.isArray(json)) return json; if (Array.isArray(json.content)) return json.content; return []; } // ----------------------------- // Toast notifications (save success / errors) // ----------------------------- type Toast = { type: "success" | "error" | "info"; message: string }; const [toast, setToast] = useState(null); const showToast = useCallback((t: Toast) => { setToast(t); window.setTimeout(() => setToast(null), 3500); }, []); // ----------------------------- // Misc UI state // ----------------------------- 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 collections // ----------------------------- 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]); const selectedByCategory: Record = useMemo( () => Object.fromEntries( Object.entries(build).map(([categoryId, partId]) => [ categoryId as BuilderSlotKey, partId ? true : false, ]) ) as Record, [build] ); const totalPrice = useMemo( () => selectedParts.reduce((sum, p) => sum + p.price, 0), [selectedParts] ); // ----------------------------- // Role -> Category resolver // NOTE: defensive while backend roles/mappings evolve // ----------------------------- const resolveCategoryId = (normalizedRole: string): BuilderSlotKey | 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"; // ✅ FIX: Lower Parts Kit canonical key if ( normalizedRole.includes("lower-parts") || normalizedRole.includes("lpk") ) return "lower-parts-kit"; if (normalizedRole.includes("trigger")) return "trigger"; if (normalizedRole.includes("grip")) return "grip"; // ✅ FIX: Safety canonical key if ( normalizedRole.includes("safety") || normalizedRole.includes("selector") ) return "safety-selector"; 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; }; // ----------------------------- // Fetch products (scoped + universal merge) // ----------------------------- useEffect(() => { const controller = new AbortController(); async function fetchProducts() { try { setLoading(true); setError(null); const size = 2000; // temporary "big bucket" until we optimize const scopedUrl = `${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent( platform )}&page=0&size=${size}`; const universalUrl = `${API_BASE_URL}/api/v1/products?page=0&size=${size}`; 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 scopedJson = await scopedRes.json(); const scopedData: GunbuilderProductFromApi[] = unwrapPage(scopedJson); let universalData: GunbuilderProductFromApi[] = []; if (universalRes && universalRes.ok) { const universalJson = await universalRes.json(); universalData = unwrapPage(universalJson); } 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; // Only accept universal fetch results for "universal" categories 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); // Merge (avoid duplicates across calls) 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 to localStorage // ----------------------------- useEffect(() => { if (typeof window === "undefined") return; try { localStorage.setItem(STORAGE_KEY, JSON.stringify(build)); } catch { // ignore } }, [build]); // ----------------------------- // When 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 BuilderSlotKey; if (UNIVERSAL_CATEGORIES.has(cid)) { next[cid] = partId; } } return next; }); }, [platform]); // ----------------------------- // Load a saved build from Vault via ?load= OR legacy ?build= // ----------------------------- useEffect(() => { const loadUuid = searchParams.get("load"); const buildParam = searchParams.get("build"); const uuidToLoad = (loadUuid && isUuid(loadUuid) ? loadUuid : null) || (buildParam && isUuid(buildParam) ? buildParam : null); if (!uuidToLoad) return; // ✅ Wait for AuthProvider hydration before calling /me endpoints. if (authLoading) return; // ✅ If not logged in, don't spam the backend; show a helpful message instead. if (!token) { setShareStatus("Please log in to load builds from your Vault."); window.setTimeout(() => setShareStatus(null), 4500); return; } const run = async () => { try { setShareStatus("Loading build…"); // NOTE: using fetch here avoids any “stale api instance” issues and lets us // explicitly attach JWT headers. const res = await fetch( `${API_BASE_URL}/api/v1/builds/me/${encodeURIComponent(uuidToLoad)}`, { headers: { "Content-Type": "application/json", ...getAuthHeaders(), }, } ); if (!res.ok) { const txt = await res.text().catch(() => ""); throw new Error(`Load failed (${res.status}) ${txt}`); } const dto = await res.json(); // BuildDto w/ items const nextBuild: Record = {}; for (const it of dto.items ?? []) { if (!it?.slot || !it?.productId) continue; nextBuild[it.slot] = String(it.productId); } setBuild(nextBuild); setShareStatus(`Loaded: ${dto.title}`); // Clean URL so refresh doesn't re-load repeatedly const qp = new URLSearchParams(searchParams.toString()); qp.delete("load"); if (buildParam && isUuid(buildParam)) qp.delete("build"); const next = qp.toString(); router.replace(next ? `/builder?${next}` : "/builder", { scroll: false, }); } catch (e: any) { setShareStatus(e?.message ?? "Failed to load build"); } finally { window.setTimeout(() => setShareStatus(null), 4500); } }; run(); }, [ searchParams, router, authLoading, token, getAuthHeaders, // API_BASE_URL is a module constant; no need to include ]); // ----------------------------- // SAVE AS… (single source of truth for saving to Vault) // - Creates a NEW saved build server-side // - Shows toast so users know it worked // ----------------------------- const handleSaveAs = async () => { if (selectedParts.length === 0) { showToast({ type: "error", message: "Add a few parts before saving." }); return; } const title = (saveAsTitle || `${platform} Build`).trim(); if (!title) { showToast({ type: "error", message: "Title is required." }); return; } const items = Object.entries(build) .filter(([, partId]) => !!partId) .map(([categoryId, partId]) => ({ productId: Number(partId), slot: categoryId, position: 0, quantity: 1, })); try { setSaveAsSaving(true); showToast({ type: "info", message: "Saving build…" }); const res = await api.post("/api/v1/builds/me", { title, description: saveAsDesc?.trim() || null, isPublic: false, items, }); if (!res.ok) { const txt = await res.text().catch(() => ""); throw new Error(txt || `Save failed (${res.status})`); } const saved = await res.json(); // BuildDto (expects { uuid, ... }) // UX: copy UUID for quick testing + user confidence try { if (saved?.uuid) await navigator.clipboard.writeText(saved.uuid); } catch { // ignore clipboard failures } showToast({ type: "success", message: "Saved to Vault ✅ (UUID copied)", }); // Close modal + reset inputs for next variant setSaveAsOpen(false); setSaveAsTitle(""); setSaveAsDesc(""); } catch (e: any) { showToast({ type: "error", message: e?.message ?? "Save failed", }); } finally { setSaveAsSaving(false); } }; // ----------------------------- // Selection handler (with hint warnings) // ----------------------------- const handleSelectPart = useCallback( ( categoryId: BuilderSlotKey, partId: string, _opts?: { confirm?: boolean } ) => { const warn = (msg: string) => { setShareStatus(msg); window.setTimeout(() => setShareStatus(null), 4000); }; const hints = getSelectionHints(categoryId, build); if (hints.length > 0) warn(hints[0]); setBuild((prev) => ({ ...prev, [categoryId]: partId, })); }, [build] ); // ----------------------------- // 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 BuilderSlotKey; 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 BuilderSlotKey]; return next; }); } } const nextPlatform = isValidPlatform(qpPlatform) ? qpPlatform : platform; // Keep URL clean/stable 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 (client-side only) 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: BuilderSlotKey[] = useMemo( () => CATEGORY_GROUPS.flatMap((group) => group.categoryIds).filter((id) => CATEGORIES.some((c) => c.id === id) ), [] ); // Copy summary text to clipboard const handleShare = async () => { if (selectedParts.length === 0) { setShareStatus("Add a few parts before sharing your build."); return; } const lines: string[] = []; lines.push("Battl 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: "BATTL — The Builder", text: "Check out my Battl Build.", url: shareUrl, }); setShareStatus("Share dialog opened."); } catch { setShareStatus( "Share canceled or unavailable. You can copy the link instead." ); } } else { await handleCopyLink(); } }; return (
{/* Toast (top-right) */} {toast && (
{toast.message}
)} {/* Save As… Modal */} {saveAsOpen && (
Save As…
Create a new saved build variant in your Vault.
setSaveAsTitle(e.target.value)} placeholder={`e.g. "${platform} Mk2 (Suppressed)"`} className="mt-1 w-full rounded-md border border-white/10 bg-black/30 px-3 py-2 text-sm text-white outline-none focus:ring-1 focus:ring-amber-400/60" />