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

/**
 * 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)
 */

import { useMemo, useState, useEffect, useCallback, useRef } from "react";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";
import { CATEGORIES } from "@/data/gunbuilderParts";
import { BUILDER_SLOTS, isSlotSatisfied } from "@/data/builderSlots";
import type { CategoryId, Part } from "@/types/gunbuilder";
import { PART_ROLE_TO_CATEGORY } from "@/lib/catalogMappings";
import { X, Link2, Square, CheckSquare } from "lucide-react";

// ✅ 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 = ["AR-15", "AR-10", "AR-9"] as const;

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

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";

const STORAGE_KEY = "gunbuilder-build-state";

// Categories that should NOT be filtered by platform (universal accessories / gear)
const UNIVERSAL_CATEGORIES = new Set<CategoryId>([
  "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: CategoryId[];
}[] = [
  {
    id: "lower-group",
    label: "Lower Receiver Parts",
    description:
      "Everything from the serialized lower to small parts, fire control, and core controls.",
    categoryIds: [
      "lower-receiver",
      "complete-lower",
      "lower-parts",
      "trigger",
      "grip",
      "safety",
      "buffer",
      "stock",
    ],
  },
  {
    id: "upper-group",
    label: "Upper Receiver Parts",
    description:
      "Barrel, upper, gas system, and the parts that keep the rifle cycling.",
    categoryIds: [
      "upper-receiver",
      "complete-upper",
      "bcg",
      "barrel",
      "gas-block",
      "gas-tube",
      "muzzle-device",
      "suppressor",
      "handguard",
      "charging-handle",
      "sights",
      "optic",
    ],
  },
  {
    id: "accessories-group",
    label: "Accessories & Gear",
    description:
      "Universal add-ons that work across platforms — mags, lights, slings, tools, and more.",
    categoryIds: [
      "magazine",
      "weapon-light",
      "foregrip",
      "bipod",
      "sling",
      "rail-accessory",
      "tools",
    ],
  },
];

export default function GunbuilderPage() {
  const searchParams = useSearchParams();
  const router = useRouter();

  // -----------------------------
  // 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 [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(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
  // -----------------------------
  const [build, setBuild] = useState<BuildState>(() => {
    if (typeof window !== "undefined") {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        try {
          return JSON.parse(stored);
        } catch {
          return {};
        }
      }
    }
    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<CategoryId, Part[]> = useMemo(() => {
    const grouped = {} as Record<CategoryId, 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<CategoryId, unknown> = useMemo(
    () =>
      Object.fromEntries(
        Object.entries(build).map(([categoryId, partId]) => [
          categoryId as CategoryId,
          partId ? true : false,
        ])
      ) as Record<CategoryId, unknown>,
    [build]
  );

  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): CategoryId | 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";

    if (
      normalizedRole.includes("lower-parts") ||
      normalizedRole.includes("lpk")
    )
      return "lower-parts";

    if (normalizedRole.includes("trigger")) return "trigger";
    if (normalizedRole.includes("grip")) return "grip";
    if (normalizedRole.includes("safety")) return "safety";
    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;
  };

  // -----------------------------
  // Selection handler (with hint warnings)
  // -----------------------------
  const handleSelectPart = useCallback(
    (categoryId: CategoryId, 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) => ({
        ...prev,
        [categoryId]: partId,
      }));
    },
    [build]
  );

  // -----------------------------
  // Fetch products (scoped + universal merge)
  // -----------------------------
  useEffect(() => {
    const controller = new AbortController();

    async function fetchProducts() {
      try {
        setLoading(true);
        setError(null);

        const scopedUrl = `${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent(
          platform
        )}`;
        const universalUrl = `${API_BASE_URL}/api/v1/products`;

        const [scopedRes, universalRes] = await Promise.all([
          fetch(scopedUrl, { signal: controller.signal }),
          fetch(universalUrl, { signal: controller.signal }).catch(
            () => null as any
          ),
        ]);

        if (!scopedRes || !scopedRes.ok) {
          const status = scopedRes?.status ?? "";
          throw new Error(`Failed to load products (${status})`);
        }

        const scopedData: GunbuilderProductFromApi[] = await scopedRes.json();

        let universalData: GunbuilderProductFromApi[] = [];
        if (universalRes && universalRes.ok) {
          universalData = await universalRes.json();
        }

        const normalize = (data: GunbuilderProductFromApi[]): Part[] =>
          data
            .map((p): Part | null => {
              const normalizedRole = (p.partRole ?? "")
                .trim()
                .toLowerCase()
                .replace(/_/g, "-");

              const categoryId = resolveCategoryId(normalizedRole);
              if (!categoryId) return null;

              // Only accept universal fetch results for "universal" categories
              if (
                data === universalData &&
                !UNIVERSAL_CATEGORIES.has(categoryId)
              ) {
                return null;
              }

              const buyUrl = p.buyUrl ?? undefined;

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

        const scopedParts = normalize(scopedData);
        const universalParts = normalize(universalData);

        // Merge (avoid duplicates across calls)
        const seen = new Set<string>();
        const merged: Part[] = [];
        for (const p of [...scopedParts, ...universalParts]) {
          const key = `${p.categoryId}:${p.id}`;
          if (seen.has(key)) continue;
          seen.add(key);
          merged.push(p);
        }

        setParts(merged);
      } catch (err: any) {
        if (err?.name === "AbortError") return;
        setError(err?.message ?? "Failed to load products");
      } finally {
        setLoading(false);
      }
    }

    fetchProducts();
    return () => controller.abort();
  }, [platform]);

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

  // -----------------------------
  // 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 CategoryId;
        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;

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

        const res = await fetch(
          `${API_BASE_URL}/api/v1/builds/me/${encodeURIComponent(uuidToLoad)}`,
          { credentials: "include" }
        );

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

        const dto = await res.json(); // BuildDto w/ items
        const nextBuild: Record<string, string> = {};

        for (const it of dto.items ?? []) {
          if (!it?.slot || !it?.productId) continue;
          nextBuild[it.slot] = String(it.productId);
        }

        setBuild(nextBuild);
        setShareStatus(`Loaded: ${dto.title}`);

        // Clean URL so 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();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams, router]);

  // -----------------------------
  // 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 fetch(`${API_BASE_URL}/api/v1/builds/me`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          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 Vault ✅ (UUID copied)",
      });

      // 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);
    }
  };

  // -----------------------------
  // 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");

    const actionKey = `${selectParam ?? ""}|${removeParam ?? ""}|${
      qpPlatform ?? ""
    }`;

    if (!selectParam && !removeParam) {
      processedActionKeyRef.current = "";
      return;
    }

    if (processedActionKeyRef.current === actionKey) return;
    processedActionKeyRef.current = actionKey;

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

      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 CategoryId];
          return next;
        });
      }
    }

    const nextPlatform = isValidPlatform(qpPlatform) ? qpPlatform : platform;

    // 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]);

  // Keep platform in sync w/ URL
  useEffect(() => {
    const qp = searchParams.get("platform");
    if (isValidPlatform(qp) && qp !== platform) {
      setPlatform(qp);
    }
  }, [searchParams, platform]);

  // 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: CategoryId[] = 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);
      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,
        });
        setShareStatus("Share dialog opened.");
      } catch {
        setShareStatus(
          "Share canceled or unavailable. You can copy the link instead."
        );
      }
    } else {
      await handleCopyLink();
    }
  };

  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>
            <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">
              BattlBuilder <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 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", 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}>
                      {p}
                    </option>
                  ))}
                </select>
              </label>
              <p className="text-[0.7rem] text-zinc-500">
                Parts list updates automatically when you change platforms.
              </p>
            </div>
          </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>

        {/* Build status strip */}
        <section className="mb-6 space-y-3">
          <h2 className="text-[0.7rem] font-semibold uppercase tracking-[0.16em] text-zinc-500">
            Build Status (Needs Refined)
          </h2>
          <div className="flex flex-wrap gap-2 md:gap-3">
            {BUILDER_SLOTS.map((slot) => {
              const satisfied = isSlotSatisfied(slot, selectedByCategory);

              return (
                <div
                  key={slot.id}
                  className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-[0.7rem] md:text-xs ${
                    satisfied
                      ? "border-emerald-500/70 bg-emerald-950/50 text-emerald-200"
                      : "border-zinc-800 bg-zinc-950/80 text-zinc-200"
                  }`}
                >
                  {satisfied ? (
                    <CheckSquare className="h-4 w-4 text-emerald-400" />
                  ) : (
                    <Square className="h-4 w-4 text-zinc-600/80" />
                  )}
                  <span className="font-medium truncate max-w-[9rem] md:max-w-[11rem]">
                    {slot.label}
                  </span>
                </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 CategoryId)
                );

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

                return (
                  <div 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>

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

                        <tbody>
                          {groupCategories.map((category) => {
                            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 hasParts = categoryParts.length > 0;

                            return (
                              <tr
                                key={category.id}
                                className="border-t border-zinc-900 hover:bg-zinc-900/60 transition-colors"
                              >
                                {/* Component */}
                                <td className="px-3 py-2 align-top">
                                  <div className="font-medium text-zinc-100">
                                    {category.name}
                                  </div>

                                  {selectedPart ? (
                                    <>
                                      <div className="text-[0.7rem] text-zinc-500 line-clamp-1">
                                        {selectedPart.name}
                                      </div>

                                      {/* Overlap chips help explain conflicts / dependencies */}
                                      <div className="mt-1 flex flex-wrap gap-1.5">
                                        {getOverlapChipsForCategory(
                                          category.id as CategoryId,
                                          build
                                        ).map((c) => (
                                          <OverlapChip
                                            key={c.key}
                                            tone={c.tone}
                                            label={c.label}
                                            detail={c.detail}
                                          />
                                        ))}
                                      </div>
                                    </>
                                  ) : hasParts ? (
                                    <div className="text-[0.7rem] text-zinc-600">
                                      No part selected
                                    </div>
                                  ) : (
                                    <div className="text-[0.7rem] text-zinc-600">
                                      No parts available yet
                                    </div>
                                  )}
                                </td>

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

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

                                {/* Sale price placeholder */}
                                <td className="px-3 py-2 align-top text-right text-zinc-400">
                                  —
                                </td>

                                {/* Caliber placeholder (future: derive from build profile) */}
                                <td className="px-3 py-2 align-top text-zinc-400">
                                  —
                                </td>

                                {/* Actions */}
                                <td className="px-3 py-2 align-top">
                                  <div className="flex justify-end gap-2">
                                    {selectedPart && selectedPart.url ? (
                                      <>
                                        <button
                                          type="button"
                                          onClick={() => {
                                            setBuild((prev) => {
                                              const next = { ...prev };
                                              delete next[category.id];
                                              return next;
                                            });
                                          }}
                                          className="inline-flex items-center justify-center rounded-md border border-zinc-700 bg-zinc-900/70 px-2 py-1 hover:bg-red-500/15 hover:border-red-400 transition-colors"
                                          aria-label="Remove part"
                                          title="Remove part"
                                        >
                                          <X className="h-3.5 w-3.5 text-zinc-400 hover:text-red-400" />
                                        </button>

                                        <a
                                          href={selectedPart.url}
                                          target="_blank"
                                          rel="noreferrer"
                                          className="inline-flex items-center justify-center rounded-md bg-amber-400 px-2 py-1 hover:bg-amber-300 transition-colors"
                                          aria-label="Buy part"
                                          title="Buy part"
                                        >
                                          <Link2 className="h-3.5 w-3.5 text-black" />
                                        </a>
                                      </>
                                    ) : hasParts ? (
                                      <Link
                                        href={{
                                          pathname: `/parts/p/${platform}/${category.id}`,
                                          query: platform ? { platform } : {},
                                        }}
                                        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"
                                      >
                                        <svg
                                          className="w-3.5 h-3.5"
                                          fill="none"
                                          stroke="currentColor"
                                          viewBox="0 0 24 24"
                                        >
                                          <path
                                            strokeLinecap="round"
                                            strokeLinejoin="round"
                                            strokeWidth={2}
                                            d="M12 4v16m8-8H4"
                                          />
                                        </svg>
                                        Choose
                                      </Link>
                                    ) : (
                                      <span className="text-[0.7rem] text-zinc-600">
                                        —
                                      </span>
                                    )}
                                  </div>
                                </td>
                              </tr>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </section>
      </div>
    </main>
  );
}