diff --git a/app/(app)/(builder)/builder/page.tsx b/app/(app)/(builder)/builder/page.tsx index 94dd248..922dabd 100644 --- a/app/(app)/(builder)/builder/page.tsx +++ b/app/(app)/(builder)/builder/page.tsx @@ -31,8 +31,9 @@ import { CATEGORIES } from "@/data/gunbuilderParts"; import { BUILDER_SLOTS, isSlotSatisfied } from "@/data/builderSlots"; import type { BuilderSlotKey, Part } from "@/types/builderSlots"; import { PART_ROLE_TO_CATEGORY } from "@/lib/catalogMappings"; +import { normalizePlatformKey } from "@/lib/platforms"; -// ✅ Centralized overlap rules + helpers +// Centralized overlap rules + helpers import OverlapChip from "@/components/builder/OverlapChip"; import { getOverlapChipsForCategory, @@ -51,7 +52,22 @@ type GunbuilderProductFromApi = { buyUrl: string | null; }; -const PLATFORMS = ["AR-15", "AR-10", "AR-9"] as const; +const PLATFORMS = ["AR15"] as const; + +// Disabling all other platforms for now +// const PLATFORMS = ["AR15", "AR10", "AR9"] as const; + +const PLATFORM_LABEL: Record<(typeof PLATFORMS)[number], string> = { + AR15: "AR-15", + // AR10: "AR-10", + // AR9: "AR-9", +}; +const isValidPlatform = ( + value: string | null +): value is (typeof PLATFORMS)[number] => + !!value && (PLATFORMS as readonly string[]).includes(value); + + const isUuid = (v: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test( @@ -146,6 +162,16 @@ export default function GunbuilderPage() { // ✅ Auth: we need the token ready before calling /builds/me/* const { token, loading: authLoading, getAuthHeaders } = useAuth(); + + const [platform, setPlatform] = useState<(typeof PLATFORMS)[number]>(() => { + if (typeof window === "undefined") return "AR15"; + const initial = new URLSearchParams(window.location.search).get("platform"); + const normalized = normalizePlatformKey(initial ?? ""); + return isValidPlatform(normalized) ? normalized : "AR15"; + }); + + // Canonical, URL-safe platform (AR15 / AR10 / AR9) +const canonicalPlatform = normalizePlatformKey(platform); // ----------------------------- // Save As… modal state (Vault variants) // ----------------------------- @@ -161,20 +187,6 @@ export default function GunbuilderPage() { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); - // ----------------------------- - // Platform state (AR-15/AR-10/AR-9) - // ----------------------------- - const isValidPlatform = ( - value: string | null - ): value is (typeof PLATFORMS)[number] => - !!value && (PLATFORMS as readonly string[]).includes(value); - - const [platform, setPlatform] = useState<(typeof PLATFORMS)[number]>(() => { - if (typeof window === "undefined") return "AR-15"; - const initial = new URLSearchParams(window.location.search).get("platform"); - return isValidPlatform(initial) ? initial : "AR-15"; - }); - // ----------------------------- // Build state (categoryId -> productId), persisted locally // ----------------------------- @@ -228,7 +240,7 @@ export default function GunbuilderPage() { const didHydrateRef = useRef(false); const lastPlatformRef = useRef(platform); - // ✅ Guard to prevent infinite loops when processing ?select / ?remove + // Guard to prevent infinite loops when processing ?select / ?remove const processedActionKeyRef = useRef(""); // ----------------------------- @@ -326,7 +338,7 @@ export default function GunbuilderPage() { if (normalizedRole.includes("suppress")) return "suppressor"; - // ✅ FIX: Lower Parts Kit canonical key + // Lower Parts Kit canonical key if ( normalizedRole.includes("lower-parts") || normalizedRole.includes("lpk") @@ -336,7 +348,7 @@ export default function GunbuilderPage() { if (normalizedRole.includes("trigger")) return "trigger"; if (normalizedRole.includes("grip")) return "grip"; - // ✅ FIX: Safety canonical key + // Safety canonical key if ( normalizedRole.includes("safety") || normalizedRole.includes("selector") @@ -385,26 +397,26 @@ export default function GunbuilderPage() { useEffect(() => { const controller = new AbortController(); - + async function hydrateSelected() { const ids = (Object.values(build).filter(Boolean) as string[]) .map(String) .sort(); - + const key = ids.join(","); if (key === lastHydrateKeyRef.current) return; lastHydrateKeyRef.current = key; - + if (ids.length === 0) { setParts([]); setError(null); setLoading(false); return; } - + setLoading(true); setError(null); - + try { const res = await fetch( `${API_BASE_URL}/api/v1/catalog/products/by-ids`, @@ -415,27 +427,27 @@ export default function GunbuilderPage() { body: JSON.stringify({ ids }), } ); - + if (!res.ok) throw new Error(`Failed to hydrate parts (${res.status})`); - + const data: GunbuilderProductFromApi[] = await res.json(); // Map products by id for quick lookup const byId = new Map(); for (const p of data) byId.set(String(p.id), p); - + // Build the hydrated parts by iterating the BUILD STATE (slot -> id) const hydrated: Part[] = Object.entries(build) .filter(([, id]) => Boolean(id)) .map(([slot, id]) => { const p = byId.get(String(id)); if (!p) return null; - + const buyUrl = p.buyUrl ?? undefined; - + return { id: String(p.id), - categoryId: slot as any, // ✅ slot is the source of truth + categoryId: slot as any, // slot is the source of truth name: p.name, brand: p.brand, price: p.price ?? 0, @@ -446,9 +458,8 @@ export default function GunbuilderPage() { } as Part; }) .filter((x): x is Part => x !== null); - + setParts(hydrated); - } catch (err: any) { if (err?.name === "AbortError") return; setError(err?.message ?? "Failed to hydrate selected parts"); @@ -456,7 +467,7 @@ export default function GunbuilderPage() { setLoading(false); } } - + hydrateSelected(); return () => controller.abort(); }, [build]); @@ -512,10 +523,10 @@ export default function GunbuilderPage() { if (!uuidToLoad) return; - // ✅ Wait for AuthProvider hydration before calling /me endpoints. + // Wait for AuthProvider hydration before calling /me endpoints. if (authLoading) return; - // ✅ If not logged in, don't spam the backend; show a helpful message instead. + // If not logged in, don't spam the backend; show a helpful message instead. if (!token) { setShareStatus("Please log in to load builds from your Vault."); window.setTimeout(() => setShareStatus(null), 4500); @@ -633,7 +644,7 @@ export default function GunbuilderPage() { showToast({ type: "success", - message: "Saved to Vault ✅ (UUID copied)", + message: "Saved to your Vault ✅ ", }); // Close modal + reset inputs for next variant @@ -674,66 +685,70 @@ export default function GunbuilderPage() { }, [build] ); - // ----------------------------- - // Handle URL query parameters: - // - ?select=categoryId:partId - // - ?remove=categoryId - // ----------------------------- - useEffect(() => { - const selectParam = searchParams.get("select"); - const removeParam = searchParams.get("remove"); - const qpPlatform = searchParams.get("platform"); + // Handle URL query parameters (?select, ?remove) and keep platform synced + canonical +useEffect(() => { + const sp = new URLSearchParams(searchParams.toString()); - const actionKey = `${selectParam ?? ""}|${removeParam ?? ""}|${ - qpPlatform ?? "" - }`; + const selectParam = sp.get("select"); + const removeParam = sp.get("remove"); - if (!selectParam && !removeParam) { - processedActionKeyRef.current = ""; - return; - } + // Normalize platform from URL (AR-15 -> AR15) + const qpPlatformRaw = sp.get("platform"); + const qpPlatform = normalizePlatformKey(qpPlatformRaw ?? ""); - if (processedActionKeyRef.current === actionKey) return; - processedActionKeyRef.current = actionKey; + // Decide canonical platform to use (URL if valid, else current state) + const nextPlatform = isValidPlatform(qpPlatform) ? qpPlatform : platform; - if (selectParam) { - const [categoryIdRaw, partId] = selectParam.split(":"); - const requestedCategoryId = categoryIdRaw as BuilderSlotKey; + // Keep React state in sync (only when needed) + if (isValidPlatform(qpPlatform) && qpPlatform !== platform) { + setPlatform(qpPlatform); + } - if (requestedCategoryId && partId) { - handleSelectPart(requestedCategoryId, partId, { confirm: false }); + // Prevent repeating select/remove actions + const actionKey = `${selectParam ?? ""}|${removeParam ?? ""}|${nextPlatform}`; + const hasAction = !!selectParam || !!removeParam; + + if (hasAction) { + if (processedActionKeyRef.current !== actionKey) { + processedActionKeyRef.current = actionKey; + + if (selectParam) { + const [categoryIdRaw, partId] = selectParam.split(":"); + const requestedCategoryId = categoryIdRaw as BuilderSlotKey; + + if (requestedCategoryId && partId) { + handleSelectPart(requestedCategoryId, partId, { confirm: false }); + } + } + + if (removeParam) { + if (CATEGORIES.some((c) => c.id === removeParam)) { + setBuild((prev) => { + const next: BuildState = { ...prev }; + delete next[removeParam as BuilderSlotKey]; + return next; + }); + } } } + } else { + // no action params → allow future actions to run + processedActionKeyRef.current = ""; + } - if (removeParam) { - if (CATEGORIES.some((c) => c.id === removeParam)) { - setBuild((prev) => { - const next: BuildState = { ...prev }; - delete next[removeParam as BuilderSlotKey]; - return next; - }); - } - } + // Canonicalize URL: set platform to canonical key and remove action params + const before = searchParams.toString(); - const nextPlatform = isValidPlatform(qpPlatform) ? qpPlatform : platform; + sp.set("platform", nextPlatform); + sp.delete("select"); + sp.delete("remove"); - // Keep URL clean/stable - const nextUrl = `/builder?platform=${encodeURIComponent(nextPlatform)}`; - if (typeof window !== "undefined") { - const current = `${window.location.pathname}${window.location.search}`; - if (current !== nextUrl) router.replace(nextUrl, { scroll: false }); - } else { - router.replace(nextUrl, { scroll: false }); - } - }, [searchParams, router, platform, handleSelectPart]); + const after = sp.toString(); - // Keep platform in sync w/ URL - useEffect(() => { - const qp = searchParams.get("platform"); - if (isValidPlatform(qp) && qp !== platform) { - setPlatform(qp); - } - }, [searchParams, platform]); + if (after !== before) { + router.replace(`/builder?${after}`, { scroll: false }); + } +}, [searchParams, router, platform, handleSelectPart]); // Build share URL whenever build changes (client-side only) useEffect(() => { @@ -971,7 +986,7 @@ export default function GunbuilderPage() { // Keep URL in sync, and clear transient action params const qp = new URLSearchParams(searchParams.toString()); - qp.set("platform", next); + qp.set("platform", normalizePlatformKey(next)); qp.delete("select"); qp.delete("remove"); @@ -983,7 +998,7 @@ export default function GunbuilderPage() { > {PLATFORMS.map((p) => ( ))} @@ -1352,11 +1367,8 @@ export default function GunbuilderPage() { ) : ( Key Label Active - Actions + + Actions + @@ -245,7 +249,15 @@ export default function AdminPlatformsPage() {
+
+ {label} +
+ {children} +
+ ); +} + +function Chip({ text, onClear }: { text: string; onClear: () => void }) { + return ( + + ); } export default function AdminProductsPage() { - // filters - const [q, setQ] = useState(""); - const [platform, setPlatform] = useState(""); - const [partRole, setPartRole] = useState(""); - const [visibility, setVisibility] = useState(""); - const [status, setStatus] = useState(""); - const [builderEligible, setBuilderEligible] = useState<"" | "true" | "false">( - "" - ); - const [adminLocked, setAdminLocked] = useState<"" | "true" | "false">(""); - // paging const [page, setPage] = useState(0); const [size, setSize] = useState(50); + // dropdown data + const [platformOptions, setPlatformOptions] = useState([]); + // data const [data, setData] = useState | null>(null); const [loading, setLoading] = useState(false); @@ -164,30 +225,35 @@ export default function AdminProductsPage() { // selection const [selected, setSelected] = useState>(new Set()); + // filters: draft vs applied (THIS is the big clarity win) + const initialFilters: AdminFilters = { + q: "", + platform: "", + partRole: "", + visibility: "", + status: "", + builderEligible: "", + adminLocked: "", + }; + + const [draft, setDraft] = useState(initialFilters); + const [applied, setApplied] = useState(initialFilters); + + // bulk action UI state + const [bulkPlatformKey, setBulkPlatformKey] = useState(""); + const [bulkPlatformLock, setBulkPlatformLock] = useState(false); + const queryParams = useMemo(() => { return { - q, - platform, - partRole, - visibility, - status, - builderEligible: builderEligible === "" ? null : builderEligible, - adminLocked: adminLocked === "" ? null : adminLocked, + ...applied, + builderEligible: + applied.builderEligible === "" ? null : applied.builderEligible, + adminLocked: applied.adminLocked === "" ? null : applied.adminLocked, page, size, sort: "updatedAt,desc", }; - }, [ - q, - platform, - partRole, - visibility, - status, - builderEligible, - adminLocked, - page, - size, - ]); + }, [applied, page, size]); const refresh = async () => { setLoading(true); @@ -195,8 +261,7 @@ export default function AdminProductsPage() { try { const res = await fetchAdminProducts(queryParams); setData(res); - // clear selection on refresh so you don’t accidentally nuke new stuff - setSelected(new Set()); + setSelected(new Set()); // prevent accidental “bulk” on new results } catch (e: any) { setErr(e?.message ?? "Failed to load."); } finally { @@ -204,23 +269,39 @@ export default function AdminProductsPage() { } }; + // auto-refresh only on paging (kept behavior) useEffect(() => { refresh(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [queryParams.page, queryParams.size]); // only auto-refresh on page/size + }, [page, size]); + + // load platforms + useEffect(() => { + (async () => { + try { + const plats = await fetchPlatforms(); + plats.sort((a, b) => a.label.localeCompare(b.label)); + setPlatformOptions(plats); + } catch (e: any) { + console.warn(e?.message ?? "Failed to load platforms"); + } + })(); + }, []); const content = data?.content ?? []; + // derive role options from current page (good enough v1) + const roleOptions = useMemo(() => buildRoleOptions(content), [content]); + + const selectedIds = Array.from(selected); + const allOnPageSelected = content.length > 0 && content.every((r) => selected.has(r.id)); const toggleAllOnPage = () => { const next = new Set(selected); - if (allOnPageSelected) { - content.forEach((r) => next.delete(r.id)); - } else { - content.forEach((r) => next.add(r.id)); - } + if (allOnPageSelected) content.forEach((r) => next.delete(r.id)); + else content.forEach((r) => next.add(r.id)); setSelected(next); }; @@ -231,29 +312,83 @@ export default function AdminProductsPage() { setSelected(next); }; - const selectedIds = Array.from(selected); + const applyFilters = async () => { + setPage(0); + setApplied({ ...draft }); + // keep your “manual” refresh model: + await refresh(); + }; + + const clearFilters = async () => { + setDraft(initialFilters); + setApplied(initialFilters); + setPage(0); + await refresh(); + }; const runBulk = async (set: Parameters[1]) => { if (selectedIds.length === 0) return; - // no confirmations per your “keep moving” vibe, but you can add one later setLoading(true); setErr(null); try { const res = await bulkUpdate(selectedIds, set); - // eslint-disable-next-line no-console - console.log("Bulk updated:", res.updatedCount); + console.log( + `Updated ${res.updatedCount}` + + (res.skippedLockedCount > 0 + ? ` • Skipped ${res.skippedLockedCount} (platform locked)` + : "") + ); await refresh(); + + if ("platform" in set) { + setBulkPlatformKey(""); + setBulkPlatformLock(false); + } } catch (e: any) { setErr(e?.message ?? "Bulk update failed."); setLoading(false); } }; + // active filter chips (optional but huge clarity) + const chips = useMemo(() => { + const out: { key: keyof AdminFilters; label: string }[] = []; + if (applied.q) out.push({ key: "q", label: `Search: ${applied.q}` }); + if (applied.platform) + out.push({ key: "platform", label: `Platform: ${applied.platform}` }); + if (applied.partRole) + out.push({ key: "partRole", label: `Role: ${applied.partRole}` }); + if (applied.visibility) + out.push({ + key: "visibility", + label: `Visibility: ${applied.visibility}`, + }); + if (applied.status) + out.push({ key: "status", label: `Status: ${applied.status}` }); + if (applied.builderEligible) + out.push({ + key: "builderEligible", + label: `Builder: ${applied.builderEligible}`, + }); + if (applied.adminLocked) + out.push({ key: "adminLocked", label: `Locked: ${applied.adminLocked}` }); + return out; + }, [applied]); + + const clearOne = async (key: keyof AdminFilters) => { + const nextDraft = { ...draft, [key]: "" } as AdminFilters; + const nextApplied = { ...applied, [key]: "" } as AdminFilters; + setDraft(nextDraft); + setApplied(nextApplied); + setPage(0); + await refresh(); + }; + return ( -
-
+
+

Admin · Products

@@ -271,167 +406,251 @@ export default function AdminProductsPage() {

- {/* Filters */} -
- setQ(e.target.value)} - placeholder="Search (name, slug, mpn, upc)…" - className="md:col-span-2 rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" - /> + {/* ROW 1: FILTER BAR */} +
+
+ + setDraft((s) => ({ ...s, q: e.target.value }))} + placeholder="name, slug, mpn, upc…" + className="w-full rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" + /> + - setPlatform(e.target.value)} - placeholder="Platform (AR-15)…" - className="rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" - /> + + + - setPartRole(e.target.value)} - placeholder="Part role (barrel)…" - className="rounded-md border border-zinc-700 bg-black px-3 py-2 text-sm" - /> + + + - + + + - + + + -
- + + + - + + + - +
+ - + +
+ + {chips.length > 0 && ( +
+ {chips.map((c) => ( + void clearOne(c.key)} + /> + ))} +
+ )}
- {/* Bulk actions */} -
-
- Selected:{" "} - - {selectedIds.length} - + {/* ROW 2: BULK BAR (only when selection > 0) */} + {selectedIds.length > 0 && ( +
+
+
+ Selected:{" "} + {selectedIds.length} +
+ +
+ +
+ + + + + +
+ +
+ + + + + + + + + + + +
+
- -
- - - - - - - - - - - -
-
+ )} {/* Errors */} {err && ( @@ -562,7 +781,7 @@ export default function AdminProductsPage() { {/* Pagination */}
- Page {(data?.number ?? 0) + 1} of {data?.totalPages ?? 1} + Page {(data?.number ?? 0) + 1} of {data?.totalPages ?? 1} •{" "} {data?.totalElements ?? 0} total
diff --git a/components/BuilderNav.tsx b/components/BuilderNav.tsx index a53ef2b..677379f 100644 --- a/components/BuilderNav.tsx +++ b/components/BuilderNav.tsx @@ -75,7 +75,7 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) { {/* Dropdown menu */} -
+
    {items.map((cat) => { const isActive = currentCategory === cat.id; @@ -114,7 +114,7 @@ export function BuilderNav({ activeCategoryId }: BuilderNavProps) { * - Everything before the RIGHT cluster is "left side" * - Then a single `ml-auto` cluster pushes everything else to the right */} -
+ )} */}
{isBuilderMode && ( diff --git a/components/parts/PartsGrid.tsx b/components/parts/PartsGrid.tsx index a0a8b05..8dd7892 100644 --- a/components/parts/PartsGrid.tsx +++ b/components/parts/PartsGrid.tsx @@ -92,7 +92,8 @@ export default function PartsGrid(props: { return ( <> {/* Header (DESKTOP ONLY) */} -
+
+ Image Part Caliber Price @@ -106,7 +107,21 @@ export default function PartsGrid(props: { key={part.id} className="group relative rounded-md border border-zinc-700 bg-zinc-900/50 p-3 transition-all hover:border-amber-400/60 hover:bg-amber-400/10" > -
+
+ {/* Image */} +
+ {part.imageUrl ? ( + // eslint-disable-next-line @next/next/no-img-element + + ) : ( +
+ )} +
{/* Part */}