lots of fixes. cant remember them all

This commit is contained in:
2025-12-18 09:42:25 -05:00
parent 607939c468
commit 4c2d767d09
28 changed files with 3342 additions and 996 deletions
+77 -39
View File
@@ -1,10 +1,11 @@
"use client";
import { useMemo, useState, useEffect } from "react";
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";
@@ -23,7 +24,7 @@ type GunbuilderProductFromApi = {
buyUrl: string | null;
};
// Map backend partRole -> CategoryId (same as /gunbuilder page)
// Map backend partRole -> CategoryId (align with builder categories)
const PART_ROLE_TO_CATEGORY: Record<string, CategoryId> = {
"upper-receiver": "upper",
barrel: "barrel",
@@ -34,6 +35,12 @@ const PART_ROLE_TO_CATEGORY: Record<string, CategoryId> = {
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)
@@ -64,6 +71,9 @@ 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);
@@ -78,23 +88,25 @@ export default function BuildDetailsPage() {
if (buildParam) {
const decoded = decodeBuildState(buildParam);
setBuild(decoded);
// Also save to localStorage
localStorage.setItem(STORAGE_KEY, JSON.stringify(decoded));
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(decoded));
} catch {
// ignore storage failures (private mode, etc.)
}
} else if (typeof window !== "undefined") {
// Load from localStorage
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
try {
const parsed = JSON.parse(stored);
setBuild(parsed);
} catch {
// Invalid stored data
// ignore invalid stored data
}
}
}
}, [searchParams]);
// Fetch live parts from backend (same source as /gunbuilder)
// Fetch live parts from backend (uses selected platform)
useEffect(() => {
const controller = new AbortController();
@@ -104,7 +116,7 @@ export default function BuildDetailsPage() {
setPartsError(null);
const res = await fetch(
`${API_BASE_URL}/api/products/gunbuilder?platform=AR-15`,
`${API_BASE_URL}/api/products?platform=${encodeURIComponent(platform)}`,
{ signal: controller.signal },
);
@@ -120,7 +132,7 @@ export default function BuildDetailsPage() {
if (!categoryId) return null;
return {
id: p.id, // already a string UUID
id: p.id,
categoryId,
name: p.name,
brand: p.brand,
@@ -134,26 +146,29 @@ export default function BuildDetailsPage() {
setParts(normalized);
} catch (err: any) {
if (err.name === "AbortError") return;
setPartsError(err.message ?? "Failed to load products");
if (err?.name === "AbortError") return;
setPartsError(err?.message ?? "Failed to load products");
} finally {
setLoadingParts(false);
}
}
fetchProducts();
return () => controller.abort();
}, []);
}, [platform]);
// Generate shareable URL
// 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?build=${encoded}`;
const url = `${window.location.origin}/builder/build?platform=${encodeURIComponent(
platform,
)}&build=${encoded}`;
setShareUrl(url);
} else if (typeof window !== "undefined") {
setShareUrl("");
}
}, [build]);
}, [build, platform]);
const selectedParts: Part[] = useMemo(() => {
if (parts.length === 0) return [];
@@ -173,31 +188,33 @@ export default function BuildDetailsPage() {
);
const handleCopyLink = async () => {
if (shareUrl) {
try {
await navigator.clipboard.writeText(shareUrl);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (err) {
console.error("Failed to copy:", err);
}
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 (navigator.share && shareUrl) {
if (!shareUrl) return;
if (navigator.share) {
try {
await navigator.share({
title: "My AR-15 Build",
text: `Check out my AR-15 build: $${totalPrice.toFixed(2)}`,
title: `My ${platform} Build`,
text: `Check out my ${platform} build: $${totalPrice.toFixed(2)}`,
url: shareUrl,
});
return;
} catch {
handleCopyLink();
// fall back to copy
}
} else {
handleCopyLink();
}
await handleCopyLink();
};
if (!loadingParts && selectedParts.length === 0) {
@@ -212,7 +229,7 @@ export default function BuildDetailsPage() {
You need to select at least one part to view your build.
</p>
<Link
href="/builder"
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
@@ -229,11 +246,12 @@ export default function BuildDetailsPage() {
{/* Header */}
<header className="mb-6">
<Link
href="/builder"
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">
@@ -246,6 +264,9 @@ export default function BuildDetailsPage() {
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">
@@ -293,6 +314,7 @@ export default function BuildDetailsPage() {
</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>
@@ -327,6 +349,10 @@ export default function BuildDetailsPage() {
p.categoryId === (category.id as CategoryId),
);
const partRole =
(CATEGORY_TO_PART_ROLE[category.id] as string | undefined) ??
"unknown";
return (
<div
key={category.id}
@@ -337,12 +363,14 @@ export default function BuildDetailsPage() {
<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
@@ -367,8 +395,14 @@ export default function BuildDetailsPage() {
</svg>
</a>
)}
<Link
href={`/builder/${category.id}/${part.id}`}
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
@@ -376,11 +410,10 @@ export default function BuildDetailsPage() {
</div>
</>
) : (
<div className="text-sm text-zinc-600">
Not selected
</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">
@@ -398,17 +431,22 @@ export default function BuildDetailsPage() {
{/* Actions */}
<div className="mt-6 flex flex-col gap-3 sm:flex-row sm:justify-between">
<Link
href="/builder"
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={() => {
localStorage.removeItem(STORAGE_KEY);
router.push("/builder");
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"
>