// 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"; import { normalizePlatformKey } from "@/lib/platforms"; // 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 = ["AR15"] as const; // Disabling all other platforms for now // const PLATFORMS = ["AR15", "AR10", "AR9"] as const; const PLATFORM_LABEL: Record<(typeof PLATFORMS)[number], string> = { AR15: "AR-15", // AR10: "AR-10", // AR9: "AR-9", }; const isValidPlatform = ( value: string | null ): value is (typeof PLATFORMS)[number] => !!value && (PLATFORMS as readonly string[]).includes(value); 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", ], }, ]; // --- Quick Checklist (simple counters only) --- // Required: core rifle components (kept intentionally small + pragmatic) const QUICK_REQUIRED_IDS = new Set([ "lower-receiver", "complete-lower", "upper-receiver", "complete-upper", "barrel", "bcg", "charging-handle", "handguard", "gas-block", "gas-tube", "muzzle-device", "trigger", "grip", "safety-selector", "buffer", "stock", ]); // Optional: Accessories & Gear group (these are nice-to-haves) const QUICK_OPTIONAL_IDS = new Set( CATEGORY_GROUPS.find((g) => g.id === "accessories-group")?.categoryIds ?? [] ); function computeQuickChecklistCounts( build: BuildState, allowedIds: Set ) { // Only count IDs that exist in our known category universe. const requiredIds = Array.from(QUICK_REQUIRED_IDS).filter((id) => allowedIds.has(id) ); const optionalIds = Array.from(QUICK_OPTIONAL_IDS).filter((id) => allowedIds.has(id) ); const requiredDone = requiredIds.filter((id) => Boolean(build[id])).length; const optionalDone = optionalIds.filter((id) => Boolean(build[id])).length; return { requiredDone, requiredTotal: requiredIds.length, optionalDone, optionalTotal: optionalIds.length, }; } // Helper to normalize all build values to strings for strict comparison function normalizeBuildState(input: any): BuildState { if (!input || typeof input !== "object") return {}; const next: BuildState = {}; for (const [k, v] of Object.entries(input)) { if (v == null) continue; // force all ids to strings for consistent comparisons next[k as BuilderSlotKey] = String(v); } return next; } // --- Table nesting (OR paths) --- type TableRowKind = "note" | "category"; type TableRow = { key: string; kind: TableRowKind; label: string; categoryId?: BuilderSlotKey; indent?: 0 | 1 | 2; tone?: "muted" | "normal"; pill?: string; locked?: boolean; }; const LOWER_PATHS = { complete: "complete-lower" as BuilderSlotKey, builderRoot: "lower-receiver" as BuilderSlotKey, builderChildren: [ "lower-parts-kit", "trigger", "grip", "safety-selector", "buffer", "stock", ] as BuilderSlotKey[], }; const UPPER_PATHS = { complete: "complete-upper" as BuilderSlotKey, builderRoot: "upper-receiver" as BuilderSlotKey, builderChildren: [ "barrel", "bcg", "charging-handle", "handguard", "gas-block", "gas-tube", "muzzle-device", ] as BuilderSlotKey[], }; function getAssemblyMode( build: BuildState, paths: { complete: BuilderSlotKey; builderRoot: BuilderSlotKey } ) { const hasComplete = Boolean(build[paths.complete]); const hasBuilderRoot = Boolean(build[paths.builderRoot]); if (hasComplete) return "complete" as const; if (hasBuilderRoot) return "builder" as const; return "none" as const; } function buildAssemblyRows(params: { groupLabel: string; build: BuildState; allowedIds: Set; paths: { complete: BuilderSlotKey; builderRoot: BuilderSlotKey; builderChildren: BuilderSlotKey[]; }; }): TableRow[] { const { groupLabel, build, allowedIds, paths } = params; const mode = getAssemblyMode(build, paths); const rows: TableRow[] = []; rows.push({ key: `${groupLabel}-note`, kind: "note", label: `${groupLabel} (choose one path)`, tone: "muted", pill: "Complete OR Builder Path", }); if (allowedIds.has(paths.complete)) { rows.push({ key: `${groupLabel}-${paths.complete}`, kind: "category", label: "Complete Assembly (Fastest)", categoryId: paths.complete, indent: 0, pill: mode === "complete" ? "Selected" : undefined, }); } if (allowedIds.has(paths.builderRoot)) { rows.push({ key: `${groupLabel}-${paths.builderRoot}`, kind: "category", label: "Build From Parts (Stripped + LPK)", categoryId: paths.builderRoot, indent: 0, pill: mode === "builder" ? "Selected" : undefined, }); } const children = paths.builderChildren.filter((id) => allowedIds.has(id)); for (const cid of children) { rows.push({ key: `${groupLabel}-${cid}`, kind: "category", label: "", categoryId: cid, indent: 1, locked: mode === "complete", pill: mode === "builder" ? "required" : undefined, tone: mode === "complete" ? "muted" : "normal", }); } return rows; } 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(); const [platform, setPlatform] = useState<(typeof PLATFORMS)[number]>("AR15"); // Canonical, URL-safe platform (AR15 / AR10 / AR9) const canonicalPlatform = normalizePlatformKey(platform); // ----------------------------- // 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(false); const [error, setError] = useState(null); // ----------------------------- // Build state (categoryId -> productId), persisted locally // ----------------------------- const [build, setBuild] = useState({}); // Hydration guard: avoid SSR/CSR HTML mismatch (platform/build were previously derived from window/localStorage) const [isHydrated, setIsHydrated] = useState(false); useEffect(() => { if (typeof window === "undefined") return; // Hydrate persisted build state only. URL actions (platform/select/remove) // are handled by the dedicated useSearchParams effect later in this file. const stored = localStorage.getItem(STORAGE_KEY); if (stored) { try { const parsed = JSON.parse(stored); if (parsed && typeof parsed === "object") { setBuild(normalizeBuildState(parsed)); } } catch { // ignore } } // Signal that hydration is complete - this allows URL param processing to run setIsHydrated(true); }, []); 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 allowedCategoryIds = useMemo( () => new Set(CATEGORIES.map((c) => c.id as BuilderSlotKey)), [] ); const quickChecklist = useMemo( () => computeQuickChecklistCounts(build, allowedCategoryIds), [build, allowedCategoryIds] ); 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"; // 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"; // 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; }; // ----------------------------- // Hydrate selected parts (only) from backend // ----------------------------- const lastHydrateKeyRef = useRef(""); useEffect(() => { const controller = new AbortController(); async function hydrateSelected() { const ids = (Object.values(build).filter(Boolean) as string[]) .map(String) .sort(); const key = ids.join(","); // If nothing selected, reset if (ids.length === 0) { lastHydrateKeyRef.current = ""; setParts([]); setError(null); setLoading(false); return; } // Only skip if we *successfully* hydrated this key previously if (key === lastHydrateKeyRef.current) return; setLoading(true); setError(null); try { const res = await fetch( `${API_BASE_URL}/api/v1/catalog/products/by-ids`, { method: "POST", signal: controller.signal, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ids }), } ); if (!res.ok) throw new Error(`Failed to hydrate parts (${res.status})`); const data: GunbuilderProductFromApi[] = await res.json(); const byId = new Map(); for (const p of data) byId.set(String(p.id), p); const hydrated: Part[] = Object.entries(build) .filter(([, id]) => Boolean(id)) .map(([slot, id]) => { const p = byId.get(String(id)); if (!p) return null; const buyUrl = p.buyUrl ?? undefined; return { id: String(p.id), categoryId: slot as any, name: p.name, brand: p.brand, price: p.price ?? 0, imageUrl: p.imageUrl ?? undefined, affiliateUrl: buyUrl, url: buyUrl, } as Part; }) .filter((x): x is Part => x !== null); setParts(hydrated); // ✅ Mark key as hydrated ONLY after success lastHydrateKeyRef.current = key; } catch (err: any) { if (err?.name === "AbortError") { // ✅ Do NOT lock the key on abort; allow retry return; } setError(err?.message ?? "Failed to hydrate selected parts"); } finally { setLoading(false); } } hydrateSelected(); return () => controller.abort(); }, [build]); // ----------------------------- // Persist build to localStorage // ----------------------------- useEffect(() => { if (typeof window === "undefined") return; if (!isHydrated) return; try { localStorage.setItem(STORAGE_KEY, JSON.stringify(build)); } catch { // ignore } }, [build, isHydrated]); // ----------------------------- // 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 your Vault ✅ ", }); // 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) => { const next: BuildState = { ...prev, [categoryId]: String(partId), }; // Write-through so query-param selections survive Next/router replaces try { if (typeof window !== "undefined") { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } } catch { // ignore } return next; }); }, [build] ); // Handle URL query parameters (?select, ?remove) and keep platform synced + canonical useEffect(() => { if (!isHydrated) return; // Wait for initial hydration to complete const sp = new URLSearchParams(searchParams.toString()); const selectParam = sp.get("select"); const removeParam = sp.get("remove"); // Normalize platform from URL (AR-15 -> AR15) const qpPlatformRaw = sp.get("platform"); const qpPlatform = normalizePlatformKey(qpPlatformRaw ?? ""); // Decide canonical platform to use (URL if valid, else current state) const nextPlatform = isValidPlatform(qpPlatform) ? qpPlatform : platform; // Keep React state in sync (only when needed) if (isValidPlatform(qpPlatform) && qpPlatform !== platform) { setPlatform(qpPlatform); } // Prevent repeating select/remove actions const actionKey = `${selectParam ?? ""}|${ removeParam ?? "" }|${nextPlatform}`; const hasAction = !!selectParam || !!removeParam; if (hasAction) { if (processedActionKeyRef.current !== actionKey) { 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]; try { if (typeof window !== "undefined") { localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); } } catch { // ignore } return next; }); } } } } else { // no action params → allow future actions to run processedActionKeyRef.current = ""; } // Canonicalize URL: set platform to canonical key and remove action params const before = searchParams.toString(); sp.set("platform", nextPlatform); sp.delete("select"); sp.delete("remove"); const after = sp.toString(); if (after !== before) { // Delay replace one tick so state updates from select/remove are not lost // during RSC navigation / dev strict mode. window.setTimeout(() => { router.replace(`/builder?${after}`, { scroll: false }); }, 0); } }, [searchParams, router, platform, handleSelectPart, isHydrated]); // 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(); } }; if (!isHydrated) { return (
Loading builder…
); } 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" />