<script lang="ts">
  import {
    procurement,
    type CatalogItem,
    type CatalogItemFilters,
    type CategoryTreeEntry,
    type EcosystemEntry,
    type EcosystemManufacturer,
  } from "$lib/optima-api/modules/procurement";
  import {
    sales,
    type LaborCustomerType,
    type LaborOptionsResponse,
    type LaborStyle,
  } from "$lib/optima-api/modules/sales";
  import EditGuard from "./EditGuard.svelte";
  import InventoryPopover from "./InventoryPopover.svelte";

  export let isOpen = false;
  export let accessToken: string;
  export let opportunityId = "";
  export let onSelect: (
    items: CatalogItem | CatalogItem[]
  ) => void | Promise<void> = () => {};

  // ── Step state ──
  // "browse"  → pick category, ecosystem, or search
  // "results" → filtered catalog items list
  type Step = "browse" | "results" | "special-order" | "labor" | "ohms";
  let step: Step = "browse";

  type SpecialOrderForm = {
    description: string;
    quantity: string;
    pricePerUnit: string;
    costPerUnit: string;
    taxable: boolean;
    procurementNotes: string;
    productNarrative: string;
    customerDescription: string;
  };

  const initialSpecialOrderForm: SpecialOrderForm = {
    description: "",
    quantity: "1",
    pricePerUnit: "",
    costPerUnit: "",
    taxable: true,
    procurementNotes: "",
    productNarrative: "",
    customerDescription: "",
  };

  let specialOrderForm: SpecialOrderForm = { ...initialSpecialOrderForm };
  let specialOrderError = "";
  let isSubmittingSpecialOrder = false;

  let ohmsForm: SpecialOrderForm = { ...initialSpecialOrderForm };
  let ohmsError = "";
  let isSubmittingOhms = false;

  type LaborForm = {
    description: string;
    quantity: string;
    pricePerUnit: string;
    costPerUnit: string;
    taxable: boolean;
    procurementNotes: string;
    productNarrative: string;
    customerDescription: string;
  };

  let laborCpuMultiplier = 0.5;
  const laborDefaultCpu = (rate: number): string =>
    String(Number((rate * laborCpuMultiplier).toFixed(2)));

  const initialLaborForm: LaborForm = {
    description: "Field Labor",
    quantity: "1",
    pricePerUnit: "100",
    costPerUnit: laborDefaultCpu(100),
    taxable: true,
    procurementNotes: "",
    productNarrative: "",
    customerDescription: "",
  };

  let laborForm: LaborForm = { ...initialLaborForm };
  type LaborType = LaborStyle;
  let laborRates: Record<LaborCustomerType, number> = {
    corporate: 100,
    residential: 85,
  };
  let laborCustomerType: LaborCustomerType = "corporate";
  let laborType: LaborType = "field";
  let laborDefaultQuantity = 1;
  let laborOptions: LaborOptionsResponse | null = null;
  let laborError = "";
  let isLoadingLaborOptions = false;
  let isSubmittingLabor = false;
  let laborShowAdvanced = false;
  let laborPpuOverridden = false;
  let laborCpuOverridden = false;
  let ohmsShowAdvanced = false;

  // ── Category / ecosystem data ──
  let categories: CategoryTreeEntry[] = [];
  let ecosystems: EcosystemEntry[] = [];
  let isLoadingTree = false;
  let treeLoaded = false;

  // ── Browse selections ──
  let selectedCategory: CategoryTreeEntry | null = null;
  let selectedGroup: CategoryTreeEntry | null = null;
  let browseMode: "category" | "ecosystem" | null = null;

  // ── Category detail: expandable groups ──
  let expandedGroupName: string | null = null;

  // Derived: available groups for category detail page
  $: categoryGroups = selectedCategory?.entries ?? [];

  // ── Ecosystem manufacturer picker ──
  let selectedEcosystem: EcosystemEntry | null = null;

  // ── Filters for results step ──
  let filters: CatalogItemFilters = {};
  let searchQuery = "";
  let filterSubcategories: CategoryTreeEntry[] = [];
  let filterManufacturers: string[] = [];
  let isLoadingFilters = false;

  // ── Results state ──
  let results: CatalogItem[] = [];
  let isLoadingResults = false;
  let resultPage = 1;
  let listedResults = 0;
  let totalResults = 0;
  let totalPages = 0;
  let nextPage: number | null = null;
  let previousPage: number | null = null;
  const rpp = 20;
  $: resultsStart = totalResults > 0 ? (resultPage - 1) * rpp + 1 : 0;
  $: resultsEnd = Math.min(resultsStart + listedResults - 1, totalResults);

  // ── Detail pane state ──
  let detailItem: CatalogItem | null = null;
  let detailPaneOpen = false;
  let paneClosing = false;
  let detailPaneMode: "item" | "cart" = "item";

  // ── Cart state ──
  let cart: CatalogItem[] = [];
  let showCartPreview = false;
  let isQuickAdding = false;
  let isAddingSelected = false;

  // ── Per-item quantity overrides ──
  let itemQuantities: Record<string, number> = {};

  function getItemQty(itemId: string): number {
    return itemQuantities[itemId] ?? 1;
  }

  function setItemQty(itemId: string, qty: number) {
    const clamped = Math.max(1, Math.floor(qty) || 1);
    itemQuantities[itemId] = clamped;
    itemQuantities = itemQuantities; // trigger reactivity
  }

  function applyQuantity(item: CatalogItem): CatalogItem {
    return { ...item, quantity: getItemQty(item.id) };
  }

  // ── Error state ──
  let errorMessage = "";

  // ── Breadcrumb ──
  $: categoryNameById = buildCategoryNameById(categories);
  $: subcategoryNameById = buildSubcategoryNameById(categories);
  $: categoryFilterLabel = resolveFilterLabel(
    filters.category,
    categoryNameById
  );
  $: subcategoryFilterLabel = resolveFilterLabel(
    filters.subcategory,
    subcategoryNameById
  );

  $: breadcrumb = buildBreadcrumb(
    step,
    browseMode,
    selectedCategory,
    selectedGroup,
    selectedEcosystem,
    filters
  );

  $: specialOrderQty = Number(specialOrderForm.quantity);
  $: specialOrderUnitPrice = Number(specialOrderForm.pricePerUnit);
  $: specialOrderUnitCost = Number(specialOrderForm.costPerUnit);
  $: specialOrderRevenue =
    Number.isFinite(specialOrderQty) && Number.isFinite(specialOrderUnitPrice)
      ? specialOrderQty * specialOrderUnitPrice
      : null;
  $: specialOrderCostTotal =
    Number.isFinite(specialOrderQty) && Number.isFinite(specialOrderUnitCost)
      ? specialOrderQty * specialOrderUnitCost
      : null;
  $: canSubmitSpecialOrder =
    specialOrderForm.description.trim().length > 0 &&
    Number.isFinite(specialOrderQty) &&
    specialOrderQty > 0 &&
    Number.isFinite(specialOrderUnitPrice) &&
    specialOrderUnitPrice >= 0 &&
    Number.isFinite(specialOrderUnitCost) &&
    specialOrderUnitCost >= 0;

  $: ohmsQty = Number(ohmsForm.quantity);
  $: ohmsUnitPrice = Number(ohmsForm.pricePerUnit);
  $: canSubmitOhms =
    Number.isFinite(ohmsQty) &&
    ohmsQty > 0 &&
    Number.isFinite(ohmsUnitPrice) &&
    ohmsUnitPrice >= 0;

  $: laborQty = Number(laborForm.quantity);
  $: laborUnitPrice = Number(laborForm.pricePerUnit);
  $: laborUnitCost = Number(laborForm.costPerUnit);
  $: laborRevenue =
    Number.isFinite(laborQty) && Number.isFinite(laborUnitPrice)
      ? laborQty * laborUnitPrice
      : null;
  $: laborCostTotal =
    Number.isFinite(laborQty) && Number.isFinite(laborUnitCost)
      ? laborQty * laborUnitCost
      : null;
  $: laborDefaultRate = laborRates[laborCustomerType];
  $: canSubmitLabor =
    Number.isFinite(laborQty) &&
    laborQty > 0 &&
    Number.isFinite(laborUnitPrice) &&
    laborUnitPrice >= 0 &&
    Number.isFinite(laborUnitCost) &&
    laborUnitCost >= 0 &&
    !isLoadingLaborOptions;

  function laborOptionLabel(style: LaborStyle): string {
    return (
      laborOptions?.options?.[style]?.name ??
      (style === "field" ? "Field Labor" : "Tech Labor")
    );
  }

  function isDefaultLaborDescription(value: string): boolean {
    const normalized = value.trim();
    if (!normalized) return true;
    return [
      "Field Labor",
      "Tech Labor",
      laborOptionLabel("field"),
      laborOptionLabel("tech"),
    ].includes(normalized);
  }

  function applyLaborDefaultsFromOptions() {
    const defaults = laborOptions?.defaults;
    const options = laborOptions?.options;
    if (!defaults || !options) return;

    laborRates = {
      corporate: defaults.rates.corporate,
      residential: defaults.rates.residential,
    };
    laborCpuMultiplier = defaults.cpuMultiplier;
    laborDefaultQuantity = defaults.quantity;
    laborCustomerType = defaults.customerType;

    const chosenOption = options[laborType];
    const chosenRate = laborRates[laborCustomerType];
    laborForm = {
      ...laborForm,
      description: chosenOption?.name ?? laborOptionLabel(laborType),
      quantity: String(laborDefaultQuantity),
      pricePerUnit: String(chosenRate),
      costPerUnit: laborDefaultCpu(chosenRate),
      taxable: chosenOption?.taxableFlag ?? laborForm.taxable,
    };
  }

  async function loadLaborOptions() {
    if (!accessToken || !opportunityId) return;
    isLoadingLaborOptions = true;
    laborError = "";
    try {
      const response = await sales.fetchLaborOptions(
        accessToken,
        opportunityId
      );
      laborOptions = response?.data ?? null;
      applyLaborDefaultsFromOptions();
    } catch (err) {
      laborError =
        err instanceof Error ? err.message : "Failed to load labor options.";
      console.error("[AddProductModal] Failed to load labor options:", err);
    } finally {
      isLoadingLaborOptions = false;
    }
  }

  function buildBreadcrumb(
    _step: Step,
    _browseMode: "category" | "ecosystem" | null,
    _selectedCategory: CategoryTreeEntry | null,
    _selectedGroup: CategoryTreeEntry | null,
    _selectedEcosystem: EcosystemEntry | null,
    _filters: CatalogItemFilters
  ): string[] {
    const crumbs: string[] = ["Browse"];
    if (_browseMode === "category" && _selectedCategory) {
      crumbs.push(_selectedCategory.name);
      if (_selectedGroup) crumbs.push(_selectedGroup.name);
    } else if (_browseMode === "ecosystem") {
      if (_selectedEcosystem) crumbs.push(_selectedEcosystem.name);
      if (_filters.manufacturer) crumbs.push(_filters.manufacturer);
    }
    if (_step === "results" && _filters.search) {
      crumbs.push(`"${_filters.search}"`);
    }
    return crumbs;
  }

  function buildCategoryNameById(
    entries: CategoryTreeEntry[]
  ): Map<number, string> {
    const map = new Map<number, string>();
    for (const category of entries) {
      if (category.cwId != null) map.set(category.cwId, category.name);
    }
    return map;
  }

  function buildSubcategoryNameById(
    entries: CategoryTreeEntry[]
  ): Map<number, string> {
    const map = new Map<number, string>();
    for (const category of entries) {
      for (const group of category.entries ?? []) {
        if ((group.subcategories?.length ?? 0) === 0 && group.cwId != null) {
          map.set(group.cwId, group.name);
        }
        for (const sub of group.subcategories ?? []) {
          if (sub.cwId != null) map.set(sub.cwId, sub.name);
        }
      }
    }
    return map;
  }

  function resolveFilterLabel(
    value: CatalogItemFilters["category"] | CatalogItemFilters["subcategory"],
    nameMap: Map<number, string>
  ): string {
    if (value == null || value === "") return "";
    if (typeof value === "number") return nameMap.get(value) ?? String(value);

    const parsed = Number(value);
    if (!Number.isNaN(parsed) && value.trim() !== "") {
      return nameMap.get(parsed) ?? value;
    }

    return value;
  }

  // ── Lifecycle ──
  $: if (isOpen && !treeLoaded) {
    loadCategoryTree();
  }

  $: filterSubcategories = collectSubcategories(selectedCategory);

  function collectSubcategories(
    category: CategoryTreeEntry | null
  ): CategoryTreeEntry[] {
    if (!category?.entries) return [];

    const seen = new Set<string>();
    const options: CategoryTreeEntry[] = [];

    for (const entry of category.entries) {
      if (entry.subcategories && entry.subcategories.length > 0) {
        // Group entry — collect its nested subcategories
        for (const sub of entry.subcategories) {
          if (sub.cwId == null) continue;
          const key = `${sub.cwId}`;
          if (seen.has(key)) continue;
          seen.add(key);
          options.push(sub);
        }
      } else if (entry.cwId != null) {
        // Direct subcategory entry
        const key = `${entry.cwId}`;
        if (seen.has(key)) continue;
        seen.add(key);
        options.push(entry);
      }
    }

    return options;
  }

  async function loadCategoryTree() {
    if (!accessToken || treeLoaded) return;
    isLoadingTree = true;
    errorMessage = "";
    try {
      const data = await procurement.fetchCategories(accessToken);
      categories = data.categories ?? [];
      ecosystems = data.ecosystems ?? [];
      treeLoaded = true;
    } catch (err) {
      errorMessage =
        err instanceof Error ? err.message : "Failed to load categories";
      console.error("Failed to load category tree:", err);
    } finally {
      isLoadingTree = false;
    }
  }

  async function loadFilterValues(
    category?: string | number,
    subcategory?: string | number
  ) {
    if (!accessToken) return;
    isLoadingFilters = true;
    try {
      const data = await procurement.fetchFilters(accessToken, {
        category,
        subcategory,
      });
      filterManufacturers = data.manufacturers ?? [];
    } catch (err) {
      console.error("Failed to load filter values:", err);
    } finally {
      isLoadingFilters = false;
    }
  }

  async function fetchResults(page: number = 1) {
    if (!accessToken) return;
    isLoadingResults = true;
    errorMessage = "";
    try {
      const response = await procurement.fetchMany(
        accessToken,
        page,
        filters,
        rpp
      );
      console.log("[AddProductModal] Catalog fetch meta:", response?.meta);
      results = response?.data ?? [];

      const pagination = response?.meta?.pagination ?? response?.pagination;
      listedResults = pagination?.listedRecords ?? results.length;
      resultPage = pagination?.currentPage ?? page;
      previousPage = pagination?.previousPage ?? null;
      nextPage = pagination?.nextPage ?? null;
      totalResults = pagination?.totalRecords ?? results.length;
      totalPages =
        pagination?.totalPages ??
        (totalResults > 0 ? Math.max(1, Math.ceil(totalResults / rpp)) : 0);
    } catch (err) {
      errorMessage =
        err instanceof Error ? err.message : "Failed to search catalog";
      console.error("Failed to fetch catalog items:", err);
    } finally {
      isLoadingResults = false;
    }
  }

  // ── Navigation: Categories ──

  function selectCategory(cat: CategoryTreeEntry) {
    selectedCategory = cat;
    selectedEcosystem = null;
    browseMode = "category";
    expandedGroupName = null;
  }

  function toggleGroup(group: CategoryTreeEntry) {
    const subs = group.subcategories ?? [];
    if (subs.length === 0) {
      // No subcategories — treat this row as the final subcategory when possible
      filters =
        group.cwId != null
          ? { category: selectedCategory?.cwId, subcategory: group.cwId }
          : { category: selectedCategory?.cwId };
      goToResults();
    } else {
      // Toggle expand/collapse
      expandedGroupName = expandedGroupName === group.name ? null : group.name;
    }
  }

  function selectSubcategory(sub: CategoryTreeEntry) {
    filters = { category: selectedCategory?.cwId, subcategory: sub.cwId };
    goToResults();
  }

  // ── Navigation: Ecosystems ──

  function selectEcosystem(eco: EcosystemEntry) {
    selectedCategory = null;
    browseMode = "ecosystem";
    selectedEcosystem = eco;
  }

  function selectEcosystemManufacturer(mfr: EcosystemManufacturer) {
    filters = { ecosystem: selectedEcosystem?.name, manufacturer: mfr.name };
    goToResults();
  }

  function selectEcosystemAll() {
    filters = { ecosystem: selectedEcosystem?.name };
    goToResults();
  }

  // ── Navigation: Search ──

  function handleSearch() {
    const query = searchQuery.trim();
    if (!query) return;
    browseMode = null;
    selectedCategory = null;
    selectedGroup = null;
    selectedEcosystem = null;
    filters = { search: query };
    goToResults();
  }

  function handleSearchKeydown(e: KeyboardEvent) {
    if (e.key === "Enter") handleSearch();
  }

  async function goToResults() {
    step = "results";
    detailPaneOpen = false;
    paneClosing = false;
    await fetchResults(1);
    if (filters.category) {
      loadFilterValues(filters.category, filters.subcategory);
    }
  }

  // ── Detail pane ──

  function openDetailPane(item: CatalogItem) {
    // Toggle: clicking the same item again closes the pane
    if (
      detailPaneOpen &&
      detailPaneMode === "item" &&
      detailItem?.id === item.id
    ) {
      closeDetailPane();
      return;
    }
    paneClosing = false;
    detailItem = item;
    detailPaneMode = "item";
    detailPaneOpen = true;
  }

  function openCartPane() {
    paneClosing = false;
    detailPaneMode = "cart";
    detailPaneOpen = true;
  }

  function closeDetailPane() {
    if (!detailPaneOpen || paneClosing) return;
    paneClosing = true;
    setTimeout(() => {
      detailPaneOpen = false;
      paneClosing = false;
    }, 180);
  }

  // ── Cart ──

  function addToCart(item: CatalogItem) {
    if (!cart.some((c) => c.id === item.id)) {
      cart = [...cart, item];
    }
  }

  function removeFromCart(item: CatalogItem) {
    cart = cart.filter((c) => c.id !== item.id);
    if (cart.length === 0 && detailPaneMode === "cart") {
      detailPaneOpen = false;
      paneClosing = false;
    }
  }

  $: detailItemInCart = detailItem
    ? cart.some((c) => c.id === detailItem?.id)
    : false;

  async function quickAdd(item: CatalogItem) {
    isQuickAdding = true;
    try {
      await Promise.resolve(onSelect(applyQuantity(item)));
      handleClose();
    } finally {
      isQuickAdding = false;
    }
  }

  async function handleAddSelected() {
    if (cart.length === 0 || isAddingSelected) return;
    isAddingSelected = true;
    try {
      await Promise.resolve(onSelect(cart.map(applyQuantity)));
      handleClose();
    } finally {
      isAddingSelected = false;
    }
  }

  // ── Back / Home ──

  $: showBackBtn =
    step !== "browse" || selectedCategory != null || selectedEcosystem != null;

  function goBack() {
    if (step === "results") {
      step = "browse";
      results = [];
      listedResults = 0;
      totalResults = 0;
      totalPages = 0;
      resultPage = 1;
      previousPage = null;
      nextPage = null;
      errorMessage = "";
      detailPaneOpen = false;
      paneClosing = false;
      if (browseMode === "category" && selectedCategory) {
        filters = {};
        // Stay on category detail page
      } else if (browseMode === "ecosystem" && filters.manufacturer) {
        filters = {};
        // Stay on ecosystem manufacturer picker
      } else {
        selectedCategory = null;
        selectedGroup = null;
        selectedEcosystem = null;
        browseMode = null;
        filters = {};
      }
      searchQuery = "";
      filterSubcategories = [];
      filterManufacturers = [];
    } else if (
      step === "special-order" ||
      step === "labor" ||
      step === "ohms"
    ) {
      step = "browse";
      specialOrderError = "";
      laborError = "";
      ohmsError = "";
    } else if (step === "browse" && selectedCategory) {
      selectedCategory = null;
      browseMode = null;
      expandedGroupName = null;
    } else if (step === "browse" && selectedEcosystem) {
      selectedEcosystem = null;
      browseMode = null;
    }
  }

  function goHome() {
    step = "browse";
    results = [];
    listedResults = 0;
    totalResults = 0;
    totalPages = 0;
    resultPage = 1;
    previousPage = null;
    nextPage = null;
    errorMessage = "";
    selectedCategory = null;
    selectedGroup = null;
    selectedEcosystem = null;
    browseMode = null;
    filters = {};
    searchQuery = "";
    detailItem = null;
    detailPaneOpen = false;
    paneClosing = false;
    filterSubcategories = [];
    filterManufacturers = [];
    expandedGroupName = null;
    specialOrderForm = { ...initialSpecialOrderForm };
    specialOrderError = "";
    ohmsForm = { ...initialSpecialOrderForm };
    ohmsError = "";
    ohmsShowAdvanced = false;
    laborForm = { ...initialLaborForm };
    laborError = "";
    isLoadingLaborOptions = false;
    isSubmittingLabor = false;
    laborOptions = null;
    laborCustomerType = "corporate";
    laborType = "field";
    laborDefaultQuantity = 1;
    laborCpuMultiplier = 0.5;
    laborRates = { corporate: 100, residential: 85 };
    laborShowAdvanced = false;
    laborPpuOverridden = false;
    laborCpuOverridden = false;
  }

  // ── Inline filters on results page ──

  function applySubcategoryFilter(subcategoryId: number) {
    filters = { ...filters, subcategory: subcategoryId };
    loadFilterValues(filters.category, subcategoryId);
    fetchResults(1);
  }

  function applyManufacturerFilter(mfr: string) {
    filters = { ...filters, manufacturer: mfr };
    fetchResults(1);
  }

  function toggleInStock() {
    filters = { ...filters, inStock: !filters.inStock };
    fetchResults(1);
  }

  function clearFilter(key: keyof CatalogItemFilters) {
    const next = { ...filters };
    delete next[key];
    filters = next;
    if (key === "subcategory" && filters.category) {
      loadFilterValues(filters.category);
    }
    fetchResults(1);
  }

  // ── Modal lifecycle ──

  function reset() {
    step = "browse";
    selectedCategory = null;
    selectedGroup = null;
    selectedEcosystem = null;
    browseMode = null;
    filters = {};
    searchQuery = "";
    results = [];
    listedResults = 0;
    totalResults = 0;
    totalPages = 0;
    resultPage = 1;
    previousPage = null;
    nextPage = null;
    detailItem = null;
    detailPaneOpen = false;
    paneClosing = false;
    detailPaneMode = "item";
    cart = [];
    showCartPreview = false;
    isQuickAdding = false;
    isAddingSelected = false;
    itemQuantities = {};
    errorMessage = "";
    filterSubcategories = [];
    filterManufacturers = [];
    expandedGroupName = null;
    specialOrderForm = { ...initialSpecialOrderForm };
    specialOrderError = "";
    isSubmittingSpecialOrder = false;
    ohmsForm = { ...initialSpecialOrderForm };
    ohmsError = "";
    isSubmittingOhms = false;
    laborForm = { ...initialLaborForm };
    laborError = "";
    isLoadingLaborOptions = false;
    isSubmittingLabor = false;
    laborOptions = null;
    laborCustomerType = "corporate";
    laborType = "field";
    laborDefaultQuantity = 1;
    laborCpuMultiplier = 0.5;
    laborRates = { corporate: 100, residential: 85 };
    laborShowAdvanced = false;
    laborPpuOverridden = false;
    laborCpuOverridden = false;
    ohmsShowAdvanced = false;
  }

  function handleClose() {
    reset();
    isOpen = false;
  }

  let guardComponent: EditGuard;

  function handleBackdropClick() {
    guardComponent?.guardClose();
  }

  function handleBackdropKeydown(e: KeyboardEvent) {
    if (e.key === "Escape") {
      if (detailPaneOpen) {
        closeDetailPane();
      } else {
        guardComponent?.guardClose();
      }
    }
  }

  // ── Quick-add special items ──

  function addSpecialOrder() {
    step = "special-order";
    specialOrderError = "";
  }

  async function submitSpecialOrder() {
    if (isSubmittingSpecialOrder) return;

    const description = specialOrderForm.description.trim();
    const quantity = Number(specialOrderForm.quantity);
    const pricePerUnit = Number(specialOrderForm.pricePerUnit);
    const costPerUnit = Number(specialOrderForm.costPerUnit);

    if (!description) {
      specialOrderError = "Description is required.";
      return;
    }

    if (!Number.isFinite(quantity) || quantity <= 0) {
      specialOrderError = "QTY must be greater than 0.";
      return;
    }

    if (!Number.isFinite(pricePerUnit) || pricePerUnit < 0) {
      specialOrderError = "Price per Unit must be 0 or greater.";
      return;
    }

    if (!Number.isFinite(costPerUnit) || costPerUnit < 0) {
      specialOrderError = "Cost per Unit must be 0 or greater.";
      return;
    }

    const specialItem: CatalogItem = {
      id: `special-order-${Date.now()}`,
      identifier: "SPECIAL-ORDER",
      description,
      category: "Special Order",
      quantity,
      price: pricePerUnit,
      cost: costPerUnit,
      taxableFlag: specialOrderForm.taxable,
      procurementNotes: specialOrderForm.procurementNotes.trim() || undefined,
      productNarrative: specialOrderForm.productNarrative.trim() || undefined,
      customerDescription:
        specialOrderForm.customerDescription.trim() || undefined,
    };

    specialOrderError = "";
    isSubmittingSpecialOrder = true;
    try {
      await Promise.resolve(onSelect(specialItem));
      handleClose();
    } catch (err) {
      specialOrderError =
        err instanceof Error ? err.message : "Failed to add special order.";
    } finally {
      isSubmittingSpecialOrder = false;
    }
  }

  function addOhms() {
    step = "ohms";
    ohmsError = "";
  }

  async function submitOhms() {
    if (isSubmittingOhms) return;

    const description = ohmsForm.description.trim();
    const quantity = Number(ohmsForm.quantity);
    const pricePerUnit = Number(ohmsForm.pricePerUnit);

    if (!Number.isFinite(quantity) || quantity <= 0) {
      ohmsError = "QTY must be greater than 0.";
      return;
    }

    if (!Number.isFinite(pricePerUnit) || pricePerUnit < 0) {
      ohmsError = "Price per Unit must be 0 or greater.";
      return;
    }

    const ohmsItem: CatalogItem = {
      id: `ohms-${Date.now()}`,
      identifier: "OHMS",
      description: description || undefined,
      cwCatalogId: 4900,
      category: "Overhead Material and Supplies",
      quantity,
      price: pricePerUnit,
      taxableFlag: ohmsForm.taxable,
      procurementNotes: ohmsForm.procurementNotes.trim() || undefined,
    };

    ohmsError = "";
    isSubmittingOhms = true;
    try {
      await Promise.resolve(onSelect(ohmsItem));
      handleClose();
    } catch (err) {
      ohmsError =
        err instanceof Error ? err.message : "Failed to add OHMS item.";
    } finally {
      isSubmittingOhms = false;
    }
  }

  async function addLabor() {
    laborForm = { ...initialLaborForm };
    laborError = "";
    isSubmittingLabor = false;
    laborCustomerType = "corporate";
    laborType = "field";
    laborDefaultQuantity = 1;
    laborCpuMultiplier = 0.5;
    laborRates = { corporate: 100, residential: 85 };
    laborShowAdvanced = false;
    laborPpuOverridden = false;
    laborCpuOverridden = false;
    step = "labor";
    await loadLaborOptions();
  }

  function setLaborCustomerType(next: LaborCustomerType) {
    laborCustomerType = next;
    const nextPrice = laborPpuOverridden
      ? laborForm.pricePerUnit
      : String(laborRates[next]);
    const nextCost = laborCpuOverridden
      ? laborForm.costPerUnit
      : laborDefaultCpu(laborRates[next]);

    laborForm = {
      ...laborForm,
      pricePerUnit: nextPrice,
      costPerUnit: nextCost,
    };
  }

  function setLaborType(next: LaborType) {
    laborType = next;
    if (isDefaultLaborDescription(laborForm.description)) {
      laborForm = {
        ...laborForm,
        description: laborOptionLabel(next),
        taxable:
          laborOptions?.options?.[next]?.taxableFlag ?? laborForm.taxable,
      };
    }
  }

  function handleLaborPpuInput(value: string) {
    laborPpuOverridden = true;
    laborForm = { ...laborForm, pricePerUnit: value };
  }

  function handleLaborCpuInput(value: string) {
    laborCpuOverridden = true;
    laborForm = { ...laborForm, costPerUnit: value };
  }

  function resetLaborRateDefaults() {
    laborPpuOverridden = false;
    laborCpuOverridden = false;
    laborForm = {
      ...laborForm,
      pricePerUnit: String(laborRates[laborCustomerType]),
      costPerUnit: laborDefaultCpu(laborRates[laborCustomerType]),
    };
  }

  async function submitLabor() {
    if (isSubmittingLabor || isLoadingLaborOptions) return;

    const hours = Number(laborForm.quantity);
    const ppu = Number(laborForm.pricePerUnit);
    const cpu = Number(laborForm.costPerUnit);

    if (!Number.isFinite(hours) || hours <= 0) {
      laborError = "Hours must be greater than 0.";
      return;
    }

    if (!Number.isFinite(ppu) || ppu < 0) {
      laborError = "PPU must be 0 or greater.";
      return;
    }

    if (!Number.isFinite(cpu) || cpu < 0) {
      laborError = "CPU must be 0 or greater.";
      return;
    }

    const selectedOption = laborOptions?.options?.[laborType];
    const laborItem: CatalogItem = {
      id: `labor-${Date.now()}`,
      identifier: "LABOR",
      cwCatalogId: selectedOption?.cwCatalogId,
      description: laborForm.description.trim() || laborOptionLabel(laborType),
      quantity: hours,
      price: ppu,
      cost: cpu,
      taxableFlag: laborForm.taxable,
      procurementNotes: laborForm.procurementNotes.trim() || undefined,
      productNarrative: laborForm.productNarrative.trim() || undefined,
      customerDescription: laborForm.customerDescription.trim() || undefined,
      laborStyle: laborType,
      customerType: laborCustomerType,
      hours,
      rate: laborRates[laborCustomerType],
      ppu,
      cpu,
    };

    laborError = "";
    isSubmittingLabor = true;
    try {
      await Promise.resolve(onSelect(laborItem));
      handleClose();
    } catch (err) {
      laborError = err instanceof Error ? err.message : "Failed to add labor.";
    } finally {
      isSubmittingLabor = false;
    }
  }

  // ── Helpers ──

  function formatPrice(amount?: number | null): string {
    if (amount == null) return "—";
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      minimumFractionDigits: 2,
    }).format(amount);
  }

  function categoryIcon(name: string): string {
    const n = name.toLowerCase();
    if (n.includes("technology")) return "cpu";
    if (n.includes("field")) return "wrench";
    if (n.includes("general")) return "package";
    return "folder";
  }

  function ecosystemIcon(name: string): string {
    const n = name.toLowerCase();
    if (n.includes("network")) return "wifi";
    if (n.includes("video") || n.includes("surveillance")) return "camera";
    if (n.includes("burg") || n.includes("alarm")) return "shield";
    return "layers";
  }
</script>

{#if isOpen}
  <EditGuard
    bind:this={guardComponent}
    isDirty={cart.length > 0}
    onDiscard={handleClose}
    message="You have items in your cart. Are you sure you want to leave?"
    let:guardClose
  >
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <div
      class="modal-backdrop"
      on:click={handleBackdropClick}
      on:keydown={handleBackdropKeydown}
    >
      <!-- svelte-ignore a11y_no_static_element_interactions -->
      <!-- svelte-ignore a11y_click_events_have_key_events -->
      <div class="modal-shell" on:click|stopPropagation>
        <div
          class="modal"
          class:pane-open={detailPaneOpen || paneClosing}
          role="dialog"
          aria-modal="true"
          aria-label="Add Product"
          tabindex="-1"
        >
          <!-- ═══ Header ═══ -->
          <div class="modal-header">
            <div class="modal-header-left">
              {#if showBackBtn}
                <button
                  class="back-btn"
                  on:click={goBack}
                  type="button"
                  aria-label="Go back"
                >
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    width="16"
                    height="16"
                  >
                    <path d="M19 12H5M12 19l-7-7 7-7" />
                  </svg>
                </button>
              {/if}
              <div class="modal-title-group">
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  width="18"
                  height="18"
                >
                  <path
                    d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"
                  />
                  <polyline points="3.27 6.96 12 12.01 20.73 6.96" />
                  <line x1="12" y1="22.08" x2="12" y2="12" />
                </svg>
                <h2>Add Product</h2>
              </div>
            </div>
            <div class="modal-header-right">
              {#if cart.length > 0}
                <!-- svelte-ignore a11y_no_static_element_interactions -->
                <div
                  class="cart-badge-area"
                  on:mouseenter={() => (showCartPreview = true)}
                  on:mouseleave={() => (showCartPreview = false)}
                >
                  <button
                    class="cart-badge"
                    type="button"
                    on:click={openCartPane}
                    aria-label="View selected items"
                  >
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="14"
                      height="14"
                    >
                      <path
                        d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"
                      />
                      <line x1="3" y1="6" x2="21" y2="6" />
                      <path d="M16 10a4 4 0 01-8 0" />
                    </svg>
                    <span class="cart-count">{cart.length}</span>
                  </button>
                  {#if showCartPreview}
                    <div class="cart-preview">
                      <div class="cart-preview-title">Selected Items</div>
                      {#each cart.slice(0, 5) as item}
                        <div class="cart-preview-item">
                          <span class="cart-preview-item-name"
                            >{#if (itemQuantities[item.id] ?? 1) > 1}<span
                                class="cart-preview-qty"
                                >{itemQuantities[item.id] ?? 1}×</span
                              >{/if}{item.description ||
                              item.identifier ||
                              "Item"}</span
                          >
                          {#if item.price != null}
                            <span class="cart-preview-item-price"
                              >{formatPrice(item.price)}</span
                            >
                          {/if}
                        </div>
                      {/each}
                      {#if cart.length > 5}
                        <div class="cart-preview-more">
                          +{cart.length - 5} more item{cart.length - 5 !== 1
                            ? "s"
                            : ""}
                        </div>
                      {/if}
                    </div>
                  {/if}
                </div>
              {/if}
              <button
                class="close-btn"
                on:click={guardClose}
                type="button"
                aria-label="Close modal"
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  width="18"
                  height="18"
                >
                  <line x1="18" y1="6" x2="6" y2="18" />
                  <line x1="6" y1="6" x2="18" y2="18" />
                </svg>
              </button>
            </div>
          </div>

          <!-- ═══ Breadcrumb ═══ -->
          {#if breadcrumb.length > 1}
            <div class="breadcrumb-bar">
              {#each breadcrumb as crumb, i}
                {#if i > 0}<span class="breadcrumb-sep">/</span>{/if}
                {#if i === 0}
                  <button
                    class="breadcrumb-link"
                    on:click={goHome}
                    type="button">{crumb}</button
                  >
                {:else if i < breadcrumb.length - 1}
                  <span class="breadcrumb-text">{crumb}</span>
                {:else}
                  <span class="breadcrumb-current">{crumb}</span>
                {/if}
              {/each}
            </div>
          {/if}

          <!-- ═══ Body ═══ -->
          <div class="modal-body">
            {#if errorMessage}
              <div class="error-banner">
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  width="14"
                  height="14"
                >
                  <circle cx="12" cy="12" r="10" />
                  <line x1="12" y1="8" x2="12" y2="12" />
                  <line x1="12" y1="16" x2="12.01" y2="16" />
                </svg>
                {errorMessage}
              </div>
            {/if}

            <!-- ═══ STEP: Browse ═══ -->
            {#if step === "browse"}
              {#if isLoadingTree}
                <div class="loading-center">
                  <svg
                    class="spin-icon"
                    viewBox="0 0 24 24"
                    width="20"
                    height="20"
                  >
                    <circle
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      stroke-width="3"
                      fill="none"
                      opacity="0.25"
                    />
                    <path
                      d="M12 2a10 10 0 0 1 10 10"
                      stroke="currentColor"
                      stroke-width="3"
                      fill="none"
                      stroke-linecap="round"
                    />
                  </svg>
                  <span>Loading catalog...</span>
                </div>
              {:else if selectedEcosystem}
                <!-- Ecosystem manufacturer picker -->
                <div class="section-label">
                  {selectedEcosystem.name} — Select a manufacturer
                </div>
                <div class="manufacturer-list">
                  <button
                    class="manufacturer-item"
                    type="button"
                    on:click={selectEcosystemAll}
                  >
                    <div class="manufacturer-item-icon all-icon">
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        width="18"
                        height="18"
                      >
                        <polygon points="12 2 2 7 12 12 22 7 12 2" />
                        <polyline points="2 17 12 22 22 17" />
                        <polyline points="2 12 12 17 22 12" />
                      </svg>
                    </div>
                    <div class="manufacturer-item-label">
                      <span class="manufacturer-item-name"
                        >All {selectedEcosystem.name}</span
                      >
                      <span class="manufacturer-item-desc"
                        >Browse all manufacturers</span
                      >
                    </div>
                    <svg
                      class="manufacturer-chevron"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="14"
                      height="14"
                    >
                      <polyline points="9 18 15 12 9 6" />
                    </svg>
                  </button>
                  {#each selectedEcosystem.manufacturers as mfr}
                    <button
                      class="manufacturer-item"
                      type="button"
                      on:click={() => selectEcosystemManufacturer(mfr)}
                    >
                      <div class="manufacturer-item-icon">
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="18"
                          height="18"
                        >
                          <rect
                            x="2"
                            y="7"
                            width="20"
                            height="14"
                            rx="2"
                            ry="2"
                          />
                          <polyline points="16 21 16 3 8 3 8 21" />
                        </svg>
                      </div>
                      <div class="manufacturer-item-label">
                        <span class="manufacturer-item-name">{mfr.name}</span>
                      </div>
                      <svg
                        class="manufacturer-chevron"
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        width="14"
                        height="14"
                      >
                        <polyline points="9 18 15 12 9 6" />
                      </svg>
                    </button>
                  {/each}
                </div>
              {:else if selectedCategory}
                <!-- Category detail page with expandable groups -->
                <div class="category-detail-page">
                  <div class="category-detail-header">
                    <div class="browse-list-icon category-icon">
                      {#if categoryIcon(selectedCategory.name) === "cpu"}
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="22"
                          height="22"
                        >
                          <rect x="4" y="4" width="16" height="16" rx="2" />
                          <rect x="9" y="9" width="6" height="6" />
                          <line x1="9" y1="1" x2="9" y2="4" /><line
                            x1="15"
                            y1="1"
                            x2="15"
                            y2="4"
                          />
                          <line x1="9" y1="20" x2="9" y2="23" /><line
                            x1="15"
                            y1="20"
                            x2="15"
                            y2="23"
                          />
                          <line x1="20" y1="9" x2="23" y2="9" /><line
                            x1="20"
                            y1="14"
                            x2="23"
                            y2="14"
                          />
                          <line x1="1" y1="9" x2="4" y2="9" /><line
                            x1="1"
                            y1="14"
                            x2="4"
                            y2="14"
                          />
                        </svg>
                      {:else if categoryIcon(selectedCategory.name) === "wrench"}
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="22"
                          height="22"
                        >
                          <path
                            d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z"
                          />
                        </svg>
                      {:else}
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="22"
                          height="22"
                        >
                          <line x1="16.5" y1="9.4" x2="7.5" y2="4.21" />
                          <path
                            d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 002 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0022 16z"
                          />
                          <polyline points="3.27 6.96 12 12.01 20.73 6.96" />
                          <line x1="12" y1="22.08" x2="12" y2="12" />
                        </svg>
                      {/if}
                    </div>
                    <div class="category-detail-title">
                      <h3>{selectedCategory.name}</h3>
                      {#if categoryGroups.length > 0}
                        <span class="category-detail-subtitle"
                          >{categoryGroups.length} groups</span
                        >
                      {/if}
                    </div>
                  </div>

                  {#if categoryGroups.length > 0}
                    <div class="group-list">
                      <!-- Browse all in category -->
                      <button
                        class="group-row browse-all-row"
                        type="button"
                        on:click={() => {
                          filters = { category: selectedCategory?.cwId };
                          goToResults();
                        }}
                      >
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <circle cx="11" cy="11" r="8" />
                          <line x1="21" y1="21" x2="16.65" y2="16.65" />
                        </svg>
                        <span class="group-name"
                          >Browse all {selectedCategory.name}</span
                        >
                        <svg
                          class="group-nav-chevron"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <polyline points="9 18 15 12 9 6" />
                        </svg>
                      </button>

                      {#each categoryGroups as group}
                        <div class="group-row-wrapper">
                          <button
                            class="group-row"
                            type="button"
                            on:click={() => toggleGroup(group)}
                          >
                            <svg
                              class="group-chevron"
                              class:expanded={expandedGroupName === group.name}
                              class:navigates={(group.subcategories?.length ??
                                0) === 0}
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="14"
                              height="14"
                            >
                              <polyline points="9 18 15 12 9 6" />
                            </svg>
                            <span class="group-name">{group.name}</span>
                            {#if (group.subcategories?.length ?? 0) > 0}
                              <span class="group-count"
                                >{group.subcategories?.length} subcategories</span
                              >
                            {/if}
                          </button>
                          {#if expandedGroupName === group.name && (group.subcategories?.length ?? 0) > 0}
                            <div class="subcategory-list">
                              {#each group.subcategories ?? [] as sub}
                                <button
                                  class="subcategory-row"
                                  type="button"
                                  on:click={() => selectSubcategory(sub)}
                                >
                                  <span class="subcategory-name"
                                    >{sub.name}</span
                                  >
                                  <svg
                                    class="subcategory-chevron"
                                    viewBox="0 0 24 24"
                                    fill="none"
                                    stroke="currentColor"
                                    stroke-width="2"
                                    width="12"
                                    height="12"
                                  >
                                    <polyline points="9 18 15 12 9 6" />
                                  </svg>
                                </button>
                              {/each}
                            </div>
                          {/if}
                        </div>
                      {/each}
                    </div>
                  {:else}
                    <button
                      class="category-browse-btn"
                      type="button"
                      on:click={() => {
                        filters = { category: selectedCategory?.cwId };
                        goToResults();
                      }}
                    >
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        width="16"
                        height="16"
                      >
                        <circle cx="11" cy="11" r="8" />
                        <line x1="21" y1="21" x2="16.65" y2="16.65" />
                      </svg>
                      Browse {selectedCategory.name}
                    </button>
                  {/if}
                </div>
              {:else}
                <!-- Top-level browse: search, categories, ecosystems -->
                <div class="search-section">
                  <div class="search-input-wrap">
                    <svg
                      class="catalog-search-icon"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="16"
                      height="16"
                    >
                      <circle cx="11" cy="11" r="8" />
                      <line x1="21" y1="21" x2="16.65" y2="16.65" />
                    </svg>
                    <input
                      type="text"
                      class="search-input"
                      placeholder="Search by name, part #, vendor SKU, or manufacturer..."
                      bind:value={searchQuery}
                      on:keydown={handleSearchKeydown}
                    />
                    {#if searchQuery.trim()}
                      <button
                        class="search-go-btn"
                        type="button"
                        on:click={handleSearch}
                        aria-label="Search catalog"
                      >
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="16"
                          height="16"
                        >
                          <line x1="5" y1="12" x2="19" y2="12" />
                          <polyline points="12 5 19 12 12 19" />
                        </svg>
                      </button>
                    {/if}
                  </div>
                </div>

                <!-- Quick-action buttons -->
                <div class="section-label">Quick Actions</div>
                <div class="quick-actions">
                  <button
                    class="quick-action-btn special-order"
                    type="button"
                    on:click={addSpecialOrder}
                  >
                    <div class="quick-action-icon special-order-icon">
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        width="18"
                        height="18"
                      >
                        <path
                          d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"
                        />
                        <polyline points="14 2 14 8 20 8" />
                        <line x1="12" y1="18" x2="12" y2="12" />
                        <line x1="9" y1="15" x2="15" y2="15" />
                      </svg>
                    </div>
                    <div class="quick-action-label">
                      <span class="quick-action-name">Special Order</span>
                      <span class="quick-action-desc"
                        >Add a non-catalog item</span
                      >
                    </div>
                  </button>
                  <button
                    class="quick-action-btn labor"
                    type="button"
                    on:click={addLabor}
                  >
                    <div class="quick-action-icon labor-icon">
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        width="18"
                        height="18"
                      >
                        <circle cx="12" cy="12" r="10" />
                        <polyline points="12 6 12 12 16 14" />
                      </svg>
                    </div>
                    <div class="quick-action-label">
                      <span class="quick-action-name">Labor</span>
                      <span class="quick-action-desc">Add labor hours</span>
                    </div>
                  </button>
                  <button
                    class="quick-action-btn ohms"
                    type="button"
                    on:click={addOhms}
                  >
                    <div class="quick-action-icon ohms-icon">
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        width="18"
                        height="18"
                      >
                        <rect
                          x="2"
                          y="7"
                          width="20"
                          height="14"
                          rx="2"
                          ry="2"
                        />
                        <path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2" />
                        <line x1="12" y1="12" x2="12" y2="16" />
                        <line x1="10" y1="14" x2="14" y2="14" />
                      </svg>
                    </div>
                    <div class="quick-action-label">
                      <span class="quick-action-name">OHMS</span>
                      <span class="quick-action-desc"
                        >Overhead material &amp; supplies</span
                      >
                    </div>
                  </button>
                </div>

                {#if categories.length > 0}
                  <div class="section-label">Categories</div>
                  <div class="browse-list">
                    {#each categories as cat}
                      <button
                        class="browse-list-item"
                        type="button"
                        on:click={() => selectCategory(cat)}
                      >
                        <div class="browse-list-icon category-icon">
                          {#if categoryIcon(cat.name) === "cpu"}
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="18"
                              height="18"
                            >
                              <rect x="4" y="4" width="16" height="16" rx="2" />
                              <rect x="9" y="9" width="6" height="6" />
                              <line x1="9" y1="1" x2="9" y2="4" /><line
                                x1="15"
                                y1="1"
                                x2="15"
                                y2="4"
                              />
                              <line x1="9" y1="20" x2="9" y2="23" /><line
                                x1="15"
                                y1="20"
                                x2="15"
                                y2="23"
                              />
                              <line x1="20" y1="9" x2="23" y2="9" /><line
                                x1="20"
                                y1="14"
                                x2="23"
                                y2="14"
                              />
                              <line x1="1" y1="9" x2="4" y2="9" /><line
                                x1="1"
                                y1="14"
                                x2="4"
                                y2="14"
                              />
                            </svg>
                          {:else if categoryIcon(cat.name) === "wrench"}
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="18"
                              height="18"
                            >
                              <path
                                d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z"
                              />
                            </svg>
                          {:else}
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="18"
                              height="18"
                            >
                              <line x1="16.5" y1="9.4" x2="7.5" y2="4.21" />
                              <path
                                d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 002 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0022 16z"
                              />
                              <polyline
                                points="3.27 6.96 12 12.01 20.73 6.96"
                              />
                              <line x1="12" y1="22.08" x2="12" y2="12" />
                            </svg>
                          {/if}
                        </div>
                        <span class="browse-list-label">{cat.name}</span>
                        {#if cat.entries && cat.entries.length > 0}
                          <span class="browse-list-count"
                            >{cat.entries.length} groups</span
                          >
                        {/if}
                        <svg
                          class="browse-list-chevron"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <polyline points="9 18 15 12 9 6" />
                        </svg>
                      </button>
                    {/each}
                  </div>
                {/if}

                {#if ecosystems.length > 0}
                  <div class="section-label">Ecosystems</div>
                  <div class="browse-list">
                    {#each ecosystems as eco}
                      <button
                        class="browse-list-item ecosystem-item"
                        type="button"
                        on:click={() => selectEcosystem(eco)}
                      >
                        <div class="browse-list-icon ecosystem-icon">
                          {#if ecosystemIcon(eco.name) === "wifi"}
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="18"
                              height="18"
                            >
                              <path d="M5 12.55a11 11 0 0114.08 0" />
                              <path d="M1.42 9a16 16 0 0121.16 0" />
                              <path d="M8.53 16.11a6 6 0 016.95 0" />
                              <line x1="12" y1="20" x2="12.01" y2="20" />
                            </svg>
                          {:else if ecosystemIcon(eco.name) === "camera"}
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="18"
                              height="18"
                            >
                              <path
                                d="M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"
                              />
                              <circle cx="12" cy="13" r="4" />
                            </svg>
                          {:else if ecosystemIcon(eco.name) === "shield"}
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="18"
                              height="18"
                            >
                              <path
                                d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"
                              />
                            </svg>
                          {:else}
                            <svg
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="2"
                              width="18"
                              height="18"
                            >
                              <polygon points="12 2 2 7 12 12 22 7 12 2" />
                              <polyline points="2 17 12 22 22 17" />
                              <polyline points="2 12 12 17 22 12" />
                            </svg>
                          {/if}
                        </div>
                        <span class="browse-list-label">{eco.name}</span>
                        <span class="browse-list-count"
                          >{eco.manufacturers.length} manufacturers</span
                        >
                        <svg
                          class="browse-list-chevron"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <polyline points="9 18 15 12 9 6" />
                        </svg>
                      </button>
                    {/each}
                  </div>
                {/if}
              {/if}

              <!-- ═══ STEP: Special Order ═══ -->
            {:else if step === "special-order"}
              <div class="special-order-form">
                <div class="special-order-hero">
                  <div class="special-order-hero-icon">
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="16"
                      height="16"
                    >
                      <path
                        d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"
                      />
                      <polyline points="14 2 14 8 20 8" />
                      <line x1="12" y1="18" x2="12" y2="12" />
                      <line x1="9" y1="15" x2="15" y2="15" />
                    </svg>
                  </div>
                  <div class="special-order-hero-copy">
                    <h4>Special Order</h4>
                    <p>
                      Create a non-catalog item with pricing and CW custom field
                      notes.
                    </p>
                  </div>
                </div>

                <div class="special-order-section">
                  <div class="section-label">Line Details</div>

                  <label class="special-order-field full">
                    <span>Description</span>
                    <input
                      type="text"
                      class="special-order-input"
                      bind:value={specialOrderForm.description}
                      placeholder="Enter item description"
                    />
                  </label>

                  <div class="special-order-grid">
                    <label class="special-order-field">
                      <span>QTY</span>
                      <input
                        type="number"
                        min="1"
                        step="1"
                        class="special-order-input"
                        bind:value={specialOrderForm.quantity}
                      />
                      <small class="special-order-help">Whole number</small>
                    </label>

                    <label class="special-order-field">
                      <span>Price per Unit</span>
                      <input
                        type="number"
                        min="0"
                        step="0.01"
                        class="special-order-input"
                        bind:value={specialOrderForm.pricePerUnit}
                      />
                      <small class="special-order-help">USD per unit</small>
                    </label>

                    <label class="special-order-field">
                      <span>Cost per Unit</span>
                      <input
                        type="number"
                        min="0"
                        step="0.01"
                        class="special-order-input"
                        bind:value={specialOrderForm.costPerUnit}
                      />
                      <small class="special-order-help">USD per unit</small>
                    </label>
                  </div>

                  <div class="special-order-totals">
                    <span>
                      Revenue Total:
                      <strong
                        >{specialOrderRevenue != null
                          ? formatPrice(specialOrderRevenue)
                          : "—"}</strong
                      >
                    </span>
                    <span>
                      Cost Total:
                      <strong
                        >{specialOrderCostTotal != null
                          ? formatPrice(specialOrderCostTotal)
                          : "—"}</strong
                      >
                    </span>
                  </div>

                  <label class="special-order-checkbox">
                    <input
                      type="checkbox"
                      bind:checked={specialOrderForm.taxable}
                    />
                    <span>Taxable</span>
                  </label>
                </div>

                <div class="special-order-section">
                  <div class="section-label">Notes & Narrative</div>

                  <label class="special-order-field full">
                    <span>Procurement Notes</span>
                    <textarea
                      class="special-order-textarea"
                      rows="3"
                      bind:value={specialOrderForm.procurementNotes}
                      placeholder="Internal procurement notes"
                    ></textarea>
                  </label>

                  <label class="special-order-field full">
                    <span>Product Narrative</span>
                    <textarea
                      class="special-order-textarea"
                      rows="3"
                      bind:value={specialOrderForm.productNarrative}
                      placeholder="Product narrative"
                    ></textarea>
                  </label>

                  <label class="special-order-field full">
                    <span>Customer Description</span>
                    <textarea
                      class="special-order-textarea"
                      rows="3"
                      bind:value={specialOrderForm.customerDescription}
                      placeholder="Customer-facing description"
                    ></textarea>
                  </label>
                </div>

                {#if specialOrderError}
                  <div class="special-order-error">{specialOrderError}</div>
                {/if}
              </div>

              <!-- ═══ STEP: OHMS ═══ -->
            {:else if step === "ohms"}
              <div class="special-order-form">
                <div class="special-order-hero">
                  <div class="special-order-hero-icon">
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="16"
                      height="16"
                    >
                      <rect x="2" y="7" width="20" height="14" rx="2" ry="2" />
                      <path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2" />
                      <line x1="12" y1="12" x2="12" y2="16" />
                      <line x1="10" y1="14" x2="14" y2="14" />
                    </svg>
                  </div>
                  <div class="special-order-hero-copy">
                    <h4>OHMS</h4>
                    <p>
                      Add an overhead material and supplies item with pricing.
                    </p>
                  </div>
                </div>

                <div class="special-order-section">
                  <div class="section-label">Line Details</div>

                  <label class="special-order-field full">
                    <span>Price per Unit</span>
                    <input
                      type="number"
                      min="0"
                      step="0.01"
                      class="special-order-input"
                      bind:value={ohmsForm.pricePerUnit}
                    />
                    <small class="special-order-help">USD per unit</small>
                  </label>

                  <label class="special-order-checkbox">
                    <input type="checkbox" bind:checked={ohmsForm.taxable} />
                    <span>Taxable</span>
                  </label>

                  <button
                    type="button"
                    class="labor-advanced-toggle"
                    on:click={() => (ohmsShowAdvanced = !ohmsShowAdvanced)}
                  >
                    {ohmsShowAdvanced ? "Hide" : "Show"} Advanced
                  </button>

                  {#if ohmsShowAdvanced}
                    <div class="labor-advanced-panel">
                      <label class="special-order-field">
                        <span>QTY</span>
                        <input
                          type="number"
                          min="1"
                          step="1"
                          class="special-order-input"
                          bind:value={ohmsForm.quantity}
                        />
                        <small class="special-order-help">Whole number</small>
                      </label>

                      <label class="special-order-field full">
                        <span>Description Override</span>
                        <input
                          type="text"
                          class="special-order-input"
                          bind:value={ohmsForm.description}
                          placeholder="Leave blank to use default product name"
                        />
                      </label>

                      <label class="special-order-field full">
                        <span>Procurement Notes</span>
                        <textarea
                          class="special-order-textarea"
                          rows="3"
                          bind:value={ohmsForm.procurementNotes}
                          placeholder="Internal procurement notes"
                        ></textarea>
                      </label>
                    </div>
                  {/if}
                </div>

                {#if ohmsError}
                  <div class="special-order-error">{ohmsError}</div>
                {/if}
              </div>

              <!-- ═══ STEP: Labor ═══ -->
            {:else if step === "labor"}
              <div class="special-order-form labor-form">
                <div class="special-order-hero">
                  <div class="special-order-hero-icon">
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="16"
                      height="16"
                    >
                      <circle cx="12" cy="12" r="10" />
                      <polyline points="12 6 12 12 16 14" />
                    </svg>
                  </div>
                  <div class="special-order-hero-copy">
                    <h4>Labor</h4>
                    <p>
                      Choose customer + labor type, then hours. Advanced
                      overrides are optional.
                    </p>
                  </div>
                </div>

                <div class="special-order-section">
                  <div class="section-label">Labor Setup</div>

                  <div class="labor-layout">
                    <div class="labor-basics-panel">
                      <div class="labor-main-grid">
                        <label class="special-order-field labor-hours-field">
                          <span>Hours</span>
                          <input
                            type="number"
                            min="0"
                            step="0.25"
                            class="special-order-input"
                            bind:value={laborForm.quantity}
                          />
                        </label>

                        <label
                          class="special-order-checkbox labor-taxable-toggle"
                        >
                          <input
                            type="checkbox"
                            bind:checked={laborForm.taxable}
                          />
                          <span>Taxable</span>
                        </label>

                        <div class="labor-rate-pill labor-rate-panel">
                          <span>Rate</span>
                          <strong
                            >{formatPrice(
                              Number.isFinite(laborUnitPrice)
                                ? laborUnitPrice
                                : laborDefaultRate
                            )}/hr</strong
                          >
                        </div>
                      </div>

                      <div class="special-order-totals">
                        <span>
                          Revenue:
                          <strong
                            >{laborRevenue != null
                              ? formatPrice(laborRevenue)
                              : "—"}</strong
                          >
                        </span>
                        <span>
                          Cost:
                          <strong
                            >{laborCostTotal != null
                              ? formatPrice(laborCostTotal)
                              : "—"}</strong
                          >
                        </span>
                      </div>

                      <small class="special-order-help">
                        Default rates: Corporate {formatPrice(
                          laborRates.corporate
                        )}/hr, Residential {formatPrice(
                          laborRates.residential
                        )}/hr. CPU defaults to {Math.round(
                          laborCpuMultiplier * 100
                        )}% of selected rate.
                      </small>
                    </div>

                    <div class="labor-types-panel">
                      <div class="labor-switch-group">
                        <div class="labor-switch-label">Customer Type</div>
                        <div class="labor-switch-track">
                          <button
                            type="button"
                            class="labor-switch-btn"
                            class:is-active={laborCustomerType === "corporate"}
                            on:click={() => setLaborCustomerType("corporate")}
                          >
                            Corporate
                          </button>
                          <button
                            type="button"
                            class="labor-switch-btn"
                            class:is-active={laborCustomerType ===
                              "residential"}
                            on:click={() => setLaborCustomerType("residential")}
                          >
                            Residential
                          </button>
                        </div>
                      </div>

                      <div class="labor-switch-group">
                        <div class="labor-switch-label">Labor Style</div>
                        <div class="labor-switch-track">
                          <button
                            type="button"
                            class="labor-switch-btn"
                            class:is-active={laborType === "field"}
                            on:click={() => setLaborType("field")}
                          >
                            Field
                          </button>
                          <button
                            type="button"
                            class="labor-switch-btn"
                            class:is-active={laborType === "tech"}
                            on:click={() => setLaborType("tech")}
                          >
                            Tech
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>

                  <button
                    type="button"
                    class="labor-advanced-toggle"
                    on:click={() => (laborShowAdvanced = !laborShowAdvanced)}
                  >
                    {laborShowAdvanced ? "Hide" : "Show"} Advanced (Override CPU
                    / PPU)
                  </button>

                  {#if laborShowAdvanced}
                    <div class="labor-advanced-panel">
                      <div class="special-order-grid labor-advanced-grid">
                        <label class="special-order-field">
                          <span>PPU (Price per Unit)</span>
                          <input
                            type="number"
                            min="0"
                            step="0.01"
                            class="special-order-input"
                            value={laborForm.pricePerUnit}
                            on:input={(e) =>
                              handleLaborPpuInput(
                                (e.currentTarget as HTMLInputElement).value
                              )}
                          />
                        </label>

                        <label class="special-order-field">
                          <span>CPU (Cost per Unit)</span>
                          <input
                            type="number"
                            min="0"
                            step="0.01"
                            class="special-order-input"
                            value={laborForm.costPerUnit}
                            on:input={(e) =>
                              handleLaborCpuInput(
                                (e.currentTarget as HTMLInputElement).value
                              )}
                          />
                        </label>
                      </div>

                      <div
                        class="special-order-grid labor-advanced-grid labor-optional-grid"
                      >
                        <label class="special-order-field">
                          <span>Procurement Notes</span>
                          <textarea
                            class="special-order-textarea labor-compact-textarea"
                            rows="2"
                            bind:value={laborForm.procurementNotes}
                            placeholder="Optional"
                          ></textarea>
                        </label>

                        <label class="special-order-field">
                          <span>Product Narrative</span>
                          <textarea
                            class="special-order-textarea labor-compact-textarea"
                            rows="2"
                            bind:value={laborForm.productNarrative}
                            placeholder="Optional"
                          ></textarea>
                        </label>
                      </div>

                      <label class="special-order-field full">
                        <span>Customer Description</span>
                        <textarea
                          class="special-order-textarea labor-compact-textarea"
                          rows="2"
                          bind:value={laborForm.customerDescription}
                          placeholder="Optional"
                        ></textarea>
                      </label>

                      <button
                        type="button"
                        class="labor-reset-btn"
                        on:click={resetLaborRateDefaults}
                      >
                        Reset to default rates
                      </button>
                    </div>
                  {/if}
                </div>

                {#if isLoadingLaborOptions}
                  <div class="loading-center">
                    <svg
                      class="spin-icon"
                      viewBox="0 0 24 24"
                      width="20"
                      height="20"
                    >
                      <circle
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        stroke-width="3"
                        fill="none"
                        opacity="0.25"
                      />
                      <path
                        d="M12 2a10 10 0 0 1 10 10"
                        stroke="currentColor"
                        stroke-width="3"
                        fill="none"
                        stroke-linecap="round"
                      />
                    </svg>
                    <span>Loading labor defaults...</span>
                  </div>
                {/if}

                {#if laborError}
                  <div class="special-order-error">{laborError}</div>
                {/if}
              </div>

              <!-- ═══ STEP: Results ═══ -->
            {:else if step === "results"}
              <div class="results-toolbar">
                <div class="results-search-wrap">
                  <svg
                    class="catalog-search-icon"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    width="14"
                    height="14"
                  >
                    <circle cx="11" cy="11" r="8" />
                    <line x1="21" y1="21" x2="16.65" y2="16.65" />
                  </svg>
                  <input
                    type="text"
                    class="results-search-input"
                    placeholder="Refine search..."
                    bind:value={searchQuery}
                    on:keydown={(e) => {
                      if (e.key === "Enter") {
                        filters = {
                          ...filters,
                          search: searchQuery.trim() || undefined,
                        };
                        fetchResults(1);
                      }
                    }}
                  />
                </div>
                <div class="results-filter-chips">
                  {#if filters.category}
                    <span class="filter-chip">
                      {categoryFilterLabel}
                      <button
                        class="chip-remove"
                        type="button"
                        on:click={() => clearFilter("category")}
                        aria-label="Remove category filter">&times;</button
                      >
                    </span>
                  {/if}
                  {#if filters.subcategory}
                    <span class="filter-chip">
                      {subcategoryFilterLabel}
                      <button
                        class="chip-remove"
                        type="button"
                        on:click={() => clearFilter("subcategory")}
                        aria-label="Remove subcategory filter">&times;</button
                      >
                    </span>
                  {/if}
                  {#if filters.ecosystem}
                    <span class="filter-chip ecosystem-chip">
                      {filters.ecosystem}
                      <button
                        class="chip-remove"
                        type="button"
                        on:click={() => clearFilter("ecosystem")}
                        aria-label="Remove ecosystem filter">&times;</button
                      >
                    </span>
                  {/if}
                  {#if filters.manufacturer}
                    <span class="filter-chip">
                      {filters.manufacturer}
                      <button
                        class="chip-remove"
                        type="button"
                        on:click={() => clearFilter("manufacturer")}
                        aria-label="Remove manufacturer filter">&times;</button
                      >
                    </span>
                  {/if}
                  {#if filters.inStock}
                    <span class="filter-chip in-stock-chip">
                      In Stock
                      <button
                        class="chip-remove"
                        type="button"
                        on:click={toggleInStock}
                        aria-label="Remove in-stock filter">&times;</button
                      >
                    </span>
                  {/if}
                </div>
              </div>

              <!-- Filter dropdowns row -->
              <div class="filter-row">
                {#if filterSubcategories.length > 0 && !filters.subcategory}
                  <select
                    class="filter-select"
                    on:change={(e) => {
                      const val = e.currentTarget.value;
                      const subcategoryId = Number(val);
                      if (!Number.isNaN(subcategoryId) && subcategoryId > 0) {
                        applySubcategoryFilter(subcategoryId);
                      }
                    }}
                  >
                    <option value="">Subcategory...</option>
                    {#each filterSubcategories as sub}
                      <option value={sub.cwId ?? ""}>{sub.name}</option>
                    {/each}
                  </select>
                {/if}
                {#if filterManufacturers.length > 0 && !filters.manufacturer}
                  <select
                    class="filter-select"
                    on:change={(e) => {
                      const val = e.currentTarget.value;
                      if (val) applyManufacturerFilter(val);
                    }}
                  >
                    <option value="">Manufacturer...</option>
                    {#each filterManufacturers as mfr}
                      <option value={mfr}>{mfr}</option>
                    {/each}
                  </select>
                {/if}
                {#if !filters.inStock}
                  <button
                    class="filter-toggle-btn"
                    type="button"
                    on:click={toggleInStock}
                  >
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="13"
                      height="13"
                    >
                      <path
                        d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"
                      />
                      <polyline points="3.27 6.96 12 12.01 20.73 6.96" />
                      <line x1="12" y1="22.08" x2="12" y2="12" />
                    </svg>
                    In Stock Only
                  </button>
                {/if}
              </div>

              <!-- Results count -->
              <div class="results-count">
                {#if isLoadingResults}
                  Searching...
                {:else if totalResults === 0}
                  No results
                {:else}
                  Showing {resultsStart}-{resultsEnd} of {totalResults}
                {/if}
              </div>

              <!-- Results list -->
              {#if isLoadingResults}
                <div class="loading-center">
                  <svg
                    class="spin-icon"
                    viewBox="0 0 24 24"
                    width="20"
                    height="20"
                  >
                    <circle
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      stroke-width="3"
                      fill="none"
                      opacity="0.25"
                    />
                    <path
                      d="M12 2a10 10 0 0 1 10 10"
                      stroke="currentColor"
                      stroke-width="3"
                      fill="none"
                      stroke-linecap="round"
                    />
                  </svg>
                </div>
              {:else if results.length === 0}
                <div class="empty-results">
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="1.5"
                    width="40"
                    height="40"
                  >
                    <circle cx="11" cy="11" r="8" />
                    <line x1="21" y1="21" x2="16.65" y2="16.65" />
                    <line x1="8" y1="11" x2="14" y2="11" />
                  </svg>
                  <span>No items match your filters</span>
                </div>
              {:else}
                <div class="results-list">
                  {#each results as item}
                    <button
                      class="result-item"
                      class:in-cart={cart.some((c) => c.id === item.id)}
                      type="button"
                      on:click={() => openDetailPane(item)}
                    >
                      <div class="result-item-main">
                        <div class="result-item-name">
                          {item.name ||
                            item.description ||
                            item.identifier ||
                            "Unknown Item"}
                        </div>
                        {#if item.identifier}
                          <div class="result-item-id">{item.identifier}</div>
                        {/if}
                        <div class="result-item-meta">
                          {#if item.manufacturer}
                            <span class="result-meta-tag"
                              >{item.manufacturer}</span
                            >
                          {/if}
                          {#if item.partNumber}
                            <span class="result-meta-tag muted"
                              >{item.partNumber}</span
                            >
                          {/if}
                          {#if item.category}
                            <span class="result-meta-tag subtle"
                              >{item.category}</span
                            >
                          {/if}
                          {#if item.subcategory}
                            <span class="result-meta-tag subtle"
                              >{item.subcategory}</span
                            >
                          {/if}
                        </div>
                      </div>
                      <div class="result-item-right">
                        {#if item.price != null}
                          <span class="result-price"
                            >{formatPrice(item.price)}</span
                          >
                        {/if}
                        {#if item.onHand != null}
                          <InventoryPopover identifier={item.id} onHand={item.onHand} />
                        {/if}
                      </div>
                      {#if cart.some((c) => c.id === item.id)}
                        <span class="in-cart-badge" title="In cart">
                          <svg
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            stroke-width="3"
                            width="12"
                            height="12"
                          >
                            <polyline points="20 6 9 17 4 12" />
                          </svg>
                        </span>
                      {:else}
                        <svg
                          class="result-chevron"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <polyline points="9 18 15 12 9 6" />
                        </svg>
                      {/if}
                    </button>
                  {/each}
                </div>

                <!-- Pagination -->
                {#if totalPages > 1 || nextPage != null || previousPage != null}
                  <div class="pagination">
                    <button
                      class="page-btn"
                      type="button"
                      disabled={previousPage == null}
                      on:click={() =>
                        previousPage != null && fetchResults(previousPage)}
                      aria-label="Previous page"
                    >
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        width="14"
                        height="14"
                      >
                        <polyline points="15 18 9 12 15 6" />
                      </svg>
                    </button>
                    <span class="page-info"
                      >Page {resultPage} of {totalPages}</span
                    >
                    <button
                      class="page-btn"
                      type="button"
                      disabled={nextPage == null}
                      on:click={() =>
                        nextPage != null && fetchResults(nextPage)}
                      aria-label="Next page"
                    >
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        width="14"
                        height="14"
                      >
                        <polyline points="9 18 15 12 9 6" />
                      </svg>
                    </button>
                  </div>
                {/if}
              {/if}
            {/if}
          </div>

          <!-- ═══ Footer ═══ -->
          <div class="modal-footer">
            <button class="btn-cancel" type="button" on:click={handleClose}>
              Cancel
            </button>
            {#if step === "special-order"}
              <button
                class="btn-submit"
                type="button"
                on:click={submitSpecialOrder}
                disabled={!canSubmitSpecialOrder || isSubmittingSpecialOrder}
              >
                {isSubmittingSpecialOrder ? "Adding..." : "Add Special Order"}
              </button>
            {:else if step === "ohms"}
              <button
                class="btn-submit"
                type="button"
                on:click={submitOhms}
                disabled={!canSubmitOhms || isSubmittingOhms}
              >
                {isSubmittingOhms ? "Adding..." : "Add OHMS Item"}
              </button>
            {:else if step === "labor"}
              <button
                class="btn-submit"
                type="button"
                on:click={submitLabor}
                disabled={!canSubmitLabor ||
                  isSubmittingLabor ||
                  isLoadingLaborOptions}
              >
                {isSubmittingLabor ? "Adding..." : "Add Labor"}
              </button>
            {:else if cart.length > 0}
              <button
                class="btn-submit"
                type="button"
                disabled={isAddingSelected}
                on:click={handleAddSelected}
              >
                {#if isAddingSelected}
                  <svg
                    class="quick-add-spinner"
                    viewBox="0 0 24 24"
                    width="14"
                    height="14"
                  >
                    <circle
                      cx="12"
                      cy="12"
                      r="10"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2.5"
                      stroke-dasharray="50"
                      stroke-linecap="round"
                    />
                  </svg>
                  Adding…
                {:else}
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    width="14"
                    height="14"
                  >
                    <line x1="12" y1="5" x2="12" y2="19" />
                    <line x1="5" y1="12" x2="19" y2="12" />
                  </svg>
                  Add Selected Items ({cart.length})
                {/if}
              </button>
            {/if}
          </div>
        </div>

        <!-- ═══ Slide-out Detail Pane (outside modal) ═══ -->
        {#if detailPaneOpen || paneClosing}
          <div class="detail-pane" class:pane-closing={paneClosing}>
            {#if detailPaneMode === "cart"}
              <!-- Cart view -->
              <div class="detail-pane-header">
                <span class="detail-pane-title"
                  >Selected Items ({cart.length})</span
                >
                <button
                  class="detail-pane-close"
                  type="button"
                  on:click={closeDetailPane}
                  aria-label="Close pane"
                >
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    width="16"
                    height="16"
                  >
                    <line x1="18" y1="6" x2="6" y2="18" />
                    <line x1="6" y1="6" x2="18" y2="18" />
                  </svg>
                </button>
              </div>
              <div class="detail-pane-body">
                {#if cart.length === 0}
                  <div class="empty-cart-message">
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="1.5"
                      width="32"
                      height="32"
                    >
                      <path
                        d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"
                      />
                      <line x1="3" y1="6" x2="21" y2="6" />
                      <path d="M16 10a4 4 0 01-8 0" />
                    </svg>
                    <span>No items selected</span>
                  </div>
                {:else}
                  {#each cart as item}
                    <div class="cart-pane-item">
                      <button
                        class="cart-pane-item-main"
                        type="button"
                        on:click={() => openDetailPane(item)}
                      >
                        <span class="cart-pane-item-name"
                          >{item.name || item.description || item.identifier || "Item"}</span
                        >
                        <div class="cart-pane-item-meta">
                          {#if item.manufacturer}
                            <span class="cart-pane-item-mfr"
                              >{item.manufacturer}</span
                            >
                          {/if}
                          {#if item.price != null}
                            <span class="cart-pane-item-price"
                              >{formatPrice(item.price)}</span
                            >
                          {/if}
                        </div>
                      </button>
                      <div class="cart-pane-item-qty">
                        <button
                          class="cart-qty-btn"
                          type="button"
                          on:click={() =>
                            setItemQty(
                              item.id,
                              (itemQuantities[item.id] ?? 1) - 1
                            )}
                          disabled={(itemQuantities[item.id] ?? 1) <= 1}
                          aria-label="Decrease quantity">−</button
                        >
                        <input
                          class="cart-qty-input"
                          type="number"
                          min="1"
                          value={itemQuantities[item.id] ?? 1}
                          on:change={(e) =>
                            setItemQty(
                              item.id,
                              parseInt(e.currentTarget.value, 10)
                            )}
                        />
                        <button
                          class="cart-qty-btn"
                          type="button"
                          on:click={() =>
                            setItemQty(
                              item.id,
                              (itemQuantities[item.id] ?? 1) + 1
                            )}
                          aria-label="Increase quantity">+</button
                        >
                      </div>
                      <button
                        class="cart-pane-item-remove"
                        type="button"
                        on:click={() => removeFromCart(item)}
                        aria-label="Remove from cart"
                      >
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          stroke-width="2"
                          width="14"
                          height="14"
                        >
                          <line x1="18" y1="6" x2="6" y2="18" />
                          <line x1="6" y1="6" x2="18" y2="18" />
                        </svg>
                      </button>
                    </div>
                  {/each}
                {/if}
              </div>
            {:else if detailPaneMode === "item" && detailItem}
              <!-- Item detail view -->
              <div class="detail-pane-header">
                <span class="detail-pane-title"
                  >{detailItem.name ||
                    detailItem.description ||
                    detailItem.identifier ||
                    "Catalog Item"}</span
                >
                <button
                  class="detail-pane-close"
                  type="button"
                  on:click={closeDetailPane}
                  aria-label="Close pane"
                >
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="2"
                    width="16"
                    height="16"
                  >
                    <line x1="18" y1="6" x2="6" y2="18" />
                    <line x1="6" y1="6" x2="18" y2="18" />
                  </svg>
                </button>
              </div>
              <div class="detail-pane-body">
                <div class="detail-view">
                  <div class="detail-header-section">
                    <h3 class="detail-name">
                      {detailItem.name ||
                        detailItem.description ||
                        detailItem.identifier ||
                        "Catalog Item"}
                    </h3>
                    {#if detailItem.manufacturer}
                      <span class="detail-mfr">{detailItem.manufacturer}</span>
                    {/if}
                  </div>

                  <div class="detail-fields">
                    {#if detailItem.identifier}
                      <div class="detail-field">
                        <span class="detail-field-label">Product ID</span>
                        <span class="detail-field-value"
                          >{detailItem.identifier}</span
                        >
                      </div>
                    {/if}
                    {#if detailItem.description}
                      <div class="detail-field">
                        <span class="detail-field-label">Customer Description</span>
                        <span class="detail-field-value"
                          >{detailItem.description}</span
                        >
                      </div>
                    {/if}
                    {#if detailItem.partNumber}
                      <div class="detail-field">
                        <span class="detail-field-label">Part Number</span>
                        <span class="detail-field-value"
                          >{detailItem.partNumber}</span
                        >
                      </div>
                    {/if}
                    {#if detailItem.vendorSku}
                      <div class="detail-field">
                        <span class="detail-field-label">Vendor SKU</span>
                        <span class="detail-field-value"
                          >{detailItem.vendorSku}</span
                        >
                      </div>
                    {/if}
                    {#if detailItem.category}
                      <div class="detail-field">
                        <span class="detail-field-label">Category</span>
                        <span class="detail-field-value"
                          >{detailItem.category}</span
                        >
                      </div>
                    {/if}
                    {#if detailItem.subcategory}
                      <div class="detail-field">
                        <span class="detail-field-label">Subcategory</span>
                        <span class="detail-field-value"
                          >{detailItem.subcategory}</span
                        >
                      </div>
                    {/if}
                    <div class="detail-field">
                      <span class="detail-field-label">Price</span>
                      <span class="detail-field-value price"
                        >{formatPrice(detailItem.price)}</span
                      >
                    </div>
                    {#if detailItem.cost != null}
                      <div class="detail-field">
                        <span class="detail-field-label">Cost</span>
                        <span class="detail-field-value"
                          >{formatPrice(detailItem.cost)}</span
                        >
                      </div>
                    {/if}
                    {#if detailItem.unitOfMeasure}
                      <div class="detail-field">
                        <span class="detail-field-label">Unit of Measure</span>
                        <span class="detail-field-value"
                          >{detailItem.unitOfMeasure}</span
                        >
                      </div>
                    {/if}
                    <div class="detail-field">
                      <span class="detail-field-label">Inventory</span>
                      <span class="detail-field-value">
                        <InventoryPopover identifier={detailItem.id} onHand={detailItem.onHand} />
                      </span>
                    </div>
                    <div class="detail-field">
                      <span class="detail-field-label">Product Narrative</span>
                      <span
                        class="detail-field-value"
                        style="white-space: pre-wrap;"
                        >{detailItem.productNarrative || "—"}</span
                      >
                    </div>
                    <div class="detail-field">
                      <span class="detail-field-label">Procurement Notes</span>
                      <span
                        class="detail-field-value"
                        style="white-space: pre-wrap;"
                        >{detailItem.procurementNotes || "—"}</span
                      >
                    </div>
                  </div>
                </div>
              </div>
              <div class="detail-pane-qty">
                <label class="detail-qty-label" for="detail-qty-input"
                  >Qty</label
                >
                <div class="detail-qty-controls">
                  <button
                    class="detail-qty-btn"
                    type="button"
                    on:click={() => {
                      if (detailItem)
                        setItemQty(
                          detailItem.id,
                          (itemQuantities[detailItem.id] ?? 1) - 1
                        );
                    }}
                    disabled={!detailItem ||
                      (itemQuantities[detailItem?.id ?? ""] ?? 1) <= 1}
                    aria-label="Decrease quantity">−</button
                  >
                  <input
                    id="detail-qty-input"
                    class="detail-qty-input"
                    type="number"
                    min="1"
                    value={detailItem
                      ? (itemQuantities[detailItem.id] ?? 1)
                      : 1}
                    on:change={(e) => {
                      if (detailItem)
                        setItemQty(
                          detailItem.id,
                          parseInt(e.currentTarget.value, 10)
                        );
                    }}
                  />
                  <button
                    class="detail-qty-btn"
                    type="button"
                    on:click={() => {
                      if (detailItem)
                        setItemQty(
                          detailItem.id,
                          (itemQuantities[detailItem.id] ?? 1) + 1
                        );
                    }}
                    aria-label="Increase quantity">+</button
                  >
                </div>
              </div>
              <div class="detail-pane-actions">
                <button
                  class="btn-quick-add"
                  type="button"
                  disabled={isQuickAdding}
                  on:click={() => {
                    if (detailItem) quickAdd(detailItem);
                  }}
                >
                  {#if isQuickAdding}
                    <svg
                      class="quick-add-spinner"
                      viewBox="0 0 24 24"
                      width="14"
                      height="14"
                    >
                      <circle
                        cx="12"
                        cy="12"
                        r="10"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2.5"
                        stroke-dasharray="50"
                        stroke-linecap="round"
                      />
                    </svg>
                    Adding…
                  {:else}
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="14"
                      height="14"
                    >
                      <polygon
                        points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"
                      />
                    </svg>
                    Quick Add
                  {/if}
                </button>
                {#if detailItemInCart}
                  <button
                    class="btn-remove-cart"
                    type="button"
                    on:click={() => {
                      if (detailItem) removeFromCart(detailItem);
                    }}
                  >
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="14"
                      height="14"
                    >
                      <polyline points="20 6 9 17 4 12" />
                    </svg>
                    In Cart — Remove
                  </button>
                {:else}
                  <button
                    class="btn-add-cart"
                    type="button"
                    on:click={() => {
                      if (detailItem) addToCart(detailItem);
                    }}
                  >
                    <svg
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="2"
                      width="14"
                      height="14"
                    >
                      <line x1="12" y1="5" x2="12" y2="19" />
                      <line x1="5" y1="12" x2="19" y2="12" />
                    </svg>
                    Add to Cart
                  </button>
                {/if}
              </div>
            {/if}
          </div>
        {/if}
      </div>
    </div>
  </EditGuard>
{/if}

<style>
  /* ── Backdrop ── */
  .modal-backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.45);
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    animation: backdropIn 0.12s ease;
  }

  /* ── Modal shell wrapper ── */
  .modal-shell {
    position: relative;
    height: 80vh;
    width: 94%;
    max-width: 720px;
    animation: modalIn 0.15s ease;
  }

  /* ── Modal ── */
  .modal {
    background: var(--bg-surface);
    border: 1px solid var(--border-subtle);
    border-radius: 14px;
    box-shadow: 0 20px 50px rgba(0, 0, 0, 0.28);
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    transition: border-radius 0.2s ease;
  }

  .modal.pane-open {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    border-right-color: transparent;
  }

  /* ── Header ── */
  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 22px 14px;
    border-bottom: 1px solid var(--border-subtle);
    flex-shrink: 0;
  }

  .modal-header-left {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .modal-header-right {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .back-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    padding: 0;
    background: none;
    border: 1px solid var(--border-subtle);
    border-radius: 7px;
    cursor: pointer;
    color: var(--text-muted);
    transition:
      background 0.12s,
      border-color 0.12s,
      color 0.12s;
  }

  .back-btn:hover {
    background: var(--card-hover-bg);
    color: var(--text-primary);
  }

  .modal-title-group {
    display: flex;
    align-items: center;
    gap: 10px;
    color: var(--text-primary);
  }

  .modal-title-group h2 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
  }

  .modal-title-group svg {
    color: var(--text-muted);
    flex-shrink: 0;
  }

  .close-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    padding: 0;
    background: none;
    border: 1px solid transparent;
    border-radius: 7px;
    cursor: pointer;
    color: var(--text-muted);
    transition:
      background 0.12s,
      border-color 0.12s,
      color 0.12s;
  }

  .close-btn:hover {
    background: var(--card-hover-bg);
    border-color: var(--border-subtle);
    color: var(--text-primary);
  }

  /* ── Cart badge ── */
  .cart-badge-area {
    position: relative;
    display: flex;
    align-items: center;
  }

  .cart-badge {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 4px 10px;
    border-radius: 7px;
    border: 1px solid var(--border-subtle);
    background: transparent;
    cursor: pointer;
    color: var(--text-secondary);
    font-size: 12px;
    font-weight: 600;
    transition:
      background 0.12s,
      color 0.12s,
      border-color 0.12s;
  }

  .cart-badge:hover {
    background: var(--card-hover-bg);
    color: var(--text-primary);
    border-color: var(--accent-color, #60a5fa);
  }

  .cart-count {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 18px;
    height: 18px;
    border-radius: 9px;
    background: var(--accent-color, #60a5fa);
    color: #fff;
    font-size: 10.5px;
    font-weight: 700;
    padding: 0 5px;
  }

  .cart-preview {
    position: absolute;
    top: calc(100% + 8px);
    right: 0;
    width: 260px;
    background: var(--bg-surface);
    border: 1px solid var(--border-subtle);
    border-radius: 10px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
    padding: 8px;
    z-index: 20;
    animation: fadeIn 0.12s ease;
  }

  .cart-preview-title {
    font-size: 10.5px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    color: var(--text-muted);
    padding: 4px 8px 6px;
  }

  .cart-preview-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    padding: 5px 8px;
    border-radius: 5px;
  }

  .cart-preview-item-name {
    font-size: 12px;
    color: var(--text-primary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
    min-width: 0;
  }

  .cart-preview-qty {
    font-weight: 700;
    color: var(--accent, #6366f1);
    margin-right: 3px;
    font-size: 11px;
  }

  .cart-preview-item-price {
    font-size: 11px;
    color: var(--text-muted);
    flex-shrink: 0;
    font-weight: 500;
  }

  .cart-preview-more {
    padding: 4px 8px;
    font-size: 11px;
    color: var(--text-muted);
    font-style: italic;
  }

  /* ── Breadcrumb ── */
  .breadcrumb-bar {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 8px 22px;
    border-bottom: 1px solid var(--border-subtle);
    font-size: 11.5px;
    flex-shrink: 0;
    overflow-x: auto;
  }

  .breadcrumb-link {
    background: none;
    border: none;
    padding: 0;
    font-size: inherit;
    color: var(--accent-color, #60a5fa);
    cursor: pointer;
    text-decoration: none;
    white-space: nowrap;
  }

  .breadcrumb-link:hover {
    text-decoration: underline;
  }

  .breadcrumb-sep {
    color: var(--text-muted);
    user-select: none;
  }

  .breadcrumb-text {
    color: var(--text-secondary);
    white-space: nowrap;
  }

  .breadcrumb-current {
    color: var(--text-primary);
    font-weight: 600;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
  }

  /* ── Body ── */
  .modal-body {
    padding: 16px 22px;
    overflow-y: auto;
    flex: 1;
  }

  /* ── Error banner ── */
  .error-banner {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 14px;
    margin-bottom: 14px;
    background: rgba(220, 38, 38, 0.08);
    border: 1px solid rgba(220, 38, 38, 0.2);
    border-radius: 8px;
    font-size: 13px;
    color: #dc2626;
  }

  /* ── Loading ── */
  .loading-center {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 12px;
    padding: 40px 0;
    color: var(--text-muted);
    font-size: 13px;
  }

  .spin-icon {
    animation: spin 0.8s linear infinite;
    color: var(--text-muted);
  }

  /* ── Search section ── */
  .search-section {
    margin-bottom: 20px;
  }

  .search-input-wrap {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 0 12px;
    border: 1px solid var(--border-subtle);
    border-radius: 9px;
    background: var(--bg-inset);
    transition:
      border-color 0.15s,
      box-shadow 0.15s;
  }

  .search-input-wrap:focus-within {
    border-color: var(--input-focus-border, #60a5fa);
    box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.1);
  }

  .catalog-search-icon {
    color: var(--text-muted);
    flex-shrink: 0;
  }

  .search-input {
    flex: 1;
    padding: 9px 0;
    border: none;
    background: transparent;
    font-size: 13px;
    color: var(--text-primary);
    outline: none;
  }

  .search-input::placeholder {
    color: var(--text-muted);
  }

  .search-go-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    padding: 0;
    background: var(--accent-color, #60a5fa);
    border: none;
    border-radius: 6px;
    cursor: pointer;
    color: #fff;
    transition: filter 0.12s;
  }

  .search-go-btn:hover {
    filter: brightness(1.15);
  }

  /* ── Special order form ── */
  .special-order-form {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .labor-form {
    gap: 8px;
  }

  .labor-form .special-order-hero {
    padding: 8px 10px;
  }

  .labor-form .special-order-section {
    gap: 8px;
    padding: 10px;
  }

  .labor-form .section-label {
    margin: 0 0 4px;
  }

  .special-order-hero {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 10px 12px;
    border: 1px solid var(--border-subtle);
    border-radius: 10px;
    background: var(--bg-inset);
  }

  .special-order-hero-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    border-radius: 8px;
    color: var(--accent-color, #60a5fa);
    background: var(--card-hover-bg);
    flex-shrink: 0;
  }

  .special-order-hero-copy h4 {
    margin: 0;
    font-size: 13px;
    color: var(--text-primary);
    font-weight: 700;
  }

  .special-order-hero-copy p {
    margin: 2px 0 0;
    font-size: 11.5px;
    color: var(--text-muted);
    line-height: 1.35;
  }

  .special-order-section {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 12px;
    border: 1px solid var(--border-subtle);
    border-radius: 10px;
    background: var(--bg-inset);
  }

  .special-order-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 8px;
  }

  .special-order-field {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .special-order-field.full {
    grid-column: 1 / -1;
  }

  .special-order-field span {
    font-size: 11px;
    font-weight: 600;
    color: var(--text-secondary);
  }

  .special-order-help {
    font-size: 10.5px;
    color: var(--text-muted);
    margin-top: -1px;
  }

  .labor-layout {
    display: grid;
    grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr);
    gap: 12px;
    align-items: stretch;
  }

  .labor-basics-panel,
  .labor-types-panel {
    border: 1px solid var(--border-subtle);
    border-radius: 9px;
    background: var(--bg-inset);
    padding: 9px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    height: 100%;
  }

  .labor-switch-group {
    display: flex;
    flex-direction: column;
    gap: 5px;
  }

  .labor-switch-label {
    font-size: 11px;
    font-weight: 600;
    color: var(--text-secondary);
  }

  .labor-switch-track {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 6px;
    padding: 3px;
    border-radius: 8px;
    border: 1px solid var(--border-subtle);
    background: var(--bg-inset);
  }

  .labor-switch-btn {
    border: 1px solid transparent;
    background: transparent;
    color: var(--text-secondary);
    font-size: 12px;
    font-weight: 600;
    padding: 7px 8px;
    border-radius: 7px;
    cursor: pointer;
    width: 100%;
    transition:
      border-color 0.12s,
      background 0.12s,
      color 0.12s;
  }

  .labor-switch-btn:hover {
    border-color: var(--border-default);
    color: var(--text-primary);
  }

  .labor-switch-btn.is-active {
    border-color: var(--input-focus-border, #60a5fa);
    background: var(--card-hover-bg);
    color: var(--text-primary);
  }

  .labor-rate-pill {
    display: inline-flex;
    align-items: center;
    width: fit-content;
    padding: 6px 10px;
    border-radius: 8px;
    border: 1px dashed var(--border-subtle);
    background: var(--card-hover-bg);
    color: var(--text-primary);
    font-size: 12px;
    font-weight: 700;
  }

  .labor-main-grid {
    display: grid;
    grid-template-columns: 124px auto auto;
    gap: 8px;
    align-items: end;
  }

  .labor-hours-field {
    width: 100%;
  }

  .labor-hours-field .special-order-input {
    text-align: right;
  }

  .labor-advanced-toggle {
    width: fit-content;
    border: 1px solid var(--border-subtle);
    background: var(--bg-inset);
    color: var(--text-secondary);
    font-size: 11.5px;
    font-weight: 600;
    padding: 6px 10px;
    border-radius: 7px;
    cursor: pointer;
  }

  .labor-taxable-toggle {
    min-height: 36px;
  }

  .labor-rate-panel {
    min-height: 36px;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 11px;
    font-weight: 600;
    color: var(--text-secondary);
  }

  .labor-rate-panel strong {
    color: var(--text-primary);
    font-size: 12px;
    font-weight: 700;
  }

  .labor-advanced-panel {
    border: 1px dashed var(--border-subtle);
    border-radius: 8px;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    background: rgba(96, 165, 250, 0.03);
  }

  .labor-advanced-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }

  .labor-reset-btn {
    width: fit-content;
    border: 1px solid var(--border-subtle);
    border-radius: 7px;
    background: transparent;
    color: var(--text-secondary);
    font-size: 11px;
    font-weight: 600;
    padding: 5px 9px;
    cursor: pointer;
  }

  .labor-compact-textarea {
    min-height: 56px;
  }

  .special-order-input,
  .special-order-textarea {
    width: 100%;
    border: 1px solid var(--border-subtle);
    border-radius: 8px;
    background: var(--bg-inset);
    color: var(--text-primary);
    font-size: 12px;
    padding: 8px 10px;
  }

  .special-order-input:focus,
  .special-order-textarea:focus {
    outline: none;
    border-color: var(--input-focus-border, #60a5fa);
    box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.1);
  }

  .special-order-textarea {
    resize: vertical;
    min-height: 70px;
  }

  .special-order-checkbox {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 12px;
    color: var(--text-secondary);
    user-select: none;
    width: fit-content;
    padding: 4px 8px;
    border: 1px solid var(--border-subtle);
    border-radius: 7px;
    background: var(--card-hover-bg);
  }

  .special-order-totals {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    padding: 8px 10px;
    border: 1px dashed var(--border-subtle);
    border-radius: 8px;
    background: rgba(96, 165, 250, 0.04);
    color: var(--text-secondary);
    font-size: 11.5px;
  }

  .special-order-totals strong {
    color: var(--text-primary);
    font-weight: 700;
    margin-left: 4px;
  }

  .special-order-error {
    color: #ef4444;
    font-size: 11.5px;
    font-weight: 500;
  }

  /* ── Section labels ── */
  .section-label {
    font-size: 11.5px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    color: var(--text-muted);
    margin-bottom: 10px;
    margin-top: 4px;
  }

  /* ── Browse list ── */
  .browse-list {
    display: flex;
    flex-direction: column;
    gap: 1px;
    margin-bottom: 18px;
  }

  .browse-list-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    border: 1px solid transparent;
    border-radius: 8px;
    background: transparent;
    cursor: pointer;
    text-align: left;
    width: 100%;
    transition:
      background 0.1s,
      border-color 0.1s;
  }

  .browse-list-item:hover {
    background: var(--card-hover-bg);
    border-color: var(--border-subtle);
  }

  .browse-list-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    border-radius: 8px;
    flex-shrink: 0;
    color: var(--text-secondary);
  }

  .browse-list-icon.category-icon {
    background: rgba(96, 165, 250, 0.08);
    color: #60a5fa;
  }

  .browse-list-icon.ecosystem-icon {
    background: rgba(139, 92, 246, 0.08);
    color: #8b5cf6;
  }

  .browse-list-label {
    flex: 1;
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .browse-list-count {
    font-size: 10.5px;
    color: var(--text-muted);
    flex-shrink: 0;
  }

  .browse-list-chevron {
    color: var(--text-muted);
    flex-shrink: 0;
  }

  /* ── Quick Actions ── */
  .quick-actions {
    display: flex;
    gap: 10px;
    margin-bottom: 18px;
  }

  .quick-action-btn {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
    padding: 12px 14px;
    border: 1px solid var(--border-subtle);
    border-radius: 10px;
    background: transparent;
    cursor: pointer;
    text-align: left;
    transition:
      background 0.12s,
      border-color 0.12s,
      box-shadow 0.12s;
  }

  .quick-action-btn:hover {
    background: var(--card-hover-bg);
    border-color: var(--border-default, var(--border-subtle));
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  }

  .quick-action-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    border-radius: 8px;
    flex-shrink: 0;
  }

  .quick-action-icon.special-order-icon {
    background: rgba(251, 191, 36, 0.1);
    color: #f59e0b;
  }

  .quick-action-icon.labor-icon {
    background: rgba(52, 211, 153, 0.1);
    color: #10b981;
  }

  .quick-action-icon.ohms-icon {
    background: rgba(99, 102, 241, 0.1);
    color: #6366f1;
  }

  .quick-action-label {
    display: flex;
    flex-direction: column;
    gap: 2px;
    min-width: 0;
  }

  .quick-action-name {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
  }

  .quick-action-desc {
    font-size: 11px;
    color: var(--text-muted);
  }

  /* ── Category detail page ── */
  .category-detail-page {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .category-detail-header {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .category-detail-title {
    display: flex;
    flex-direction: column;
    gap: 2px;
  }

  .category-detail-title h3 {
    margin: 0;
    font-size: 17px;
    font-weight: 700;
    color: var(--text-primary);
  }

  .category-detail-subtitle {
    font-size: 12px;
    color: var(--text-muted);
  }

  .category-browse-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 10px 20px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    background: var(--accent-color, #0066cc);
    border: 1px solid transparent;
    color: #fff;
    transition: filter 0.15s;
    align-self: flex-start;
  }

  .category-browse-btn:hover {
    filter: brightness(1.1);
  }

  /* ── Expandable group rows ── */
  .group-list {
    display: flex;
    flex-direction: column;
    gap: 0;
  }

  .group-row-wrapper {
    display: contents;
  }

  .group-row {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    width: 100%;
    border: 1px solid transparent;
    border-radius: 8px;
    background: transparent;
    cursor: pointer;
    text-align: left;
    transition:
      background 0.1s,
      border-color 0.1s;
  }

  .group-row:hover {
    background: var(--card-hover-bg);
    border-color: var(--border-subtle);
  }

  .browse-all-row {
    margin-bottom: 4px;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--border-subtle);
    border-radius: 8px 8px 0 0;
  }

  .browse-all-row:hover {
    border-bottom-color: var(--border-subtle);
  }

  .group-chevron {
    color: var(--text-muted);
    flex-shrink: 0;
    transition: transform 0.2s ease;
  }

  .group-chevron.expanded {
    transform: rotate(90deg);
  }

  .group-chevron.navigates {
    transition: none;
  }

  .group-nav-chevron {
    color: var(--text-muted);
    flex-shrink: 0;
  }

  .group-name {
    flex: 1;
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .group-count {
    font-size: 10.5px;
    color: var(--text-muted);
    flex-shrink: 0;
  }

  /* ── Subcategory rows (expanded) ── */
  .subcategory-list {
    display: flex;
    flex-direction: column;
    margin-left: 20px;
    padding-left: 12px;
    border-left: 2px solid var(--border-subtle);
    margin-bottom: 6px;
    animation: expandIn 0.15s ease;
  }

  .subcategory-row {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 7px 12px;
    width: 100%;
    border: none;
    border-radius: 6px;
    background: transparent;
    cursor: pointer;
    text-align: left;
    transition: background 0.1s;
  }

  .subcategory-row:hover {
    background: var(--card-hover-bg);
  }

  .subcategory-name {
    flex: 1;
    font-size: 12.5px;
    font-weight: 500;
    color: var(--text-secondary);
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .subcategory-row:hover .subcategory-name {
    color: var(--text-primary);
  }

  .subcategory-chevron {
    color: var(--text-muted);
    flex-shrink: 0;
    opacity: 0;
    transition: opacity 0.1s;
  }

  .subcategory-row:hover .subcategory-chevron {
    opacity: 1;
  }

  /* ── Manufacturer picker (ecosystems) ── */
  .manufacturer-list {
    display: flex;
    flex-direction: column;
    gap: 1px;
  }

  .manufacturer-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    border: 1px solid transparent;
    border-radius: 8px;
    background: transparent;
    cursor: pointer;
    text-align: left;
    width: 100%;
    transition:
      background 0.1s,
      border-color 0.1s;
  }

  .manufacturer-item:hover {
    background: var(--card-hover-bg);
    border-color: var(--border-subtle);
  }

  .manufacturer-item-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    border-radius: 8px;
    flex-shrink: 0;
    background: rgba(139, 92, 246, 0.08);
    color: #8b5cf6;
  }

  .manufacturer-item-icon.all-icon {
    background: rgba(96, 165, 250, 0.08);
    color: #60a5fa;
  }

  .manufacturer-item-label {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 1px;
    min-width: 0;
  }

  .manufacturer-item-name {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
  }

  .manufacturer-item-desc {
    font-size: 11px;
    color: var(--text-muted);
  }

  .manufacturer-chevron {
    color: var(--text-muted);
    flex-shrink: 0;
    opacity: 0.5;
  }

  .manufacturer-item:hover .manufacturer-chevron {
    opacity: 1;
  }

  /* ── Results toolbar ── */
  .results-toolbar {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
    margin-bottom: 10px;
  }

  .results-search-wrap {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 0 10px;
    border: 1px solid var(--border-subtle);
    border-radius: 7px;
    background: var(--bg-inset);
    flex: 1;
    min-width: 180px;
    transition: border-color 0.15s;
  }

  .results-search-wrap:focus-within {
    border-color: var(--input-focus-border, #60a5fa);
  }

  .results-search-input {
    flex: 1;
    padding: 6px 0;
    border: none;
    background: transparent;
    font-size: 12px;
    color: var(--text-primary);
    outline: none;
  }

  .results-search-input::placeholder {
    color: var(--text-muted);
  }

  /* ── Filter chips ── */
  .results-filter-chips {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }

  .filter-chip {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 3px 8px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 500;
    background: rgba(96, 165, 250, 0.1);
    color: #60a5fa;
    border: 1px solid rgba(96, 165, 250, 0.2);
    white-space: nowrap;
  }

  .filter-chip.ecosystem-chip {
    background: rgba(139, 92, 246, 0.1);
    color: #8b5cf6;
    border-color: rgba(139, 92, 246, 0.2);
  }

  .filter-chip.in-stock-chip {
    background: rgba(34, 197, 94, 0.1);
    color: #22c55e;
    border-color: rgba(34, 197, 94, 0.2);
  }

  .chip-remove {
    background: none;
    border: none;
    padding: 0 2px;
    font-size: 14px;
    line-height: 1;
    cursor: pointer;
    color: inherit;
    opacity: 0.7;
    transition: opacity 0.1s;
  }

  .chip-remove:hover {
    opacity: 1;
  }

  /* ── Filter row ── */
  .filter-row {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 10px;
    flex-wrap: wrap;
  }

  .filter-select {
    padding: 4px 28px 4px 8px;
    border: 1px solid var(--border-subtle);
    border-radius: 6px;
    background: var(--bg-inset);
    font-size: 11.5px;
    color: var(--text-primary);
    cursor: pointer;
    appearance: none;
    -webkit-appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2.5'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 8px center;
  }

  .filter-select:focus {
    outline: none;
    border-color: var(--input-focus-border, #60a5fa);
  }

  .filter-toggle-btn {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 10px;
    border: 1px dashed var(--border-subtle);
    border-radius: 6px;
    background: transparent;
    font-size: 11px;
    font-weight: 500;
    color: var(--text-secondary);
    cursor: pointer;
    transition:
      background 0.12s,
      border-color 0.12s,
      color 0.12s;
  }

  .filter-toggle-btn:hover {
    background: rgba(34, 197, 94, 0.06);
    border-color: rgba(34, 197, 94, 0.3);
    color: #22c55e;
  }

  /* ── Results count ── */
  .results-count {
    font-size: 11px;
    color: var(--text-muted);
    margin-bottom: 8px;
  }

  /* ── Empty results ── */
  .empty-results {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    padding: 40px 0;
    color: var(--text-muted);
    font-size: 13px;
  }

  /* ── Results list ── */
  .results-list {
    display: flex;
    flex-direction: column;
    gap: 2px;
  }

  .result-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 10px 12px;
    border: 1px solid transparent;
    border-radius: 8px;
    background: transparent;
    cursor: pointer;
    text-align: left;
    width: 100%;
    transition:
      background 0.1s,
      border-color 0.1s;
  }

  .result-item:hover {
    background: var(--card-hover-bg);
    border-color: var(--border-subtle);
  }

  .result-item.in-cart {
    border-color: rgba(96, 165, 250, 0.25);
    background: rgba(96, 165, 250, 0.04);
  }

  .result-item.in-cart:hover {
    background: rgba(96, 165, 250, 0.08);
  }

  .result-item-main {
    flex: 1;
    min-width: 0;
  }

  .result-item-name {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-primary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .result-item-id {
    font-size: 11px;
    color: var(--text-muted, #888);
    margin-top: 1px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .result-item-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    margin-top: 3px;
  }

  .result-meta-tag {
    font-size: 10.5px;
    font-weight: 500;
    color: var(--text-secondary);
    padding: 1px 6px;
    border-radius: 4px;
    background: var(--bg-inset);
    border: 1px solid var(--border-subtle);
    white-space: nowrap;
  }

  .result-meta-tag.muted {
    color: var(--text-muted);
  }

  .result-meta-tag.subtle {
    opacity: 0.7;
  }

  .result-item-right {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 2px;
    flex-shrink: 0;
  }

  .result-price {
    font-size: 12.5px;
    font-weight: 600;
    color: var(--text-primary);
  }

  .result-stock {
    font-size: 10px;
    font-weight: 600;
    padding: 1px 6px;
    border-radius: 4px;
  }

  .result-stock.in-stock {
    color: #22c55e;
    background: rgba(34, 197, 94, 0.08);
  }

  .result-stock.out-of-stock {
    color: var(--text-muted);
    background: var(--bg-inset);
  }

  .result-chevron {
    color: var(--text-muted);
    flex-shrink: 0;
    opacity: 0.5;
  }

  .result-item:hover .result-chevron {
    opacity: 1;
  }

  .in-cart-badge {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 20px;
    height: 20px;
    border-radius: 10px;
    background: rgba(96, 165, 250, 0.15);
    color: #60a5fa;
    flex-shrink: 0;
  }

  /* ── Pagination ── */
  .pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
    padding: 14px 0 4px;
  }

  .page-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    padding: 0;
    border: 1px solid var(--border-subtle);
    border-radius: 7px;
    background: var(--bg-inset);
    cursor: pointer;
    color: var(--text-secondary);
    transition:
      background 0.12s,
      color 0.12s;
  }

  .page-btn:hover:not(:disabled) {
    background: var(--card-hover-bg);
    color: var(--text-primary);
  }

  .page-btn:disabled {
    opacity: 0.35;
    cursor: not-allowed;
  }

  .page-info {
    font-size: 12px;
    color: var(--text-muted);
  }

  /* ── Slide-out pane (outside modal) ── */
  .detail-pane {
    position: absolute;
    top: 0;
    left: 100%;
    bottom: 0;
    width: 320px;
    background: color-mix(in srgb, var(--bg-surface) 82%, transparent);
    backdrop-filter: blur(16px) saturate(1.4);
    -webkit-backdrop-filter: blur(16px) saturate(1.4);
    border: 1px solid color-mix(in srgb, var(--border-subtle) 60%, transparent);
    border-left: none;
    border-radius: 0 14px 14px 0;
    box-shadow: 8px 4px 24px rgba(0, 0, 0, 0.15);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    animation: paneSlideIn 0.2s ease;
  }

  .detail-pane-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    padding: 14px 16px;
    border-bottom: 1px solid var(--border-subtle);
    flex-shrink: 0;
  }

  .detail-pane-title {
    font-size: 13px;
    font-weight: 700;
    color: var(--text-primary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
    min-width: 0;
  }

  .detail-pane-close {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 26px;
    height: 26px;
    padding: 0;
    background: none;
    border: 1px solid transparent;
    border-radius: 6px;
    cursor: pointer;
    color: var(--text-muted);
    flex-shrink: 0;
    transition:
      background 0.12s,
      color 0.12s;
  }

  .detail-pane-close:hover {
    background: var(--card-hover-bg);
    color: var(--text-primary);
  }

  .detail-pane-body {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
  }

  .detail-pane-qty {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 16px;
    border-top: 1px solid var(--border-subtle);
    flex-shrink: 0;
  }

  .detail-qty-label {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-secondary);
    min-width: 24px;
  }

  .detail-qty-controls {
    display: flex;
    align-items: center;
    gap: 0;
    border: 1px solid var(--border-subtle);
    border-radius: 8px;
    overflow: hidden;
  }

  .detail-qty-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border: none;
    background: var(--bg-surface, rgba(255, 255, 255, 0.04));
    color: var(--text-secondary);
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition:
      background 0.12s,
      color 0.12s;
    user-select: none;
  }

  .detail-qty-btn:hover:not(:disabled) {
    background: var(--bg-hover, rgba(255, 255, 255, 0.08));
    color: var(--text-primary);
  }

  .detail-qty-btn:disabled {
    opacity: 0.35;
    cursor: not-allowed;
  }

  .detail-qty-input {
    width: 60px;
    height: 32px;
    border: none;
    border-left: 1px solid var(--border-subtle);
    border-right: 1px solid var(--border-subtle);
    background: transparent;
    color: var(--text-primary);
    font-size: 13px;
    font-weight: 600;
    text-align: center;
    -moz-appearance: textfield;
    appearance: textfield;
  }

  .detail-qty-input::-webkit-inner-spin-button,
  .detail-qty-input::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }

  .detail-pane-actions {
    display: flex;
    flex-direction: column;
    gap: 6px;
    padding: 14px 16px;
    border-top: 1px solid var(--border-subtle);
    flex-shrink: 0;
  }

  /* ── Detail view (inside pane) ── */
  .detail-view {
    padding: 0;
  }

  .detail-header-section {
    margin-bottom: 16px;
  }

  .detail-name {
    margin: 0 0 4px;
    font-size: 15px;
    font-weight: 700;
    color: var(--text-primary);
    line-height: 1.3;
  }

  .detail-mfr {
    font-size: 12px;
    color: var(--text-secondary);
    font-weight: 500;
  }

  .detail-fields {
    display: grid;
    grid-template-columns: 1fr;
    gap: 10px;
  }

  .detail-field {
    display: flex;
    flex-direction: column;
    gap: 2px;
  }

  .detail-field-label {
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.04em;
    color: var(--text-muted);
  }

  .detail-field-value {
    font-size: 13px;
    font-weight: 500;
    color: var(--text-primary);
  }

  .detail-field-value.price {
    font-weight: 700;
    color: var(--accent-color, #60a5fa);
  }

  .stock-badge {
    display: inline-flex;
    align-items: center;
    padding: 2px 8px;
    border-radius: 5px;
    font-size: 11px;
    font-weight: 600;
  }

  .stock-badge.in-stock {
    color: #22c55e;
    background: rgba(34, 197, 94, 0.08);
  }

  .stock-badge.out-of-stock {
    color: #ef4444;
    background: rgba(239, 68, 68, 0.08);
  }

  .stock-badge.unknown {
    color: var(--text-muted);
    background: var(--bg-inset);
  }

  /* ── Pane action buttons ── */
  .btn-add-cart {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 16px;
    border-radius: 7px;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    background: var(--accent-color, #60a5fa);
    border: 1px solid transparent;
    color: #fff;
    transition: filter 0.15s;
  }

  .btn-add-cart:hover {
    filter: brightness(1.1);
  }

  .btn-remove-cart {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 16px;
    border-radius: 7px;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    background: rgba(96, 165, 250, 0.1);
    border: 1px solid rgba(96, 165, 250, 0.25);
    color: #60a5fa;
    transition:
      background 0.15s,
      border-color 0.15s;
  }

  .btn-remove-cart:hover {
    background: rgba(220, 38, 38, 0.08);
    border-color: rgba(220, 38, 38, 0.25);
    color: #ef4444;
  }

  .btn-quick-add {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 16px;
    border-radius: 7px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    background: transparent;
    border: 1px solid var(--border-subtle);
    color: var(--text-secondary);
    transition:
      background 0.15s,
      border-color 0.15s,
      color 0.15s;
  }

  .btn-quick-add:hover {
    background: rgba(250, 204, 21, 0.06);
    border-color: rgba(250, 204, 21, 0.3);
    color: #eab308;
  }

  .btn-quick-add:disabled {
    opacity: 0.65;
    cursor: not-allowed;
  }

  .btn-quick-add:disabled:hover {
    background: transparent;
    border-color: var(--border-subtle);
    color: var(--text-secondary);
  }

  @keyframes quick-add-spin {
    to {
      transform: rotate(360deg);
    }
  }

  .quick-add-spinner {
    animation: quick-add-spin 0.8s linear infinite;
  }

  /* ── Cart pane items ── */
  .cart-pane-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 4px;
    border-radius: 8px;
    transition: background 0.1s;
  }

  .cart-pane-item:hover {
    background: var(--card-hover-bg);
  }

  .cart-pane-item-main {
    flex: 1;
    min-width: 0;
    padding: 6px 8px;
    border: none;
    border-radius: 6px;
    background: transparent;
    cursor: pointer;
    text-align: left;
    transition: background 0.1s;
  }

  .cart-pane-item-main:hover {
    background: var(--bg-inset);
  }

  .cart-pane-item-name {
    display: block;
    font-size: 12.5px;
    font-weight: 600;
    color: var(--text-primary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .cart-pane-item-meta {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-top: 2px;
  }

  .cart-pane-item-mfr {
    font-size: 11px;
    color: var(--text-muted);
  }

  .cart-pane-item-price {
    font-size: 11px;
    font-weight: 600;
    color: var(--text-secondary);
  }

  .cart-pane-item-remove {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 26px;
    height: 26px;
    padding: 0;
    background: none;
    border: 1px solid transparent;
    border-radius: 6px;
    cursor: pointer;
    color: var(--text-muted);
    flex-shrink: 0;
    transition:
      background 0.12s,
      color 0.12s,
      border-color 0.12s;
  }

  .cart-pane-item-remove:hover {
    background: rgba(220, 38, 38, 0.08);
    color: #ef4444;
    border-color: rgba(220, 38, 38, 0.2);
  }

  .cart-pane-item-qty {
    display: flex;
    align-items: center;
    gap: 0;
    border: 1px solid var(--border-subtle);
    border-radius: 6px;
    overflow: hidden;
    flex-shrink: 0;
  }

  .cart-qty-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border: none;
    background: var(--bg-surface, rgba(255, 255, 255, 0.04));
    color: var(--text-secondary);
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition:
      background 0.12s,
      color 0.12s;
    user-select: none;
    padding: 0;
  }

  .cart-qty-btn:hover:not(:disabled) {
    background: var(--bg-hover, rgba(255, 255, 255, 0.08));
    color: var(--text-primary);
  }

  .cart-qty-btn:disabled {
    opacity: 0.35;
    cursor: not-allowed;
  }

  .cart-qty-input {
    width: 44px;
    height: 24px;
    border: none;
    border-left: 1px solid var(--border-subtle);
    border-right: 1px solid var(--border-subtle);
    background: transparent;
    color: var(--text-primary);
    font-size: 11px;
    font-weight: 600;
    text-align: center;
    -moz-appearance: textfield;
    appearance: textfield;
    padding: 0;
  }

  .cart-qty-input::-webkit-inner-spin-button,
  .cart-qty-input::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }

  .empty-cart-message {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    padding: 32px 0;
    color: var(--text-muted);
    font-size: 13px;
  }

  /* ── Footer ── */
  .modal-footer {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 8px;
    padding: 14px 22px;
    border-top: 1px solid var(--border-subtle);
    flex-shrink: 0;
  }

  .btn-cancel {
    padding: 7px 16px;
    border-radius: 7px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    background: var(--bg-inset);
    border: 1px solid var(--border-subtle);
    color: var(--text-secondary);
    transition:
      background 0.15s,
      border-color 0.15s;
  }

  .btn-cancel:hover:not(:disabled) {
    background: var(--card-hover-bg);
    border-color: var(--border-default);
    color: var(--text-primary);
  }

  .btn-submit {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 7px 18px;
    border-radius: 7px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    background: var(--accent-color, #0066cc);
    border: 1px solid transparent;
    color: #fff;
    transition: filter 0.15s;
  }

  .btn-submit:hover:not(:disabled) {
    filter: brightness(1.1);
  }

  .btn-submit:disabled {
    opacity: 0.45;
    cursor: not-allowed;
  }

  /* ── Animations ── */
  @keyframes backdropIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  @keyframes modalIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }

  @keyframes paneSlideIn {
    from {
      transform: translateX(-20px);
      opacity: 0;
    }
    to {
      transform: translateX(0);
      opacity: 1;
    }
  }

  @keyframes paneSlideOut {
    from {
      transform: translateX(0);
      opacity: 1;
    }
    to {
      transform: translateX(-20px);
      opacity: 0;
    }
  }

  .detail-pane.pane-closing {
    animation: paneSlideOut 0.18s ease forwards;
  }

  @keyframes expandIn {
    from {
      opacity: 0;
      max-height: 0;
    }
    to {
      opacity: 1;
      max-height: 500px;
    }
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(-4px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  /* ── Mobile ── */
  @media (max-width: 768px) {
    .modal-backdrop {
      align-items: flex-end;
    }

    .modal-shell {
      width: 100%;
      max-width: 100%;
      height: 92vh;
      flex-direction: column;
      animation: modalSheetIn 0.3s cubic-bezier(0.32, 0.72, 0, 1);
    }

    .modal {
      width: 100%;
      max-width: 100%;
      border-radius: 14px 14px 0 0;
    }

    .modal.pane-open {
      border-radius: 14px 14px 0 0;
      border-right-color: var(--border-subtle);
    }

    @keyframes modalSheetIn {
      from {
        opacity: 0;
        transform: translateY(100%);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .modal-body {
      padding: 14px 16px;
    }

    .modal-header {
      padding: 14px 16px 12px;
    }

    .modal-footer {
      padding: 12px 16px;
    }

    .breadcrumb-bar {
      padding: 8px 16px;
    }

    .search-input {
      font-size: 16px;
    }

    .results-search-input {
      font-size: 16px;
    }

    .special-order-grid {
      grid-template-columns: 1fr;
    }

    .labor-layout {
      grid-template-columns: 1fr;
    }

    .labor-main-grid {
      grid-template-columns: 1fr;
      align-items: stretch;
    }

    .labor-advanced-grid {
      grid-template-columns: 1fr;
    }

    .special-order-input,
    .special-order-textarea {
      font-size: 16px;
    }

    .filter-select {
      font-size: 16px;
      padding: 8px 32px 8px 10px;
    }

    .btn-cancel,
    .btn-submit {
      padding: 10px 18px;
      font-size: 14px;
    }

    .detail-pane {
      width: 100%;
      max-width: 100%;
      border-radius: 0;
      border-left: 1px solid var(--border-subtle);
      border-top: none;
    }
  }
</style>
