wired up an accounts page and my builds (my vault)
This commit is contained in:
@@ -1 +0,0 @@
|
||||
<main className="min-h-screen bg-white text-zinc-900 dark:bg-black dark:text-zinc-50">
|
||||
@@ -1,482 +0,0 @@
|
||||
//
|
||||
// This page is most likely temporary. We probably do not need this page
|
||||
//
|
||||
//
|
||||
//
|
||||
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } 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 {
|
||||
Pencil,
|
||||
Link2,
|
||||
Square,
|
||||
CheckSquare,
|
||||
} from "lucide-react";
|
||||
|
||||
const API_BASE_URL =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
|
||||
|
||||
const STORAGE_KEY = "gunbuilder-build-state";
|
||||
|
||||
type BuildState = Partial<Record<CategoryId, string>>;
|
||||
|
||||
type GunbuilderProductFromApi = {
|
||||
id: number;
|
||||
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 UNIVERSAL_CATEGORIES = new Set<CategoryId>([
|
||||
"magazine",
|
||||
"weapon-light",
|
||||
"foregrip",
|
||||
"bipod",
|
||||
"sling",
|
||||
"rail-accessory",
|
||||
"tools",
|
||||
"optic",
|
||||
"sights",
|
||||
]);
|
||||
|
||||
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",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
function isValidPlatform(
|
||||
value: string | null
|
||||
): value is (typeof PLATFORMS)[number] {
|
||||
return !!value && (PLATFORMS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
function safeDecodeBuildParam(buildParam: string | null): BuildState | null {
|
||||
if (!buildParam) return null;
|
||||
|
||||
try {
|
||||
// build param is base64(json)
|
||||
const json = window.atob(buildParam);
|
||||
const parsed = JSON.parse(json) as BuildState;
|
||||
return parsed && typeof parsed === "object" ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function formatPrice(n: number) {
|
||||
return `$${n.toFixed(2)}`;
|
||||
}
|
||||
|
||||
export default function BuildSummaryPage() {
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
|
||||
const qpPlatform = searchParams.get("platform");
|
||||
const platform = isValidPlatform(qpPlatform) ? qpPlatform : "AR-15";
|
||||
|
||||
const [build, setBuild] = useState<BuildState>({});
|
||||
const [parts, setParts] = useState<Part[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Load build from ?build=... OR localStorage
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const buildParam = searchParams.get("build");
|
||||
const decoded = safeDecodeBuildParam(buildParam);
|
||||
|
||||
if (decoded) {
|
||||
setBuild(decoded);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
setBuild(stored ? (JSON.parse(stored) as BuildState) : {});
|
||||
} catch {
|
||||
setBuild({});
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// Fetch product data so we can resolve ids -> Part info
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
async function fetchProducts() {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
// scoped (platform)
|
||||
const scopedUrl = `${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent(
|
||||
platform
|
||||
)}`;
|
||||
|
||||
// universal (optional)
|
||||
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) {
|
||||
throw new Error(`Failed to load products (${scopedRes?.status ?? ""})`);
|
||||
}
|
||||
|
||||
const scopedData: GunbuilderProductFromApi[] = await scopedRes.json();
|
||||
|
||||
let universalData: GunbuilderProductFromApi[] = [];
|
||||
if (universalRes && universalRes.ok) {
|
||||
universalData = await universalRes.json();
|
||||
}
|
||||
|
||||
// NOTE: We only need enough to render the summary.
|
||||
// We will map “everything we can” and ignore unknown categories.
|
||||
const toCategoryId = (rawRole: string): CategoryId | null => {
|
||||
const role = (rawRole ?? "").trim().toLowerCase().replace(/_/g, "-");
|
||||
|
||||
// quick defensive mapping (mirrors your builder page strategy)
|
||||
if (role.includes("complete-upper")) return "complete-upper";
|
||||
if (role.includes("complete-lower")) return "complete-lower";
|
||||
if (role === "upper-receiver" || role === "upper") return "upper-receiver";
|
||||
if (role === "lower-receiver" || role === "lower") return "lower-receiver";
|
||||
if (role.includes("charging")) return "charging-handle";
|
||||
if (role.includes("handguard")) return "handguard";
|
||||
if (role.includes("bcg") || role.includes("bolt-carrier")) return "bcg";
|
||||
if (role.includes("barrel")) return "barrel";
|
||||
if (role.includes("gas-block") || role.includes("gasblock")) return "gas-block";
|
||||
if (role.includes("gas-tube") || role.includes("gastube")) return "gas-tube";
|
||||
if (role.includes("muzzle") || role.includes("flash") || role.includes("brake") || role.includes("comp"))
|
||||
return "muzzle-device";
|
||||
if (role.includes("suppress")) return "suppressor";
|
||||
if (role.includes("lower-parts") || role.includes("lpk")) return "lower-parts";
|
||||
if (role.includes("trigger")) return "trigger";
|
||||
if (role.includes("grip")) return "grip";
|
||||
if (role.includes("safety")) return "safety";
|
||||
if (role.includes("buffer")) return "buffer";
|
||||
if (role.includes("stock")) return "stock";
|
||||
if (role.includes("optic") || role.includes("scope")) return "optic";
|
||||
if (role.includes("sight")) return "sights";
|
||||
if (role.includes("mag")) return "magazine";
|
||||
if (role.includes("weapon-light") || (role.includes("light") && !role.includes("flight")))
|
||||
return "weapon-light";
|
||||
if (role.includes("foregrip") || role.includes("grip-vertical")) return "foregrip";
|
||||
if (role.includes("bipod")) return "bipod";
|
||||
if (role.includes("sling")) return "sling";
|
||||
if (role.includes("rail-accessory") || role.includes("rail-attachment")) return "rail-accessory";
|
||||
if (role.includes("tool")) return "tools";
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const normalize = (data: GunbuilderProductFromApi[], isUniversal: boolean): Part[] =>
|
||||
data
|
||||
.map((p): Part | null => {
|
||||
const categoryId = toCategoryId(p.partRole);
|
||||
if (!categoryId) return null;
|
||||
|
||||
if (isUniversal && !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.imageUrl as any) ?? (p as any).mainImageUrl ?? undefined,
|
||||
affiliateUrl: buyUrl,
|
||||
url: buyUrl,
|
||||
notes: undefined,
|
||||
};
|
||||
})
|
||||
.filter((p): p is Part => p !== null);
|
||||
|
||||
const scopedParts = normalize(scopedData, false);
|
||||
const universalParts = normalize(universalData, true);
|
||||
|
||||
const seen = new Set<string>();
|
||||
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]);
|
||||
|
||||
const summaryCategoryOrder: CategoryId[] = useMemo(
|
||||
() =>
|
||||
CATEGORY_GROUPS.flatMap((g) => g.categoryIds).filter((id) =>
|
||||
CATEGORIES.some((c) => c.id === id)
|
||||
),
|
||||
[]
|
||||
);
|
||||
|
||||
const selectedParts = useMemo(() => {
|
||||
const out: { categoryId: CategoryId; part?: Part }[] = [];
|
||||
for (const cid of summaryCategoryOrder) {
|
||||
const partId = build[cid];
|
||||
const part = partId ? parts.find((p) => p.id === partId && p.categoryId === cid) : undefined;
|
||||
out.push({ categoryId: cid, part });
|
||||
}
|
||||
return out;
|
||||
}, [build, parts, summaryCategoryOrder]);
|
||||
|
||||
const total = useMemo(
|
||||
() => selectedParts.reduce((sum, row) => sum + (row.part?.price ?? 0), 0),
|
||||
[selectedParts]
|
||||
);
|
||||
|
||||
const filledCount = useMemo(
|
||||
() => selectedParts.filter((r) => !!r.part).length,
|
||||
[selectedParts]
|
||||
);
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-white text-zinc-900 dark:bg-black dark:text-zinc-50">
|
||||
<div className="mx-auto max-w-6xl px-4 py-6 lg:py-10">
|
||||
{/* Header */}
|
||||
<header className="mb-6">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500">
|
||||
BATTL BUILDERS
|
||||
</p>
|
||||
<h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight">
|
||||
Build <span className="text-amber-300">Summary</span>
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-zinc-400 max-w-2xl">
|
||||
Snapshot of your current selections. (V1: data resolves from your local build state + live products.)
|
||||
</p>
|
||||
<div className="mt-3 text-xs text-zinc-500">
|
||||
Platform: <span className="text-zinc-200 font-semibold">{platform}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-end gap-2">
|
||||
<div className="text-right">
|
||||
<div className="text-[10px] uppercase tracking-[0.16em] text-zinc-500">
|
||||
Total
|
||||
</div>
|
||||
<div className="text-2xl font-semibold text-amber-300">
|
||||
{formatPrice(total)}
|
||||
</div>
|
||||
<div className="text-xs text-zinc-500 mt-1">
|
||||
{filledCount} / {summaryCategoryOrder.length} selected
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const qp = new URLSearchParams();
|
||||
qp.set("platform", platform);
|
||||
router.push(`/builder?${qp.toString()}`);
|
||||
}}
|
||||
className="rounded-md border border-zinc-700 bg-zinc-900/70 px-3 py-2 text-xs font-semibold text-zinc-200 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
|
||||
>
|
||||
Back to Builder
|
||||
</button>
|
||||
|
||||
<Link
|
||||
href={{ pathname: "/builder", query: platform ? { platform } : {} }}
|
||||
className="rounded-md bg-amber-400 px-3 py-2 text-xs font-semibold text-black hover:bg-amber-300 transition-colors"
|
||||
>
|
||||
Edit Build
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Body */}
|
||||
<section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-4 md:p-6">
|
||||
{loading ? (
|
||||
<p className="py-10 text-center text-sm text-zinc-500">Loading…</p>
|
||||
) : error ? (
|
||||
<p className="py-10 text-center text-sm text-red-400">
|
||||
{error} — check that the Ballistic API is running.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{CATEGORY_GROUPS.map((group) => {
|
||||
const rows = group.categoryIds
|
||||
.filter((cid) => summaryCategoryOrder.includes(cid))
|
||||
.map((cid) => {
|
||||
const cat = CATEGORIES.find((c) => c.id === cid);
|
||||
const partId = build[cid];
|
||||
const part = partId
|
||||
? parts.find((p) => p.id === partId && p.categoryId === cid)
|
||||
: undefined;
|
||||
return { cid, cat, part };
|
||||
});
|
||||
|
||||
return (
|
||||
<div key={group.id} className="rounded-md border border-zinc-800 bg-zinc-950/80">
|
||||
<div className="border-b border-zinc-800 px-4 py-3">
|
||||
<div className="text-sm font-semibold text-zinc-100">{group.label}</div>
|
||||
{group.description && (
|
||||
<div className="mt-1 text-xs text-zinc-500">{group.description}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="divide-y divide-zinc-900">
|
||||
{rows.map(({ cid, cat, part }) => (
|
||||
<div key={cid} className="flex items-start justify-between gap-4 px-4 py-3">
|
||||
<div className="min-w-0">
|
||||
<div className="text-xs font-semibold text-zinc-300">
|
||||
{cat?.name ?? cid}
|
||||
</div>
|
||||
{part ? (
|
||||
<div className="mt-1 text-sm text-zinc-100 truncate">
|
||||
<span className="text-zinc-400">{part.brand}</span>{" "}
|
||||
{part.name}
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-1 text-sm text-zinc-600">
|
||||
Not selected
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="shrink-0 text-right">
|
||||
<div className="text-xs text-zinc-500">Price</div>
|
||||
<div className={`text-sm font-semibold ${part ? "text-amber-300" : "text-zinc-600"}`}>
|
||||
{part ? formatPrice(part.price) : "—"}
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex justify-end gap-2">
|
||||
<Link
|
||||
href={{
|
||||
pathname: `/parts/p/${platform}/${cid}`,
|
||||
query: platform ? { platform } : {},
|
||||
}}
|
||||
className="inline-flex items-center justify-center rounded-md border border-zinc-700 bg-zinc-900/70 px-2.5 py-1.5 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
|
||||
title={part ? "Change part" : "Choose part"}
|
||||
aria-label={part ? "Change part" : "Choose part"}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5 text-zinc-300" />
|
||||
</Link>
|
||||
|
||||
{part?.url ? (
|
||||
<a
|
||||
href={part.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center justify-center rounded-md bg-amber-400 px-2.5 py-1.5 hover:bg-amber-300 transition-colors"
|
||||
title="Buy part"
|
||||
aria-label="Buy part"
|
||||
>
|
||||
<Link2 className="h-3.5 w-3.5 text-black" />
|
||||
</a>
|
||||
) : (
|
||||
<span className="inline-flex items-center justify-center rounded-md border border-zinc-800 bg-zinc-950 px-2.5 py-1.5 text-[11px] text-zinc-600">
|
||||
—
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<div className="mt-4 text-center text-xs text-zinc-600">
|
||||
Tip: If you landed here from a shared link, it uses <code>?build=</code> first; otherwise it reads your local build.
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+115
-26
@@ -1,3 +1,4 @@
|
||||
// app/(builder)/builder/page.tsx
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState, useEffect, useCallback, useRef } from "react";
|
||||
@@ -7,7 +8,7 @@ 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";
|
||||
import { X, Link2, Square, CheckSquare } from "lucide-react";
|
||||
|
||||
// ✅ Centralized overlap rules + helpers
|
||||
import OverlapChip from "@/components/builder/OverlapChip";
|
||||
@@ -288,10 +289,6 @@ export default function GunbuilderPage() {
|
||||
|
||||
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);
|
||||
@@ -300,7 +297,6 @@ export default function GunbuilderPage() {
|
||||
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,
|
||||
@@ -437,6 +433,54 @@ export default function GunbuilderPage() {
|
||||
});
|
||||
}, [platform]);
|
||||
|
||||
// ✅ Load a saved build from Vault via ?load=<uuid>
|
||||
useEffect(() => {
|
||||
const loadUuid = searchParams.get("load");
|
||||
if (!loadUuid) return;
|
||||
|
||||
const run = async () => {
|
||||
try {
|
||||
setShareStatus("Loading build…");
|
||||
|
||||
// NOTE: your backend GET route is /api/v1/products/builds/{uuid}
|
||||
const res = await fetch(
|
||||
`${API_BASE_URL}/api/v1/products/builds/${encodeURIComponent(
|
||||
loadUuid
|
||||
)}`,
|
||||
{ credentials: "include" }
|
||||
);
|
||||
|
||||
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<string, string> = {};
|
||||
|
||||
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 reload doesn't re-fetch
|
||||
const qp = new URLSearchParams(searchParams.toString());
|
||||
qp.delete("load");
|
||||
router.replace(`/builder?${qp.toString()}`, { scroll: false });
|
||||
} catch (e: any) {
|
||||
setShareStatus(e?.message ?? "Failed to load build");
|
||||
} finally {
|
||||
window.setTimeout(() => setShareStatus(null), 4500);
|
||||
}
|
||||
};
|
||||
|
||||
run();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [searchParams, router]);
|
||||
|
||||
// Handle URL query parameters:
|
||||
// - ?select=categoryId:partId
|
||||
// - ?remove=categoryId
|
||||
@@ -527,6 +571,53 @@ export default function GunbuilderPage() {
|
||||
[]
|
||||
);
|
||||
|
||||
// Handler to Save user build to account
|
||||
const handleSaveToAccount = async () => {
|
||||
if (selectedParts.length === 0) {
|
||||
setShareStatus("Add a few parts before saving.");
|
||||
return;
|
||||
}
|
||||
|
||||
const title = `${platform} Build`;
|
||||
|
||||
const items = Object.entries(build)
|
||||
.filter(([, partId]) => !!partId)
|
||||
.map(([categoryId, partId]) => ({
|
||||
productId: Number(partId),
|
||||
slot: categoryId,
|
||||
position: 0,
|
||||
quantity: 1,
|
||||
}));
|
||||
|
||||
try {
|
||||
setShareStatus("Saving build…");
|
||||
|
||||
const res = await fetch(`${API_BASE_URL}/api/v1/products/me/builds`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({
|
||||
title,
|
||||
description: null,
|
||||
isPublic: false,
|
||||
items,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const txt = await res.text().catch(() => "");
|
||||
throw new Error(`Save failed (${res.status}) ${txt}`);
|
||||
}
|
||||
|
||||
const saved = await res.json(); // BuildDto
|
||||
setShareStatus(`Saved! Build UUID: ${saved.uuid}`);
|
||||
} catch (e: any) {
|
||||
setShareStatus(e?.message ?? "Save failed");
|
||||
} finally {
|
||||
window.setTimeout(() => setShareStatus(null), 4500);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShare = async () => {
|
||||
if (selectedParts.length === 0) {
|
||||
setShareStatus("Add a few parts before sharing your build.");
|
||||
@@ -680,20 +771,6 @@ export default function GunbuilderPage() {
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex flex-col items-stretch gap-2 sm:flex-row sm:flex-wrap">
|
||||
<Link
|
||||
href={{
|
||||
pathname: "/builder/build",
|
||||
query: platform ? { platform } : {},
|
||||
}}
|
||||
className={`w-full sm:w-auto rounded-md border border-amber-400/60 bg-amber-400/10 px-3 py-2 text-sm font-medium text-amber-200 hover:bg-amber-400/15 text-center transition-colors ${
|
||||
selectedParts.length === 0
|
||||
? "opacity-40 cursor-not-allowed pointer-events-none"
|
||||
: ""
|
||||
}`}
|
||||
>
|
||||
Build Summary
|
||||
</Link>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleShare}
|
||||
@@ -724,6 +801,20 @@ export default function GunbuilderPage() {
|
||||
>
|
||||
Clear Build
|
||||
</button>
|
||||
|
||||
{/* Save Build */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSaveToAccount}
|
||||
disabled={selectedParts.length === 0}
|
||||
className={`w-full sm:w-auto rounded-md px-3 py-2 text-sm font-semibold transition-colors border ${
|
||||
selectedParts.length === 0
|
||||
? "bg-zinc-900/80 text-zinc-600 border-zinc-800 cursor-not-allowed"
|
||||
: "bg-amber-400 text-black border-amber-300 hover:bg-amber-300"
|
||||
}`}
|
||||
>
|
||||
Save Build
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -877,14 +968,12 @@ export default function GunbuilderPage() {
|
||||
|
||||
<tbody>
|
||||
{groupCategories.map((category) => {
|
||||
const categoryParts =
|
||||
partsByCategory[category.id] ?? [];
|
||||
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)
|
||||
? categoryParts.find((p) => p.id === selectedPartId) ??
|
||||
parts.find((p) => p.id === selectedPartId)
|
||||
: undefined;
|
||||
|
||||
const hasParts = categoryParts.length > 0;
|
||||
@@ -1031,4 +1120,4 @@ export default function GunbuilderPage() {
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,460 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useStat, 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 { buildDetailHref } from "@/app/parts/_components/buildDetailHref";
|
||||
|
||||
type BuildState = Partial<Record<CategoryId, string>>; // categoryId -> partId
|
||||
const STORAGE_KEY = "gunbuilder-build-state";
|
||||
|
||||
const API_BASE_URL =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
|
||||
|
||||
type GunbuilderProductFromApi = {
|
||||
id: string; // backend UUID string
|
||||
name: string;
|
||||
brand: string;
|
||||
platform: string;
|
||||
partRole: string;
|
||||
price: number | null;
|
||||
mainImageUrl: string | null;
|
||||
buyUrl: string | null;
|
||||
};
|
||||
|
||||
// Map backend partRole -> CategoryId (align with builder categories)
|
||||
const PART_ROLE_TO_CATEGORY: Record<string, CategoryId> = {
|
||||
"upper-receiver": "upper",
|
||||
barrel: "barrel",
|
||||
handguard: "handguard",
|
||||
"charging-handle": "chargingHandle",
|
||||
"buffer-kit": "buffer",
|
||||
"lower-parts-kit": "lowerParts",
|
||||
sight: "sights",
|
||||
};
|
||||
|
||||
// Inverse: CategoryId -> backend partRole (for building detail URLs)
|
||||
const CATEGORY_TO_PART_ROLE: Partial<Record<CategoryId, string>> =
|
||||
Object.fromEntries(
|
||||
Object.entries(PART_ROLE_TO_CATEGORY).map(([role, cat]) => [cat, role]),
|
||||
) as Partial<Record<CategoryId, string>>;
|
||||
|
||||
// Encode build state to URL-friendly string
|
||||
function encodeBuildState(build: BuildState): string {
|
||||
const entries = Object.entries(build)
|
||||
.filter(([_, partId]) => partId)
|
||||
.map(([categoryId, partId]) => `${categoryId}:${partId}`)
|
||||
.join(",");
|
||||
return btoa(entries);
|
||||
}
|
||||
|
||||
// Decode URL string to build state
|
||||
function decodeBuildState(encoded: string): BuildState {
|
||||
try {
|
||||
const decoded = atob(encoded);
|
||||
const build: BuildState = {};
|
||||
decoded.split(",").forEach((entry) => {
|
||||
const [categoryId, partId] = entry.split(":");
|
||||
if (categoryId && partId) {
|
||||
build[categoryId as CategoryId] = partId;
|
||||
}
|
||||
});
|
||||
return build;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export default function BuildDetailsPage() {
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
|
||||
// ✅ Option A: platform is a query param and is passed through to backend
|
||||
const platform = searchParams.get("platform") ?? "AR-15";
|
||||
|
||||
const [build, setBuild] = useState<BuildState>({});
|
||||
const [shareUrl, setShareUrl] = useState<string>("");
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const [parts, setParts] = useState<Part[]>([]);
|
||||
const [loadingParts, setLoadingParts] = useState(true);
|
||||
const [partsError, setPartsError] = useState<string | null>(null);
|
||||
|
||||
// Load build from URL params or localStorage
|
||||
useEffect(() => {
|
||||
const buildParam = searchParams.get("build");
|
||||
if (buildParam) {
|
||||
const decoded = decodeBuildState(buildParam);
|
||||
setBuild(decoded);
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(decoded));
|
||||
} catch {
|
||||
// ignore storage failures (private mode, etc.)
|
||||
}
|
||||
} else if (typeof window !== "undefined") {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored) {
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
setBuild(parsed);
|
||||
} catch {
|
||||
// ignore invalid stored data
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
// Fetch live parts from backend (uses selected platform)
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
async function fetchProducts() {
|
||||
try {
|
||||
setLoadingParts(true);
|
||||
setPartsError(null);
|
||||
|
||||
const res = await fetch(
|
||||
`${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent(platform)}`,
|
||||
{ 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) return null;
|
||||
|
||||
return {
|
||||
id: p.id,
|
||||
categoryId,
|
||||
name: p.name,
|
||||
brand: p.brand,
|
||||
price: p.price ?? 0,
|
||||
imageUrl: p.mainImageUrl ?? undefined,
|
||||
url: p.buyUrl ?? undefined,
|
||||
notes: undefined,
|
||||
};
|
||||
})
|
||||
.filter(Boolean) as Part[];
|
||||
|
||||
setParts(normalized);
|
||||
} catch (err: any) {
|
||||
if (err?.name === "AbortError") return;
|
||||
setPartsError(err?.message ?? "Failed to load products");
|
||||
} finally {
|
||||
setLoadingParts(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchProducts();
|
||||
return () => controller.abort();
|
||||
}, [platform]);
|
||||
|
||||
// Generate shareable URL (includes platform)
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined" && Object.keys(build).length > 0) {
|
||||
const encoded = encodeBuildState(build);
|
||||
const url = `${window.location.origin}/builder/build?platform=${encodeURIComponent(
|
||||
platform,
|
||||
)}&build=${encoded}`;
|
||||
setShareUrl(url);
|
||||
} else if (typeof window !== "undefined") {
|
||||
setShareUrl("");
|
||||
}
|
||||
}, [build, platform]);
|
||||
|
||||
const selectedParts: Part[] = useMemo(() => {
|
||||
if (parts.length === 0) return [];
|
||||
return Object.entries(build)
|
||||
.map(([categoryId, partId]) =>
|
||||
parts.find(
|
||||
(p) =>
|
||||
p.id === partId && p.categoryId === (categoryId as CategoryId),
|
||||
),
|
||||
)
|
||||
.filter(Boolean) as Part[];
|
||||
}, [build, parts]);
|
||||
|
||||
const totalPrice = useMemo(
|
||||
() => selectedParts.reduce((sum, p) => sum + p.price, 0),
|
||||
[selectedParts],
|
||||
);
|
||||
|
||||
const handleCopyLink = async () => {
|
||||
if (!shareUrl) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(shareUrl);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch (err) {
|
||||
console.error("Failed to copy:", err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleShare = async () => {
|
||||
if (!shareUrl) return;
|
||||
|
||||
if (navigator.share) {
|
||||
try {
|
||||
await navigator.share({
|
||||
title: `My ${platform} Build`,
|
||||
text: `Check out my ${platform} build: $${totalPrice.toFixed(2)}`,
|
||||
url: shareUrl,
|
||||
});
|
||||
return;
|
||||
} catch {
|
||||
// fall back to copy
|
||||
}
|
||||
}
|
||||
|
||||
await handleCopyLink();
|
||||
};
|
||||
|
||||
if (!loadingParts && selectedParts.length === 0) {
|
||||
return (
|
||||
<main className="min-h-screen bg-black text-zinc-50">
|
||||
<div className="mx-auto max-w-4xl px-4 py-6 lg:py-10">
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-semibold text-zinc-50 mb-4">
|
||||
No Build Selected
|
||||
</h1>
|
||||
<p className="text-sm text-zinc-400 mb-6">
|
||||
You need to select at least one part to view your build.
|
||||
</p>
|
||||
<Link
|
||||
href={`/builder?platform=${encodeURIComponent(platform)}`}
|
||||
className="inline-block rounded-md border border-amber-400/60 bg-amber-400/10 px-4 py-2 text-sm font-medium text-amber-200 hover:bg-amber-400/15 transition-colors"
|
||||
>
|
||||
Go to Builder
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-black text-zinc-50">
|
||||
<div className="mx-auto max-w-6xl px-4 py-6 lg:py-10">
|
||||
{/* Header */}
|
||||
<header className="mb-6">
|
||||
<Link
|
||||
href={`/builder?platform=${encodeURIComponent(platform)}`}
|
||||
className="text-xs text-zinc-400 hover:text-zinc-300 mb-4 inline-block"
|
||||
>
|
||||
← Back to The Armory
|
||||
</Link>
|
||||
|
||||
<div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
|
||||
<div>
|
||||
<p className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500">
|
||||
Shadow Standard
|
||||
</p>
|
||||
<h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight">
|
||||
Build <span className="text-amber-300">Summary</span>
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-zinc-400 max-w-xl">
|
||||
Review your build, purchase parts from our affiliate partners, or
|
||||
share your build with others.
|
||||
</p>
|
||||
<p className="mt-2 text-xs text-zinc-500">
|
||||
Platform: <span className="text-zinc-200">{platform}</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 md:mt-0">
|
||||
<div className="text-xs text-zinc-400">Total Build Price</div>
|
||||
<div className="text-3xl font-semibold text-amber-300">
|
||||
${totalPrice.toFixed(2)}
|
||||
</div>
|
||||
<div className="text-xs text-zinc-500">
|
||||
{selectedParts.length} / {CATEGORIES.length} parts selected
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Share Section */}
|
||||
<section className="mb-6 rounded-lg border border-zinc-800 bg-zinc-950/60 p-4">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex-1">
|
||||
<h2 className="text-xs font-semibold tracking-[0.16em] uppercase text-zinc-400 mb-2">
|
||||
Share Your Build
|
||||
</h2>
|
||||
<p className="text-sm text-zinc-400">
|
||||
Share this link to let others view your build or bookmark it to
|
||||
come back later.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleShare}
|
||||
className="rounded-md border border-zinc-700 bg-zinc-900/50 px-4 py-2 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
|
||||
>
|
||||
Share
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopyLink}
|
||||
className={`rounded-md border px-4 py-2 text-sm font-medium transition-colors ${
|
||||
copied
|
||||
? "border-green-500 bg-green-500/10 text-green-400"
|
||||
: "border-zinc-700 bg-zinc-900/50 text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600"
|
||||
}`}
|
||||
>
|
||||
{copied ? "Copied!" : "Copy Link"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{shareUrl && (
|
||||
<div className="mt-3 p-3 rounded-md bg-zinc-900/50 border border-zinc-800">
|
||||
<p className="text-xs text-zinc-500 mb-1">Shareable URL:</p>
|
||||
<p className="text-xs text-zinc-400 break-all font-mono">
|
||||
{shareUrl}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Build Parts */}
|
||||
<section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-4 md:p-6">
|
||||
<h2 className="text-xs font-semibold tracking-[0.16em] uppercase text-zinc-400 mb-4">
|
||||
Selected Parts
|
||||
</h2>
|
||||
|
||||
{loadingParts && (
|
||||
<p className="text-sm text-zinc-500 mb-4">Loading parts…</p>
|
||||
)}
|
||||
{partsError && (
|
||||
<p className="text-sm text-red-400 mb-4">
|
||||
{partsError} — check the Ballistic API.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{CATEGORIES.map((category) => {
|
||||
const selectedPartId = build[category.id];
|
||||
const part = parts.find(
|
||||
(p) =>
|
||||
p.id === selectedPartId &&
|
||||
p.categoryId === (category.id as CategoryId),
|
||||
);
|
||||
|
||||
const partRole =
|
||||
(CATEGORY_TO_PART_ROLE[category.id] as string | undefined) ??
|
||||
"unknown";
|
||||
|
||||
return (
|
||||
<div
|
||||
key={category.id}
|
||||
className="border border-zinc-800 rounded-md p-4 bg-zinc-900/30"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="flex-1">
|
||||
<div className="text-[0.7rem] uppercase tracking-[0.16em] text-zinc-500 mb-2">
|
||||
{category.name}
|
||||
</div>
|
||||
|
||||
{part ? (
|
||||
<>
|
||||
<div className="text-lg font-semibold text-zinc-50 mb-1">
|
||||
<span className="text-zinc-400">{part.brand}</span>{" "}
|
||||
{part.name}
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex gap-2 flex-wrap">
|
||||
{part.url && (
|
||||
<a
|
||||
href={part.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 rounded-md border border-amber-400/60 bg-amber-400/10 px-4 py-2 text-sm font-medium text-amber-200 hover:bg-amber-400/15 transition-colors"
|
||||
>
|
||||
Purchase from Retailer
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
)}
|
||||
|
||||
<Link
|
||||
href={buildDetailHref({
|
||||
id: part.id,
|
||||
name: part.name,
|
||||
platform,
|
||||
partRole,
|
||||
} as any)}
|
||||
className="inline-flex items-center rounded-md border border-zinc-700 bg-zinc-900/50 px-4 py-2 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
|
||||
>
|
||||
View Details
|
||||
</Link>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-sm text-zinc-600">Not selected</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{part && (
|
||||
<div className="text-right">
|
||||
<div className="text-2xl font-semibold text-amber-300">
|
||||
${part.price.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="mt-6 flex flex-col gap-3 sm:flex-row sm:justify-between">
|
||||
<Link
|
||||
href={`/builder?platform=${encodeURIComponent(platform)}`}
|
||||
className="rounded-md border border-zinc-700 bg-zinc-900/50 px-6 py-3 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors text-center"
|
||||
>
|
||||
Edit Build
|
||||
</Link>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
try {
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
router.push(`/builder?platform=${encodeURIComponent(platform)}`);
|
||||
}}
|
||||
className="rounded-md border border-zinc-700 bg-zinc-900/50 px-6 py-3 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
|
||||
>
|
||||
Clear Build
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user