wired up an accounts page and my builds (my vault)

This commit is contained in:
2025-12-19 08:05:03 -05:00
parent c6d1bce771
commit b76ced45f1
9 changed files with 566 additions and 1055 deletions
+44
View File
@@ -0,0 +1,44 @@
// app/(account)/account/page.tsx
"use client";
import { useAuth } from "@/context/AuthContext";
export default function AccountPage() {
const { user, loading } = useAuth();
if (loading) return <div className="text-sm opacity-70">Loading</div>;
if (!user) {
return (
<div className="text-sm opacity-70">
Youre not logged in. Please log in to view your account.
</div>
);
}
return (
<div className="space-y-4">
<div>
<h2 className="text-lg font-semibold">Profile</h2>
<p className="text-sm opacity-70">
Basic account info (well expand this soon).
</p>
</div>
<div className="rounded-xl border border-white/10 bg-white/5 p-4 space-y-2">
<div className="text-sm">
<span className="opacity-70">Email:</span>{" "}
<span className="font-medium">{user.email}</span>
</div>
<div className="text-sm">
<span className="opacity-70">Display name:</span>{" "}
<span className="font-medium">{user.displayName || "—"}</span>
</div>
<div className="text-sm">
<span className="opacity-70">Role:</span>{" "}
<span className="font-medium">{user.role}</span>
</div>
</div>
</div>
);
}
+60
View File
@@ -0,0 +1,60 @@
// app/(account)/layout.tsx
import Link from "next/link";
const nav = [
{ href: "/account", label: "My Account" },
{ href: "/account/settings", label: "Settings" },
];
export default function AccountLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="min-h-screen">
<div className="mx-auto max-w-6xl px-4 py-6">
{/* Header */}
<div className="mb-6 flex items-center justify-between">
<div>
<h1 className="text-2xl font-semibold">Account</h1>
<p className="text-sm opacity-70">
Profile, password, and account settings.
</p>
</div>
<Link href="/builder" className="text-sm opacity-80 hover:underline">
Back to Builder
</Link>
</div>
<div className="grid gap-6 md:grid-cols-[240px_1fr]">
<aside className="rounded-xl border border-white/10 bg-white/5 p-3">
<nav className="flex flex-col gap-1">
{nav.map((item) => (
<Link
key={item.href}
href={item.href}
className="rounded-lg px-3 py-2 text-sm opacity-80 hover:bg-white/10 hover:opacity-100"
>
{item.label}
</Link>
))}
<div className="my-2 border-t border-white/10" />
<Link
href="/vault"
className="rounded-lg px-3 py-2 text-sm opacity-80 hover:bg-white/10 hover:opacity-100"
>
My Vault
</Link>
</nav>
</aside>
<main className="rounded-xl border border-white/10 bg-white/5 p-4">
{children}
</main>
</div>
</div>
</div>
);
}
-1
View File
@@ -1 +0,0 @@
<main className="min-h-screen bg-white text-zinc-900 dark:bg-black dark:text-zinc-50">
-482
View File
@@ -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
View File
@@ -1,3 +1,4 @@
// app/(builder)/builder/page.tsx
"use client"; "use client";
import { useMemo, useState, useEffect, useCallback, useRef } from "react"; 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 { BUILDER_SLOTS, isSlotSatisfied } from "@/data/builderSlots";
import type { CategoryId, Part } from "@/types/gunbuilder"; import type { CategoryId, Part } from "@/types/gunbuilder";
import { PART_ROLE_TO_CATEGORY } from "@/lib/catalogMappings"; 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 // ✅ Centralized overlap rules + helpers
import OverlapChip from "@/components/builder/OverlapChip"; import OverlapChip from "@/components/builder/OverlapChip";
@@ -288,10 +289,6 @@ export default function GunbuilderPage() {
const handleSelectPart = useCallback( const handleSelectPart = useCallback(
(categoryId: CategoryId, partId: string, _opts?: { confirm?: boolean }) => { (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) => { const warn = (msg: string) => {
setShareStatus(msg); setShareStatus(msg);
window.setTimeout(() => setShareStatus(null), 4000); window.setTimeout(() => setShareStatus(null), 4000);
@@ -300,7 +297,6 @@ export default function GunbuilderPage() {
const hints = getSelectionHints(categoryId, build); const hints = getSelectionHints(categoryId, build);
if (hints.length > 0) warn(hints[0]); if (hints.length > 0) warn(hints[0]);
// ✅ Only set the selection. No deletes. No clearing.
setBuild((prev) => ({ setBuild((prev) => ({
...prev, ...prev,
[categoryId]: partId, [categoryId]: partId,
@@ -437,6 +433,54 @@ export default function GunbuilderPage() {
}); });
}, [platform]); }, [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: // Handle URL query parameters:
// - ?select=categoryId:partId // - ?select=categoryId:partId
// - ?remove=categoryId // - ?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 () => { const handleShare = async () => {
if (selectedParts.length === 0) { if (selectedParts.length === 0) {
setShareStatus("Add a few parts before sharing your build."); setShareStatus("Add a few parts before sharing your build.");
@@ -680,20 +771,6 @@ export default function GunbuilderPage() {
</div> </div>
<div className="mt-2 flex flex-col items-stretch gap-2 sm:flex-row sm:flex-wrap"> <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 <button
type="button" type="button"
onClick={handleShare} onClick={handleShare}
@@ -724,6 +801,20 @@ export default function GunbuilderPage() {
> >
Clear Build Clear Build
</button> </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>
</div> </div>
@@ -877,14 +968,12 @@ export default function GunbuilderPage() {
<tbody> <tbody>
{groupCategories.map((category) => { {groupCategories.map((category) => {
const categoryParts = const categoryParts = partsByCategory[category.id] ?? [];
partsByCategory[category.id] ?? [];
const selectedPartId = build[category.id]; const selectedPartId = build[category.id];
const selectedPart = selectedPartId const selectedPart = selectedPartId
? categoryParts.find( ? categoryParts.find((p) => p.id === selectedPartId) ??
(p) => p.id === selectedPartId parts.find((p) => p.id === selectedPartId)
) ?? parts.find((p) => p.id === selectedPartId)
: undefined; : undefined;
const hasParts = categoryParts.length > 0; const hasParts = categoryParts.length > 0;
@@ -1031,4 +1120,4 @@ export default function GunbuilderPage() {
</div> </div>
</main> </main>
); );
} }
-460
View File
@@ -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>
);
}
@@ -5,8 +5,16 @@ import Link from "next/link";
import { useParams, useRouter, useSearchParams } from "next/navigation"; import { useParams, useRouter, useSearchParams } from "next/navigation";
import type { CategoryId } from "@/types/gunbuilder"; import type { CategoryId } from "@/types/gunbuilder";
import { PART_ROLE_TO_CATEGORY, normalizePartRole } from "@/lib/catalogMappings"; import {
PART_ROLE_TO_CATEGORY,
normalizePartRole,
} from "@/lib/catalogMappings";
/**
* API Shapes
* - OfferFromApi: what /api/v1/products/:id returns in offers[]
* - GunbuilderProductFromApi: the product detail contract (v1)
*/
type OfferFromApi = { type OfferFromApi = {
merchantName?: string | null; merchantName?: string | null;
price?: number | null; price?: number | null;
@@ -23,21 +31,19 @@ type GunbuilderProductFromApi = {
partRole: string; partRole: string;
price: number | null; price: number | null;
// image fields can vary depending on endpoint/version // Optional (legacy fallback label if product.offers is missing)
merchantName?: string | null;
imageUrl?: string | null; imageUrl?: string | null;
mainImageUrl?: string | null; mainImageUrl?: string | null;
// single best-link (legacy)
buyUrl?: string | null; buyUrl?: string | null;
// stock info
inStock?: boolean | null; inStock?: boolean | null;
// richer details (optional)
shortDescription?: string | null; shortDescription?: string | null;
description?: string | null; description?: string | null;
// offers (optional) // New: offers[] from the API
offers?: OfferFromApi[] | null; offers?: OfferFromApi[] | null;
}; };
@@ -50,6 +56,10 @@ const STORAGE_KEY = "gunbuilder-build-state";
const PLATFORMS = ["AR-15", "AR-10", "AR-9"] as const; const PLATFORMS = ["AR-15", "AR-10", "AR-9"] as const;
/**
* Extract numeric id from slug like: "1217-radian-ar-15..."
* This keeps URLs pretty while still letting us fetch by ID.
*/
function extractNumericId(productSlug: string): number | null { function extractNumericId(productSlug: string): number | null {
if (!productSlug) return null; if (!productSlug) return null;
const first = productSlug.split("-")[0]; const first = productSlug.split("-")[0];
@@ -62,18 +72,23 @@ function formatPrice(price: number | null | undefined): string {
return `$${price.toFixed(2)}`; return `$${price.toFixed(2)}`;
} }
/**
* Sort offers:
* 1) lowest price first
* 2) in-stock before out-of-stock
* 3) merchant name tiebreaker
*/
function sortOffers(offers: OfferFromApi[]): OfferFromApi[] { function sortOffers(offers: OfferFromApi[]): OfferFromApi[] {
return [...offers].sort((a, b) => { return [...offers].sort((a, b) => {
const ap = a.price ?? Number.POSITIVE_INFINITY; const ap = a.price ?? Number.POSITIVE_INFINITY;
const bp = b.price ?? Number.POSITIVE_INFINITY; const bp = b.price ?? Number.POSITIVE_INFINITY;
if (ap !== bp) return ap - bp; if (ap !== bp) return ap - bp;
// in-stock first // in-stock first (false sorts later)
const aStock = a.inStock === false ? 1 : 0; const aStock = a.inStock === false ? 1 : 0;
const bStock = b.inStock === false ? 1 : 0; const bStock = b.inStock === false ? 1 : 0;
if (aStock !== bStock) return aStock - bStock; if (aStock !== bStock) return aStock - bStock;
// merchant name
return (a.merchantName ?? "").localeCompare(b.merchantName ?? ""); return (a.merchantName ?? "").localeCompare(b.merchantName ?? "");
}); });
} }
@@ -97,6 +112,10 @@ export default function ProductDetailsPage() {
[partRoleParam] [partRoleParam]
); );
/**
* categoryId drives builder state selection/removal
* (based on partRole -> category mapping).
*/
const categoryId = useMemo(() => { const categoryId = useMemo(() => {
return ( return (
PART_ROLE_TO_CATEGORY[partRoleParam] ?? PART_ROLE_TO_CATEGORY[partRoleParam] ??
@@ -134,15 +153,22 @@ export default function ProductDetailsPage() {
return () => window.removeEventListener("storage", onStorage); return () => window.removeEventListener("storage", onStorage);
}, []); }, []);
const selectedPartIdForCategory = categoryId ? build?.[categoryId] : undefined; const selectedPartIdForCategory = categoryId
? build?.[categoryId]
: undefined;
const isSelected = const isSelected =
!!categoryId && selectedPartIdForCategory === (numericId ? String(numericId) : ""); !!categoryId &&
selectedPartIdForCategory === (numericId ? String(numericId) : "");
// Product fetch state
const [product, setProduct] = useState<GunbuilderProductFromApi | null>(null); const [product, setProduct] = useState<GunbuilderProductFromApi | null>(null);
const [loading, setLoading] = useState<boolean>(true); const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
// If platform segment is missing/empty, normalize into the new route /**
* Route normalization:
* If platform segment is missing/empty, rewrite to canonical /parts/p route.
*/
useEffect(() => { useEffect(() => {
if (platformParam) return; if (platformParam) return;
@@ -155,9 +181,19 @@ export default function ProductDetailsPage() {
)}/${encodeURIComponent(productSlug)}?${qp.toString()}` )}/${encodeURIComponent(productSlug)}?${qp.toString()}`
); );
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [platformParam, platform, partRoleParam, productSlug, router, searchParams]); }, [
platformParam,
platform,
partRoleParam,
productSlug,
router,
searchParams,
]);
// Fetch product /**
* Fetch product details from API:
* GET /api/v1/products/:id
*/
useEffect(() => { useEffect(() => {
if (!numericId) { if (!numericId) {
setError("Invalid product id."); setError("Invalid product id.");
@@ -193,10 +229,14 @@ export default function ProductDetailsPage() {
return () => controller.abort(); return () => controller.abort();
}, [numericId]); }, [numericId]);
/**
* Builder selection toggle:
* - If selected -> remove from build
* - Else -> add to build
*/
const handleTogglePart = () => { const handleTogglePart = () => {
if (!numericId) return; if (!numericId) return;
// If mapping is missing, dont send a bogus builder action
if (!categoryId) { if (!categoryId) {
alert( alert(
`No CategoryId mapping found for partRole "${partRoleParam}". Add it in catalogMappings.` `No CategoryId mapping found for partRole "${partRoleParam}". Add it in catalogMappings.`
@@ -219,9 +259,11 @@ export default function ProductDetailsPage() {
const imageUrl = product?.imageUrl ?? product?.mainImageUrl ?? null; const imageUrl = product?.imageUrl ?? product?.mainImageUrl ?? null;
// Offers normalization: /**
// - If product.offers exists, use it. * Offers normalization:
// - Otherwise, fall back to a single “offer” from product.buyUrl/product.price. * - If product.offers exists, use & sort it (real offers).
* - Otherwise, fallback to a single offer derived from product.buyUrl/product.price (legacy).
*/
const offers = useMemo(() => { const offers = useMemo(() => {
if (!product) return []; if (!product) return [];
@@ -231,7 +273,7 @@ export default function ProductDetailsPage() {
if (product.buyUrl) { if (product.buyUrl) {
return sortOffers([ return sortOffers([
{ {
merchantName: "Merchant", merchantName: product.merchantName ?? "Merchant",
price: product.price, price: product.price,
buyUrl: product.buyUrl, buyUrl: product.buyUrl,
inStock: product.inStock ?? true, inStock: product.inStock ?? true,
@@ -242,6 +284,20 @@ export default function ProductDetailsPage() {
return []; return [];
}, [product]); }, [product]);
/**
* Best offer (for the "Buy from ..." CTA)
* IMPORTANT: this must be defined AFTER offers is computed
* (do NOT reference `offers` inside the offers useMemo).
*/
const bestOffer = offers[0] ?? null;
/**
* Helper: identify the best offer row
* We compare by buyUrl (stable + unique enough for MVP)
*/
const isBestOffer = (offer: OfferFromApi) =>
!!bestOffer && offer.buyUrl && offer.buyUrl === bestOffer.buyUrl;
if (!categoryId) { if (!categoryId) {
return ( return (
<main className="min-h-screen bg-black text-zinc-50"> <main className="min-h-screen bg-black text-zinc-50">
@@ -256,9 +312,9 @@ export default function ProductDetailsPage() {
<span className="text-zinc-200">catalogMappings</span>. <span className="text-zinc-200">catalogMappings</span>.
</p> </p>
<Link <Link
href={`/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent( href={`/parts/p/${encodeURIComponent(
partRoleParam platform
)}`} )}/${encodeURIComponent(partRoleParam)}`}
className="text-amber-300 hover:text-amber-200 underline" className="text-amber-300 hover:text-amber-200 underline"
> >
Back to Parts List Back to Parts List
@@ -276,16 +332,19 @@ export default function ProductDetailsPage() {
<header className="mb-6"> <header className="mb-6">
<div className="flex flex-wrap items-center gap-2 text-xs text-zinc-500"> <div className="flex flex-wrap items-center gap-2 text-xs text-zinc-500">
<Link <Link
href={{ pathname: "/builder", query: platform ? { platform } : {} }} href={{
pathname: "/builder",
query: platform ? { platform } : {},
}}
className="hover:text-zinc-300" className="hover:text-zinc-300"
> >
The Armory Builder
</Link> </Link>
<span className="text-zinc-700">/</span> <span className="text-zinc-700">/</span>
<Link <Link
href={`/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent( href={`/parts/p/${encodeURIComponent(
partRoleParam platform
)}`} )}/${encodeURIComponent(partRoleParam)}`}
className="hover:text-zinc-300" className="hover:text-zinc-300"
> >
Parts Parts
@@ -303,14 +362,17 @@ export default function ProductDetailsPage() {
Product <span className="text-amber-300">Details</span> Product <span className="text-amber-300">Details</span>
</h1> </h1>
<p className="mt-2 text-sm text-zinc-400 max-w-2xl"> <p className="mt-2 text-sm text-zinc-400 max-w-2xl">
Offers, pricing placeholders, and builder actions all on the canonical Offers, pricing placeholders, and builder actions all on the
/parts/p route. canonical /parts/p route.
</p> </p>
</div> </div>
{/* Platform switch (updates NEW route) */} {/* Platform switch (updates NEW route) */}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<label htmlFor="platform-select" className="text-xs text-zinc-500"> <label
htmlFor="platform-select"
className="text-xs text-zinc-500"
>
Platform Platform
</label> </label>
<select <select
@@ -388,9 +450,9 @@ export default function ProductDetailsPage() {
<div className="mt-3 flex gap-2"> <div className="mt-3 flex gap-2">
<Link <Link
href={`/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent( href={`/parts/p/${encodeURIComponent(
partRoleParam platform
)}`} )}/${encodeURIComponent(partRoleParam)}`}
className="flex-1 rounded-md border border-zinc-700 bg-zinc-900/70 px-3 py-2 text-center text-xs font-medium text-zinc-300 transition-colors hover:border-zinc-600 hover:bg-zinc-800" className="flex-1 rounded-md border border-zinc-700 bg-zinc-900/70 px-3 py-2 text-center text-xs font-medium text-zinc-300 transition-colors hover:border-zinc-600 hover:bg-zinc-800"
> >
Back to List Back to List
@@ -416,13 +478,16 @@ export default function ProductDetailsPage() {
<h3 className="text-xs font-semibold uppercase tracking-[0.16em] text-zinc-500"> <h3 className="text-xs font-semibold uppercase tracking-[0.16em] text-zinc-500">
Price History Price History
</h3> </h3>
<span className="text-[10px] text-zinc-600">placeholder</span> <span className="text-[10px] text-zinc-600">
placeholder
</span>
</div> </div>
<div className="mt-2 h-28 rounded border border-zinc-800 bg-zinc-950 flex items-center justify-center text-xs text-zinc-600"> <div className="mt-2 h-28 rounded border border-zinc-800 bg-zinc-950 flex items-center justify-center text-xs text-zinc-600">
Pricing graph will go here Pricing graph will go here
</div> </div>
<p className="mt-2 text-[11px] text-zinc-500"> <p className="mt-2 text-[11px] text-zinc-500">
Well wire this to price snapshots once the offer model is stable. Well wire this to price snapshots once the offer model is
stable.
</p> </p>
</div> </div>
</div> </div>
@@ -512,19 +577,39 @@ export default function ProductDetailsPage() {
</thead> </thead>
<tbody className="divide-y divide-zinc-800"> <tbody className="divide-y divide-zinc-800">
{offers.map((o, idx) => ( {offers.map((o, idx) => (
<tr key={idx} className="hover:bg-zinc-900/40"> <tr
<td className="px-3 py-2 text-zinc-200"> key={idx}
{o.merchantName ?? "Merchant"} className={`hover:bg-zinc-900/40 ${
isBestOffer(o)
? "bg-amber-400/10 border-l-2 border-amber-400"
: ""
}`}
>
{" "}
<td className="px-3 py-2 text-zinc-200 flex items-center">
<span>{o.merchantName ?? "Merchant"}</span>
{isBestOffer(o) && (
<span className="ml-2 inline-flex items-center rounded bg-amber-400 px-2 py-0.5 text-[10px] font-semibold text-black">
BEST
</span>
)}
</td> </td>
<td className="px-3 py-2 text-xs"> <td className="px-3 py-2 text-xs">
{o.inStock === false ? ( {o.inStock === false ? (
<span className="text-red-300">Out of stock</span> <span className="text-red-300">
Out of stock
</span>
) : ( ) : (
<span className="text-emerald-300">In stock</span> <span className="text-emerald-300">
In stock
</span>
)} )}
</td> </td>
<td className="px-3 py-2 text-right font-semibold text-amber-300"> <td className="px-3 py-2 text-right font-semibold text-amber-300">
{o.price != null ? `$${o.price.toFixed(2)}` : "—"} {o.price != null
? `$${o.price.toFixed(2)}`
: "—"}
</td> </td>
<td className="px-3 py-2 text-right"> <td className="px-3 py-2 text-right">
{o.buyUrl ? ( {o.buyUrl ? (
@@ -537,7 +622,9 @@ export default function ProductDetailsPage() {
Buy Buy
</a> </a>
) : ( ) : (
<span className="text-xs text-zinc-600"></span> <span className="text-xs text-zinc-600">
</span>
)} )}
</td> </td>
</tr> </tr>
@@ -547,21 +634,21 @@ export default function ProductDetailsPage() {
</div> </div>
) : ( ) : (
<p className="mt-3 text-sm text-zinc-500"> <p className="mt-3 text-sm text-zinc-500">
No offers attached yet. Once offers are available, this becomes the No offers attached yet. Once offers are available, this
where to buy table. becomes the where to buy table.
</p> </p>
)} )}
{/* Keep a single "best" buy CTA if buyUrl exists */} {/* Best Offer CTA (uses sorted offers[0]) */}
{product.buyUrl ? ( {bestOffer?.buyUrl ? (
<div className="mt-3 flex justify-end"> <div className="mt-3 flex justify-end">
<a <a
href={product.buyUrl} href={bestOffer.buyUrl}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
className="rounded-md border border-zinc-700 bg-zinc-900/70 px-4 py-2 text-sm font-semibold text-zinc-200 hover:bg-zinc-800" className="rounded-md border border-zinc-700 bg-zinc-900/70 px-4 py-2 text-sm font-semibold text-zinc-200 hover:bg-zinc-800"
> >
Buy from Merchant Buy from {bestOffer.merchantName ?? "Merchant"}
</a> </a>
</div> </div>
) : null} ) : null}
@@ -586,4 +673,4 @@ export default function ProductDetailsPage() {
</div> </div>
</main> </main>
); );
} }
+170
View File
@@ -0,0 +1,170 @@
// app/vault/page.tsx
"use client";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
type BuildDto = {
id: string;
uuid: string; // UUID string
title: string;
description?: string | null;
isPublic?: boolean | null;
createdAt?: string | null;
updatedAt?: string | null;
};
const API_BASE_URL =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
function fmt(d?: string | null) {
if (!d) return "—";
const dt = new Date(d);
if (Number.isNaN(dt.getTime())) return d;
return dt.toLocaleString();
}
export default function VaultPage() {
const router = useRouter();
const { user, loading, getAuthHeaders } = useAuth();
const [builds, setBuilds] = useState<BuildDto[]>([]);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const authed = !!user;
useEffect(() => {
if (!loading && !authed) {
router.replace("/login");
}
}, [loading, authed, router]);
const headers = useMemo(() => getAuthHeaders(), [getAuthHeaders]);
useEffect(() => {
if (loading || !authed) return;
let cancelled = false;
(async () => {
setBusy(true);
setError(null);
try {
const res = await fetch(`${API_BASE_URL}/api/v1/products/me/builds`, {
method: "GET",
headers,
});
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(text || `Request failed (${res.status})`);
}
const data = (await res.json()) as BuildDto[];
if (!cancelled) setBuilds(Array.isArray(data) ? data : []);
} catch (e: any) {
if (!cancelled) setError(e?.message || "Failed to load builds");
} finally {
if (!cancelled) setBusy(false);
}
})();
return () => {
cancelled = true;
};
}, [loading, authed, headers]);
if (loading) {
return (
<div className="mx-auto max-w-6xl px-4 py-6">
<div className="text-sm opacity-70">Loading</div>
</div>
);
}
// If not authed, we already redirected; render nothing.
if (!authed) return null;
return (
<div className="mx-auto max-w-6xl px-4 py-6">
<div className="mb-6 flex items-start justify-between gap-4">
<div>
<h1 className="text-2xl font-semibold">Vault</h1>
<p className="text-sm opacity-70">
Your saved builds. Load one into the builder or publish it later.
</p>
</div>
<div className="flex items-center gap-3">
<Link
href="/builder"
className="rounded-md border border-white/10 bg-white/5 px-3 py-1.5 text-sm hover:bg-white/10"
>
New Build
</Link>
<Link
href="/account"
className="text-sm opacity-80 hover:underline"
>
Account
</Link>
</div>
</div>
{error ? (
<div className="mb-4 rounded-xl border border-red-500/30 bg-red-500/10 p-3 text-sm">
{error}
</div>
) : null}
<div className="rounded-xl border border-white/10 bg-white/5">
<div className="flex items-center justify-between border-b border-white/10 px-4 py-3">
<div className="text-sm font-medium">My Builds</div>
<div className="text-xs opacity-70">
{busy ? "Refreshing…" : `${builds.length} total`}
</div>
</div>
{builds.length === 0 ? (
<div className="p-4 text-sm opacity-70">
No builds yet. Create one in the builder and hit Save to Vault.
</div>
) : (
<ul className="divide-y divide-white/10">
{builds.map((b) => (
<li key={b.uuid} className="p-4 flex items-start justify-between gap-4">
<div className="min-w-0">
<div className="font-medium truncate">{b.title}</div>
<div className="mt-1 text-xs opacity-70">
Updated: {fmt(b.updatedAt)} UUID:{" "}
<span className="font-mono">{b.uuid}</span>
</div>
{b.description ? (
<div className="mt-2 text-sm opacity-80 line-clamp-2">
{b.description}
</div>
) : null}
</div>
<div className="flex shrink-0 items-center gap-2">
{/* Placeholder: wire this to "load into builder" next */}
<Link
href={`/builder?build=${b.uuid}`}
className="rounded-md border border-white/10 bg-white/5 px-3 py-1.5 text-xs hover:bg-white/10"
>
Open
</Link>
</div>
</li>
))}
</ul>
)}
</div>
</div>
);
}
+41 -37
View File
@@ -3,18 +3,40 @@
import Link from "next/link"; import Link from "next/link";
import Image from "next/image"; import Image from "next/image";
import { usePathname } from "next/navigation";
import { useAuth } from "@/context/AuthContext"; import { useAuth } from "@/context/AuthContext";
import ThemeToggle from "@/components/ThemeToggle"; import ThemeToggle from "@/components/ThemeToggle";
function NavLink({
href,
children,
}: {
href: string;
children: React.ReactNode;
}) {
const pathname = usePathname();
const active = pathname === href;
return (
<Link
href={href}
className={[
"text-xs font-medium transition-colors",
active ? "text-zinc-100" : "text-zinc-400 hover:text-zinc-100",
].join(" ")}
>
{children}
</Link>
);
}
export function TopNav() { export function TopNav() {
const { user, logout, loading } = useAuth(); const { user, logout, loading } = useAuth();
const isAuthenticated = !!user; const isAuthenticated = !!user;
return ( return (
<header className="border-b border-zinc-200 bg-white/95 dark:border-zinc-800 dark:bg-black/95 backdrop-blur"> <header className="border-b border-zinc-200 bg-white/95 dark:border-zinc-800 dark:bg-black/95 backdrop-blur">
{/* Main nav row */}
<div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-2"> <div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-2">
{/* Left: Brand / Home */} {/* Left: Brand / Home */}
<Link <Link
@@ -24,42 +46,31 @@ export function TopNav() {
<Image <Image
src="/battl/battl-logo-mark-2.svg" src="/battl/battl-logo-mark-2.svg"
alt="Battl Builders Logo" alt="Battl Builders Logo"
width={260} // adjust to taste width={260}
height={48} // adjust to taste height={48}
className="block" className="block"
/> />
</Link> </Link>
{/* Right side actions */} {/* Right side actions */}
<div className="flex items-center gap-3"> <div className="flex items-center gap-4">
{/* Search placeholder */} <ThemeToggle />
{/* <button
type="button"
className="inline-flex h-8 w-8 items-center justify-center rounded-full border border-zinc-700 bg-zinc-900/60 text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 hover:border-zinc-500 transition-colors"
aria-label="Search (coming soon)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
className="h-4 w-4"
>
<circle cx="11" cy="11" r="6" />
<line x1="16.5" y1="16.5" x2="21" y2="21" />
</svg>
</button> */}
{loading ? ( {loading ? (
<span className="text-xs text-zinc-500">Checking session</span> <span className="text-xs text-zinc-500">Checking session</span>
) : isAuthenticated ? ( ) : isAuthenticated ? (
<> <>
<span className="hidden text-xs text-zinc-300 sm:inline"> <NavLink href="/vault">Vault</NavLink>
{/* Email/displayName links to Account */}
<Link
href="/account"
className="hidden text-xs text-zinc-300 hover:text-zinc-100 transition-colors sm:inline"
title="Account"
>
{user.displayName || user.email} {user.displayName || user.email}
</span> </Link>
<button <button
type="button" type="button"
onClick={logout} onClick={logout}
@@ -70,25 +81,18 @@ export function TopNav() {
</> </>
) : ( ) : (
<> <>
<Link <NavLink href="/login">Log In</NavLink>
href="/login"
className="text-xs font-medium text-zinc-400 hover:text-zinc-100 transition-colors"
>
Log In
</Link>
<Link <Link
href="/register" href="/register"
className="rounded-md border border-amber-400/70 bg-amber-400/10 px-3 py-1.5 text-xs font-semibold text-amber-200 hover:bg-amber-400/20 transition-colors" className="rounded-md border border-amber-400/70 bg-amber-400/10 px-3 py-1.5 text-xs font-semibold text-amber-200 hover:bg-amber-400/20 transition-colors"
> >
Join Beta Join Beta
</Link> </Link>
<div className="flex items-center gap-3">
<ThemeToggle />
</div>
</> </>
)} )}
</div> </div>
</div> </div>
</header> </header>
); );
} }