"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { flushSync } from "react-dom";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Label } from "@open-mercato/ui/primitives/label";
import { Input } from "@open-mercato/ui/primitives/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Switch } from "@open-mercato/ui/primitives/switch";
import { ProductMediaManager } from "./ProductMediaManager.js";
import { MetadataEditor } from "./MetadataEditor.js";
import { formatTaxRateLabel } from "./productForm.js";
import { CATALOG_GTIN_TYPES } from "../../data/types.js";
import { E } from "../../../../generated/entities.ids.generated.js";
function VariantBuilder({
  values,
  setValue,
  errors,
  optionDefinitions,
  priceKinds,
  taxRates
}) {
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsx(VariantBasicsSection, { values, setValue, errors }),
    /* @__PURE__ */ jsx(VariantOptionValuesSection, { values, setValue, optionDefinitions }),
    /* @__PURE__ */ jsx(VariantDimensionsSection, { values, setValue }),
    /* @__PURE__ */ jsx(VariantMetadataSection, { values, setValue }),
    /* @__PURE__ */ jsx(VariantPricesSection, { values, setValue, priceKinds, taxRates }),
    /* @__PURE__ */ jsx(VariantMediaSection, { values, setValue })
  ] });
}
function VariantBasicsSection({ values, setValue, errors }) {
  const t = useT();
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsxs(Label, { className: "flex items-center gap-1", children: [
        t("catalog.variants.form.nameLabel", "Name"),
        /* @__PURE__ */ jsx("span", { className: "text-red-600", children: "*" })
      ] }),
      /* @__PURE__ */ jsx(
        Input,
        {
          value: values.name,
          onChange: (event) => setValue("name", event.target.value),
          placeholder: t("catalog.variants.form.namePlaceholder", "e.g., Blue / Small")
        }
      ),
      errors.name ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: errors.name }) : null
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-2", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { children: t("catalog.variants.form.skuLabel", "SKU") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            value: values.sku,
            onChange: (event) => setValue("sku", event.target.value),
            placeholder: t("catalog.variants.form.skuPlaceholder", "Unique identifier")
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { children: t("catalog.variants.form.barcodeLabel", "Barcode") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            value: values.barcode,
            onChange: (event) => setValue("barcode", event.target.value),
            placeholder: t("catalog.variants.form.barcodePlaceholder", "EAN, UPC, etc.")
          }
        ),
        errors.barcode ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.barcode }) : null
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-2", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "catalog-variant-gtin-type", children: t("catalog.variants.form.gtinTypeLabel", "Identifier type (GTIN)") }),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: values.gtinType ?? "none",
            onValueChange: (value) => setValue("gtinType", value === "none" ? null : value),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { id: "catalog-variant-gtin-type", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsx(SelectItem, { value: "none", children: t("catalog.variants.form.gtinTypeNone", "Untyped") }),
                CATALOG_GTIN_TYPES.map((type) => /* @__PURE__ */ jsx(SelectItem, { value: type, children: t(`catalog.variants.form.gtinTypes.${type}`, type.toUpperCase()) }, type))
              ] })
            ]
          }
        ),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t(
          "catalog.variants.form.gtinTypeHint",
          "Typed barcodes are validated and kept unique per organization."
        ) }),
        errors.gtinType ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.gtinType }) : null
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "catalog-variant-hs-code", children: t("catalog.variants.form.hsCodeLabel", "HS code (customs tariff)") }),
        /* @__PURE__ */ jsx(
          Input,
          {
            id: "catalog-variant-hs-code",
            value: values.hsCode,
            onChange: (event) => setValue("hsCode", event.target.value)
          }
        ),
        errors.hsCode ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: errors.hsCode }) : null
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-2", children: [
      /* @__PURE__ */ jsxs("label", { className: "flex items-center justify-between gap-2 rounded border px-3 py-2", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t("catalog.variants.form.isDefaultLabel", "Default variant") }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("catalog.variants.form.isDefaultHint", "Used in storefronts") })
        ] }),
        /* @__PURE__ */ jsx(Switch, { checked: values.isDefault, onCheckedChange: (next) => setValue("isDefault", next) })
      ] }),
      /* @__PURE__ */ jsxs("label", { className: "flex items-center justify-between gap-2 rounded border px-3 py-2", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t("catalog.variants.form.isActiveLabel", "Active") }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("catalog.variants.form.isActiveHint", "Inactive variants stay hidden") })
        ] }),
        /* @__PURE__ */ jsx(Switch, { checked: values.isActive !== false, onCheckedChange: (next) => setValue("isActive", next) })
      ] })
    ] })
  ] });
}
function VariantOptionValuesSection({
  values,
  setValue,
  optionDefinitions,
  showHeading = true
}) {
  const t = useT();
  const handleOptionChange = React.useCallback(
    (code, next) => {
      setValue("optionValues", { ...values.optionValues ?? {}, [code]: next });
    },
    [setValue, values.optionValues]
  );
  if (!optionDefinitions.length) return null;
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    showHeading ? /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("catalog.variants.form.options", "Option values") }) : null,
    /* @__PURE__ */ jsx("div", { className: "grid gap-4 md:grid-cols-2", children: optionDefinitions.map((option) => /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: option.label }),
      /* @__PURE__ */ jsxs(
        Select,
        {
          value: values.optionValues?.[option.code] || void 0,
          onValueChange: (value) => handleOptionChange(option.code, value ?? ""),
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("catalog.variants.form.optionPlaceholder", "Select value") }) }),
            /* @__PURE__ */ jsx(SelectContent, { children: option.values.map((value) => /* @__PURE__ */ jsx(SelectItem, { value: value.label, children: value.label }, value.id)) })
          ]
        }
      )
    ] }, option.code)) })
  ] });
}
function VariantDimensionsSection({ values, setValue, showHeading = true }) {
  const t = useT();
  const metadata = normalizeMetadata(values.metadata);
  const dimensionValues = normalizeDimensions(metadata);
  const weightValues = normalizeWeight(metadata);
  const dimensionUnitPlaceholder = t("catalog.variants.form.dimensionUnitPlaceholder", "cm");
  const weightUnitPlaceholder = t("catalog.variants.form.weightUnitPlaceholder", "kg");
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    showHeading ? /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("catalog.variants.form.dimensions", "Dimensions & weight") }) : null,
    /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-2", children: [
      /* @__PURE__ */ jsx(
        DimensionInput,
        {
          label: t("catalog.variants.form.width", "Width"),
          value: dimensionValues.width ?? "",
          onChange: (value) => setValue("metadata", applyDimension(metadata, "width", value))
        }
      ),
      /* @__PURE__ */ jsx(
        DimensionInput,
        {
          label: t("catalog.variants.form.height", "Height"),
          value: dimensionValues.height ?? "",
          onChange: (value) => setValue("metadata", applyDimension(metadata, "height", value))
        }
      ),
      /* @__PURE__ */ jsx(
        DimensionInput,
        {
          label: t("catalog.variants.form.depth", "Depth"),
          value: dimensionValues.depth ?? "",
          onChange: (value) => setValue("metadata", applyDimension(metadata, "depth", value))
        }
      ),
      /* @__PURE__ */ jsx(
        DimensionInput,
        {
          label: t("catalog.variants.form.dimensionUnit", "Size unit"),
          value: dimensionValues.unit ?? "",
          placeholder: dimensionUnitPlaceholder,
          onChange: (value) => setValue("metadata", applyDimension(metadata, "unit", value))
        }
      ),
      /* @__PURE__ */ jsx(
        DimensionInput,
        {
          label: t("catalog.variants.form.weight", "Weight"),
          value: weightValues.value ?? "",
          onChange: (value) => setValue("metadata", applyWeight(metadata, "value", value))
        }
      ),
      /* @__PURE__ */ jsx(
        DimensionInput,
        {
          label: t("catalog.variants.form.weightUnit", "Weight unit"),
          value: weightValues.unit ?? "",
          placeholder: weightUnitPlaceholder,
          onChange: (value) => setValue("metadata", applyWeight(metadata, "unit", value))
        }
      )
    ] })
  ] });
}
function VariantMetadataSection({
  values,
  setValue,
  showIntro = true,
  embedded = false
}) {
  const metadata = normalizeMetadata(values.metadata);
  const systemMetadata = React.useMemo(() => extractSystemMetadata(metadata), [metadata]);
  const customMetadata = React.useMemo(() => stripSystemMetadata(metadata), [metadata]);
  const handleMetadataChange = React.useCallback(
    (next) => {
      const merged = {};
      Object.entries(systemMetadata).forEach(([key, value]) => {
        merged[key] = value;
      });
      Object.entries(next).forEach(([key, value]) => {
        merged[key] = value;
      });
      setValue("metadata", merged);
    },
    [setValue, systemMetadata]
  );
  return /* @__PURE__ */ jsx(
    MetadataEditor,
    {
      value: customMetadata,
      onChange: handleMetadataChange,
      title: showIntro ? void 0 : "",
      description: showIntro ? void 0 : "",
      embedded
    }
  );
}
function VariantPricesSection({
  values,
  setValue,
  priceKinds,
  taxRates,
  showHeader = true,
  embedded = false
}) {
  const t = useT();
  const pricesRef = React.useRef(values.prices);
  React.useEffect(() => {
    pricesRef.current = values.prices;
  }, [values.prices]);
  const updatePrice = React.useCallback(
    (priceKindId, patch) => {
      const currentPrices = pricesRef.current ?? {};
      const prev = currentPrices[priceKindId] ?? { priceKindId, amount: "", displayMode: "excluding-tax" };
      const nextPrices = { ...currentPrices, [priceKindId]: { ...prev, ...patch, priceKindId } };
      pricesRef.current = nextPrices;
      flushSync(() => setValue("prices", nextPrices));
    },
    [setValue]
  );
  const containerClass = embedded ? "space-y-4" : "space-y-4 rounded-lg border p-4";
  const selectedTaxRate = values.taxRateId ? taxRates.find((rate) => rate.id === values.taxRateId) ?? null : null;
  const fallbackSelectedTaxRate = values.taxRateId && !selectedTaxRate ? {
    id: values.taxRateId,
    name: values.taxRateId,
    code: null,
    rate: null,
    isDefault: false
  } : null;
  const displayedSelectedTaxRate = selectedTaxRate ?? fallbackSelectedTaxRate;
  const displayedTaxRates = fallbackSelectedTaxRate ? [fallbackSelectedTaxRate, ...taxRates] : taxRates;
  const taxRateOptionsKey = displayedTaxRates.map((rate) => `${rate.id}:${formatTaxRateLabel(rate)}`).join("\0");
  const taxRateSelectKey = `variant-tax-rate:${values.taxRateId ?? ""}:${taxRateOptionsKey}`;
  return /* @__PURE__ */ jsxs("div", { className: containerClass, children: [
    showHeader ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("catalog.variants.form.pricesLabel", "Prices") }),
        /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("catalog.variants.form.pricesHint", "Populate list prices per price kind.") })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2", children: /* @__PURE__ */ jsxs(
        Select,
        {
          value: values.taxRateId || void 0,
          onValueChange: (value) => {
            if (value) setValue("taxRateId", value);
          },
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("catalog.variants.form.pricesTaxNone", "No tax override"), children: displayedSelectedTaxRate ? formatTaxRateLabel(displayedSelectedTaxRate) : void 0 }) }),
            /* @__PURE__ */ jsx(SelectContent, { children: displayedTaxRates.map((rate) => /* @__PURE__ */ jsx(SelectItem, { value: rate.id, children: formatTaxRateLabel(rate) }, rate.id)) })
          ]
        },
        taxRateSelectKey
      ) })
    ] }) : /* @__PURE__ */ jsx("div", { className: "flex justify-end", children: /* @__PURE__ */ jsxs(
      Select,
      {
        value: values.taxRateId || void 0,
        onValueChange: (value) => {
          if (value) setValue("taxRateId", value);
        },
        children: [
          /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("catalog.variants.form.pricesTaxNone", "No tax override"), children: displayedSelectedTaxRate ? formatTaxRateLabel(displayedSelectedTaxRate) : void 0 }) }),
          /* @__PURE__ */ jsx(SelectContent, { children: displayedTaxRates.map((rate) => /* @__PURE__ */ jsx(SelectItem, { value: rate.id, children: formatTaxRateLabel(rate) }, rate.id)) })
        ]
      },
      taxRateSelectKey
    ) }),
    /* @__PURE__ */ jsx("div", { className: "space-y-3", children: priceKinds.length ? priceKinds.map((kind) => {
      const draft = values.prices?.[kind.id];
      return /* @__PURE__ */ jsxs("div", { className: "rounded bg-muted/50 p-3", children: [
        /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between", children: /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("p", { className: "text-sm font-semibold", children: kind.title }),
          /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: kind.currencyCode ? `${kind.currencyCode.toUpperCase()} \u2022 ${kind.displayMode === "including-tax" ? t("catalog.priceKinds.form.displayMode.include", "Including tax") : t("catalog.priceKinds.form.displayMode.exclude", "Excluding tax")}` : t("catalog.variants.form.priceMissingCurrency", "No currency configured") })
        ] }) }),
        /* @__PURE__ */ jsx(
          Input,
          {
            className: "mt-3",
            value: draft?.amount ?? "",
            onInput: (event) => updatePrice(kind.id, { amount: event.currentTarget.value }),
            onChange: (event) => updatePrice(kind.id, { amount: event.target.value }),
            placeholder: "0.00"
          }
        )
      ] }, kind.id);
    }) : /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("catalog.variants.form.pricesEmpty", "No price kinds configured yet.") }) })
  ] });
}
function VariantMediaSection({ values, setValue, showLabel = true }) {
  const t = useT();
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    showLabel ? /* @__PURE__ */ jsx(Label, { children: t("catalog.variants.form.media", "Media") }) : null,
    /* @__PURE__ */ jsx(
      ProductMediaManager,
      {
        entityId: E.catalog.catalog_product_variant,
        draftRecordId: values.mediaDraftId,
        items: Array.isArray(values.mediaItems) ? values.mediaItems : [],
        defaultMediaId: values.defaultMediaId,
        onItemsChange: (next) => setValue("mediaItems", next),
        onDefaultChange: (next) => setValue("defaultMediaId", next)
      }
    )
  ] });
}
function DimensionInput({
  label,
  value,
  onChange,
  placeholder = "0"
}) {
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
    /* @__PURE__ */ jsx(Label, { className: "text-xs uppercase text-muted-foreground", children: label }),
    /* @__PURE__ */ jsx(Input, { value: value ?? "", onChange: (event) => onChange(event.target.value), placeholder })
  ] });
}
function normalizeMetadata(input) {
  return typeof input === "object" && input ? { ...input } : {};
}
function normalizeDimensions(metadata) {
  const raw = metadata.dimensions;
  if (!raw || typeof raw !== "object") return {};
  return {
    width: typeof raw.width === "number" ? raw.width : void 0,
    height: typeof raw.height === "number" ? raw.height : void 0,
    depth: typeof raw.depth === "number" ? raw.depth : void 0,
    unit: typeof raw.unit === "string" ? raw.unit : void 0
  };
}
function normalizeWeight(metadata) {
  const raw = metadata.weight;
  if (!raw || typeof raw !== "object") return {};
  return {
    value: typeof raw.value === "number" ? raw.value : void 0,
    unit: typeof raw.unit === "string" ? raw.unit : void 0
  };
}
function applyDimension(metadata, field, raw) {
  const dims = normalizeDimensions(metadata);
  if (field === "unit") {
    dims.unit = raw;
  } else {
    const numeric = Number(raw);
    dims[field] = Number.isNaN(numeric) ? void 0 : numeric;
  }
  const clean = cleanupDimensions(dims);
  if (clean) return { ...metadata, dimensions: clean };
  const copy = { ...metadata };
  delete copy.dimensions;
  return copy;
}
function applyWeight(metadata, field, raw) {
  const weight = normalizeWeight(metadata);
  if (field === "unit") weight.unit = raw;
  else {
    const numeric = Number(raw);
    weight.value = Number.isNaN(numeric) ? void 0 : numeric;
  }
  const clean = cleanupWeight(weight);
  if (clean) return { ...metadata, weight: clean };
  const copy = { ...metadata };
  delete copy.weight;
  return copy;
}
function cleanupDimensions(dims) {
  const clean = {};
  if (typeof dims.width === "number" && Number.isFinite(dims.width)) clean.width = dims.width;
  if (typeof dims.height === "number" && Number.isFinite(dims.height)) clean.height = dims.height;
  if (typeof dims.depth === "number" && Number.isFinite(dims.depth)) clean.depth = dims.depth;
  if (typeof dims.unit === "string" && dims.unit.trim().length) clean.unit = dims.unit;
  return Object.keys(clean).length ? clean : null;
}
function cleanupWeight(weight) {
  const clean = {};
  if (typeof weight.value === "number" && Number.isFinite(weight.value)) clean.value = weight.value;
  if (typeof weight.unit === "string" && weight.unit.trim().length) clean.unit = weight.unit;
  return Object.keys(clean).length ? clean : null;
}
function stripSystemMetadata(metadata) {
  const copy = {};
  for (const [key, value] of Object.entries(metadata)) {
    if (key === "dimensions" || key === "weight") continue;
    copy[key] = value;
  }
  return copy;
}
function extractSystemMetadata(metadata) {
  const system = {};
  if (metadata.dimensions) system.dimensions = metadata.dimensions;
  if (metadata.weight) system.weight = metadata.weight;
  return system;
}
export {
  VariantBasicsSection,
  VariantBuilder,
  VariantDimensionsSection,
  VariantMediaSection,
  VariantMetadataSection,
  VariantOptionValuesSection,
  VariantPricesSection
};
//# sourceMappingURL=VariantBuilder.js.map
