"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import {
  CrudForm
} from "@open-mercato/ui/backend/CrudForm";
import { createCrud } from "@open-mercato/ui/backend/utils/crud";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { TagsInput } from "@open-mercato/ui/backend/inputs/TagsInput";
import MarkdownField from "@open-mercato/ui/backend/inputs/MarkdownField";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Label } from "@open-mercato/ui/primitives/label";
import { RadioGroup, Radio } from "@open-mercato/ui/primitives/radio";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { cn } from "@open-mercato/shared/lib/utils";
import {
  Plus,
  Trash2,
  FileText,
  AlignLeft,
  ChevronLeft,
  ChevronRight,
  AlertCircle,
  Settings
} from "lucide-react";
import {
  apiCall,
  readApiResultOrThrow
} from "@open-mercato/ui/backend/utils/apiCall";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { E } from "../../../../../../generated/entities.ids.generated.js";
import {
  ProductMediaManager
} from "@open-mercato/core/modules/catalog/components/products/ProductMediaManager";
import { ProductCategorizeSection } from "@open-mercato/core/modules/catalog/components/products/ProductCategorizeSection";
import {
  PRODUCT_FORM_STEPS,
  productFormSchema,
  createInitialProductFormValues,
  createVariantDraft,
  buildOptionValuesKey,
  haveSameOptionValues,
  normalizePriceKindSummary,
  formatTaxRateLabel,
  slugify,
  createLocalId,
  buildOptionSchemaDefinition,
  buildVariantCombinations,
  normalizeProductDimensions,
  normalizeProductWeight,
  sanitizeProductDimensions,
  sanitizeProductWeight,
  updateDimensionValue,
  updateWeightValue,
  isConfigurableProductType,
  buildComplianceProductPayload
} from "@open-mercato/core/modules/catalog/components/products/productForm";
import { CATALOG_PRODUCT_TYPES } from "@open-mercato/core/modules/catalog/data/types";
import {
  buildAttachmentImageUrl,
  slugifyAttachmentFileName
} from "@open-mercato/core/modules/attachments/lib/imageUrls";
import { ProductUomSection } from "@open-mercato/core/modules/catalog/components/products/ProductUomSection";
import { ProductComplianceSection } from "@open-mercato/core/modules/catalog/components/products/ProductComplianceSection";
import { canonicalizeUnitCode } from "@open-mercato/core/modules/catalog/lib/unitCodes";
import {
  UNIT_PRICE_REFERENCE_UNITS,
  toPositiveNumberOrNull,
  toIntegerInRangeOrDefault,
  normalizeProductConversionInputs
} from "@open-mercato/core/modules/catalog/components/products/productFormUtils";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("catalog");
const productFormTypedSchema = productFormSchema;
const TRUE_BOOLEAN_VALUES = /* @__PURE__ */ new Set(["true", "1", "yes", "y", "t"]);
const matchField = (fieldId) => (value) => value === fieldId || value.startsWith(`${fieldId}.`) || value.startsWith(`${fieldId}[`);
const matchPrefix = (prefix) => (value) => value.startsWith(prefix);
const STEP_FIELD_MATCHERS = {
  general: [
    matchField("title"),
    matchField("sku"),
    matchField("productType"),
    matchField("description"),
    matchField("mediaItems"),
    matchField("mediaDraftId"),
    matchPrefix("defaultMedia"),
    matchPrefix("dimensions"),
    matchPrefix("weight")
  ],
  organize: [
    matchField("categoryIds"),
    matchField("channelIds"),
    matchField("tags")
  ],
  uom: [
    matchField("defaultUnit"),
    matchField("defaultSalesUnit"),
    matchField("defaultSalesUnitQuantity"),
    matchField("uomRoundingScale"),
    matchField("uomRoundingMode"),
    matchField("unitPriceEnabled"),
    matchField("unitPriceReferenceUnit"),
    matchField("unitPriceBaseQuantity"),
    matchPrefix("unitConversions")
  ],
  compliance: [
    matchField("countryOfOriginCode"),
    matchField("pkwiuCode"),
    matchField("cnCode"),
    matchField("hsCode"),
    matchField("taxClassificationCode"),
    matchField("gtuCodes"),
    matchField("ageMin"),
    matchField("isExciseGood"),
    matchField("exciseCategory"),
    matchField("requiresPrescription"),
    matchPrefix("hazmat"),
    matchField("unNumber"),
    matchField("containsLithiumBattery"),
    matchField("launchAt"),
    matchField("endOfLifeAt"),
    matchField("availableFrom"),
    matchField("availableUntil"),
    matchField("minOrderQty"),
    matchField("maxOrderQty"),
    matchField("orderQtyIncrement"),
    matchField("requiresShipping"),
    matchField("isQuoteOnly"),
    matchField("seoTitle"),
    matchField("seoDescription"),
    matchField("canonicalUrl")
  ],
  variants: [
    matchField("hasVariants"),
    matchPrefix("options"),
    matchPrefix("variants")
  ]
};
function resolveStepForField(fieldId) {
  const normalized = fieldId?.trim();
  if (!normalized) return null;
  for (const step of PRODUCT_FORM_STEPS) {
    const matchers = STEP_FIELD_MATCHERS[step];
    if (matchers.some((matcher) => matcher(normalized))) return step;
  }
  return null;
}
function resolveBooleanFlag(value) {
  if (typeof value === "boolean") return value;
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase();
    if (!normalized) return false;
    if (TRUE_BOOLEAN_VALUES.has(normalized)) return true;
    if (["false", "0", "no", "n", "f"].includes(normalized)) return false;
  }
  if (typeof value === "number") return value !== 0;
  return false;
}
function readInboxProductDraft() {
  try {
    const raw = sessionStorage.getItem("inbox_ops.productDraft");
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (!parsed.actionId || !parsed.proposalId || !parsed.payload) return null;
    return parsed;
  } catch {
    return null;
  }
}
function CreateCatalogProductPage() {
  const t = useT();
  const router = useRouter();
  const searchParams = useSearchParams();
  const fromInboxAction = searchParams.get("fromInboxAction");
  const inboxDraft = React.useMemo(() => {
    if (!fromInboxAction) return null;
    return readInboxProductDraft();
  }, [fromInboxAction]);
  const initialValuesRef = React.useRef(null);
  if (!initialValuesRef.current) {
    const initial = createInitialProductFormValues();
    if (inboxDraft?.payload) {
      const p = inboxDraft.payload;
      if (typeof p.title === "string" && p.title.trim()) initial.title = p.title.trim();
      if (typeof p.description === "string" && p.description.trim()) initial.description = p.description.trim();
    }
    initialValuesRef.current = initial;
  }
  const [priceKinds, setPriceKinds] = React.useState([]);
  const [taxRates, setTaxRates] = React.useState([]);
  React.useEffect(() => {
    const loadPriceKinds = async () => {
      try {
        const payload = await readApiResultOrThrow("/api/catalog/price-kinds?pageSize=100", void 0, {
          errorMessage: t(
            "catalog.priceKinds.errors.load",
            "Failed to load price kinds."
          )
        });
        const items = Array.isArray(payload.items) ? payload.items : [];
        setPriceKinds(
          items.map((item) => normalizePriceKindSummary(item)).filter((item) => item !== null)
        );
      } catch (err) {
        logger.error("catalog.price-kinds.fetch failed", { err });
        setPriceKinds([]);
      }
    };
    loadPriceKinds().catch(() => {
    });
  }, [t]);
  React.useEffect(() => {
    const loadTaxRates = async () => {
      try {
        const payload = await readApiResultOrThrow("/api/sales/tax-rates?pageSize=100", void 0, {
          errorMessage: t(
            "catalog.products.create.taxRates.error",
            "Failed to load tax rates."
          ),
          fallback: { items: [] }
        });
        const items = Array.isArray(payload.items) ? payload.items : [];
        setTaxRates(
          items.map((item) => {
            const rawRate = typeof item.rate === "number" ? item.rate : Number(item.rate ?? Number.NaN);
            return {
              id: String(item.id),
              name: typeof item.name === "string" && item.name.trim().length ? item.name : t(
                "catalog.products.create.taxRates.unnamed",
                "Untitled tax rate"
              ),
              code: typeof item.code === "string" && item.code.trim().length ? item.code : null,
              rate: Number.isFinite(rawRate) ? rawRate : null,
              isDefault: resolveBooleanFlag(
                typeof item.isDefault !== "undefined" ? item.isDefault : item.is_default
              )
            };
          })
        );
      } catch (err) {
        logger.error("sales.tax-rates.fetch failed", { err });
        setTaxRates([]);
      }
    };
    loadTaxRates().catch(() => {
    });
  }, [t]);
  const groups = React.useMemo(
    () => [
      {
        id: "builder",
        column: 1,
        component: ({
          values,
          setValue,
          errors,
          requiredFieldIds
        }) => /* @__PURE__ */ jsx(
          ProductBuilder,
          {
            values,
            setValue,
            errors,
            priceKinds,
            taxRates,
            requiredFieldIds
          }
        )
      },
      {
        id: "product-meta",
        column: 2,
        title: t("catalog.products.create.meta.title", "Product meta"),
        description: t(
          "catalog.products.create.meta.description",
          "Manage subtitle and handle for storefronts."
        ),
        component: ({
          values,
          setValue,
          errors
        }) => /* @__PURE__ */ jsx(
          ProductMetaSection,
          {
            values,
            setValue,
            errors,
            taxRates
          }
        )
      }
    ],
    [priceKinds, taxRates, t]
  );
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: t("catalog.products.create.title", "Create product"),
      backHref: "/backend/catalog/products",
      fields: [],
      groups,
      injectionSpotId: "crud-form:catalog.product",
      initialValues: initialValuesRef.current ?? createInitialProductFormValues(),
      schema: productFormTypedSchema,
      submitLabel: t("catalog.products.create.submit", "Create"),
      cancelHref: "/backend/catalog/products",
      onSubmit: async (formValues) => {
        const title = formValues.title?.trim();
        if (!title) {
          throw createCrudFormError(
            t(
              "catalog.products.create.errors.title",
              "Provide a product title."
            ),
            {
              title: t(
                "catalog.products.create.errors.title",
                "Provide a product title."
              )
            }
          );
        }
        const handle = formValues.handle?.trim() || void 0;
        const description = formValues.description?.trim() || void 0;
        const defaultMediaId = typeof formValues.defaultMediaId === "string" && formValues.defaultMediaId.trim().length ? formValues.defaultMediaId : null;
        const mediaItems = Array.isArray(formValues.mediaItems) ? formValues.mediaItems : [];
        const attachmentIds = mediaItems.map((item) => typeof item.id === "string" ? item.id : null).filter((value) => !!value);
        const mediaDraftId = typeof formValues.mediaDraftId === "string" ? formValues.mediaDraftId : "";
        const defaultMediaEntry = defaultMediaId ? mediaItems.find((item) => item.id === defaultMediaId) : null;
        const defaultMediaUrl = defaultMediaEntry ? buildAttachmentImageUrl(defaultMediaEntry.id, {
          slug: slugifyAttachmentFileName(defaultMediaEntry.fileName)
        }) : null;
        const optionSchemaDefinition = buildOptionSchemaDefinition(
          formValues.options,
          title
        );
        const dimensions = sanitizeProductDimensions(
          formValues.dimensions ?? null
        );
        const weight = sanitizeProductWeight(formValues.weight ?? null);
        const resolveTaxRateValue = (taxRateId) => {
          if (!taxRateId) return null;
          const match = taxRates.find((rate) => rate.id === taxRateId);
          return typeof match?.rate === "number" ? match.rate : null;
        };
        const productLevelTaxRateId = formValues.taxRateId ?? null;
        const productTaxRate = resolveTaxRateValue(productLevelTaxRateId);
        const resolveVariantTax = (variant) => {
          const resolvedVariantTaxRateId = variant.taxRateId ?? productLevelTaxRateId;
          const resolvedVariantTaxRate = resolveTaxRateValue(resolvedVariantTaxRateId) ?? (resolvedVariantTaxRateId ? null : productTaxRate ?? null);
          return { resolvedVariantTaxRateId, resolvedVariantTaxRate };
        };
        const defaultUnit = canonicalizeUnitCode(formValues.defaultUnit);
        const defaultSalesUnit = canonicalizeUnitCode(
          formValues.defaultSalesUnit
        );
        const defaultSalesUnitQuantity = toPositiveNumberOrNull(formValues.defaultSalesUnitQuantity) ?? 1;
        const uomRoundingScale = toIntegerInRangeOrDefault(
          formValues.uomRoundingScale,
          0,
          6,
          4
        );
        const uomRoundingMode = formValues.uomRoundingMode === "down" || formValues.uomRoundingMode === "up" ? formValues.uomRoundingMode : "half_up";
        const unitPriceEnabled = Boolean(formValues.unitPriceEnabled);
        const unitPriceReferenceUnit = canonicalizeUnitCode(
          formValues.unitPriceReferenceUnit
        );
        const unitPriceBaseQuantity = toPositiveNumberOrNull(
          formValues.unitPriceBaseQuantity
        );
        if (defaultSalesUnit && !defaultUnit) {
          const message = t(
            "catalog.products.uom.errors.baseRequired",
            "Base unit is required when default sales unit is set."
          );
          throw createCrudFormError(message, { defaultSalesUnit: message });
        }
        const conversionInputs = normalizeProductConversionInputs(
          formValues.unitConversions,
          t(
            "catalog.products.uom.errors.duplicateConversion",
            "Duplicate conversion unit is not allowed."
          )
        );
        if (conversionInputs.length && !defaultUnit) {
          const message = t(
            "catalog.products.uom.errors.baseRequiredForConversions",
            "Base unit is required when conversions are configured."
          );
          throw createCrudFormError(message, { defaultUnit: message });
        }
        const defaultUnitKey = defaultUnit?.toLowerCase() ?? null;
        const defaultSalesUnitKey = defaultSalesUnit?.toLowerCase() ?? null;
        if (defaultUnitKey && defaultSalesUnitKey && defaultSalesUnitKey !== defaultUnitKey) {
          const hasDefaultSalesConversion = conversionInputs.some(
            (entry) => entry.isActive && entry.unitCode.toLowerCase() === defaultSalesUnitKey
          );
          if (!hasDefaultSalesConversion) {
            const message = t(
              "catalog.products.uom.errors.defaultSalesConversionRequired",
              "Active conversion for default sales unit is required when it differs from base unit."
            );
            throw createCrudFormError(message, {
              defaultSalesUnit: message,
              unitConversions: message
            });
          }
        }
        if (unitPriceEnabled) {
          if (!unitPriceReferenceUnit || !UNIT_PRICE_REFERENCE_UNITS.has(
            unitPriceReferenceUnit
          )) {
            const message = t(
              "catalog.products.unitPrice.errors.referenceUnit",
              "Reference unit is required when unit price display is enabled."
            );
            throw createCrudFormError(message, {
              unitPriceReferenceUnit: message
            });
          }
          if (unitPriceBaseQuantity === null) {
            const message = t(
              "catalog.products.unitPrice.errors.baseQuantity",
              "Base quantity is required when unit price display is enabled."
            );
            throw createCrudFormError(message, {
              unitPriceBaseQuantity: message
            });
          }
        }
        const productPayload = {
          title,
          subtitle: formValues.subtitle?.trim() || void 0,
          description,
          handle,
          sku: formValues.sku?.trim() || void 0,
          productType: formValues.productType || "simple",
          taxRateId: formValues.taxRateId ?? null,
          taxRate: productTaxRate ?? null,
          isConfigurable: isConfigurableProductType(
            formValues.productType || "simple"
          ),
          defaultMediaId: defaultMediaId ?? void 0,
          defaultMediaUrl: defaultMediaUrl ?? void 0,
          dimensions,
          weightValue: weight?.value ?? null,
          weightUnit: weight?.unit ?? null,
          defaultUnit: defaultUnit ?? null,
          defaultSalesUnit: defaultSalesUnit ?? defaultUnit ?? null,
          defaultSalesUnitQuantity,
          uomRoundingScale,
          uomRoundingMode,
          unitPriceEnabled,
          unitPriceReferenceUnit: unitPriceEnabled ? unitPriceReferenceUnit : void 0,
          unitPriceBaseQuantity: unitPriceEnabled ? unitPriceBaseQuantity : void 0,
          ...buildComplianceProductPayload(formValues)
        };
        if (optionSchemaDefinition) {
          productPayload.optionSchema = optionSchemaDefinition;
        }
        const categoryIds = Array.isArray(formValues.categoryIds) ? formValues.categoryIds.map((id) => typeof id === "string" ? id.trim() : "").filter((id) => id.length) : [];
        if (categoryIds.length) {
          productPayload.categoryIds = Array.from(new Set(categoryIds));
        }
        const tags = Array.isArray(formValues.tags) ? Array.from(
          new Set(
            formValues.tags.map((tag) => typeof tag === "string" ? tag.trim() : "").filter((tag) => tag.length)
          )
        ) : [];
        if (tags.length) {
          productPayload.tags = tags;
        }
        const channelIds = Array.isArray(formValues.channelIds) ? formValues.channelIds.map((id) => typeof id === "string" ? id.trim() : "").filter((id) => id.length) : [];
        if (channelIds.length) {
          productPayload.offers = channelIds.map((channelId) => ({
            channelId,
            title,
            description,
            defaultMediaId: defaultMediaId ?? void 0,
            defaultMediaUrl: defaultMediaUrl ?? void 0
          }));
        }
        const variantDrafts = (Array.isArray(formValues.variants) && formValues.variants.length ? formValues.variants : [
          createVariantDraft(formValues.taxRateId ?? null, {
            isDefault: true
          })
        ]) ?? [];
        const priceRequests = [];
        for (const variant of variantDrafts) {
          const { resolvedVariantTaxRateId, resolvedVariantTaxRate } = resolveVariantTax(variant);
          for (const priceKind of priceKinds) {
            const value = variant.prices?.[priceKind.id]?.amount?.trim();
            if (!value) continue;
            const numeric = Number(value);
            if (Number.isNaN(numeric) || !Number.isFinite(numeric) || numeric < 0) {
              throw createCrudFormError(
                t(
                  "catalog.products.create.errors.priceNonNegative",
                  "Prices must be zero or greater."
                )
              );
            }
            const currencyCode = typeof priceKind.currencyCode === "string" && priceKind.currencyCode.trim().length ? priceKind.currencyCode.trim().toUpperCase() : "";
            if (!currencyCode) {
              throw createCrudFormError(
                t(
                  "catalog.products.create.errors.currency",
                  "Provide a currency for all price kinds."
                ),
                {}
              );
            }
            priceRequests.push({
              variantDraftId: variant.id,
              priceKindId: priceKind.id,
              currencyCode,
              amount: numeric,
              displayMode: priceKind.displayMode,
              taxRateId: resolvedVariantTaxRateId ?? null,
              taxRateValue: resolvedVariantTaxRate ?? null
            });
          }
        }
        const cleanupState = { productId: null, variantIds: [] };
        try {
          const { result: created } = await createCrud(
            "catalog/products",
            productPayload
          );
          const productId = created?.id;
          if (!productId) {
            throw createCrudFormError(
              t(
                "catalog.products.create.errors.id",
                "Product id missing after create."
              )
            );
          }
          cleanupState.productId = productId;
          for (const conversion of conversionInputs) {
            await createCrud("catalog/product-unit-conversions", {
              productId,
              unitCode: conversion.unitCode,
              toBaseFactor: conversion.toBaseFactor,
              sortOrder: conversion.sortOrder,
              isActive: conversion.isActive
            });
          }
          const variantIdMap = {};
          for (const variant of variantDrafts) {
            const { resolvedVariantTaxRateId, resolvedVariantTaxRate } = resolveVariantTax(variant);
            const variantPayload = {
              productId,
              name: variant.title?.trim() || Object.values(variant.optionValues).join(" / ") || "Variant",
              sku: variant.sku?.trim() || void 0,
              isDefault: Boolean(variant.isDefault),
              isActive: true,
              optionValues: Object.keys(variant.optionValues).length ? variant.optionValues : void 0,
              taxRateId: resolvedVariantTaxRateId ?? null,
              taxRate: resolvedVariantTaxRate ?? null
            };
            const { result: variantResult } = await createCrud("catalog/variants", variantPayload);
            const variantId = variantResult?.variantId ?? variantResult?.id;
            if (!variantId) {
              throw createCrudFormError(
                t(
                  "catalog.products.create.errors.variant",
                  "Failed to create variant."
                )
              );
            }
            variantIdMap[variant.id] = variantId;
            cleanupState.variantIds.push(variantId);
          }
          for (const draft of priceRequests) {
            const variantId = variantIdMap[draft.variantDraftId];
            if (!variantId) continue;
            const pricePayload = {
              productId,
              variantId,
              currencyCode: draft.currencyCode,
              priceKindId: draft.priceKindId
            };
            if (draft.taxRateId) {
              pricePayload.taxRateId = draft.taxRateId;
            } else if (typeof draft.taxRateValue === "number" && Number.isFinite(draft.taxRateValue)) {
              pricePayload.taxRate = draft.taxRateValue;
            }
            if (draft.displayMode === "including-tax") {
              pricePayload.unitPriceGross = draft.amount;
            } else {
              pricePayload.unitPriceNet = draft.amount;
            }
            await createCrud("catalog/prices", pricePayload);
          }
          if (mediaDraftId && attachmentIds.length) {
            const transfer = await apiCall(
              "/api/attachments/transfer",
              {
                method: "POST",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({
                  entityId: E.catalog.catalog_product,
                  attachmentIds,
                  fromRecordId: mediaDraftId,
                  toRecordId: productId
                })
              },
              { fallback: null }
            );
            if (!transfer.ok) {
              logger.error("attachments.transfer.failed", { err: transfer.result?.error });
            }
          }
          if (inboxDraft) {
            try {
              sessionStorage.removeItem("inbox_ops.productDraft");
            } catch {
            }
            try {
              await apiCall(
                `/api/inbox_ops/proposals/${inboxDraft.proposalId}/actions/${inboxDraft.actionId}/complete`,
                {
                  method: "PATCH",
                  body: JSON.stringify({
                    createdEntityId: productId,
                    createdEntityType: "catalog_product"
                  })
                }
              );
            } catch {
              flash(
                t(
                  "inbox_ops.flash.complete_failed",
                  "Product created but failed to update inbox action status."
                ),
                "warning"
              );
            }
          }
          flash(
            t("catalog.products.create.success", "Product created."),
            "success"
          );
          if (inboxDraft) {
            router.push(
              `/backend/inbox-ops/proposals/${encodeURIComponent(inboxDraft.proposalId)}`
            );
          } else {
            router.push(`/backend/catalog/products/${productId}`);
          }
        } catch (err) {
          await cleanupFailedProduct(
            cleanupState.productId,
            cleanupState.variantIds
          );
          throw err;
        }
      }
    }
  ) }) });
}
async function cleanupFailedProduct(productId, variantIds) {
  if (!productId && variantIds.length === 0) return;
  if (variantIds.length) {
    const variantDeletes = variantIds.map(
      (variantId) => apiCall(`/api/catalog/variants?id=${encodeURIComponent(variantId)}`, {
        method: "DELETE"
      }).catch(() => null)
    );
    await Promise.allSettled(variantDeletes);
  }
  if (productId) {
    await apiCall(`/api/catalog/products?id=${encodeURIComponent(productId)}`, {
      method: "DELETE"
    }).catch(() => null);
  }
}
function ProductDimensionsFields({
  values,
  setValue
}) {
  const t = useT();
  const dimensionValues = normalizeProductDimensions(values.dimensions);
  const weightValues = normalizeProductWeight(values.weight);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4 rounded-lg border p-4", children: [
    /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("catalog.products.edit.dimensions", "Dimensions & weight") }),
    /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-2", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: t("catalog.products.edit.dimensions.width", "Width") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            type: "number",
            value: dimensionValues?.width ?? "",
            onChange: (event) => setValue(
              "dimensions",
              updateDimensionValue(
                values.dimensions ?? null,
                "width",
                event.target.value
              )
            ),
            placeholder: "0"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: t("catalog.products.edit.dimensions.height", "Height") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            type: "number",
            value: dimensionValues?.height ?? "",
            onChange: (event) => setValue(
              "dimensions",
              updateDimensionValue(
                values.dimensions ?? null,
                "height",
                event.target.value
              )
            ),
            placeholder: "0"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: t("catalog.products.edit.dimensions.depth", "Depth") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            type: "number",
            value: dimensionValues?.depth ?? "",
            onChange: (event) => setValue(
              "dimensions",
              updateDimensionValue(
                values.dimensions ?? null,
                "depth",
                event.target.value
              )
            ),
            placeholder: "0"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: t("catalog.products.edit.dimensions.unit", "Size unit") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            value: dimensionValues?.unit ?? "",
            onChange: (event) => setValue(
              "dimensions",
              updateDimensionValue(
                values.dimensions ?? null,
                "unit",
                event.target.value
              )
            ),
            placeholder: "cm"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: t("catalog.products.edit.weight.value", "Weight") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            type: "number",
            value: weightValues?.value ?? "",
            onChange: (event) => setValue(
              "weight",
              updateWeightValue(
                values.weight ?? null,
                "value",
                event.target.value
              )
            ),
            placeholder: "0"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: t("catalog.products.edit.weight.unit", "Weight unit") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            value: weightValues?.unit ?? "",
            onChange: (event) => setValue(
              "weight",
              updateWeightValue(
                values.weight ?? null,
                "unit",
                event.target.value
              )
            ),
            placeholder: "kg"
          }
        )
      ] })
    ] })
  ] });
}
function ProductBuilder({
  values,
  setValue,
  errors,
  priceKinds,
  taxRates,
  requiredFieldIds
}) {
  const t = useT();
  const steps = PRODUCT_FORM_STEPS;
  const [currentStep, setCurrentStep] = React.useState(0);
  const defaultTaxRate = React.useMemo(
    () => values.taxRateId ? taxRates.find((rate) => rate.id === values.taxRateId) ?? null : null,
    [taxRates, values.taxRateId]
  );
  React.useEffect(() => {
    if (values.taxRateId) return;
    if (!taxRates.length) return;
    const fallback = taxRates.find((rate) => rate.isDefault);
    if (!fallback) return;
    setValue("taxRateId", fallback.id);
  }, [taxRates, setValue, values.taxRateId]);
  const stepErrors = React.useMemo(() => {
    const map = steps.reduce(
      (acc, step) => {
        acc[step] = [];
        return acc;
      },
      {}
    );
    Object.entries(errors).forEach(([fieldId, message]) => {
      const step = resolveStepForField(fieldId);
      if (!step) return;
      const text = typeof message === "string" && message.trim().length ? message.trim() : null;
      if (text) map[step] = [...map[step], text];
    });
    return map;
  }, [errors, steps]);
  const errorSignature = React.useMemo(
    () => Object.keys(errors).sort((a, b) => a.localeCompare(b)).join("|"),
    [errors]
  );
  const lastErrorSignatureRef = React.useRef(null);
  React.useEffect(() => {
    if (!errorSignature || errorSignature === lastErrorSignatureRef.current)
      return;
    lastErrorSignatureRef.current = errorSignature;
    const currentStepKey2 = steps[currentStep];
    if (currentStepKey2 && stepErrors[currentStepKey2]?.length) return;
    const fallbackIndex = steps.findIndex(
      (step) => (stepErrors[step] ?? []).length > 0
    );
    if (fallbackIndex >= 0 && fallbackIndex !== currentStep) {
      setCurrentStep(fallbackIndex);
    }
  }, [currentStep, errorSignature, setCurrentStep, stepErrors, steps]);
  const defaultTaxRateLabel = defaultTaxRate ? formatTaxRateLabel(defaultTaxRate) : null;
  const inventoryDisabledHint = t(
    "catalog.products.create.variantsBuilder.inventoryDisabled",
    "Inventory tracking controls are not available yet."
  );
  React.useEffect(() => {
    if (currentStep >= steps.length) setCurrentStep(0);
  }, [currentStep, steps.length]);
  const currentStepKey = steps[currentStep] ?? steps[0];
  const mediaItems = React.useMemo(
    () => Array.isArray(values.mediaItems) ? values.mediaItems : [],
    [values.mediaItems]
  );
  const handleMediaItemsChange = React.useCallback(
    (nextItems) => {
      setValue("mediaItems", nextItems);
      const hasCurrent = nextItems.some(
        (item) => item.id === values.defaultMediaId
      );
      if (!hasCurrent) {
        const fallbackId = nextItems[0]?.id ?? null;
        setValue("defaultMediaId", fallbackId);
        if (fallbackId && nextItems[0]) {
          setValue(
            "defaultMediaUrl",
            buildAttachmentImageUrl(fallbackId, {
              slug: slugifyAttachmentFileName(nextItems[0].fileName)
            })
          );
        } else {
          setValue("defaultMediaUrl", "");
        }
      }
    },
    [setValue, values.defaultMediaId]
  );
  const handleDefaultMediaChange = React.useCallback(
    (attachmentId) => {
      setValue("defaultMediaId", attachmentId);
      if (!attachmentId) {
        setValue("defaultMediaUrl", "");
        return;
      }
      const target = mediaItems.find((item) => item.id === attachmentId);
      if (target) {
        setValue(
          "defaultMediaUrl",
          buildAttachmentImageUrl(target.id, {
            slug: slugifyAttachmentFileName(target.fileName)
          })
        );
      }
    },
    [mediaItems, setValue]
  );
  const ensureVariants = React.useCallback(() => {
    const optionDefinitions = Array.isArray(values.options) ? values.options : [];
    if (!values.hasVariants || !optionDefinitions.length) {
      if (!values.variants || !values.variants.length) {
        setValue("variants", [
          createVariantDraft(values.taxRateId ?? null, { isDefault: true })
        ]);
      }
      return;
    }
    const combos = buildVariantCombinations(optionDefinitions);
    const existing = Array.isArray(values.variants) ? values.variants : [];
    const existingByKey = new Map(
      existing.map((variant) => [
        buildOptionValuesKey(variant.optionValues),
        variant
      ])
    );
    let hasDefault = existing.some((variant) => variant.isDefault);
    let changed = existing.length !== combos.length;
    const nextVariants = combos.map((combo, index) => {
      const key = buildOptionValuesKey(combo);
      const existingMatch = existingByKey.get(key);
      if (existingMatch) {
        if (existingMatch.isDefault) hasDefault = true;
        if (!haveSameOptionValues(existingMatch.optionValues, combo)) {
          changed = true;
          return { ...existingMatch, optionValues: combo };
        }
        if (existing[index] !== existingMatch) {
          changed = true;
        }
        return existingMatch;
      }
      changed = true;
      return createVariantDraft(values.taxRateId ?? null, {
        title: Object.values(combo).join(" / "),
        optionValues: combo
      });
    });
    if (!nextVariants.length) return;
    if (!hasDefault) {
      changed = true;
      nextVariants[0] = { ...nextVariants[0], isDefault: true };
    }
    if (changed) {
      setValue("variants", nextVariants);
    }
  }, [
    values.options,
    values.variants,
    values.hasVariants,
    values.taxRateId,
    setValue
  ]);
  React.useEffect(() => {
    ensureVariants();
  }, [ensureVariants]);
  React.useEffect(() => {
    if (!values.taxRateId) return;
    const variants = Array.isArray(values.variants) ? values.variants : [];
    if (!variants.length) return;
    let changed = false;
    const nextVariants = variants.map((variant) => {
      if (variant.taxRateId) return variant;
      changed = true;
      return { ...variant, taxRateId: values.taxRateId };
    });
    if (changed) {
      setValue("variants", nextVariants);
    }
  }, [values.taxRateId, values.variants, setValue]);
  const setVariantField = React.useCallback(
    (variantId, field, value) => {
      const next = (Array.isArray(values.variants) ? values.variants : []).map(
        (variant) => {
          if (variant.id !== variantId) return variant;
          return { ...variant, [field]: value };
        }
      );
      setValue("variants", next);
    },
    [values.variants, setValue]
  );
  const setVariantPrice = React.useCallback(
    (variantId, priceKindId, amount) => {
      if (amount.trim().startsWith("-")) return;
      const next = (Array.isArray(values.variants) ? values.variants : []).map(
        (variant) => {
          if (variant.id !== variantId) return variant;
          const nextPrices = { ...variant.prices ?? {} };
          if (amount === "") {
            delete nextPrices[priceKindId];
          } else {
            nextPrices[priceKindId] = { amount };
          }
          return {
            ...variant,
            prices: nextPrices
          };
        }
      );
      setValue("variants", next);
    },
    [values.variants, setValue]
  );
  const markDefaultVariant = React.useCallback(
    (variantId) => {
      const next = (Array.isArray(values.variants) ? values.variants : []).map(
        (variant) => ({
          ...variant,
          isDefault: variant.id === variantId
        })
      );
      setValue("variants", next);
    },
    [values.variants, setValue]
  );
  const handleOptionTitleChange = React.useCallback(
    (optionId, title) => {
      const next = (Array.isArray(values.options) ? values.options : []).map(
        (option) => {
          if (option.id !== optionId) return option;
          return { ...option, title };
        }
      );
      setValue("options", next);
    },
    [values.options, setValue]
  );
  const setOptionValues = React.useCallback(
    (optionId, labels) => {
      const normalized = labels.map((label) => label.trim()).filter((label) => label.length);
      const unique = Array.from(new Set(normalized));
      const next = (Array.isArray(values.options) ? values.options : []).map(
        (option) => {
          if (option.id !== optionId) return option;
          const existingByLabel = new Map(
            option.values.map((value) => [value.label, value])
          );
          const nextValues = unique.map(
            (label) => existingByLabel.get(label) ?? { id: createLocalId(), label }
          );
          return {
            ...option,
            values: nextValues
          };
        }
      );
      setValue("options", next);
    },
    [values.options, setValue]
  );
  const addOption = React.useCallback(() => {
    const next = [
      ...Array.isArray(values.options) ? values.options : [],
      { id: createLocalId(), title: "", values: [] }
    ];
    setValue("options", next);
  }, [values.options, setValue]);
  const removeOption = React.useCallback(
    (optionId) => {
      const next = (Array.isArray(values.options) ? values.options : []).filter(
        (option) => option.id !== optionId
      );
      setValue("options", next);
    },
    [values.options, setValue]
  );
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsx("nav", { className: "flex gap-6 border-b pb-2 text-sm font-medium", children: steps.map((step, index) => /* @__PURE__ */ jsxs(
      Button,
      {
        type: "button",
        variant: "ghost",
        size: "sm",
        className: cn(
          "relative h-auto rounded-none px-0 py-1 pb-2 font-medium",
          currentStep === index ? "text-foreground" : "text-muted-foreground hover:text-foreground"
        ),
        onClick: () => setCurrentStep(index),
        children: [
          step === "general" && t("catalog.products.create.steps.general", "General data"),
          step === "organize" && t("catalog.products.create.steps.organize", "Organize"),
          step === "uom" && t("catalog.products.uom.title", "Units of measure"),
          step === "compliance" && t("catalog.products.compliance.title", "Compliance & commerce"),
          step === "variants" && t("catalog.products.create.steps.variants", "Variants"),
          (stepErrors[step]?.length ?? 0) > 0 ? /* @__PURE__ */ jsx(
            "span",
            {
              className: "absolute -right-2 top-0 h-2 w-2 rounded-full bg-destructive",
              "aria-hidden": "true"
            }
          ) : null,
          currentStep === index ? /* @__PURE__ */ jsx("span", { className: "absolute inset-x-0 -bottom-px h-0.5 bg-foreground rounded-full" }) : null
        ]
      },
      step
    )) }),
    currentStepKey === "general" ? /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", "data-crud-field-id": "title", children: [
        /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-1", children: [
          t("catalog.products.form.title", "Title"),
          /* @__PURE__ */ jsx("span", { className: "text-status-error-text", children: "*" })
        ] }),
        /* @__PURE__ */ jsx(
          Input,
          {
            value: values.title,
            onChange: (event) => setValue("title", event.target.value),
            placeholder: t(
              "catalog.products.create.placeholders.title",
              "e.g., Summer sneaker"
            )
          }
        ),
        errors.title ? /* @__PURE__ */ jsx("p", { className: "text-xs text-status-error-text", children: errors.title }) : null
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", "data-crud-field-id": "description", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-1", children: [
            t("catalog.products.form.description", "Description"),
            requiredFieldIds?.has("description") ? /* @__PURE__ */ jsx("span", { className: "text-status-error-text", children: "*" }) : null
          ] }),
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              onClick: () => setValue("useMarkdown", !values.useMarkdown),
              className: "gap-2 text-xs",
              children: [
                values.useMarkdown ? /* @__PURE__ */ jsx(AlignLeft, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(FileText, { className: "h-4 w-4" }),
                values.useMarkdown ? t(
                  "catalog.products.create.actions.usePlain",
                  "Use plain text"
                ) : t(
                  "catalog.products.create.actions.useMarkdown",
                  "Use markdown"
                )
              ]
            }
          )
        ] }),
        values.useMarkdown ? /* @__PURE__ */ jsx(
          MarkdownField,
          {
            value: values.description,
            onChange: (val) => setValue("description", val ?? "")
          }
        ) : /* @__PURE__ */ jsx(
          "textarea",
          {
            className: "min-h-[180px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
            value: values.description,
            onChange: (event) => setValue("description", event.target.value),
            placeholder: t(
              "catalog.products.create.placeholders.description",
              "Describe the product..."
            )
          }
        ),
        errors.description ? /* @__PURE__ */ jsx("p", { className: "text-xs text-status-error-text", children: errors.description }) : null
      ] }),
      /* @__PURE__ */ jsx(
        ProductMediaManager,
        {
          entityId: E.catalog.catalog_product,
          draftRecordId: values.mediaDraftId,
          items: mediaItems,
          defaultMediaId: values.defaultMediaId ?? null,
          onItemsChange: handleMediaItemsChange,
          onDefaultChange: handleDefaultMediaChange
        }
      ),
      /* @__PURE__ */ jsx(
        ProductDimensionsFields,
        {
          values,
          setValue
        }
      )
    ] }) : null,
    currentStepKey === "organize" ? /* @__PURE__ */ jsx(
      ProductCategorizeSection,
      {
        values,
        setValue,
        errors
      }
    ) : null,
    currentStepKey === "uom" ? /* @__PURE__ */ jsx(
      ProductUomSection,
      {
        values,
        setValue,
        errors,
        embedded: true
      }
    ) : null,
    currentStepKey === "compliance" ? /* @__PURE__ */ jsx(
      ProductComplianceSection,
      {
        values,
        setValue,
        errors,
        embedded: true
      }
    ) : null,
    currentStepKey === "variants" ? /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
      /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm font-medium", children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "checkbox",
            className: "h-4 w-4 rounded border",
            checked: values.hasVariants,
            onChange: (event) => {
              const checked = event.target.checked;
              setValue("hasVariants", checked);
              if (checked && !isConfigurableProductType(
                values.productType || "simple"
              )) {
                setValue("productType", "configurable");
              } else if (!checked && isConfigurableProductType(
                values.productType || "simple"
              )) {
                setValue("productType", "simple");
              }
            }
          }
        ),
        t(
          "catalog.products.create.variantsBuilder.toggle",
          "Yes, this is a product with variants"
        )
      ] }),
      values.hasVariants ? /* @__PURE__ */ jsxs("div", { className: "space-y-4 rounded-lg border p-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
          /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t(
            "catalog.products.create.optionsBuilder.title",
            "Product options"
          ) }),
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              onClick: addOption,
              children: [
                /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }),
                t(
                  "catalog.products.create.optionsBuilder.add",
                  "Add option"
                )
              ]
            }
          )
        ] }),
        (Array.isArray(values.options) ? values.options : []).map(
          (option) => /* @__PURE__ */ jsxs("div", { className: "rounded-md bg-muted/50 p-4", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(
                Input,
                {
                  value: option.title,
                  onChange: (event) => handleOptionTitleChange(option.id, event.target.value),
                  placeholder: t(
                    "catalog.products.create.optionsBuilder.placeholder",
                    "e.g., Color"
                  ),
                  className: "flex-1"
                }
              ),
              /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  size: "icon",
                  type: "button",
                  onClick: () => removeOption(option.id),
                  children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "mt-3 space-y-2", children: [
              /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: t(
                "catalog.products.create.optionsBuilder.values",
                "Values"
              ) }),
              /* @__PURE__ */ jsx(
                TagsInput,
                {
                  value: option.values.map((value) => value.label),
                  onChange: (labels) => setOptionValues(option.id, labels),
                  placeholder: t(
                    "catalog.products.create.optionsBuilder.valuePlaceholder",
                    "Type a value and press Enter"
                  )
                }
              )
            ] })
          ] }, option.id)
        ),
        !values.options?.length ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(
          "catalog.products.create.optionsBuilder.empty",
          "No options yet. Add your first option to generate variants."
        ) }) : null
      ] }) : null,
      /* @__PURE__ */ jsxs("div", { className: "rounded-lg border", children: [
        /* @__PURE__ */ jsx(
          RadioGroup,
          {
            className: "contents",
            name: "defaultVariant",
            value: (Array.isArray(values.variants) ? values.variants : []).find((v) => v.isDefault)?.id ?? "",
            onValueChange: (next) => markDefaultVariant(next),
            children: /* @__PURE__ */ jsx("div", { className: "w-full overflow-x-auto", children: /* @__PURE__ */ jsxs("table", { className: "w-full min-w-[900px] table-fixed border-collapse text-sm", children: [
              /* @__PURE__ */ jsx("thead", { className: "bg-muted/50", children: /* @__PURE__ */ jsxs("tr", { children: [
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: t(
                  "catalog.products.create.variantsBuilder.defaultOption",
                  "Default option"
                ) }),
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: t("catalog.products.form.variants", "Variant title") }),
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: t("catalog.products.create.variantsBuilder.sku", "SKU") }),
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: t(
                  "catalog.products.create.variantsBuilder.vatColumn",
                  "Tax class"
                ) }),
                priceKinds.map((kind) => /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-left", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
                    /* @__PURE__ */ jsx("span", { children: t(
                      "catalog.products.create.variantsBuilder.priceColumn",
                      "Price {{title}}"
                    ).replace("{{title}}", kind.title) }),
                    /* @__PURE__ */ jsx(
                      "small",
                      {
                        title: kind.displayMode === "including-tax" ? t(
                          "catalog.priceKinds.form.displayMode.include",
                          "Including tax"
                        ) : t(
                          "catalog.priceKinds.form.displayMode.exclude",
                          "Excluding tax"
                        ),
                        className: "text-xs text-muted-foreground",
                        children: kind.displayMode === "including-tax" ? "\u24C9" : "\u24C3"
                      }
                    )
                  ] }),
                  /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: kind.currencyCode?.toUpperCase() ?? t(
                    "catalog.products.create.variantsBuilder.currencyMissing",
                    "Currency missing"
                  ) })
                ] }) }, kind.id)),
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-center", children: t(
                  "catalog.products.create.variantsBuilder.manageInventory",
                  "Managed inventory"
                ) }),
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-center", children: t(
                  "catalog.products.create.variantsBuilder.allowBackorder",
                  "Allow backorder"
                ) }),
                /* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-center", children: t(
                  "catalog.products.create.variantsBuilder.inventoryKit",
                  "Has inventory kit"
                ) })
              ] }) }),
              /* @__PURE__ */ jsx("tbody", { children: (Array.isArray(values.variants) && values.variants.length ? values.variants : [
                createVariantDraft(values.taxRateId ?? null, {
                  isDefault: true
                })
              ]).map((variant) => /* @__PURE__ */ jsxs("tr", { className: "border-t", children: [
                /* @__PURE__ */ jsxs("td", { className: "px-3 py-2", children: [
                  /* @__PURE__ */ jsxs("label", { className: "inline-flex items-center gap-1 text-xs", children: [
                    /* @__PURE__ */ jsx(Radio, { value: variant.id }),
                    variant.isDefault ? t(
                      "catalog.products.create.variantsBuilder.defaultLabel",
                      "Default option value"
                    ) : t(
                      "catalog.products.create.variantsBuilder.makeDefault",
                      "Set as default"
                    )
                  ] }),
                  values.hasVariants && variant.optionValues ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: Object.values(variant.optionValues).join(" / ") }) : null
                ] }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2", children: /* @__PURE__ */ jsx(
                  Input,
                  {
                    value: variant.title,
                    onChange: (event) => setVariantField(
                      variant.id,
                      "title",
                      event.target.value
                    ),
                    placeholder: t(
                      "catalog.products.create.variantsBuilder.titlePlaceholder",
                      "Variant title"
                    )
                  }
                ) }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2", children: /* @__PURE__ */ jsx(
                  Input,
                  {
                    value: variant.sku,
                    onChange: (event) => setVariantField(
                      variant.id,
                      "sku",
                      event.target.value
                    ),
                    placeholder: t(
                      "catalog.products.create.variantsBuilder.skuPlaceholder",
                      "e.g., SKU-001"
                    )
                  }
                ) }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2", children: /* @__PURE__ */ jsxs(
                  Select,
                  {
                    value: variant.taxRateId || void 0,
                    onValueChange: (value) => setVariantField(variant.id, "taxRateId", value || null),
                    disabled: !taxRates.length,
                    children: [
                      /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(
                        SelectValue,
                        {
                          placeholder: defaultTaxRateLabel ? t(
                            "catalog.products.create.variantsBuilder.vatOptionDefault",
                            "Use product tax class ({{label}})"
                          ).replace("{{label}}", defaultTaxRateLabel) : t(
                            "catalog.products.create.variantsBuilder.vatOptionNone",
                            "No tax class"
                          )
                        }
                      ) }),
                      /* @__PURE__ */ jsx(SelectContent, { children: taxRates.map((rate) => /* @__PURE__ */ jsx(SelectItem, { value: rate.id, children: formatTaxRateLabel(rate) }, rate.id)) })
                    ]
                  }
                ) }),
                priceKinds.map((kind) => /* @__PURE__ */ jsx("td", { className: "px-3 py-2", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: kind.currencyCode ?? "\u2014" }),
                  /* @__PURE__ */ jsx(
                    Input,
                    {
                      type: "number",
                      value: variant.prices?.[kind.id]?.amount ?? "",
                      onChange: (event) => setVariantPrice(
                        variant.id,
                        kind.id,
                        event.target.value
                      ),
                      placeholder: "0.00",
                      min: 0
                    }
                  )
                ] }) }, kind.id)),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-center", children: /* @__PURE__ */ jsx(
                  "input",
                  {
                    type: "checkbox",
                    className: "h-4 w-4 rounded border disabled:cursor-not-allowed disabled:opacity-50",
                    checked: variant.manageInventory,
                    onChange: (event) => setVariantField(
                      variant.id,
                      "manageInventory",
                      event.target.checked
                    ),
                    disabled: true,
                    title: inventoryDisabledHint
                  }
                ) }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-center", children: /* @__PURE__ */ jsx(
                  "input",
                  {
                    type: "checkbox",
                    className: "h-4 w-4 rounded border disabled:cursor-not-allowed disabled:opacity-50",
                    checked: variant.allowBackorder,
                    onChange: (event) => setVariantField(
                      variant.id,
                      "allowBackorder",
                      event.target.checked
                    ),
                    disabled: true,
                    title: inventoryDisabledHint
                  }
                ) }),
                /* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-center", children: /* @__PURE__ */ jsx(
                  "input",
                  {
                    type: "checkbox",
                    className: "h-4 w-4 rounded border disabled:cursor-not-allowed disabled:opacity-50",
                    checked: variant.hasInventoryKit,
                    onChange: (event) => setVariantField(
                      variant.id,
                      "hasInventoryKit",
                      event.target.checked
                    ),
                    disabled: true,
                    title: inventoryDisabledHint
                  }
                ) })
              ] }, variant.id)) })
            ] }) })
          }
        ),
        !priceKinds.length ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 border-t px-4 py-3 text-sm text-muted-foreground", children: [
          /* @__PURE__ */ jsx(AlertCircle, { className: "h-4 w-4" }),
          t(
            "catalog.products.create.variantsBuilder.noPriceKinds",
            "Configure price kinds in Catalog settings to add price columns."
          )
        ] }) : null
      ] })
    ] }) : null,
    /* @__PURE__ */ jsxs("div", { className: "flex justify-between border-t pt-4", children: [
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "outline",
          size: "sm",
          onClick: () => setCurrentStep(Math.max(0, currentStep - 1)),
          disabled: currentStep === 0,
          className: "gap-2",
          children: [
            /* @__PURE__ */ jsx(ChevronLeft, { className: "h-4 w-4" }),
            t("catalog.products.create.steps.previous", "Previous")
          ]
        }
      ),
      currentStepKey !== "variants" ? /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "outline",
          size: "sm",
          onClick: () => setCurrentStep(Math.min(steps.length - 1, currentStep + 1)),
          className: "gap-2",
          children: [
            t("catalog.products.create.steps.continue", "Continue"),
            /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" })
          ]
        }
      ) : /* @__PURE__ */ jsx("span", {})
    ] })
  ] });
}
function ProductMetaSection({
  values,
  setValue,
  errors,
  taxRates
}) {
  const t = useT();
  const handleValue = typeof values.handle === "string" ? values.handle : "";
  const titleSource = typeof values.title === "string" ? values.title : "";
  const autoHandleEnabledRef = React.useRef(handleValue.trim().length === 0);
  React.useEffect(() => {
    if (!autoHandleEnabledRef.current) return;
    const normalizedTitle = titleSource.trim();
    if (!normalizedTitle) {
      if (handleValue) {
        setValue("handle", "");
      }
      return;
    }
    const nextHandle = slugify(normalizedTitle);
    if (nextHandle !== handleValue) {
      setValue("handle", nextHandle);
    }
  }, [titleSource, handleValue, setValue]);
  const handleHandleInputChange = React.useCallback(
    (event) => {
      const nextValue = event.target.value;
      autoHandleEnabledRef.current = nextValue.trim().length === 0;
      setValue("handle", nextValue);
    },
    [setValue]
  );
  const handleGenerateHandle = React.useCallback(() => {
    const slug = slugify(titleSource);
    autoHandleEnabledRef.current = true;
    setValue("handle", slug);
  }, [titleSource, setValue]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { children: t("catalog.products.form.subtitle", "Subtitle") }),
      /* @__PURE__ */ jsx(
        Input,
        {
          value: typeof values.subtitle === "string" ? values.subtitle : "",
          onChange: (event) => setValue("subtitle", event.target.value),
          placeholder: t(
            "catalog.products.create.placeholders.subtitle",
            "Optional subtitle"
          )
        }
      ),
      errors.subtitle ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: errors.subtitle }) : null
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { children: t("catalog.products.form.handle", "Handle") }),
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx(
          Input,
          {
            value: handleValue,
            onChange: handleHandleInputChange,
            placeholder: t(
              "catalog.products.create.placeholders.handle",
              "e.g., summer-sneaker"
            ),
            className: "font-mono lowercase"
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "outline",
            onClick: handleGenerateHandle,
            children: t("catalog.products.create.actions.generateHandle", "Generate")
          }
        )
      ] }),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
        "catalog.products.create.handleHelp",
        "Handle is used for URLs and must be unique."
      ) }),
      errors.handle ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: errors.handle }) : null
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { children: t("catalog.products.form.sku", "SKU") }),
      /* @__PURE__ */ jsx(
        Input,
        {
          value: values.sku,
          onChange: (event) => setValue("sku", event.target.value),
          placeholder: t(
            "catalog.products.create.placeholders.sku",
            "e.g., PROD-001"
          ),
          className: "font-mono"
        }
      ),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
        "catalog.products.create.skuHelp",
        "Unique product identifier. Letters, numbers, hyphens, underscores, periods."
      ) }),
      errors.sku ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: errors.sku }) : null
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { children: t("catalog.products.form.productType", "Product type") }),
      /* @__PURE__ */ jsxs(
        Select,
        {
          value: values.productType || "simple",
          onValueChange: (value) => {
            const nextType = value;
            setValue("productType", nextType);
            const nextIsConfigurable = isConfigurableProductType(nextType);
            if (nextIsConfigurable && !values.hasVariants) {
              setValue("hasVariants", true);
            } else if (!nextIsConfigurable && values.hasVariants) {
              setValue("hasVariants", false);
            }
          },
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, {}) }),
            /* @__PURE__ */ jsx(SelectContent, { children: CATALOG_PRODUCT_TYPES.map((type) => {
              const isDisabled = type === "bundle" || type === "grouped";
              return /* @__PURE__ */ jsxs(SelectItem, { value: type, disabled: isDisabled, children: [
                t(`catalog.products.types.${type}`, type),
                isDisabled ? ` (${t("common.comingSoon", "Coming soon")})` : ""
              ] }, type);
            }) })
          ]
        }
      ),
      errors.productType ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: errors.productType }) : null
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
        /* @__PURE__ */ jsx(Label, { children: t("catalog.products.create.taxRates.label", "Tax class") }),
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "icon",
            onClick: () => {
              if (typeof window !== "undefined") {
                window.open(
                  "/backend/config/sales?section=tax-rates",
                  "_blank",
                  "noopener,noreferrer"
                );
              }
            },
            title: t(
              "catalog.products.create.taxRates.manage",
              "Manage tax classes"
            ),
            className: "text-muted-foreground hover:text-foreground",
            children: [
              /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { className: "sr-only", children: t(
                "catalog.products.create.taxRates.manage",
                "Manage tax classes"
              ) })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsxs(
        Select,
        {
          value: values.taxRateId || void 0,
          onValueChange: (value) => setValue("taxRateId", value || null),
          disabled: !taxRates.length,
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(
              SelectValue,
              {
                placeholder: taxRates.length ? t("catalog.products.create.taxRates.noneSelected", "No tax class selected") : t("catalog.products.create.taxRates.emptyOption", "No tax classes available")
              }
            ) }),
            /* @__PURE__ */ jsx(SelectContent, { children: taxRates.map((rate) => /* @__PURE__ */ jsx(SelectItem, { value: rate.id, children: formatTaxRateLabel(rate) }, rate.id)) })
          ]
        }
      ),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: taxRates.length ? t(
        "catalog.products.create.taxRates.help",
        "Applied to new prices unless overridden per variant."
      ) : t(
        "catalog.products.create.taxRates.empty",
        "Define tax classes under Sales \u2192 Configuration."
      ) }),
      errors.taxRateId ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: errors.taxRateId }) : null
    ] })
  ] });
}
export {
  CreateCatalogProductPage as default
};
//# sourceMappingURL=page.js.map
