"use client";

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 "@/data/partRoleMappings";
import { Pencil, Link2, Square, CheckSquare } from "lucide-react";

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 API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";

type BuildState = Partial<Record<CategoryId, string>>; // categoryId -> partId

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",
    ],
  },
];

// ===== Build rules: complete assemblies make sub-parts unnecessary =====
const COMPLETE_UPPER_CATEGORY: CategoryId = "complete-upper";
const COMPLETE_LOWER_CATEGORY: CategoryId = "complete-lower";

// If a complete upper is selected, these categories are considered "included".
const UPPER_INCLUDED_CATEGORIES = new Set<CategoryId>([
  "upper-receiver",
  "bcg",
  "barrel",
  "gas-block",
  "gas-tube",
  "muzzle-device",
  "suppressor",
  "handguard",
  "charging-handle",
]);

const LOWER_INCLUDED_CATEGORIES = new Set<CategoryId>([
  "lower-receiver",
  "lower-parts",
  "trigger",
  "grip",
  "safety",
  "buffer",
  "stock",
]);

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

  const [parts, setParts] = useState<Part[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

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

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

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

  // ---------- Selection logic ----------
  const handleSelectPart = useCallback(
    (
      categoryId: CategoryId,
      partId: string,
      opts?: { confirm?: boolean }
    ) => {
      const shouldConfirm = opts?.confirm !== false;

      if (shouldConfirm && typeof window !== "undefined") {
        if (categoryId === COMPLETE_UPPER_CATEGORY) {
          const toClear = Array.from(UPPER_INCLUDED_CATEGORIES).filter(
            (cid) => !!build[cid]
          );
          if (toClear.length > 0) {
            const labels = toClear
              .map((cid) => CATEGORIES.find((c) => c.id === cid)?.name ?? cid)
              .join(", ");

            const ok = window.confirm(
              `Selecting a Complete Upper will remove your currently selected upper parts:\n\n${labels}\n\nContinue?`
            );
            if (!ok) return;
          }
        }

        if (categoryId === COMPLETE_LOWER_CATEGORY) {
          const toClear = Array.from(LOWER_INCLUDED_CATEGORIES).filter(
            (cid) => !!build[cid]
          );
          if (toClear.length > 0) {
            const labels = toClear
              .map((cid) => CATEGORIES.find((c) => c.id === cid)?.name ?? cid)
              .join(", ");

            const ok = window.confirm(
              `Selecting a Complete Lower will remove your currently selected lower parts:\n\n${labels}\n\nContinue?`
            );
            if (!ok) return;
          }
        }

        if (
          UPPER_INCLUDED_CATEGORIES.has(categoryId) &&
          !!build[COMPLETE_UPPER_CATEGORY]
        ) {
          const ok = window.confirm(
            `Selecting this part will remove your selected Complete Upper. Continue?`
          );
          if (!ok) return;
        }

        if (
          LOWER_INCLUDED_CATEGORIES.has(categoryId) &&
          !!build[COMPLETE_LOWER_CATEGORY]
        ) {
          const ok = window.confirm(
            `Selecting this part will remove your selected Complete Lower. Continue?`
          );
          if (!ok) return;
        }
      }

      setBuild((prev) => {
        const updated: BuildState = {
          ...prev,
          [categoryId]: partId,
        };

        if (categoryId === COMPLETE_UPPER_CATEGORY) {
          for (const cid of UPPER_INCLUDED_CATEGORIES) {
            delete updated[cid];
          }
        }

        if (UPPER_INCLUDED_CATEGORIES.has(categoryId)) {
          delete updated[COMPLETE_UPPER_CATEGORY];
        }

        if (categoryId === COMPLETE_LOWER_CATEGORY) {
          for (const cid of LOWER_INCLUDED_CATEGORIES) {
            delete updated[cid];
          }
        }

        if (LOWER_INCLUDED_CATEGORIES.has(categoryId)) {
          delete updated[COMPLETE_LOWER_CATEGORY];
        }

        return updated;
      });
    },
    [build]
  );

  // ---------- Fetch products ----------
  useEffect(() => {
    const controller = new AbortController();

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

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

        const universalUrl = `${API_BASE_URL}/api/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;

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

        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 state whenever it changes
  useEffect(() => {
    if (typeof window === "undefined") return;
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(build));
    } catch {
      // ignore
    }
  }, [build]);

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

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

    // Build a unique key for this action so we only apply it once.
    const actionKey = `${selectParam ?? ""}|${removeParam ?? ""}|${
      qpPlatform ?? ""
    }`;

    // If no action, clear the ref and do nothing.
    if (!selectParam && !removeParam) {
      processedActionKeyRef.current = "";
      return;
    }

    // Prevent infinite loops: if we already processed this exact actionKey, stop.
    if (processedActionKeyRef.current === actionKey) return;
    processedActionKeyRef.current = actionKey;

    // Apply actions
    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;

    // Clean URL (remove select/remove) but ONLY if needed.
    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
  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]);

  // Use group ordering for the summary as well
  const summaryCategoryOrder: CategoryId[] = useMemo(
    () =>
      CATEGORY_GROUPS.flatMap((group) => group.categoryIds).filter((id) =>
        CATEGORIES.some((c) => c.id === id)
      ),
    []
  );

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

    const lines: string[] = [];
    lines.push("B 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: "Shadow Standard — The Armory Build",
          text: "Check out my Shadow Standard Armory 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-black text-zinc-50">
      <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);

                    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">
              <Link
                href={{
                  pathname: "/builder/build",
                  query: platform ? { platform } : {},
                }}
                className={`w-full sm:w-auto rounded-md border border-amber-400/60 bg-amber-400/10 px-3 py-2 text-sm font-medium text-amber-200 hover:bg-amber-400/15 text-center transition-colors ${
                  selectedParts.length === 0
                    ? "opacity-40 cursor-not-allowed pointer-events-none"
                    : ""
                }`}
              >
                Build Summary
              </Link>

              <button
                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={() => {
                  setBuild({});
                  if (typeof window !== "undefined") {
                    localStorage.removeItem(STORAGE_KEY);
                  }
                }}
                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>
            </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>
                                  ) : 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 */}
                                <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 ? (
                                      <>
                                        <Link
                                          href={{
                                            pathname: `/parts/${category.id}`,
                                            query: platform ? { platform } : {},
                                          }}
                                          className="hidden md:inline-flex items-center justify-center rounded-md border border-zinc-700 bg-zinc-900/70 px-2 py-1 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
                                          aria-label="Change part"
                                          title="Change part"
                                        >
                                          <Pencil className="h-3.5 w-3.5 text-zinc-300" />
                                        </Link>

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