import {
  optionalInt
} from "./chunk-AJLGY3LQ.js";
import {
  i18n
} from "./chunk-ZZ4JC4WE.js";
import {
  require_dist
} from "./chunk-52KJSIHS.js";
import {
  __toESM
} from "./chunk-NBMM2TZK.js";

// src/pages/products/create/constants.ts
import { z } from "zod";

// src/pages/products/create/utils.ts
var import_types = __toESM(require_dist(), 1);
var normalizeProductFormValues = (values) => {
  const thumbnail = values.media?.find((media) => media.isThumbnail)?.url;
  const images = values.media?.filter((media) => !media.isThumbnail).map((media) => ({ url: media.url }));
  const hasAxis = (values.attributes ?? []).some(
    (a) => a.use_for_variants && toValueArray(a.values).length > 0
  );
  const attributes = normalizeFormAttributes(values.attributes ?? []);
  if (!hasAxis) {
    attributes.push({
      title: "Default Option",
      type: import_types.AttributeType.MULTI_SELECT,
      values: ["Default"],
      is_variant_axis: true
    });
  }
  return {
    is_giftcard: false,
    status: values.status,
    tags: values?.tags?.length ? values.tags?.map((tag) => ({ id: tag })) : void 0,
    images,
    collection_id: values.collection_id || void 0,
    categories: values.category_id ? [{ id: values.category_id }] : void 0,
    type_id: values.type_id || void 0,
    handle: values.handle?.trim(),
    origin_country: values.origin_country || void 0,
    material: values.material || void 0,
    mid_code: values.mid_code || void 0,
    hs_code: values.hs_code || void 0,
    thumbnail,
    title: values.title.trim(),
    subtitle: values.subtitle?.trim(),
    description: values.description?.trim(),
    discountable: values.discountable,
    width: values.width ? parseFloat(values.width) : void 0,
    length: values.length ? parseFloat(values.length) : void 0,
    height: values.height ? parseFloat(values.height) : void 0,
    weight: values.weight ? parseFloat(values.weight) : void 0,
    attributes: attributes.length ? attributes : void 0,
    variants: normalizeVariants(
      values.variants.filter((variant) => variant.should_create),
      hasAxis
    )
  };
};
var normalizeVariants = (variants, hasAxis) => {
  return variants.map((variant) => {
    const opts = variant.options;
    const hasOpts = opts && Object.keys(opts).length > 0;
    return {
      title: variant.title || (hasOpts ? Object.values(opts).join(" / ") : "Default variant"),
      options: hasOpts ? opts : hasAxis ? void 0 : { "Default Option": "Default" },
      sku: variant.sku || void 0,
      variant_rank: variant.variant_rank
    };
  });
};
var toValueArray = (values) => Array.isArray(values) ? values.filter(Boolean) : values ? [values] : [];
var normalizeFormAttributes = (attributes) => {
  const result = [];
  for (const attr of attributes) {
    const vals = toValueArray(attr.values);
    const type = attr.type;
    const isSelect = type === "single_select" || type === "multi_select";
    if (attr.attribute_id) {
      if (isSelect || attr.use_for_variants) {
        const nameToId = new Map(
          (attr.available_values ?? []).map((v) => [v.name, v.id])
        );
        const valueIds = vals.map((name) => nameToId.get(name)).filter(Boolean);
        if (!valueIds.length) continue;
        result.push({ id: attr.attribute_id, value_ids: valueIds });
      } else {
        if (!vals.length || !vals[0]) continue;
        result.push({
          id: attr.attribute_id,
          value: type === "toggle" ? vals[0] === "true" : vals[0]
        });
      }
    } else if (attr.is_custom && attr.title) {
      if (!vals.length) continue;
      if (attr.use_for_variants) {
        result.push({
          title: attr.title,
          type: type ?? import_types.AttributeType.MULTI_SELECT,
          values: vals,
          is_variant_axis: true
        });
      } else if (isSelect) {
        result.push({
          title: attr.title,
          type,
          values: vals
        });
      } else {
        result.push({
          title: attr.title,
          type: type ?? import_types.AttributeType.TEXT,
          value: type === "toggle" ? vals[0] === "true" : vals[0]
        });
      }
    }
  }
  return result;
};
var decorateVariantsWithDefaultValues = (variants) => {
  return variants.map((variant) => ({
    ...variant,
    title: variant.title || "",
    sku: variant.sku || ""
  }));
};
var getPermutations = (data) => {
  if (data.length === 0) return [];
  if (data.length === 1) {
    return data[0].values.map((value) => ({ [data[0].title]: value }));
  }
  const [first, ...rest] = data;
  return first.values.flatMap(
    (value) => getPermutations(rest).map((perm) => ({ [first.title]: value, ...perm }))
  );
};
var generateVariantsFromAttributes = (attributes, currentVariants) => {
  const variantAxes = attributes.filter((attr) => attr.use_for_variants).map((attr) => ({
    title: attr.title,
    values: Array.isArray(attr.values) ? attr.values : attr.values ? [attr.values] : []
  })).filter((axis) => axis.title && axis.values.length > 0);
  if (variantAxes.length === 0) {
    const hasDefault = currentVariants.some((v) => v.is_default);
    if (hasDefault && currentVariants.length > 0) {
      return currentVariants;
    }
    return decorateVariantsWithDefaultValues([
      {
        title: "Default variant",
        should_create: true,
        variant_rank: 0,
        options: {},
        is_default: true
      }
    ]);
  }
  const permutations = getPermutations(variantAxes);
  const newVariants = currentVariants.reduce((acc, variant) => {
    const opts = variant.options;
    if (!opts || Object.keys(opts).length === 0) return acc;
    const match = permutations.find(
      (perm) => Object.keys(opts).every((key) => opts[key] === perm[key])
    );
    if (match) {
      acc.push({
        ...variant,
        title: Object.values(match).join(" / "),
        options: match,
        is_default: false
      });
    }
    return acc;
  }, []);
  const usedSet = new Set(
    newVariants.map((v) => JSON.stringify(v.options))
  );
  for (const perm of permutations) {
    if (!usedSet.has(JSON.stringify(perm))) {
      newVariants.push({
        title: Object.values(perm).join(" / "),
        options: perm,
        should_create: true,
        variant_rank: newVariants.length
      });
    }
  }
  return newVariants;
};

// src/pages/products/create/constants.ts
var MediaSchema = z.object({
  id: z.string().optional(),
  url: z.string(),
  isThumbnail: z.boolean(),
  file: z.any().nullable()
  // File
});
var ProductCreateVariantSchema = z.object({
  should_create: z.boolean(),
  is_default: z.boolean().optional(),
  title: z.string(),
  upc: z.string().optional(),
  ean: z.string().optional(),
  barcode: z.string().optional(),
  mid_code: z.string().optional(),
  hs_code: z.string().optional(),
  width: optionalInt,
  height: optionalInt,
  length: optionalInt,
  weight: optionalInt,
  material: z.string().optional(),
  origin_country: z.string().optional(),
  sku: z.string().optional(),
  options: z.record(z.string(), z.string()).optional(),
  variant_rank: z.number()
});
var ProductCreateSchema = z.object({
  title: z.string().min(1, {
    message: i18n.t("products.fields.title.required")
  }),
  subtitle: z.string().optional(),
  handle: z.string().optional(),
  description: z.string().optional(),
  discountable: z.boolean(),
  type_id: z.string().optional(),
  collection_id: z.string().optional(),
  category_id: z.string().min(1, {
    message: i18n.t("products.create.errors.categoryRequired")
  }),
  tags: z.array(z.string()).optional(),
  origin_country: z.string().optional(),
  material: z.string().optional(),
  width: z.string().optional(),
  length: z.string().optional(),
  height: z.string().optional(),
  weight: z.string().optional(),
  mid_code: z.string().optional(),
  hs_code: z.string().optional(),
  attributes: z.array(z.object({
    attribute_id: z.string().optional(),
    title: z.string().min(1),
    values: z.union([z.string(), z.array(z.string())]).optional(),
    is_custom: z.boolean(),
    is_required: z.boolean().optional(),
    use_for_variants: z.boolean(),
    type: z.string().optional(),
    available_values: z.array(z.object({
      id: z.string(),
      name: z.string()
    })).optional()
  })).optional().superRefine((attributes, ctx) => {
    attributes?.forEach((attr, index) => {
      if (!attr.is_required) return;
      const isEmpty = attr.values === void 0 || attr.values === "" || Array.isArray(attr.values) && attr.values.length === 0;
      if (!isEmpty) return;
      let messageKey = "products.create.errors.requiredAttribute";
      if (attr.type === "single_select" || attr.type === "toggle") {
        messageKey = "products.create.errors.requiredAttributeSelect";
      } else if (attr.type === "multi_select") {
        messageKey = "products.create.errors.requiredAttributeMultiSelect";
      } else if (attr.type === "text" || attr.type === "unit") {
        messageKey = "products.create.errors.requiredAttributeEnter";
      }
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: [index, "values"],
        message: i18n.t(messageKey)
      });
    });
  }),
  variants: z.array(ProductCreateVariantSchema).min(1),
  media: z.array(MediaSchema).optional()
}).superRefine((data, ctx) => {
  if (data.variants.every((v) => !v.should_create)) {
    return ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ["variants"],
      message: "invalid_length"
    });
  }
  const skus = /* @__PURE__ */ new Set();
  data.variants.forEach((v, index) => {
    if (v.sku) {
      if (skus.has(v.sku)) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: [`variants.${index}.sku`],
          message: i18n.t("products.create.errors.uniqueSku")
        });
      }
      skus.add(v.sku);
    }
  });
});
var EditProductMediaSchema = z.object({
  media: z.array(MediaSchema)
});
var PRODUCT_CREATE_FORM_DEFAULTS = {
  discountable: true,
  tags: [],
  variants: decorateVariantsWithDefaultValues([
    {
      title: i18n.t("products.create.defaults.variantTitle"),
      should_create: true,
      variant_rank: 0,
      options: {},
      is_default: true
    }
  ]),
  attributes: [],
  media: [],
  category_id: "",
  collection_id: "",
  description: "",
  handle: "",
  height: "",
  hs_code: "",
  length: "",
  material: "",
  mid_code: "",
  origin_country: "",
  subtitle: "",
  title: "",
  type_id: "",
  weight: "",
  width: ""
};

// src/components/common/file-upload/file-upload.tsx
import { ArrowDownTray, XMark } from "@medusajs/icons";
import { IconButton, Text, clx } from "@medusajs/ui";
import { useRef, useState } from "react";

// src/lib/format-file-size.ts
var formatFileSize = (bytes) => {
  if (bytes === 0) return "0 B";
  const units = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`;
};

// src/components/common/file-upload/file-upload.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var FileUpload = ({
  label,
  hint,
  multiple = true,
  hasError,
  formats,
  onUploaded,
  onRemove,
  uploadedImage = "",
  fileName,
  fileSize
}) => {
  const [isDragOver, setIsDragOver] = useState(false);
  const inputRef = useRef(null);
  const dropZoneRef = useRef(null);
  const handleOpenFileSelector = () => {
    inputRef.current?.click();
  };
  const handleDragEnter = (event) => {
    event.preventDefault();
    event.stopPropagation();
    const files = event.dataTransfer?.files;
    if (!files) {
      return;
    }
    setIsDragOver(true);
  };
  const handleDragLeave = (event) => {
    event.preventDefault();
    event.stopPropagation();
    if (!dropZoneRef.current || dropZoneRef.current.contains(event.relatedTarget)) {
      return;
    }
    setIsDragOver(false);
  };
  const handleUploaded = (files) => {
    if (!files) {
      return;
    }
    const fileList = Array.from(files);
    const fileObj = fileList.map((file) => {
      const id = Math.random().toString(36).substring(7);
      const previewUrl = URL.createObjectURL(file);
      return {
        id,
        url: previewUrl,
        file
      };
    });
    onUploaded(fileObj);
  };
  const handleDrop = (event) => {
    event.preventDefault();
    event.stopPropagation();
    setIsDragOver(false);
    handleUploaded(event.dataTransfer?.files);
  };
  const handleFileChange = async (event) => {
    handleUploaded(event.target.files);
  };
  const showFileRow = !multiple && uploadedImage;
  if (showFileRow) {
    return /* @__PURE__ */ jsxs("div", { children: [
      /* @__PURE__ */ jsxs("div", { className: "bg-ui-bg-component shadow-borders-base flex items-center gap-x-3 rounded-lg p-3", children: [
        /* @__PURE__ */ jsx("div", { className: "flex h-10 w-[30px] shrink-0 items-center justify-center overflow-hidden rounded-md", children: /* @__PURE__ */ jsx(
          "img",
          {
            src: uploadedImage,
            alt: fileName,
            className: "h-full w-full object-cover"
          }
        ) }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col", children: [
          /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", weight: "plus", children: fileName || "image" }),
          fileSize != null && /* @__PURE__ */ jsx(
            Text,
            {
              size: "small",
              leading: "compact",
              className: "text-ui-fg-subtle",
              children: formatFileSize(fileSize)
            }
          )
        ] }),
        onRemove && /* @__PURE__ */ jsx(
          IconButton,
          {
            type: "button",
            variant: "transparent",
            size: "small",
            onClick: onRemove,
            children: /* @__PURE__ */ jsx(XMark, {})
          }
        )
      ] }),
      /* @__PURE__ */ jsx(
        "input",
        {
          hidden: true,
          "aria-label": "File upload",
          ref: inputRef,
          onChange: handleFileChange,
          type: "file",
          accept: formats.join(","),
          multiple: false
        }
      )
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsxs(
      "button",
      {
        ref: dropZoneRef,
        type: "button",
        onClick: handleOpenFileSelector,
        onDrop: handleDrop,
        onDragOver: (e) => e.preventDefault(),
        onDragEnter: handleDragEnter,
        onDragLeave: handleDragLeave,
        className: clx(
          "bg-ui-bg-component border-ui-border-strong transition-fg group flex w-full flex-col items-center gap-y-2 rounded-lg border border-dashed p-8",
          "hover:border-ui-border-interactive focus:border-ui-border-interactive",
          "focus:shadow-borders-focus outline-none focus:border-solid",
          {
            "!border-ui-border-error": hasError,
            "!border-ui-border-interactive": isDragOver
          }
        ),
        children: [
          /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle group-disabled:text-ui-fg-disabled flex items-center gap-x-2", children: [
            /* @__PURE__ */ jsx(ArrowDownTray, {}),
            /* @__PURE__ */ jsx(Text, { children: label })
          ] }),
          !!hint && /* @__PURE__ */ jsx(
            Text,
            {
              size: "small",
              leading: "compact",
              className: "text-ui-fg-muted group-disabled:text-ui-fg-disabled",
              children: hint
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ jsx(
      "input",
      {
        hidden: true,
        "aria-label": "File upload",
        ref: inputRef,
        onChange: handleFileChange,
        type: "file",
        accept: formats.join(","),
        multiple
      }
    )
  ] });
};

export {
  normalizeProductFormValues,
  generateVariantsFromAttributes,
  MediaSchema,
  ProductCreateSchema,
  EditProductMediaSchema,
  PRODUCT_CREATE_FORM_DEFAULTS,
  formatFileSize,
  FileUpload
};
