// app/(builder)/builder/page.tsx
"use client";

import { Suspense } from "react";

/**
 * Battl Builder - Main builder page
 *
 * Key flows:
 * 1) Build selections are stored locally (localStorage) so users can come back.
 * 2) "Save As…" creates a NEW saved build in the user's Vault (server-side).
 * 3) Vault -> Builder loads builds via ?load=<uuid> (also supports legacy ?build=<uuid>).
 *
 * Notes for devs:
 * - We intentionally keep ONE save-to-vault handler: handleSaveAs()
 * - Toast is used for clear user feedback (save success/fail)
 *
 * Auth note:
 * - /api/v1/builds/me/* requires JWT.
 * - The builder can render before AuthContext hydrates from localStorage, so we
 *   guard “load build” calls until auth is ready to avoid a 401.
 */

import { useMemo, useState, useEffect, useCallback, useRef } from "react";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";
import { X, Link2, Square, CheckSquare } from "lucide-react";

import { useApi } from "@/lib/api";
import { useAuth } from "@/context/AuthContext";
import { trackBuildStarted, trackPartSelected, trackAffiliateLinkClicked, trackBuildShared, trackBuildSaved } from "@/lib/analytics";

import { CATEGORIES } from "@/data/gunbuilderParts";
import { BUILDER_SLOTS, isSlotSatisfied } from "@/data/builderSlots";
import type { BuilderSlotKey, Part } from "@/types/builderSlots";
import { PART_ROLE_TO_CATEGORY } from "@/lib/catalogMappings";
import { normalizePlatformKey } from "@/lib/platforms";

// Centralized overlap rules + helpers
import OverlapChip from "@/components/builder/OverlapChip";
import {
  getOverlapChipsForCategory,
  getSelectionHints,
  type BuildState,
} from "@/lib/buildOverlaps";

type GunbuilderProductFromApi = {
  id: number; // backend numeric id
  name: string;
  brand: string;
  platform: string;
  partRole: string;
  price: number | null;
  imageUrl: string | null;
  buyUrl: string | null;
};

const PLATFORMS = ["AR15"] as const;

// Disabling all other platforms for now
// const PLATFORMS = ["AR15", "AR10", "AR9"] as const;

const PLATFORM_LABEL: Record<(typeof PLATFORMS)[number], string> = {
  AR15: "AR-15",
  // AR10: "AR-10",
  // AR9: "AR-9",
};
const isValidPlatform = (
  value: string | null
): value is (typeof PLATFORMS)[number] =>
  !!value && (PLATFORMS as readonly string[]).includes(value);

const isUuid = (v: string) =>
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
    v
  );

// API routes now handled by Next.js /api routes (server-side)

const STORAGE_KEY = "gunbuilder-build-state";

// Categories that should NOT be filtered by platform (universal accessories / gear)
const UNIVERSAL_CATEGORIES = new Set<BuilderSlotKey>([
  "magazine",
  "weapon-light",
  "foregrip",
  "bipod",
  "sling",
  "rail-accessory",
  "tools",
  // Optics & sights are intentionally treated as universal
  "optic",
  "sights",
]);

// Category groups for the main grid
const CATEGORY_GROUPS: {
  id: string;
  label: string;
  description?: string;
  categoryIds: BuilderSlotKey[];
}[] = [
  {
    id: "lower-group",
    label: "Lower Receiver Parts",
    description:
      "Everything from the serialized lower to small parts, fire control, and core controls.",
    categoryIds: [
      "lower-receiver",
      "complete-lower",
      "lower-parts-kit",
      "trigger",
      "grip",
      "safety-selector",
      "buffer",
      "stock",
    ],
  },
  {
    id: "upper-group",
    label: "Upper Receiver Parts",
    description:
      "Barrel, upper, gas system, and the parts that keep the rifle cycling.",
    categoryIds: [
      "upper-receiver",
      "complete-upper",
      "bcg",
      "barrel",
      "gas-block",
      "gas-tube",
      "muzzle-device",
      "suppressor",
      "handguard",
      "charging-handle",
      "sights",
      "optic",
    ],
  },
  {
    id: "accessories-group",
    label: "Accessories & Gear",
    description:
      "Universal add-ons that work across platforms — mags, lights, slings, tools, and more.",
    categoryIds: [
      "magazine",
      "weapon-light",
      "foregrip",
      "bipod",
      "sling",
      "rail-accessory",
      "tools",
    ],
  },
];

// --- Quick Checklist (simple counters only) ---
// Required: core rifle components (kept intentionally small + pragmatic)
const QUICK_REQUIRED_IDS = new Set<BuilderSlotKey>([
  "lower-receiver",
  "complete-lower",
  "upper-receiver",
  "complete-upper",

  "barrel",
  "bcg",
  "charging-handle",
  "handguard",
  "gas-block",
  "gas-tube",
  "muzzle-device",

  "trigger",
  "grip",
  "safety-selector",
  "buffer",
  "stock",
]);

// Optional: Accessories & Gear group (these are nice-to-haves)
const QUICK_OPTIONAL_IDS = new Set<BuilderSlotKey>(
  CATEGORY_GROUPS.find((g) => g.id === "accessories-group")?.categoryIds ?? []
);

function computeQuickChecklistCounts(
  build: BuildState,
  allowedIds: Set<BuilderSlotKey>
) {
  // Only count IDs that exist in our known category universe.
  const requiredIds = Array.from(QUICK_REQUIRED_IDS).filter((id) =>
    allowedIds.has(id)
  );
  const optionalIds = Array.from(QUICK_OPTIONAL_IDS).filter((id) =>
    allowedIds.has(id)
  );

  const requiredDone = requiredIds.filter((id) => Boolean(build[id])).length;
  const optionalDone = optionalIds.filter((id) => Boolean(build[id])).length;

  return {
    requiredDone,
    requiredTotal: requiredIds.length,
    optionalDone,
    optionalTotal: optionalIds.length,
  };
}

// Helper to normalize all build values to strings for strict comparison
function normalizeBuildState(input: any): BuildState {
  if (!input || typeof input !== "object") return {};
  const next: BuildState = {};
  for (const [k, v] of Object.entries(input)) {
    if (v == null) continue;
    // force all ids to strings for consistent comparisons
    next[k as BuilderSlotKey] = String(v);
  }
  return next;
}

// --- Table nesting (OR paths) ---
type TableRowKind = "note" | "category";

type TableRow = {
  key: string;
  kind: TableRowKind;
  label: string;
  categoryId?: BuilderSlotKey;
  indent?: 0 | 1 | 2;
  tone?: "muted" | "normal";
  pill?: string;
  locked?: boolean;
};

const LOWER_PATHS = {
  complete: "complete-lower" as BuilderSlotKey,
  builderRoot: "lower-receiver" as BuilderSlotKey,
  builderChildren: [
    "lower-parts-kit",
    "trigger",
    "grip",
    "safety-selector",
    "buffer",
    "stock",
  ] as BuilderSlotKey[],
};

const UPPER_PATHS = {
  complete: "complete-upper" as BuilderSlotKey,
  builderRoot: "upper-receiver" as BuilderSlotKey,
  builderChildren: [
    "barrel",
    "bcg",
    "charging-handle",
    "handguard",
    "gas-block",
    "gas-tube",
    "muzzle-device",
  ] as BuilderSlotKey[],
};

function getAssemblyMode(
  build: BuildState,
  paths: { complete: BuilderSlotKey; builderRoot: BuilderSlotKey }
) {
  const hasComplete = Boolean(build[paths.complete]);
  const hasBuilderRoot = Boolean(build[paths.builderRoot]);
  if (hasComplete) return "complete" as const;
  if (hasBuilderRoot) return "builder" as const;
  return "none" as const;
}

function buildAssemblyRows(params: {
  groupLabel: string;
  build: BuildState;
  allowedIds: Set<BuilderSlotKey>;
  paths: {
    complete: BuilderSlotKey;
    builderRoot: BuilderSlotKey;
    builderChildren: BuilderSlotKey[];
  };
}): TableRow[] {
  const { groupLabel, build, allowedIds, paths } = params;

  const mode = getAssemblyMode(build, paths);

  const rows: TableRow[] = [];

  rows.push({
    key: `${groupLabel}-note`,
    kind: "note",
    label: `${groupLabel} (choose one path)`,
    tone: "muted",
    pill: "Complete OR Builder Path",
  });

  if (allowedIds.has(paths.complete)) {
    rows.push({
      key: `${groupLabel}-${paths.complete}`,
      kind: "category",
      label: "Completed Lower (Fastest)",
      categoryId: paths.complete,
      indent: 0,
      pill: mode === "complete" ? "Selected" : undefined,
    });
  }

  if (allowedIds.has(paths.builderRoot)) {
    rows.push({
      key: `${groupLabel}-${paths.builderRoot}`,
      kind: "category",
      label: "Build From Parts (Stripped + LPK)",
      categoryId: paths.builderRoot,
      indent: 0,
      pill: mode === "builder" ? "Selected" : undefined,
    });
  }

  const children = paths.builderChildren.filter((id) => allowedIds.has(id));
  for (const cid of children) {
    rows.push({
      key: `${groupLabel}-${cid}`,
      kind: "category",
      label: "",
      categoryId: cid,
      indent: 1,
      locked: mode === "complete",
      pill: mode === "builder" ? "required" : undefined,
      tone: mode === "complete" ? "muted" : "normal",
    });
  }

  return rows;
}

function GunbuilderPageContent() {
  const searchParams = useSearchParams();
  const router = useRouter();

  const api = useApi();

  // ✅ Auth: check if user is logged in
  const { user, loading: authLoading } = useAuth();

  const [platform, setPlatform] = useState<(typeof PLATFORMS)[number]>("AR15");

  // Canonical, URL-safe platform (AR15 / AR10 / AR9)
  const canonicalPlatform = normalizePlatformKey(platform);
  // -----------------------------
  // Save As… modal state (Vault variants)
  // -----------------------------
  const [saveAsOpen, setSaveAsOpen] = useState(false);
  const [saveAsTitle, setSaveAsTitle] = useState("");
  const [saveAsDesc, setSaveAsDesc] = useState("");
  const [saveAsSaving, setSaveAsSaving] = useState(false); // prevents double-submit

  // -----------------------------
  // Parts data state
  // -----------------------------
  const [parts, setParts] = useState<Part[]>([]);
  const previousPartIdsRef = useRef<Set<string>>(new Set());
  const isFirstPartsHydrationRef = useRef(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // -----------------------------
  // Build state (categoryId -> productId), persisted locally
  // -----------------------------
  const [build, setBuild] = useState<BuildState>({});

  // Hydration guard: avoid SSR/CSR HTML mismatch (platform/build were previously derived from window/localStorage)
  const [isHydrated, setIsHydrated] = useState(false);

  useEffect(() => {
    if (typeof window === "undefined") return;

    // Intentional: Object.keys(...).length > 0 tightens the original condition.
    // Previously, an empty {} from localStorage would call setBuild(normalizeBuildState({})),
    // which is a no-op. The new check skips that call, which is safe and correct.
    let hasBuild = false;
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      try {
        const parsed = JSON.parse(stored);
        if (parsed && typeof parsed === "object" && Object.keys(parsed).length > 0) {
          setBuild(normalizeBuildState(parsed));
          hasBuild = true;
        }
      } catch {
        // ignore
      }
    }

    // Fire build_started only for genuinely new builds:
    // - No existing parts in localStorage
    // - No ?select= param (share-link arrivals have empty localStorage but are not starting fresh)
    // Use window.location.search directly: this effect runs at mount before any router
    // processing, making window.location.search the authoritative source of the landing URL.
    const hasSelectParam = new URLSearchParams(window.location.search).has("select");
    if (!hasBuild && !hasSelectParam) {
      trackBuildStarted();
    }

    // Signal that hydration is complete - this allows URL param processing to run
    setIsHydrated(true);
  }, []);

  type PageResponse<T> = {
    content: T[];
    totalElements?: number;
    totalPages?: number;
    number?: number;
    size?: number;
  };

  function unwrapPage<T>(json: any): T[] {
    if (!json) return [];
    if (Array.isArray(json)) return json;
    if (Array.isArray(json.content)) return json.content;
    return [];
  }

  // -----------------------------
  // Toast notifications (save success / errors)
  // -----------------------------
  type Toast = { type: "success" | "error" | "info"; message: string };
  const [toast, setToast] = useState<Toast | null>(null);

  const showToast = useCallback((t: Toast) => {
    setToast(t);
    window.setTimeout(() => setToast(null), 3500);
  }, []);

  // -----------------------------
  // Misc UI state
  // -----------------------------
  const [shareStatus, setShareStatus] = useState<string | null>(null);
  const [shareUrl, setShareUrl] = useState<string>("");

  // Guards so “platform change clears build” does NOT run on initial hydration / URL sync.
  const didHydrateRef = useRef(false);
  const lastPlatformRef = useRef(platform);

  // Guard to prevent infinite loops when processing ?select / ?remove
  const processedActionKeyRef = useRef<string>("");

  // -----------------------------
  // Derived collections
  // -----------------------------
  const partsByCategory: Record<BuilderSlotKey, Part[]> = useMemo(() => {
    const grouped = {} as Record<BuilderSlotKey, Part[]>;
    for (const category of CATEGORIES) {
      grouped[category.id] = parts.filter((p) => p.categoryId === category.id);
    }
    return grouped;
  }, [parts]);

  const selectedParts: Part[] = useMemo(() => {
    const seen = new Set<string>();
    const resolved = Object.values(build)
      .map((partId) =>
        partId ? parts.find((p) => p.id === partId) : undefined
      )
      .filter(Boolean) as Part[];

    return resolved.filter((p) => {
      if (seen.has(p.id)) return false;
      seen.add(p.id);
      return true;
    });
  }, [build, parts]);

  const selectedByCategory: Record<BuilderSlotKey, unknown> = useMemo(
    () =>
      Object.fromEntries(
        Object.entries(build).map(([categoryId, partId]) => [
          categoryId as BuilderSlotKey,
          partId ? true : false,
        ])
      ) as Record<BuilderSlotKey, unknown>,
    [build]
  );

  const allowedCategoryIds = useMemo(
    () => new Set(CATEGORIES.map((c) => c.id as BuilderSlotKey)),
    []
  );

  const quickChecklist = useMemo(
    () => computeQuickChecklistCounts(build, allowedCategoryIds),
    [build, allowedCategoryIds]
  );

  const totalPrice = useMemo(
    () => selectedParts.reduce((sum, p) => sum + p.price, 0),
    [selectedParts]
  );

  // -----------------------------
  // Role -> Category resolver
  // NOTE: defensive while backend roles/mappings evolve
  // -----------------------------
  const resolveCategoryId = (normalizedRole: string): BuilderSlotKey | null => {
    if (normalizedRole === "upper-receiver") return "upper-receiver";
    if (normalizedRole.includes("complete-upper")) return "complete-upper";

    if (normalizedRole === "lower-receiver") return "lower-receiver";
    if (normalizedRole.includes("complete-lower")) return "complete-lower";

    if (normalizedRole === "upper") return "upper-receiver";
    if (normalizedRole === "lower") return "lower-receiver";

    if (normalizedRole.includes("charging")) return "charging-handle";

    if (
      normalizedRole.includes("handguard") ||
      (normalizedRole.includes("rail") &&
        !normalizedRole.includes("rail-accessory"))
    )
      return "handguard";

    if (
      normalizedRole.includes("bcg") ||
      normalizedRole.includes("bolt-carrier")
    )
      return "bcg";

    if (normalizedRole.includes("barrel")) return "barrel";

    if (
      normalizedRole.includes("gas-block") ||
      normalizedRole.includes("gasblock")
    )
      return "gas-block";

    if (
      normalizedRole.includes("gas-tube") ||
      normalizedRole.includes("gastube")
    )
      return "gas-tube";

    if (
      normalizedRole.includes("muzzle") ||
      normalizedRole.includes("flash") ||
      normalizedRole.includes("brake") ||
      normalizedRole.includes("comp")
    )
      return "muzzle-device";

    if (normalizedRole.includes("suppress")) return "suppressor";

    //  Lower Parts Kit canonical key
    if (
      normalizedRole.includes("lower-parts") ||
      normalizedRole.includes("lpk")
    )
      return "lower-parts-kit";

    if (normalizedRole.includes("trigger")) return "trigger";
    if (normalizedRole.includes("grip")) return "grip";

    //  Safety canonical key
    if (
      normalizedRole.includes("safety") ||
      normalizedRole.includes("selector")
    )
      return "safety-selector";

    if (normalizedRole.includes("buffer")) return "buffer";
    if (normalizedRole.includes("stock")) return "stock";

    if (normalizedRole.includes("optic") || normalizedRole.includes("scope"))
      return "optic";
    if (normalizedRole.includes("sight")) return "sights";

    if (normalizedRole.includes("mag")) return "magazine";

    if (
      normalizedRole.includes("weapon-light") ||
      (normalizedRole.includes("light") && !normalizedRole.includes("flight"))
    )
      return "weapon-light";

    if (
      normalizedRole.includes("foregrip") ||
      normalizedRole.includes("grip-vertical")
    )
      return "foregrip";

    if (normalizedRole.includes("bipod")) return "bipod";
    if (normalizedRole.includes("sling")) return "sling";

    if (
      normalizedRole.includes("rail-accessory") ||
      normalizedRole.includes("rail-attachment")
    )
      return "rail-accessory";

    if (normalizedRole.includes("tool")) return "tools";

    return (PART_ROLE_TO_CATEGORY as any)[normalizedRole] ?? null;
  };

  // -----------------------------
  // Hydrate selected parts (only) from backend
  // -----------------------------
  const lastHydrateKeyRef = useRef<string>("");

  useEffect(() => {
    const controller = new AbortController();

    async function hydrateSelected() {
      const ids = (Object.values(build).filter(Boolean) as string[])
        .map(String)
        .sort();

      const key = ids.join(",");

      // If nothing selected, reset
      if (ids.length === 0) {
        lastHydrateKeyRef.current = "";
        setParts([]);
        previousPartIdsRef.current = new Set(); // keep in sync so re-selecting fires the event
        setError(null);
        setLoading(false);
        return;
      }

      // Only skip if we *successfully* hydrated this key previously
      if (key === lastHydrateKeyRef.current) return;

      setLoading(true);
      setError(null);

      try {
        const res = await fetch(
          `/api/catalog/products/by-ids`,
          {
            method: "POST",
            signal: controller.signal,
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ ids }),
          }
        );

        if (!res.ok) throw new Error(`Failed to hydrate parts (${res.status})`);

        const data: GunbuilderProductFromApi[] = await res.json();

        const byId = new Map<string, GunbuilderProductFromApi>();
        for (const p of data) byId.set(String(p.id), p);

        const hydrated: Part[] = Object.entries(build)
          .filter(([, id]) => Boolean(id))
          .map(([slot, id]) => {
            const p = byId.get(String(id));
            if (!p) return null;

            const buyUrl = p.buyUrl ?? undefined;

            return {
              id: String(p.id),
              categoryId: slot as any,
              name: p.name,
              brand: p.brand,
              price: p.price ?? 0,
              imageUrl: p.imageUrl ?? undefined,
              affiliateUrl: buyUrl,
              url: buyUrl,
            } as Part;
          })
          .filter((x): x is Part => x !== null);

        setParts(hydrated);

        // Track newly selected parts after API fetch — fires with real name, not a numeric ID.
        // Skip the first hydration: this covers both localStorage build restoration and ?select=
        // share-link arrivals. Neither represents a live user interaction in the current session.
        if (isFirstPartsHydrationRef.current) {
          isFirstPartsHydrationRef.current = false;
        } else {
          const prevIds = previousPartIdsRef.current;
          for (const p of hydrated) {
            if (!prevIds.has(String(p.id))) {
              trackPartSelected(p.categoryId as BuilderSlotKey, p.name, String(p.id));
            }
          }
        }
        previousPartIdsRef.current = new Set(hydrated.map((p) => String(p.id)));

        // ✅ Mark key as hydrated ONLY after success
        lastHydrateKeyRef.current = key;
      } catch (err: any) {
        if (err?.name === "AbortError") {
          // ✅ Do NOT lock the key on abort; allow retry
          return;
        }
        setError(err?.message ?? "Failed to hydrate selected parts");
      } finally {
        setLoading(false);
      }
    }

    hydrateSelected();
    return () => controller.abort();
  }, [build]);

  // -----------------------------
  // Persist build to localStorage
  // -----------------------------
  useEffect(() => {
    if (typeof window === "undefined") return;
    if (!isHydrated) return;
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(build));
    } catch {
      // ignore
    }
  }, [build, isHydrated]);

  // -----------------------------
  // When platform changes, clear ONLY platform-scoped selections
  // -----------------------------
  useEffect(() => {
    const prev = lastPlatformRef.current;
    lastPlatformRef.current = platform;

    if (!didHydrateRef.current) {
      didHydrateRef.current = true;
      return;
    }

    if (prev === platform) return;

    setBuild((prevBuild) => {
      const next: BuildState = {};
      for (const [categoryId, partId] of Object.entries(prevBuild)) {
        const cid = categoryId as BuilderSlotKey;
        if (UNIVERSAL_CATEGORIES.has(cid)) {
          next[cid] = partId;
        }
      }
      return next;
    });
  }, [platform]);

  // -----------------------------
  // Load a saved build from Vault via ?load=<uuid> OR legacy ?build=<uuid>
  // -----------------------------
  useEffect(() => {
    const loadUuid = searchParams.get("load");
    const buildParam = searchParams.get("build");

    const uuidToLoad =
      (loadUuid && isUuid(loadUuid) ? loadUuid : null) ||
      (buildParam && isUuid(buildParam) ? buildParam : null);

    if (!uuidToLoad) return;

    // Wait for AuthProvider hydration before calling /me endpoints.
    if (authLoading) return;

    // If not logged in, don't spam the backend; show a helpful message instead.
    if (!user) {
      setShareStatus("Please log in to load builds from your Vault.");
      window.setTimeout(() => setShareStatus(null), 4500);
      return;
    }

    const run = async () => {
      try {
        setShareStatus("Loading build…");

        // NOTE: using fetch here goes through our Next.js API routes with HTTP-only cookies
        const res = await fetch(
          `/api/builds/${encodeURIComponent(uuidToLoad)}`,
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        );

        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 refresh doesn't re-load repeatedly
        const qp = new URLSearchParams(searchParams.toString());
        qp.delete("load");
        if (buildParam && isUuid(buildParam)) qp.delete("build");

        const next = qp.toString();
        router.replace(next ? `/builder?${next}` : "/builder", {
          scroll: false,
        });
      } catch (e: any) {
        setShareStatus(e?.message ?? "Failed to load build");
      } finally {
        window.setTimeout(() => setShareStatus(null), 4500);
      }
    };

    run();
  }, [
    searchParams,
    router,
    authLoading,
    user,
  ]);

  // -----------------------------
  // SAVE AS… (single source of truth for saving to Vault)
  // - Creates a NEW saved build server-side
  // - Shows toast so users know it worked
  // -----------------------------
  const handleSaveAs = async () => {
    if (selectedParts.length === 0) {
      showToast({ type: "error", message: "Add a few parts before saving." });
      return;
    }

    const title = (saveAsTitle || `${platform} Build`).trim();
    if (!title) {
      showToast({ type: "error", message: "Title is required." });
      return;
    }

    const items = Object.entries(build)
      .filter(([, partId]) => !!partId)
      .map(([categoryId, partId]) => ({
        productId: Number(partId),
        slot: categoryId,
        position: 0,
        quantity: 1,
      }));

    try {
      setSaveAsSaving(true);
      showToast({ type: "info", message: "Saving build…" });

      const res = await api.post("/api/v1/builds/me", {
        title,
        description: saveAsDesc?.trim() || null,
        isPublic: false,
        items,
      });

      if (!res.ok) {
        const txt = await res.text().catch(() => "");
        throw new Error(txt || `Save failed (${res.status})`);
      }

      const saved = await res.json(); // BuildDto (expects { uuid, ... })

      // UX: copy UUID for quick testing + user confidence
      try {
        if (saved?.uuid) await navigator.clipboard.writeText(saved.uuid);
      } catch {
        // ignore clipboard failures
      }

      showToast({
        type: "success",
        message: "Saved to your Vault ✅ ",
      });
      trackBuildSaved();

      // Close modal + reset inputs for next variant
      setSaveAsOpen(false);
      setSaveAsTitle("");
      setSaveAsDesc("");
    } catch (e: any) {
      showToast({
        type: "error",
        message: e?.message ?? "Save failed",
      });
    } finally {
      setSaveAsSaving(false);
    }
  };

  // -----------------------------
  // Selection handler (with hint warnings)
  // -----------------------------
  const handleSelectPart = useCallback(
    (
      categoryId: BuilderSlotKey,
      partId: string,
      _opts?: { confirm?: boolean }
    ) => {
      const warn = (msg: string) => {
        setShareStatus(msg);
        window.setTimeout(() => setShareStatus(null), 4000);
      };

      const hints = getSelectionHints(categoryId, build);
      if (hints.length > 0) warn(hints[0]);

      setBuild((prev) => {
        const next: BuildState = {
          ...prev,
          [categoryId]: String(partId),
        };
        // Write-through so query-param selections survive Next/router replaces
        try {
          if (typeof window !== "undefined") {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
          }
        } catch {
          // ignore
        }
        return next;
      });
    },
    [build]
  );
  // Handle URL query parameters (?select, ?remove) and keep platform synced + canonical
  useEffect(() => {
    if (!isHydrated) return; // Wait for initial hydration to complete

    const sp = new URLSearchParams(searchParams.toString());

    const selectParam = sp.get("select");
    const removeParam = sp.get("remove");

    // Normalize platform from URL (AR-15 -> AR15)
    const qpPlatformRaw = sp.get("platform");
    const qpPlatform = normalizePlatformKey(qpPlatformRaw ?? "");

    // Decide canonical platform to use (URL if valid, else current state)
    const nextPlatform = isValidPlatform(qpPlatform) ? qpPlatform : platform;

    // Keep React state in sync (only when needed)
    if (isValidPlatform(qpPlatform) && qpPlatform !== platform) {
      setPlatform(qpPlatform);
    }

    // Prevent repeating select/remove actions
    const actionKey = `${selectParam ?? ""}|${
      removeParam ?? ""
    }|${nextPlatform}`;
    const hasAction = !!selectParam || !!removeParam;

    if (hasAction) {
      if (processedActionKeyRef.current !== actionKey) {
        processedActionKeyRef.current = actionKey;

        if (selectParam) {
          const [categoryIdRaw, partId] = selectParam.split(":");
          const requestedCategoryId = categoryIdRaw as BuilderSlotKey;

          if (requestedCategoryId && partId) {
            handleSelectPart(requestedCategoryId, partId, { confirm: false });
          }
        }

        if (removeParam) {
          if (CATEGORIES.some((c) => c.id === removeParam)) {
            setBuild((prev) => {
              const next: BuildState = { ...prev };
              delete next[removeParam as BuilderSlotKey];
              try {
                if (typeof window !== "undefined") {
                  localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
                }
              } catch {
                // ignore
              }
              return next;
            });
          }
        }
      }
    } else {
      // no action params → allow future actions to run
      processedActionKeyRef.current = "";
    }

    // Canonicalize URL: set platform to canonical key and remove action params
    const before = searchParams.toString();

    sp.set("platform", nextPlatform);
    sp.delete("select");
    sp.delete("remove");

    const after = sp.toString();

    if (after !== before) {
      // Delay replace one tick so state updates from select/remove are not lost
      // during RSC navigation / dev strict mode.
      window.setTimeout(() => {
        router.replace(`/builder?${after}`, { scroll: false });
      }, 0);
    }
  }, [searchParams, router, platform, handleSelectPart, isHydrated]);

  // Build share URL whenever build changes (client-side only)
  useEffect(() => {
    if (typeof window === "undefined") return;

    if (Object.keys(build).length === 0) {
      setShareUrl("");
      return;
    }

    try {
      const payload = JSON.stringify(build);
      const encoded = window.btoa(payload);
      const origin = window.location?.origin ?? "";
      const url = `${origin}/builder/build?build=${encodeURIComponent(
        encoded
      )}`;
      setShareUrl(url);
    } catch {
      setShareUrl("");
    }
  }, [build]);

  const summaryCategoryOrder: BuilderSlotKey[] = useMemo(
    () =>
      CATEGORY_GROUPS.flatMap((group) => group.categoryIds).filter((id) =>
        CATEGORIES.some((c) => c.id === id)
      ),
    []
  );

  // Copy summary text to clipboard
  const handleShare = async () => {
    if (selectedParts.length === 0) {
      setShareStatus("Add a few parts before sharing your build.");
      return;
    }

    const lines: string[] = [];
    lines.push("Battl Build");
    lines.push("");
    lines.push(`Total: $${totalPrice.toFixed(2)}`);
    lines.push("");

    summaryCategoryOrder.forEach((categoryId) => {
      const cat = CATEGORIES.find((c) => c.id === categoryId);
      if (!cat) return;

      const selectedPartId = build[cat.id];
      const part = parts.find(
        (p) => p.id === selectedPartId && p.categoryId === cat.id
      );

      if (part) {
        lines.push(
          `${cat.name}: ${part.brand} — ${part.name} ($${part.price.toFixed(
            2
          )})`
        );
      } else {
        lines.push(`${cat.name}: [Not selected]`);
      }
    });

    const text = lines.join("\n");

    try {
      await navigator.clipboard.writeText(text);
      setShareStatus("Build summary copied to clipboard.");
    } catch {
      setShareStatus(
        "Could not access clipboard. You can copy from the build summary page."
      );
    }
  };

  const handleCopyLink = async () => {
    if (!shareUrl) {
      setShareStatus("No shareable link available yet.");
      return;
    }

    try {
      await navigator.clipboard.writeText(shareUrl);
      trackBuildShared();
      setShareStatus("Shareable link copied to clipboard.");
    } catch {
      setShareStatus("Could not copy link to clipboard.");
    }
  };

  const handleNativeShare = async () => {
    if (!shareUrl) {
      setShareStatus("No shareable link available yet.");
      return;
    }

    if (navigator.share) {
      try {
        await navigator.share({
          title: "BATTL — The Builder",
          text: "Check out my Battl Build.",
          url: shareUrl,
        });
        trackBuildShared(); // fires only on successful share, not on cancel
        setShareStatus("Share dialog opened.");
      } catch {
        setShareStatus(
          "Share canceled or unavailable. You can copy the link instead."
        );
      }
    } else {
      await handleCopyLink();
    }
  };

  if (!isHydrated) {
    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">
          <div className="rounded-lg border border-zinc-800 bg-zinc-950/80 p-4">
            <div className="text-sm text-zinc-400">Loading builder…</div>
          </div>
        </div>
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-white text-zinc-900 dark:bg-black dark:text-zinc-50">
      {/* Toast (top-right) */}
      {toast && (
        <div className="fixed top-4 right-4 z-50">
          <div
            className={`rounded-lg border px-4 py-3 text-sm shadow-lg backdrop-blur
              ${
                toast.type === "success"
                  ? "border-emerald-500/30 bg-emerald-500/15 text-emerald-100"
                  : toast.type === "error"
                  ? "border-red-500/30 bg-red-500/15 text-red-100"
                  : "border-white/10 bg-white/10 text-white"
              }`}
          >
            {toast.message}
          </div>
        </div>
      )}

      {/* Save As… Modal */}
      {saveAsOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
          <div className="w-full max-w-lg rounded-xl border border-white/10 bg-zinc-950 p-4">
            <div className="flex items-start justify-between gap-4">
              <div>
                <div className="text-sm font-semibold">Save As…</div>
                <div className="text-xs text-zinc-400">
                  Create a new saved build variant in your Vault.
                </div>
              </div>

              <button
                type="button"
                onClick={() => setSaveAsOpen(false)}
                className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-xs hover:bg-white/10"
              >
                Close
              </button>
            </div>

            <div className="mt-4 space-y-3">
              <div>
                <label className="block text-xs font-medium text-zinc-300">
                  Title
                </label>
                <input
                  value={saveAsTitle}
                  onChange={(e) => setSaveAsTitle(e.target.value)}
                  placeholder={`e.g. "${platform} Mk2 (Suppressed)"`}
                  className="mt-1 w-full rounded-md border border-white/10 bg-black/30 px-3 py-2 text-sm text-white outline-none focus:ring-1 focus:ring-amber-400/60"
                />
              </div>

              <div>
                <label className="block text-xs font-medium text-zinc-300">
                  Description (optional)
                </label>
                <textarea
                  value={saveAsDesc}
                  onChange={(e) => setSaveAsDesc(e.target.value)}
                  rows={3}
                  placeholder="Notes for future-you…"
                  className="mt-1 w-full rounded-md border border-white/10 bg-black/30 px-3 py-2 text-sm text-white outline-none focus:ring-1 focus:ring-amber-400/60"
                />
              </div>

              <div className="flex items-center justify-end gap-2 pt-2">
                <button
                  type="button"
                  onClick={() => setSaveAsOpen(false)}
                  className="text-sm text-zinc-300 hover:underline"
                  disabled={saveAsSaving}
                >
                  Cancel
                </button>

                <button
                  type="button"
                  onClick={handleSaveAs}
                  disabled={saveAsSaving}
                  className={`rounded-md px-4 py-2 text-sm font-semibold text-black ${
                    saveAsSaving
                      ? "bg-amber-400/60 cursor-not-allowed"
                      : "bg-amber-400 hover:bg-amber-300"
                  }`}
                >
                  {saveAsSaving ? "Saving…" : "Save"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="mx-auto max-w-6xl px-4 py-6 lg:py-10">
        {/* Header */}
        <header className="mb-6">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <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">
                Builder <span className="text-amber-300">Early Access</span>
              </h1>
              <p className="mt-2 text-sm text-zinc-400 max-w-xl">
                Explore components from trusted brands, choose one part per
                category, track live prices, and watch your total build cost
                update as you go. This early-access builder keeps your setup saved
                locally so you can come back and refine it anytime.
              </p>
            </div>

            {user?.role === "ADMIN" ? (
              <Link
                href="/admin"
                className="inline-flex items-center gap-2 rounded-md border border-amber-400/40 bg-amber-400/10 px-3 py-2 text-xs font-semibold text-amber-200 hover:border-amber-300 hover:text-amber-100"
              >
                Admin Toolbar →
              </Link>
            ) : null}
          </div>

          <div className="mt-4 flex flex-wrap items-center gap-3">
            <label className="text-xs font-medium text-zinc-400 flex items-center gap-2">
              Platform
              <select
                value={platform}
                onChange={(e) => {
                  const next = e.target.value as (typeof PLATFORMS)[number];
                  setPlatform(next);

                  // Keep URL in sync, and clear transient action params
                  const qp = new URLSearchParams(searchParams.toString());
                  qp.set("platform", normalizePlatformKey(next));
                  qp.delete("select");
                  qp.delete("remove");

                  router.replace(`/builder?${qp.toString()}`, {
                    scroll: false,
                  });
                }}
                className="rounded-md border border-zinc-700 bg-zinc-900 px-2 py-1 text-xs text-zinc-100 focus:outline-none focus:ring-1 focus:ring-amber-400"
              >
                {PLATFORMS.map((p) => (
                  <option key={p} value={p}>
                    {PLATFORM_LABEL[p]}
                  </option>
                ))}
              </select>
            </label>
            <p className="text-[0.7rem] text-zinc-500">
                Parts list updates automatically when you change platforms.
              </p>
            </div>
        </header>

        {/* Build summary panel */}
        <section className="mb-6 rounded-lg border border-zinc-800 bg-zinc-950/80 p-3 md:p-4 flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
          {/* Left */}
          <div className="flex flex-col gap-2">
            <h2 className="text-xs font-semibold uppercase tracking-[0.16em] text-amber-300">
              My Build Breakdown
            </h2>

            <div>
              <div className="text-xs text-zinc-400">Current build total</div>
              <div className="text-2xl font-semibold text-amber-300">
                ${totalPrice.toFixed(2)}
              </div>
              <div className="text-xs text-zinc-500 mt-1">
                {selectedParts.length} / {CATEGORIES.length} categories filled
              </div>
            </div>

            <div className="mt-2 flex flex-col items-stretch gap-2 sm:flex-row sm:flex-wrap">
              <button
                type="button"
                onClick={handleShare}
                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-zinc-900/80 text-zinc-200 border-zinc-700 hover:bg-zinc-800"
                }`}
                disabled={selectedParts.length === 0}
              >
                Copy Build Summary
              </button>

              <button
                type="button"
                onClick={() => {
                  // Reset local build state
                  setBuild({});
                  if (typeof window !== "undefined") {
                    localStorage.removeItem(STORAGE_KEY);
                  }
                  showToast({ type: "info", message: "Build cleared." });
                }}
                disabled={selectedParts.length === 0}
                className={`w-full sm:w-auto rounded-md border border-zinc-700 bg-zinc-900/50 px-3 py-2 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors ${
                  selectedParts.length === 0
                    ? "opacity-40 cursor-not-allowed"
                    : ""
                }`}
              >
                Clear Build
              </button>

              {/* Save As… triggers modal */}
              <button
                type="button"
                onClick={() => setSaveAsOpen(true)}
                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 As…
              </button>

              {/* Optional: quick access to Vault */}
              <Link
                href="/vault"
                className="w-full sm:w-auto rounded-md border border-white/10 bg-white/5 px-3 py-2 text-sm font-medium text-zinc-200 hover:bg-white/10 text-center"
              >
                Go to Vault →
              </Link>
            </div>
          </div>

          {/* Right */}
          <div className="flex flex-col gap-3 md:items-end md:text-right md:flex-1">
            {selectedParts.length > 0 && shareUrl && (
              <div className="w-full md:w-auto">
                <h3 className="text-[0.7rem] font-semibold uppercase tracking-[0.16em] text-zinc-400">
                  Share Your Build
                </h3>
                <p className="mt-1 text-[0.7rem] text-zinc-500">
                  Share this link to let others view your build or bookmark it
                  to come back later.
                </p>

                <div className="mt-2 flex flex-col gap-2 md:flex-row md:items-center">
                  <div className="flex-1">
                    <div className="text-[0.65rem] uppercase tracking-[0.16em] text-zinc-500 mb-1">
                      Shareable URL
                    </div>
                    <input
                      type="text"
                      readOnly
                      value={shareUrl}
                      className="w-full rounded-md border border-zinc-700 bg-zinc-950/80 px-2 py-1.5 text-[0.7rem] text-zinc-200 font-mono outline-none focus:ring-1 focus:ring-amber-400"
                    />
                  </div>

                  <div className="flex gap-2 md:flex-none md:mt-5">
                    <button
                      type="button"
                      onClick={handleNativeShare}
                      className="flex-1 md:flex-none rounded-md bg-zinc-900/80 px-3 py-1.5 text-[0.75rem] font-semibold text-zinc-100 border border-zinc-700 hover:bg-zinc-800 hover:border-zinc-500 transition-colors"
                    >
                      Share
                    </button>

                    <button
                      type="button"
                      onClick={handleCopyLink}
                      className="flex-1 md:flex-none rounded-md bg-amber-400 px-3 py-1.5 text-[0.75rem] font-semibold text-black hover:bg-amber-300 transition-colors"
                    >
                      Copy Link
                    </button>
                  </div>
                </div>
              </div>
            )}

            {shareStatus && (
              <p className="mt-1 text-[0.7rem] text-zinc-500">{shareStatus}</p>
            )}
          </div>
        </section>

        {/* Quick Checklist (new user-friendly) */}
        <section className="mb-6 rounded-lg border border-zinc-800 bg-zinc-950/60 p-3 md:p-4">
          <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
            <div>
              <h2 className="text-[0.7rem] font-semibold uppercase tracking-[0.16em] text-zinc-500">
                Quick Checklist
              </h2>
              <p className="mt-1 text-xs text-zinc-500 max-w-2xl">
                New here? Focus on the{" "}
                <span className="text-amber-300">Required</span> items first.
                Optional items live under accessories and upgrades. Use the
                floating hub (bottom-right) to jump to anything you&apos;re
                missing.
              </p>
            </div>

            <div className="flex items-center gap-3">
              <div className="rounded-lg border border-white/10 bg-white/5 px-3 py-2">
                <div className="text-[0.65rem] uppercase tracking-[0.14em] text-zinc-500">
                  Required
                </div>
                <div className="mt-0.5 text-sm font-semibold text-zinc-100">
                  {quickChecklist.requiredDone}
                  <span className="text-zinc-500"> / </span>
                  {quickChecklist.requiredTotal}
                </div>
              </div>

              <div className="rounded-lg border border-white/10 bg-white/5 px-3 py-2">
                <div className="text-[0.65rem] uppercase tracking-[0.14em] text-zinc-500">
                  Optional
                </div>
                <div className="mt-0.5 text-sm font-semibold text-zinc-100">
                  {quickChecklist.optionalDone}
                  <span className="text-zinc-500"> / </span>
                  {quickChecklist.optionalTotal}
                </div>
              </div>
            </div>
          </div>
        </section>

        {/* Layout */}
        <section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-3 md:p-4">
          <p className="mb-4 text-xs text-zinc-500">
            Work top-down through the major sections. Each row shows your
            current pick for that part type, with price and a direct buy link—or
            a quick way to choose a part if you haven&apos;t picked one yet.
          </p>

          {loading && (
            <p className="text-sm text-zinc-500">Loading parts from backend…</p>
          )}
          {error && !loading && (
            <p className="text-sm text-red-400">
              {error} — check that the Ballistic API is running and CORS is
              configured.
            </p>
          )}

          {!loading && !error && (
            <div className="space-y-6">
              {CATEGORY_GROUPS.map((group) => {
                const groupCategories = CATEGORIES.filter((c) =>
                  group.categoryIds.includes(c.id as BuilderSlotKey)
                );

                const allowedIds = new Set(
                  groupCategories.map((c) => c.id as BuilderSlotKey)
                );

                const isLower = group.id === "lower-group";
                const isUpper = group.id === "upper-group";

                const tableRows: TableRow[] = isLower
                  ? buildAssemblyRows({
                      groupLabel: "Lower Assembly",
                      build,
                      allowedIds,
                      paths: LOWER_PATHS,
                    })
                  : isUpper
                  ? buildAssemblyRows({
                      groupLabel: "Upper Assembly",
                      build,
                      allowedIds,
                      paths: UPPER_PATHS,
                    })
                  : groupCategories.map((c) => ({
                      key: c.id,
                      kind: "category",
                      label: "",
                      categoryId: c.id as BuilderSlotKey,
                      indent: 0,
                    }));

                if (groupCategories.length === 0) return null;

                // Check if there are locked/conflicting parts in this group
                const hasConflicts = tableRows.some(
                  (row) => row.kind === "category" && row.locked
                );

                return (
                  <div
                    id={`group-${group.id}`}
                    key={group.id}
                    className="space-y-3"
                  >
                    {" "}
                    <div className="flex items-baseline justify-between gap-2">
                      <div>
                        <h2 className="text-sm font-semibold text-zinc-100">
                          {group.label}
                        </h2>
                        {group.description && (
                          <p className="text-xs text-zinc-500 mt-1 max-w-xl">
                            {group.description}
                          </p>
                        )}
                      </div>
                    </div>

                    {hasConflicts && (
                      <div className="rounded-md border border-amber-500/30 bg-amber-500/10 p-3">
                        <div className="flex items-start gap-2">
                          <span className="text-amber-400 text-sm">⚠</span>
                          <div className="flex-1">
                            <p className="text-sm font-medium text-amber-300">
                              Part Conflict Detected
                            </p>
                            <p className="text-xs text-zinc-300 mt-1">
                              Some parts below are disabled because you've selected a complete assembly that already includes them. To customize individual parts, remove the complete assembly first.
                            </p>
                          </div>
                        </div>
                      </div>
                    )}

                    <div className="overflow-x-auto rounded-md border border-zinc-800 bg-zinc-950/80">
                      <table className="min-w-full text-[11px] sm:text-xs md:text-sm">
                        <thead>
                          <tr className="border-b border-zinc-800 bg-zinc-900/60">
                            <th className="px-2 sm:px-3 py-2 text-left font-semibold text-zinc-400">
                              Component / Part Type
                            </th>
                            <th className="hidden sm:table-cell px-2 sm:px-3 py-2 text-left font-semibold text-zinc-400">
                              Brand
                            </th>
                            <th className="px-2 sm:px-3 py-2 text-right font-semibold text-zinc-400">
                              Price
                            </th>
                            <th className="hidden md:table-cell px-2 sm:px-3 py-2 text-right font-semibold text-zinc-400">
                              Sale Price
                            </th>
                            <th className="hidden md:table-cell px-2 sm:px-3 py-2 text-left font-semibold text-zinc-400">
                              Caliber
                            </th>
                            <th className="px-2 sm:px-3 py-2 text-right font-semibold text-zinc-400">
                              Buy / Choose
                            </th>
                          </tr>
                        </thead>

                        <tbody>
                          {tableRows.map((row) => {
                            if (row.kind === "note") {
                              return (
                                <tr
                                  key={row.key}
                                  className="border-t border-zinc-900"
                                >
                                  <td
                                    colSpan={6}
                                    className="px-2 sm:px-3 py-2 text-[0.7rem] text-zinc-500 bg-zinc-950/70"
                                  >
                                    <div className="flex items-center justify-between gap-2">
                                      <div className="font-semibold text-zinc-400">
                                        {row.label}
                                      </div>
                                      {row.pill === "Selected" && (
                                        <span className="rounded-full border border-zinc-800 bg-zinc-900/60 px-2 py-0.5 text-[0.65rem] text-zinc-400">
                                          Selected
                                        </span>
                                      )}

                                      {row.pill === "required" && (
                                        <span className="ml-1 text-red-500">
                                          *
                                        </span>
                                      )}
                                    </div>
                                  </td>
                                </tr>
                              );
                            }

                            const categoryId = row.categoryId as BuilderSlotKey;
                            const category = CATEGORIES.find(
                              (c) => c.id === categoryId
                            );
                            if (!category) return null;

                            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)
                              : undefined;

                            const indent = row.indent ?? 0;
                            const isLocked = Boolean(row.locked);

                            return (
                              <tr
                                key={row.key}
                                className={`border-t border-zinc-900 hover:bg-zinc-900/60 transition-colors ${
                                  row.tone === "muted" ? "opacity-70" : ""
                                }`}
                              >
                                <td className="px-2 sm:px-3 py-2 align-top">
                                  <div className="flex items-start gap-2">
                                    {indent > 0 && (
                                      <div
                                        aria-hidden
                                        className="mt-1 h-3 w-3 rounded-sm border border-zinc-800 bg-zinc-950"
                                        style={{
                                          marginLeft: `${indent * 10}px`,
                                        }}
                                      />
                                    )}

                                    <div className="min-w-0">
                                      <div className="flex items-center gap-2">
                                        <div className="font-medium text-zinc-100">
                                          {row.label
                                            ? row.label
                                            : category.name}
                                        </div>
                                        {row.pill === "required" && (
                                          <span
                                            className="ml-1 text-red-400"
                                            aria-hidden="true"
                                          >
                                            *
                                          </span>
                                        )}
                                      </div>

                                      {selectedPart ? (
                                        <Link
                                          href={`/parts/p/${canonicalPlatform}/${category.id}/${selectedPart.id}-${selectedPart.name
                                            .toLowerCase()
                                            .replace(/[^a-z0-9]+/g, "-")
                                            .replace(/(^-|-$)/g, "")}`}
                                          className="text-[0.7rem] text-zinc-500 hover:text-amber-300 hover:underline line-clamp-1 transition-colors"
                                        >
                                          {selectedPart.name}
                                        </Link>
                                      ) : (
                                        <div className="text-[0.7rem] text-zinc-600">
                                          No part selected
                                        </div>
                                      )}
                                    </div>
                                  </div>
                                </td>

                                <td className="hidden sm:table-cell px-2 sm:px-3 py-2 align-top text-zinc-300">
                                  {selectedPart ? selectedPart.brand : "—"}
                                </td>

                                <td className="px-2 sm:px-3 py-2 align-top text-right text-amber-300">
                                  {selectedPart
                                    ? `$${selectedPart.price.toFixed(2)}`
                                    : "—"}
                                </td>

                                <td className="hidden md:table-cell px-2 sm:px-3 py-2 align-top text-right text-zinc-400">
                                  —
                                </td>
                                <td className="hidden md:table-cell px-2 sm:px-3 py-2 align-top text-zinc-400">
                                  —
                                </td>

                                <td className="px-2 sm:px-3 py-2 align-top">
                                  <div className="flex justify-end gap-2">
                                    {isLocked ? (
                                      <div className="flex items-center gap-2">
                                        <span className="text-[0.7rem] text-amber-400/70">
                                          ⚠ Disabled
                                        </span>
                                        <div className="group relative">
                                          <button
                                            type="button"
                                            className="text-zinc-500 hover:text-zinc-300 text-xs"
                                            title="Why is this disabled?"
                                          >
                                            ⓘ
                                          </button>
                                          <div className="invisible group-hover:visible absolute right-0 top-6 z-10 w-64 rounded-md border border-zinc-800 bg-zinc-950 p-3 text-xs text-zinc-300 shadow-xl">
                                            <p className="font-semibold text-amber-300 mb-1">
                                              Part Conflict
                                            </p>
                                            <p>
                                              You've selected a complete assembly which already includes this part. Remove the complete assembly to select individual parts.
                                            </p>
                                          </div>
                                        </div>
                                      </div>
                                    ) : selectedPart ? (
                                      <>
                                        {selectedPart.affiliateUrl && (
                                          <a
                                            href={selectedPart.affiliateUrl}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-md border border-amber-600 bg-amber-500 px-3 py-1.5 text-xs font-semibold text-black hover:bg-amber-400 transition-colors"
                                            onClick={() => {
                                              try {
                                                const retailer = new URL(selectedPart.affiliateUrl).hostname.replace(/^www\./, "");
                                                trackAffiliateLinkClicked(selectedPart.name, retailer);
                                              } catch {
                                                // ignore malformed URLs — if affiliateUrl is malformed, the link href is also broken
                                              }
                                            }}
                                          >
                                            Buy
                                          </a>
                                        )}
                                        <button
                                          type="button"
                                          onClick={() => {
                                            setBuild((prev) => {
                                              const next: BuildState = { ...prev };
                                              delete next[category.id];
                                              try {
                                                if (typeof window !== "undefined") {
                                                  localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
                                                }
                                              } catch {
                                                // ignore
                                              }
                                              return next;
                                            });
                                          }}
                                          className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-md border border-red-700 bg-red-900/50 px-3 py-1.5 text-xs font-medium text-red-300 hover:bg-red-900 hover:border-red-600 transition-colors"
                                        >
                                          Remove
                                        </button>
                                      </>
                                    ) : (
                                      <Link
                                        href={`/parts/${encodeURIComponent(
                                          category.id
                                        )}?platform=${encodeURIComponent(
                                          canonicalPlatform
                                        )}`}
                                        className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-md border border-zinc-700 bg-zinc-900/70 px-3 py-1.5 text-xs font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
                                      >
                                        Choose
                                      </Link>
                                    )}
                                  </div>
                                </td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </section>
      </div>
    </main>
  );
}

export default function GunbuilderPage() {
  return (
    <Suspense fallback={
      <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">
          <div className="rounded-lg border border-zinc-800 bg-zinc-950/80 p-4">
            <div className="text-sm text-zinc-400">Loading builder…</div>
          </div>
        </div>
      </main>
    }>
      <GunbuilderPageContent />
    </Suspense>
  );
}
