import {
  defineTabMeta
} from "./chunk-LEWA4BPH.js";
import {
  DataGrid,
  createDataGridHelper
} from "./chunk-5FBQOAXU.js";
import {
  HandleInput
} from "./chunk-HJ56YXBU.js";
import {
  SwitchBox
} from "./chunk-YVCBMOJG.js";
import {
  SingleCategoryCombobox
} from "./chunk-P76QYIFF.js";
import {
  useComboboxData
} from "./chunk-OVPAOBZB.js";
import {
  UploadMediaFormItem
} from "./chunk-SCPQYA26.js";
import {
  PRODUCT_CREATE_FORM_DEFAULTS,
  ProductCreateSchema,
  generateVariantsFromAttributes,
  normalizeProductFormValues
} from "./chunk-UWU6VSO4.js";
import {
  ChipInput
} from "./chunk-KDE4HKH2.js";
import {
  useAttributeTableFilters,
  useAttributeTableQuery
} from "./chunk-4OQLPIUZ.js";
import {
  Combobox
} from "./chunk-VBRTC2VU.js";
import {
  TabbedForm,
  useTabbedForm
} from "./chunk-WJ5EU3KW.js";
import {
  RouteFocusModal,
  StackedFocusModal,
  useRouteModal,
  useStackedModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import {
  require_dist
} from "./chunk-52KJSIHS.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  useFeatureFlags
} from "./chunk-RLRWDHME.js";
import {
  useCreateProduct,
  useProductAttributes
} from "./chunk-YAUGB4LD.js";
import {
  sdk
} from "./chunk-DTGEFKK4.js";
import {
  __toESM
} from "./chunk-NBMM2TZK.js";

// src/pages/products/create/product-create.tsx
import { Children as Children2 } from "react";
import { useTranslation as useTranslation9 } from "react-i18next";

// src/pages/products/create/components/product-create-form/product-create-form.tsx
var import_types6 = __toESM(require_dist(), 1);
import { Button as Button3, toast } from "@medusajs/ui";
import { useEffect as useEffect3, useMemo as useMemo3, Children } from "react";
import { useForm, useWatch as useWatch2 } from "react-hook-form";
import { useTranslation as useTranslation8 } from "react-i18next";
import { zodResolver } from "@hookform/resolvers/zod";

// src/pages/products/create/components/product-create-attributes-form/product-create-attributes-form.tsx
var import_types = __toESM(require_dist(), 1);
import { XMarkMini } from "@medusajs/icons";
import {
  Button as Button2,
  Heading,
  Hint,
  IconButton,
  InlineTip,
  Input,
  Label,
  Select,
  Switch,
  Text,
  Textarea
} from "@medusajs/ui";
import { useEffect as useEffect2 } from "react";
import {
  Controller,
  useFieldArray
} from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/products/create/components/product-create-attributes-form/product-create-add-attributes-modal.tsx
import { Badge, Button, Checkbox } from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import {
  createColumnHelper
} from "@tanstack/react-table";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var ADD_ATTRIBUTES_MODAL_ID = "add-attributes";
var PAGE_SIZE = 20;
var MAX_VISIBLE_VALUES = 2;
var ATTRIBUTE_TYPE_LABELS = {
  single_select: "attributes.type.select",
  multi_select: "attributes.type.multivalue",
  unit: "attributes.type.unit",
  toggle: "attributes.type.toggle",
  text: "attributes.type.text_area"
};
var ProductCreateAddAttributesModal = () => {
  const form = useTabbedForm();
  const { t } = useTranslation();
  const { getValues, setValue } = form;
  const { setIsOpen, getIsOpen } = useStackedModal();
  const [rowSelection, setRowSelection] = useState({});
  const [selected, setSelected] = useState([]);
  const categoryId = form.watch("category_id");
  const { searchParams, raw } = useAttributeTableQuery({
    pageSize: PAGE_SIZE,
    prefix: ADD_ATTRIBUTES_MODAL_ID
  });
  const attributesQuery = useMemo(
    () => ({ ...searchParams, category_id: categoryId || void 0 }),
    [searchParams, categoryId]
  );
  const { product_attributes, count, isLoading, isError, error } = useProductAttributes(attributesQuery, {
    placeholderData: keepPreviousData
  });
  const open = getIsOpen(ADD_ATTRIBUTES_MODAL_ID);
  useEffect(() => {
    if (!open) {
      return;
    }
    const attributes = getValues("attributes") ?? [];
    const existing = attributes.filter((a) => a.attribute_id);
    const selection = {};
    const entries = [];
    for (const a of existing) {
      if (a.attribute_id) {
        selection[a.attribute_id] = true;
        const apiAttr = product_attributes?.find(
          (pa) => pa.id === a.attribute_id
        );
        entries.push({
          id: a.attribute_id,
          name: a.title,
          values: Array.isArray(a.values) ? a.values : a.values ? [a.values] : [],
          is_variant_axis: a.use_for_variants,
          type: a.type ?? apiAttr?.type ?? "",
          available_values: a.available_values ?? apiAttr?.values?.map((v) => ({
            id: v.id,
            name: v.name
          })) ?? []
        });
      }
    }
    if (product_attributes) {
      for (const attr of product_attributes) {
        if (attr.is_required && !selection[attr.id]) {
          selection[attr.id] = true;
          entries.push({
            id: attr.id,
            name: attr.name,
            values: [],
            is_variant_axis: attr.is_variant_axis,
            type: attr.type,
            available_values: attr.values?.map((v) => ({ id: v.id, name: v.name })) ?? []
          });
        }
      }
    }
    setRowSelection(selection);
    setSelected(entries);
  }, [open, getValues, product_attributes]);
  const updater = (fn) => {
    const next = typeof fn === "function" ? fn(rowSelection) : fn;
    if (product_attributes) {
      for (const attr of product_attributes) {
        if (attr.is_required) {
          next[attr.id] = true;
        }
      }
    }
    const addedIds = new Set(
      Object.keys(next).filter((id) => next[id] && !rowSelection[id])
    );
    const addedAttributes = addedIds.size > 0 ? product_attributes?.filter((attr) => addedIds.has(attr.id)).map((attr) => ({
      id: attr.id,
      name: attr.name,
      values: [],
      is_variant_axis: attr.is_variant_axis,
      type: attr.type,
      available_values: attr.values?.map((v) => ({ id: v.id, name: v.name })) ?? []
    })) ?? [] : [];
    setSelected((prev) => {
      const kept = prev.filter((a) => next[a.id]);
      return Array.from(/* @__PURE__ */ new Set([...kept, ...addedAttributes]));
    });
    setRowSelection(next);
  };
  const handleAdd = () => {
    const currentAttributes = getValues("attributes") ?? [];
    const customAttributes = currentAttributes.filter((a) => a.is_custom);
    const requiredIds = new Set(
      product_attributes?.filter((a) => a.is_required).map((a) => a.id) ?? []
    );
    const selectedAttributes = selected.map((a) => ({
      attribute_id: a.id,
      title: a.name,
      values: a.values,
      is_custom: false,
      is_required: requiredIds.has(a.id),
      use_for_variants: a.is_variant_axis,
      type: a.type,
      available_values: a.available_values
    }));
    setValue("attributes", [...selectedAttributes, ...customAttributes], {
      shouldDirty: true,
      shouldTouch: true
    });
    setIsOpen(ADD_ATTRIBUTES_MODAL_ID, false);
  };
  const filters = useAttributeTableFilters();
  const columns = useColumns();
  const { table } = useDataTable({
    data: product_attributes ?? [],
    columns,
    count,
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE,
    enablePagination: true,
    enableRowSelection: (row) => !row.original.is_required,
    rowSelection: { state: rowSelection, updater },
    prefix: ADD_ATTRIBUTES_MODAL_ID
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs(StackedFocusModal.Content, { className: "flex flex-col overflow-hidden", children: [
    /* @__PURE__ */ jsx(StackedFocusModal.Header, {}),
    /* @__PURE__ */ jsx(StackedFocusModal.Body, { className: "flex size-full flex-col overflow-hidden", children: /* @__PURE__ */ jsx(
      _DataTable,
      {
        table,
        columns,
        count,
        pageSize: PAGE_SIZE,
        isLoading,
        filters,
        orderBy: [
          { key: "name", label: t("attributes.fields.name") },
          { key: "created_at", label: t("fields.createdAt") },
          { key: "updated_at", label: t("fields.updatedAt") }
        ],
        queryObject: raw,
        prefix: ADD_ATTRIBUTES_MODAL_ID,
        layout: "fill",
        pagination: true,
        search: true,
        noRecords: {
          title: t("products.create.attributes.noAttributesTitle"),
          message: t("products.create.attributes.noAttributesDescription")
        }
      }
    ) }),
    /* @__PURE__ */ jsx(StackedFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx(StackedFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx(Button, { size: "small", onClick: handleAdd, type: "button", children: t("actions.save") })
    ] }) })
  ] });
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => /* @__PURE__ */ jsx(
          Checkbox,
          {
            checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
            onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
          }
        ),
        cell: ({ row }) => /* @__PURE__ */ jsx(
          Checkbox,
          {
            checked: row.getIsSelected(),
            disabled: !row.getCanSelect(),
            onCheckedChange: (value) => row.toggleSelected(!!value),
            onClick: (e) => e.stopPropagation()
          }
        )
      }),
      columnHelper.accessor("name", {
        header: t("attributes.fields.productAttribute")
      }),
      columnHelper.accessor("handle", {
        header: t("attributes.fields.handle"),
        cell: (info) => {
          const handle = info.getValue();
          return handle ? `/${handle}` : "-";
        }
      }),
      columnHelper.accessor("is_required", {
        header: t("attributes.fields.required"),
        cell: (info) => info.getValue() ? t("filters.radio.yes") : t("filters.radio.no")
      }),
      columnHelper.accessor("type", {
        header: t("attributes.fields.type"),
        cell: (info) => {
          const type = info.getValue();
          const labelKey = ATTRIBUTE_TYPE_LABELS[type];
          return labelKey ? t(labelKey) : type;
        }
      }),
      columnHelper.accessor("is_variant_axis", {
        header: t("attributes.fields.variantAxis"),
        cell: (info) => info.getValue() ? t("filters.radio.yes") : t("filters.radio.no")
      }),
      columnHelper.display({
        id: "values",
        header: t("attributes.fields.values"),
        cell: ({ row }) => {
          const values = row.original.type === "toggle" ? [] : row.original.values ?? [];
          if (!values.length) {
            return /* @__PURE__ */ jsx("span", { className: "text-ui-fg-muted", children: "-" });
          }
          const visible = values.slice(0, MAX_VISIBLE_VALUES);
          const remaining = values.length - MAX_VISIBLE_VALUES;
          return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-1", children: [
            visible.map((v) => /* @__PURE__ */ jsx(Badge, { size: "2xsmall", color: "grey", children: v.name }, v.id)),
            remaining > 0 && /* @__PURE__ */ jsxs(Badge, { size: "2xsmall", color: "grey", children: [
              "+",
              remaining
            ] })
          ] });
        }
      })
    ],
    [t]
  );
};

// src/pages/products/create/components/product-create-attributes-form/product-create-attributes-form.tsx
import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var Root = () => {
  const { t } = useTranslation2();
  const form = useTabbedForm();
  const { setIsOpen } = useStackedModal();
  const { fields, append, remove } = useFieldArray({
    control: form.control,
    name: "attributes"
  });
  const handleCreateNew = () => {
    append({
      attribute_id: void 0,
      title: "",
      values: [],
      is_custom: true,
      use_for_variants: false
    });
  };
  const handleAddExisting = () => {
    setIsOpen(ADD_ATTRIBUTES_MODAL_ID, true);
  };
  return /* @__PURE__ */ jsxs2(
    "div",
    {
      className: "flex flex-col items-center p-16",
      "data-testid": "product-create-attributes-form",
      children: [
        /* @__PURE__ */ jsx2(StackedFocusModal, { id: ADD_ATTRIBUTES_MODAL_ID, children: /* @__PURE__ */ jsx2(ProductCreateAddAttributesModal, {}) }),
        /* @__PURE__ */ jsxs2("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8", children: [
          /* @__PURE__ */ jsxs2("div", { children: [
            /* @__PURE__ */ jsx2(Heading, { level: "h2", children: t("products.create.attributes.header") }),
            /* @__PURE__ */ jsx2(
              Text,
              {
                size: "small",
                className: "text-ui-fg-subtle mt-1 whitespace-pre-line",
                children: t("products.create.attributes.description")
              }
            )
          ] }),
          /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-x-2", children: [
            /* @__PURE__ */ jsx2(
              Button2,
              {
                type: "button",
                variant: "secondary",
                size: "small",
                onClick: handleAddExisting,
                "data-testid": "product-create-attributes-add-existing",
                children: t("products.create.attributes.addExisting")
              }
            ),
            /* @__PURE__ */ jsx2(
              Button2,
              {
                type: "button",
                variant: "secondary",
                size: "small",
                onClick: handleCreateNew,
                "data-testid": "product-create-attributes-create-new",
                children: t("products.create.attributes.createNew")
              }
            )
          ] }),
          fields.some((f) => !f.is_custom && !!f.attribute_id) && /* @__PURE__ */ jsx2(SelectedAttributes, { fields, remove }),
          fields.some((f) => f.is_custom) && /* @__PURE__ */ jsx2(
            "ul",
            {
              className: "flex flex-col gap-y-4",
              "data-testid": "product-create-attributes-list",
              children: fields.map((field, index) => {
                if (!field.is_custom) return null;
                const useForVariants = form.watch(
                  `attributes.${index}.use_for_variants`
                );
                return /* @__PURE__ */ jsxs2(
                  "li",
                  {
                    className: "bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-start gap-1.5 rounded-xl p-1.5",
                    "data-testid": `product-create-attribute-row-${index}`,
                    children: [
                      /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-[min-content,1fr] items-center gap-1.5", children: [
                        /* @__PURE__ */ jsx2("div", { className: "flex items-center px-2 py-1.5", children: /* @__PURE__ */ jsx2(
                          Label,
                          {
                            size: "xsmall",
                            weight: "plus",
                            className: "text-ui-fg-subtle",
                            htmlFor: `attributes.${index}.title`,
                            children: t("fields.title")
                          }
                        ) }),
                        /* @__PURE__ */ jsx2(
                          Input,
                          {
                            className: "bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover",
                            ...form.register(
                              `attributes.${index}.title`
                            ),
                            placeholder: t(
                              "products.create.attributes.titlePlaceholder"
                            ),
                            "data-testid": `product-create-attribute-title-${index}`
                          }
                        ),
                        /* @__PURE__ */ jsx2("div", { className: "flex items-center px-2 py-1.5", children: /* @__PURE__ */ jsx2(
                          Label,
                          {
                            size: "xsmall",
                            weight: "plus",
                            className: "text-ui-fg-subtle",
                            htmlFor: `attributes.${index}.values`,
                            children: t("fields.values")
                          }
                        ) }),
                        /* @__PURE__ */ jsx2(
                          Controller,
                          {
                            control: form.control,
                            name: `attributes.${index}.values`,
                            render: ({ field: { onChange, value, ...field2 } }) => useForVariants ? /* @__PURE__ */ jsx2(
                              ChipInput,
                              {
                                ...field2,
                                variant: "contrast",
                                value: Array.isArray(value) ? value : [],
                                onChange,
                                placeholder: t(
                                  "products.create.attributes.valuePlaceholder"
                                ),
                                "data-testid": `product-create-attribute-values-${index}`
                              }
                            ) : /* @__PURE__ */ jsx2(
                              Textarea,
                              {
                                ...field2,
                                className: "bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover",
                                value: Array.isArray(value) ? value[0] ?? "" : value ?? "",
                                onChange: (e) => onChange(e.target.value),
                                placeholder: t(
                                  "products.create.attributes.valuePlaceholder"
                                ),
                                "data-testid": `product-create-attribute-values-${index}`
                              }
                            )
                          }
                        ),
                        /* @__PURE__ */ jsx2("div", {}),
                        /* @__PURE__ */ jsx2(
                          Form.Field,
                          {
                            control: form.control,
                            name: `attributes.${index}.use_for_variants`,
                            render: ({
                              field: { value, onChange, ref }
                            }) => /* @__PURE__ */ jsx2(Form.Item, { children: /* @__PURE__ */ jsxs2(
                              "div",
                              {
                                className: "flex items-start gap-x-3 py-1.5",
                                "data-testid": `product-create-attribute-use-for-variants-${index}`,
                                children: [
                                  /* @__PURE__ */ jsx2(Form.Control, { children: /* @__PURE__ */ jsx2(
                                    Switch,
                                    {
                                      ref,
                                      className: "shrink-0 rtl:rotate-180",
                                      checked: value,
                                      onCheckedChange: onChange
                                    }
                                  ) }),
                                  /* @__PURE__ */ jsxs2("div", { className: "flex flex-col", children: [
                                    /* @__PURE__ */ jsx2(Label, { size: "xsmall", weight: "plus", children: t(
                                      "products.create.attributes.useForVariants"
                                    ) }),
                                    /* @__PURE__ */ jsx2(Hint, { className: "!txt-small", children: t(
                                      "products.create.attributes.useForVariantsDescription"
                                    ) })
                                  ] })
                                ]
                              }
                            ) })
                          }
                        )
                      ] }),
                      /* @__PURE__ */ jsx2(
                        IconButton,
                        {
                          type: "button",
                          size: "small",
                          variant: "transparent",
                          className: "text-ui-fg-muted",
                          onClick: () => remove(index),
                          "data-testid": `product-create-attribute-remove-${index}`,
                          children: /* @__PURE__ */ jsx2(XMarkMini, {})
                        }
                      )
                    ]
                  },
                  field.id
                );
              })
            }
          ),
          /* @__PURE__ */ jsx2(RequiredAttributes, {})
        ] })
      ]
    }
  );
};
var SelectedAttributes = ({
  fields,
  remove
}) => {
  const { t } = useTranslation2();
  const form = useTabbedForm();
  const entries = fields.map((field, index) => ({ field, index })).filter(
    ({ field }) => !field.is_custom && !field.is_required && !!field.attribute_id
  );
  if (!entries.length) return null;
  return /* @__PURE__ */ jsx2(
    "ul",
    {
      className: "flex flex-col gap-y-4",
      "data-testid": "product-create-selected-attributes-list",
      children: entries.map(({ field, index }) => {
        const attrType = field.type;
        const availableValues = field.available_values ?? [];
        return /* @__PURE__ */ jsxs2(
          "li",
          {
            className: "bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-start gap-1.5 rounded-xl p-1.5",
            "data-testid": `product-create-selected-attribute-row-${index}`,
            children: [
              /* @__PURE__ */ jsxs2("div", { className: "grid grid-cols-[min-content,1fr] items-center gap-1.5", children: [
                /* @__PURE__ */ jsx2("div", { className: "flex items-center px-2 py-1.5", children: /* @__PURE__ */ jsx2(
                  Label,
                  {
                    size: "xsmall",
                    weight: "plus",
                    className: "text-ui-fg-subtle",
                    children: t("fields.title")
                  }
                ) }),
                /* @__PURE__ */ jsx2(
                  Input,
                  {
                    value: field.title,
                    disabled: true,
                    className: "bg-ui-bg-field-component",
                    "data-testid": `product-create-selected-attribute-title-${index}`
                  }
                ),
                /* @__PURE__ */ jsx2("div", { className: "flex items-center px-2 py-1.5", children: /* @__PURE__ */ jsx2(
                  Label,
                  {
                    size: "xsmall",
                    weight: "plus",
                    className: "text-ui-fg-subtle",
                    children: t("fields.values")
                  }
                ) }),
                attrType === import_types.AttributeType.MULTI_SELECT ? /* @__PURE__ */ jsx2(
                  Controller,
                  {
                    control: form.control,
                    name: `attributes.${index}.values`,
                    render: ({ field: { onChange, value, ref, ...rest } }) => /* @__PURE__ */ jsx2(
                      Combobox,
                      {
                        ...rest,
                        ref,
                        value: Array.isArray(value) ? value : [],
                        onChange: (val) => onChange(val ?? []),
                        options: availableValues.map((v) => ({
                          value: v.name,
                          label: v.name
                        })),
                        placeholder: t(
                          "products.create.attributes.selectValues"
                        )
                      }
                    )
                  }
                ) : attrType === import_types.AttributeType.SINGLE_SELECT ? /* @__PURE__ */ jsx2(
                  Controller,
                  {
                    control: form.control,
                    name: `attributes.${index}.values`,
                    render: ({ field: { onChange, value, ref, ...rest } }) => /* @__PURE__ */ jsxs2(
                      Select,
                      {
                        ...rest,
                        value: typeof value === "string" ? value : value?.[0] ?? "",
                        onValueChange: onChange,
                        children: [
                          /* @__PURE__ */ jsx2(Select.Trigger, { ref, children: /* @__PURE__ */ jsx2(
                            Select.Value,
                            {
                              placeholder: t(
                                "products.create.attributes.selectValuePlaceholder"
                              )
                            }
                          ) }),
                          /* @__PURE__ */ jsx2(Select.Content, { children: availableValues.map((v) => /* @__PURE__ */ jsx2(Select.Item, { value: v.name, children: v.name }, v.id)) })
                        ]
                      }
                    )
                  }
                ) : attrType === import_types.AttributeType.TEXT ? /* @__PURE__ */ jsx2(
                  Controller,
                  {
                    control: form.control,
                    name: `attributes.${index}.values`,
                    render: ({ field: { onChange, value, ...rest } }) => /* @__PURE__ */ jsx2(
                      Textarea,
                      {
                        ...rest,
                        className: "bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover",
                        value: typeof value === "string" ? value : value?.[0] ?? "",
                        onChange: (e) => onChange(e.target.value),
                        placeholder: t(
                          "products.create.attributes.enterValuePlaceholder"
                        )
                      }
                    )
                  }
                ) : attrType === import_types.AttributeType.TOGGLE ? /* @__PURE__ */ jsx2(
                  Controller,
                  {
                    control: form.control,
                    name: `attributes.${index}.values`,
                    render: ({ field: { onChange, value, ...rest } }) => /* @__PURE__ */ jsxs2(
                      Select,
                      {
                        ...rest,
                        value: typeof value === "string" ? value : value?.[0] ?? "",
                        onValueChange: onChange,
                        children: [
                          /* @__PURE__ */ jsx2(Select.Trigger, { children: /* @__PURE__ */ jsx2(
                            Select.Value,
                            {
                              placeholder: t(
                                "products.create.attributes.selectValuePlaceholder"
                              )
                            }
                          ) }),
                          /* @__PURE__ */ jsxs2(Select.Content, { children: [
                            /* @__PURE__ */ jsx2(Select.Item, { value: "true", children: t("filters.radio.yes") }),
                            /* @__PURE__ */ jsx2(Select.Item, { value: "false", children: t("filters.radio.no") })
                          ] })
                        ]
                      }
                    )
                  }
                ) : /* @__PURE__ */ jsx2(
                  Controller,
                  {
                    control: form.control,
                    name: `attributes.${index}.values`,
                    render: ({ field: { onChange, value, ...rest } }) => /* @__PURE__ */ jsx2(
                      Input,
                      {
                        ...rest,
                        value: typeof value === "string" ? value : value?.[0] ?? "",
                        onChange: (e) => onChange(e.target.value),
                        placeholder: t(
                          "products.create.attributes.enterValuePlaceholder"
                        )
                      }
                    )
                  }
                ),
                field.use_for_variants && /* @__PURE__ */ jsxs2(Fragment, { children: [
                  /* @__PURE__ */ jsx2("div", {}),
                  /* @__PURE__ */ jsx2(VariantAxisTip, { className: "border-none" })
                ] })
              ] }),
              /* @__PURE__ */ jsx2(
                IconButton,
                {
                  type: "button",
                  size: "small",
                  variant: "transparent",
                  className: "text-ui-fg-muted",
                  onClick: () => remove(index),
                  "data-testid": `product-create-selected-attribute-remove-${index}`,
                  children: /* @__PURE__ */ jsx2(XMarkMini, {})
                }
              )
            ]
          },
          field.id
        );
      })
    }
  );
};
var RequiredAttributes = () => {
  const { t } = useTranslation2();
  const form = useTabbedForm();
  const categoryId = form.watch("category_id");
  const { product_attributes } = useProductAttributes(
    {
      category_id: categoryId,
      is_required: true
    },
    { enabled: !!categoryId }
  );
  const attributes = form.watch("attributes") || [];
  useEffect2(() => {
    if (!product_attributes) return;
    const currentAttributes = form.getValues("attributes") || [];
    const requiredIds = new Set(
      product_attributes.map((a) => a.id)
    );
    const otherAttributes = currentAttributes.filter(
      (a) => a.is_custom || !requiredIds.has(a.attribute_id ?? "")
    );
    const requiredAttributes = product_attributes.map(
      (attr) => {
        const existing = currentAttributes.find(
          (a) => a.attribute_id === attr.id
        );
        if (existing) return existing;
        return {
          attribute_id: attr.id,
          title: attr.name,
          values: attr.type === import_types.AttributeType.MULTI_SELECT ? [] : attr.type === import_types.AttributeType.TOGGLE ? "false" : "",
          is_custom: false,
          is_required: true,
          use_for_variants: attr.is_variant_axis,
          type: attr.type,
          available_values: attr.values?.map((v) => ({ id: v.id, name: v.name })) ?? []
        };
      }
    );
    form.setValue("attributes", [...otherAttributes, ...requiredAttributes]);
  }, [product_attributes, form]);
  if (!categoryId || !product_attributes?.length) return null;
  const requiredEntries = attributes.map((attr, index) => ({ attr, index })).filter(({ attr }) => !attr.is_custom);
  return /* @__PURE__ */ jsxs2(Fragment, { children: [
    /* @__PURE__ */ jsx2("div", { className: "border-ui-border-base border-t border-dashed" }),
    /* @__PURE__ */ jsxs2(
      "div",
      {
        className: "flex flex-col gap-y-6",
        "data-testid": "product-create-attributes-required",
        children: [
          /* @__PURE__ */ jsxs2("div", { children: [
            /* @__PURE__ */ jsx2(Text, { size: "small", weight: "plus", leading: "compact", children: t("products.create.attributes.requiredAttributes") }),
            /* @__PURE__ */ jsx2(Text, { size: "small", className: "text-ui-fg-subtle", children: t("products.create.attributes.requiredAttributesHint") })
          ] }),
          requiredEntries.map(({ attr, index }) => {
            const apiAttr = product_attributes.find(
              (a) => a.id === attr.attribute_id
            );
            if (!apiAttr) return null;
            return /* @__PURE__ */ jsx2(
              RequiredAttributeField,
              {
                attribute: apiAttr,
                index
              },
              apiAttr.id
            );
          })
        ]
      }
    )
  ] });
};
var RequiredAttributeField = ({
  attribute,
  index
}) => {
  const { t } = useTranslation2();
  const form = useTabbedForm();
  return /* @__PURE__ */ jsx2(
    Form.Field,
    {
      control: form.control,
      name: `attributes.${index}.values`,
      render: ({ field: { onChange, value, ref, ...field } }) => /* @__PURE__ */ jsxs2(Form.Item, { children: [
        /* @__PURE__ */ jsx2(Form.Label, { children: attribute.name }),
        /* @__PURE__ */ jsx2(Form.Control, { children: attribute.type === import_types.AttributeType.SINGLE_SELECT ? /* @__PURE__ */ jsxs2(
          Select,
          {
            ...field,
            value: typeof value === "string" ? value : value?.[0] ?? "",
            onValueChange: onChange,
            children: [
              /* @__PURE__ */ jsx2(Select.Trigger, { ref, children: /* @__PURE__ */ jsx2(
                Select.Value,
                {
                  placeholder: t(
                    "products.create.attributes.selectValuePlaceholder"
                  )
                }
              ) }),
              /* @__PURE__ */ jsx2(Select.Content, { children: attribute.values?.map((v) => /* @__PURE__ */ jsx2(Select.Item, { value: v.name, children: v.name }, v.id)) })
            ]
          }
        ) : attribute.type === import_types.AttributeType.MULTI_SELECT ? /* @__PURE__ */ jsx2(
          Combobox,
          {
            ...field,
            ref,
            value: Array.isArray(value) ? value : [],
            onChange: (val) => onChange(val ?? []),
            options: attribute.values?.map((v) => ({
              value: v.name,
              label: v.name
            })) ?? [],
            placeholder: t(
              "products.create.attributes.selectValues"
            )
          }
        ) : attribute.type === import_types.AttributeType.TEXT ? /* @__PURE__ */ jsx2(
          Input,
          {
            ...field,
            ref,
            value: typeof value === "string" ? value : value?.[0] ?? "",
            onChange: (e) => onChange(e.target.value),
            placeholder: t(
              "products.create.attributes.enterValuePlaceholder"
            )
          }
        ) : attribute.type === import_types.AttributeType.TOGGLE ? /* @__PURE__ */ jsx2(
          Switch,
          {
            ...field,
            className: "rtl:rotate-180",
            checked: value === "true" || value === true,
            onCheckedChange: (checked) => onChange(String(checked))
          }
        ) : /* @__PURE__ */ jsx2(
          Input,
          {
            ...field,
            ref,
            value: typeof value === "string" ? value : value?.[0] ?? "",
            onChange: (e) => onChange(e.target.value),
            placeholder: t(
              "products.create.attributes.enterValuePlaceholder"
            )
          }
        ) }),
        /* @__PURE__ */ jsx2(Form.ErrorMessage, {}),
        attribute.is_variant_axis && /* @__PURE__ */ jsx2(VariantAxisTip, {})
      ] })
    }
  );
};
var VariantAxisTip = ({ className }) => {
  const { t } = useTranslation2();
  return /* @__PURE__ */ jsx2(
    InlineTip,
    {
      className,
      label: t("products.create.attributes.tip"),
      children: t("products.create.attributes.variantAxisTip")
    }
  );
};
Root._tabMeta = defineTabMeta({
  id: "attributes",
  labelKey: "products.create.tabs.attributes",
  validationFields: ["attributes"]
});
var ProductCreateAttributesForm = Root;

// src/pages/products/create/components/product-create-details-form/product-create-details-form.tsx
import { Heading as Heading2 } from "@medusajs/ui";
import { useTranslation as useTranslation5 } from "react-i18next";

// src/pages/products/create/components/product-create-details-form/components/product-create-details-general-section/product-create-general-section.tsx
import { Input as Input2, Textarea as Textarea2 } from "@medusajs/ui";
import { useTranslation as useTranslation3 } from "react-i18next";
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var ProductCreateGeneralSection = () => {
  const form = useTabbedForm();
  const { t } = useTranslation3();
  return /* @__PURE__ */ jsxs3("div", { id: "general", className: "flex flex-col gap-y-6", "data-testid": "product-create-general-section", children: [
    /* @__PURE__ */ jsx3("div", { className: "flex flex-col gap-y-2", "data-testid": "product-create-general-section-fields", children: /* @__PURE__ */ jsxs3("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-3", "data-testid": "product-create-general-section-title-fields", children: [
      /* @__PURE__ */ jsx3(
        Form.Field,
        {
          control: form.control,
          name: "title",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs3(Form.Item, { "data-testid": "product-create-general-section-title-item", children: [
              /* @__PURE__ */ jsx3(Form.Label, { "data-testid": "product-create-general-section-title-label", children: t("products.fields.title.label") }),
              /* @__PURE__ */ jsx3(Form.Control, { "data-testid": "product-create-general-section-title-control", children: /* @__PURE__ */ jsx3(Input2, { ...field, placeholder: t("products.fields.title.placeholder"), "data-testid": "product-create-general-section-title-input" }) }),
              /* @__PURE__ */ jsx3(Form.ErrorMessage, {})
            ] });
          }
        }
      ),
      /* @__PURE__ */ jsx3(
        Form.Field,
        {
          control: form.control,
          name: "subtitle",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs3(Form.Item, { "data-testid": "product-create-general-section-subtitle-item", children: [
              /* @__PURE__ */ jsx3(Form.Label, { optional: true, "data-testid": "product-create-general-section-subtitle-label", children: t("products.fields.subtitle.label") }),
              /* @__PURE__ */ jsx3(Form.Control, { "data-testid": "product-create-general-section-subtitle-control", children: /* @__PURE__ */ jsx3(Input2, { ...field, placeholder: t("products.fields.subtitle.placeholder"), "data-testid": "product-create-general-section-subtitle-input" }) })
            ] });
          }
        }
      ),
      /* @__PURE__ */ jsx3(
        Form.Field,
        {
          control: form.control,
          name: "handle",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs3(Form.Item, { "data-testid": "product-create-general-section-handle-item", children: [
              /* @__PURE__ */ jsx3(
                Form.Label,
                {
                  tooltip: t("products.fields.handle.tooltip"),
                  optional: true,
                  "data-testid": "product-create-general-section-handle-label",
                  children: t("fields.handle")
                }
              ),
              /* @__PURE__ */ jsx3(Form.Control, { "data-testid": "product-create-general-section-handle-control", children: /* @__PURE__ */ jsx3(HandleInput, { ...field, placeholder: t("products.fields.handle.placeholder"), "data-testid": "product-create-general-section-handle-input" }) })
            ] });
          }
        }
      )
    ] }) }),
    /* @__PURE__ */ jsx3(
      Form.Field,
      {
        control: form.control,
        name: "description",
        render: ({ field }) => {
          return /* @__PURE__ */ jsxs3(Form.Item, { "data-testid": "product-create-general-section-description-item", children: [
            /* @__PURE__ */ jsx3(Form.Label, { optional: true, "data-testid": "product-create-general-section-description-label", children: t("products.fields.description.label") }),
            /* @__PURE__ */ jsx3(Form.Control, { "data-testid": "product-create-general-section-description-control", children: /* @__PURE__ */ jsx3(Textarea2, { ...field, placeholder: t("products.fields.description.placeholder"), "data-testid": "product-create-general-section-description-input" }) })
          ] });
        }
      }
    )
  ] });
};

// src/pages/products/create/components/product-create-details-form/components/product-create-details-media-section/product-create-details-media-section.tsx
import {
  defaultDropAnimationSideEffects,
  DndContext,
  DragOverlay,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors
} from "@dnd-kit/core";
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import {
  DotsSix,
  StackPerspective,
  ThumbnailBadge,
  Trash,
  XMark
} from "@medusajs/icons";
import { IconButton as IconButton2, Text as Text2 } from "@medusajs/ui";
import { useState as useState2 } from "react";
import { useFieldArray as useFieldArray2 } from "react-hook-form";
import { useTranslation as useTranslation4 } from "react-i18next";
import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
var dropAnimationConfig = {
  sideEffects: defaultDropAnimationSideEffects({
    styles: {
      active: {
        opacity: "0.4"
      }
    }
  })
};
var ProductCreateMediaSection = () => {
  const form = useTabbedForm();
  const { fields, append, remove } = useFieldArray2({
    name: "media",
    control: form.control,
    keyName: "field_id"
  });
  const [activeId, setActiveId] = useState2(null);
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates
    })
  );
  const handleDragStart = (event) => {
    setActiveId(event.active.id);
  };
  const handleDragEnd = (event) => {
    setActiveId(null);
    const { active, over } = event;
    if (active.id !== over?.id) {
      const oldIndex = fields.findIndex((item) => item.field_id === active.id);
      const newIndex = fields.findIndex((item) => item.field_id === over?.id);
      form.setValue("media", arrayMove(fields, oldIndex, newIndex), {
        shouldDirty: true,
        shouldTouch: true
      });
    }
  };
  const handleDragCancel = () => {
    setActiveId(null);
  };
  const getOnDelete = (index) => {
    return () => {
      remove(index);
    };
  };
  const getMakeThumbnail = (index) => {
    return () => {
      const newFields = fields.map((field, i) => {
        return {
          ...field,
          isThumbnail: i === index
        };
      });
      form.setValue("media", newFields, {
        shouldDirty: true,
        shouldTouch: true
      });
    };
  };
  const getItemHandlers = (index) => {
    return {
      onDelete: getOnDelete(index),
      onMakeThumbnail: getMakeThumbnail(index)
    };
  };
  return /* @__PURE__ */ jsxs4("div", { id: "media", className: "flex flex-col gap-y-2", "data-testid": "product-create-media-section", children: [
    /* @__PURE__ */ jsx4(UploadMediaFormItem, { form, append, showHint: false }),
    /* @__PURE__ */ jsxs4(
      DndContext,
      {
        sensors,
        onDragEnd: handleDragEnd,
        onDragStart: handleDragStart,
        onDragCancel: handleDragCancel,
        children: [
          /* @__PURE__ */ jsx4(DragOverlay, { dropAnimation: dropAnimationConfig, children: activeId ? /* @__PURE__ */ jsx4(
            MediaGridItemOverlay,
            {
              field: fields.find((m) => m.field_id === activeId)
            }
          ) : null }),
          /* @__PURE__ */ jsx4("ul", { className: "flex flex-col gap-y-2", "data-testid": "product-create-media-section-list", children: /* @__PURE__ */ jsx4(SortableContext, { items: fields.map((field) => field.field_id), children: fields.map((field, index) => {
            const { onDelete, onMakeThumbnail } = getItemHandlers(index);
            return /* @__PURE__ */ jsx4(
              MediaItem,
              {
                field,
                onDelete,
                onMakeThumbnail
              },
              field.field_id
            );
          }) }) })
        ]
      }
    )
  ] });
};
var MediaItem = ({ field, onDelete, onMakeThumbnail }) => {
  const { t } = useTranslation4();
  const {
    attributes,
    listeners,
    setNodeRef,
    setActivatorNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({ id: field.field_id });
  const style = {
    opacity: isDragging ? 0.4 : void 0,
    transform: CSS.Translate.toString(transform),
    transition
  };
  if (!field.file) {
    return null;
  }
  return /* @__PURE__ */ jsxs4(
    "li",
    {
      className: "bg-ui-bg-component shadow-elevation-card-rest flex items-center justify-between rounded-lg px-3 py-2",
      ref: setNodeRef,
      style,
      "data-testid": `product-create-media-section-item-${field.field_id}`,
      children: [
        /* @__PURE__ */ jsxs4("div", { className: "flex items-center gap-x-2", children: [
          /* @__PURE__ */ jsx4(
            IconButton2,
            {
              variant: "transparent",
              type: "button",
              size: "small",
              ...attributes,
              ...listeners,
              ref: setActivatorNodeRef,
              className: "cursor-grab touch-none active:cursor-grabbing",
              children: /* @__PURE__ */ jsx4(DotsSix, { className: "text-ui-fg-muted" })
            }
          ),
          /* @__PURE__ */ jsxs4("div", { className: "flex items-center gap-x-3", children: [
            /* @__PURE__ */ jsx4("div", { className: "bg-ui-bg-base h-10 w-[30px] overflow-hidden rounded-md", children: /* @__PURE__ */ jsx4(ThumbnailPreview, { url: field.url }) }),
            /* @__PURE__ */ jsxs4("div", { className: "flex flex-col", children: [
              /* @__PURE__ */ jsx4(Text2, { size: "small", leading: "compact", children: field.file.name }),
              /* @__PURE__ */ jsxs4("div", { className: "flex items-center gap-x-1", children: [
                field.isThumbnail && /* @__PURE__ */ jsx4(ThumbnailBadge, {}),
                /* @__PURE__ */ jsx4(
                  Text2,
                  {
                    size: "xsmall",
                    leading: "compact",
                    className: "text-ui-fg-subtle",
                    children: formatFileSize(field.file.size)
                  }
                )
              ] })
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxs4("div", { className: "flex items-center gap-x-1", children: [
          /* @__PURE__ */ jsx4(
            ActionMenu,
            {
              groups: [
                {
                  actions: [
                    {
                      label: t("products.media.makeThumbnail"),
                      icon: /* @__PURE__ */ jsx4(StackPerspective, {}),
                      onClick: onMakeThumbnail
                    }
                  ]
                },
                {
                  actions: [
                    {
                      icon: /* @__PURE__ */ jsx4(Trash, {}),
                      label: t("actions.delete"),
                      onClick: onDelete
                    }
                  ]
                }
              ]
            }
          ),
          /* @__PURE__ */ jsx4(
            IconButton2,
            {
              type: "button",
              size: "small",
              variant: "transparent",
              onClick: onDelete,
              children: /* @__PURE__ */ jsx4(XMark, {})
            }
          )
        ] })
      ]
    }
  );
};
var MediaGridItemOverlay = ({ field }) => {
  return /* @__PURE__ */ jsxs4("li", { className: "bg-ui-bg-component shadow-elevation-card-rest flex items-center justify-between rounded-lg px-3 py-2", children: [
    /* @__PURE__ */ jsxs4("div", { className: "flex items-center gap-x-2", children: [
      /* @__PURE__ */ jsx4(
        IconButton2,
        {
          variant: "transparent",
          size: "small",
          className: "cursor-grab touch-none active:cursor-grabbing",
          children: /* @__PURE__ */ jsx4(DotsSix, { className: "text-ui-fg-muted" })
        }
      ),
      /* @__PURE__ */ jsxs4("div", { className: "flex items-center gap-x-3", children: [
        /* @__PURE__ */ jsx4("div", { className: "bg-ui-bg-base h-10 w-[30px] overflow-hidden rounded-md", children: /* @__PURE__ */ jsx4(ThumbnailPreview, { url: field.url }) }),
        /* @__PURE__ */ jsxs4("div", { className: "flex flex-col", children: [
          /* @__PURE__ */ jsx4(Text2, { size: "small", leading: "compact", children: field.file?.name }),
          /* @__PURE__ */ jsxs4("div", { className: "flex items-center gap-x-1", children: [
            field.isThumbnail && /* @__PURE__ */ jsx4(ThumbnailBadge, {}),
            /* @__PURE__ */ jsx4(
              Text2,
              {
                size: "xsmall",
                leading: "compact",
                className: "text-ui-fg-subtle",
                children: formatFileSize(field.file?.size ?? 0)
              }
            )
          ] })
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxs4("div", { className: "flex items-center gap-x-1", children: [
      /* @__PURE__ */ jsx4(ActionMenu, { groups: [] }),
      /* @__PURE__ */ jsx4(
        IconButton2,
        {
          type: "button",
          size: "small",
          variant: "transparent",
          onClick: () => {
          },
          children: /* @__PURE__ */ jsx4(XMark, {})
        }
      )
    ] })
  ] });
};
var ThumbnailPreview = ({ url }) => {
  if (!url) {
    return null;
  }
  return /* @__PURE__ */ jsx4("img", { src: url, alt: "", className: "size-full object-cover object-center" });
};
function formatFileSize(bytes, decimalPlaces = 2) {
  if (bytes === 0) {
    return "0 Bytes";
  }
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(decimalPlaces)) + " " + sizes[i];
}

// src/pages/products/create/components/product-create-details-form/product-create-details-form.tsx
import { jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
var Root2 = () => {
  return /* @__PURE__ */ jsx5(
    "div",
    {
      className: "flex flex-col items-center p-16",
      "data-testid": "product-create-details-form",
      children: /* @__PURE__ */ jsxs5(
        "div",
        {
          className: "flex w-full max-w-[720px] flex-col gap-y-8",
          "data-testid": "product-create-details-form-content",
          children: [
            /* @__PURE__ */ jsx5(Header, {}),
            /* @__PURE__ */ jsxs5(
              "div",
              {
                className: "flex flex-col gap-y-6",
                "data-testid": "product-create-details-form-sections",
                children: [
                  /* @__PURE__ */ jsx5(ProductCreateGeneralSection, {}),
                  /* @__PURE__ */ jsx5(ProductCreateMediaSection, {})
                ]
              }
            )
          ]
        }
      )
    }
  );
};
Root2._tabMeta = defineTabMeta({
  id: "details",
  labelKey: "products.create.tabs.details",
  validationFields: ["title", "handle", "description", "media"]
});
var ProductCreateDetailsForm = Root2;
var Header = () => {
  const { t } = useTranslation5();
  return /* @__PURE__ */ jsx5(
    "div",
    {
      className: "flex flex-col",
      "data-testid": "product-create-details-form-header",
      children: /* @__PURE__ */ jsx5(Heading2, { "data-testid": "product-create-details-form-heading", children: t("products.create.header") })
    }
  );
};

// src/pages/products/create/components/product-create-organize-form/components/product-create-organize-section/product-create-details-organize-section.tsx
import { Heading as Heading3 } from "@medusajs/ui";
import { useTranslation as useTranslation6 } from "react-i18next";
import { jsx as jsx6, jsxs as jsxs6 } from "react/jsx-runtime";
var ProductCreateOrganizationSection = () => {
  const form = useTabbedForm();
  const { t } = useTranslation6();
  const collections = useComboboxData({
    queryKey: ["product_collections"],
    queryFn: (params) => sdk.vendor.collections.query(params),
    getOptions: (data) => data.collections.map((collection) => ({
      label: collection.title,
      value: collection.id
    }))
  });
  const types = useComboboxData({
    queryKey: ["product_types"],
    queryFn: (params) => sdk.vendor.productTypes.query(params),
    getOptions: (data) => data.product_types.map((type) => ({
      label: type.value,
      value: type.id
    }))
  });
  const tags = useComboboxData({
    queryKey: ["product_tags"],
    queryFn: (params) => sdk.vendor.productTags.query(params),
    getOptions: (data) => data.product_tags.map((tag) => ({
      label: tag.value,
      value: tag.id
    }))
  });
  return /* @__PURE__ */ jsxs6("div", { id: "organize", className: "flex flex-col gap-y-8", "data-testid": "product-create-organize-section", children: [
    /* @__PURE__ */ jsx6(Heading3, { "data-testid": "product-create-organize-section-heading", children: t("products.organization.header") }),
    /* @__PURE__ */ jsx6(
      SwitchBox,
      {
        control: form.control,
        name: "discountable",
        label: t("products.fields.discountable.label"),
        description: t("products.fields.discountable.hint"),
        optional: true
      }
    ),
    /* @__PURE__ */ jsxs6("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2", "data-testid": "product-create-organize-section-category-collection", children: [
      /* @__PURE__ */ jsx6(
        Form.Field,
        {
          control: form.control,
          name: "category_id",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs6(Form.Item, { "data-testid": "product-create-organize-section-category-item", children: [
              /* @__PURE__ */ jsx6(
                Form.Label,
                {
                  tooltip: t("products.fields.primaryCategory.tooltip"),
                  "data-testid": "product-create-organize-section-category-label",
                  children: t("fields.category")
                }
              ),
              /* @__PURE__ */ jsx6(Form.Control, { "data-testid": "product-create-organize-section-category-control", children: /* @__PURE__ */ jsx6(SingleCategoryCombobox, { ...field }) }),
              /* @__PURE__ */ jsx6(Form.ErrorMessage, {})
            ] });
          }
        }
      ),
      /* @__PURE__ */ jsx6(
        Form.Field,
        {
          control: form.control,
          name: "collection_id",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs6(Form.Item, { "data-testid": "product-create-organize-section-collection-item", children: [
              /* @__PURE__ */ jsx6(Form.Label, { optional: true, "data-testid": "product-create-organize-section-collection-label", children: t("products.fields.collection.label") }),
              /* @__PURE__ */ jsx6(Form.Control, { "data-testid": "product-create-organize-section-collection-control", children: /* @__PURE__ */ jsx6(
                Combobox,
                {
                  ...field,
                  options: collections.options,
                  searchValue: collections.searchValue,
                  onSearchValueChange: collections.onSearchValueChange,
                  fetchNextPage: collections.fetchNextPage
                }
              ) }),
              /* @__PURE__ */ jsx6(Form.ErrorMessage, {})
            ] });
          }
        }
      )
    ] }),
    /* @__PURE__ */ jsxs6("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2", "data-testid": "product-create-organize-section-type-tags", children: [
      /* @__PURE__ */ jsx6(
        Form.Field,
        {
          control: form.control,
          name: "type_id",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs6(Form.Item, { "data-testid": "product-create-organize-section-type-item", children: [
              /* @__PURE__ */ jsx6(Form.Label, { optional: true, "data-testid": "product-create-organize-section-type-label", children: t("products.fields.type.label") }),
              /* @__PURE__ */ jsx6(Form.Control, { "data-testid": "product-create-organize-section-type-control", children: /* @__PURE__ */ jsx6(
                Combobox,
                {
                  ...field,
                  options: types.options,
                  searchValue: types.searchValue,
                  onSearchValueChange: types.onSearchValueChange,
                  fetchNextPage: types.fetchNextPage
                }
              ) }),
              /* @__PURE__ */ jsx6(Form.ErrorMessage, {})
            ] });
          }
        }
      ),
      /* @__PURE__ */ jsx6(
        Form.Field,
        {
          control: form.control,
          name: "tags",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs6(Form.Item, { "data-testid": "product-create-organize-section-tags-item", children: [
              /* @__PURE__ */ jsx6(Form.Label, { optional: true, "data-testid": "product-create-organize-section-tags-label", children: t("products.fields.tags.label") }),
              /* @__PURE__ */ jsx6(Form.Control, { "data-testid": "product-create-organize-section-tags-control", children: /* @__PURE__ */ jsx6(
                Combobox,
                {
                  ...field,
                  options: tags.options,
                  searchValue: tags.searchValue,
                  onSearchValueChange: tags.onSearchValueChange,
                  fetchNextPage: tags.fetchNextPage
                }
              ) }),
              /* @__PURE__ */ jsx6(Form.ErrorMessage, {})
            ] });
          }
        }
      )
    ] })
  ] });
};

// src/pages/products/create/components/product-create-organize-form/product-create-organize-form.tsx
import { jsx as jsx7 } from "react/jsx-runtime";
var Root3 = () => {
  return /* @__PURE__ */ jsx7(
    "div",
    {
      className: "flex flex-col items-center p-16",
      "data-testid": "product-create-organize-form",
      children: /* @__PURE__ */ jsx7(
        "div",
        {
          className: "flex w-full max-w-[720px] flex-col gap-y-8",
          "data-testid": "product-create-organize-form-content",
          children: /* @__PURE__ */ jsx7(ProductCreateOrganizationSection, {})
        }
      )
    }
  );
};
Root3._tabMeta = defineTabMeta({
  id: "organize",
  labelKey: "products.create.tabs.organize",
  validationFields: [
    "type_id",
    "collection_id",
    "category_id",
    "tags",
    "origin_country",
    "material",
    "width",
    "length",
    "height",
    "weight",
    "mid_code",
    "hs_code"
  ]
});
var ProductCreateOrganizeForm = Root3;

// src/pages/products/create/components/product-create-variants-form/product-create-variants-form.tsx
import { Input as Input3 } from "@medusajs/ui";
import { useMemo as useMemo2, useState as useState3 } from "react";
import { useWatch } from "react-hook-form";
import { useTranslation as useTranslation7 } from "react-i18next";
import { jsx as jsx8 } from "react/jsx-runtime";
var Root4 = () => {
  const { t } = useTranslation7();
  const form = useTabbedForm();
  const { setCloseOnEscape } = useRouteModal();
  const [search, setSearch] = useState3("");
  const variants = useWatch({
    control: form.control,
    name: "variants",
    defaultValue: []
  });
  const watchedAttributes = useWatch({
    control: form.control,
    name: "attributes",
    defaultValue: []
  });
  const variantAxes = useMemo2(() => {
    return (watchedAttributes ?? []).filter((attr) => attr.use_for_variants && attr.title).map((attr) => ({
      title: attr.title
    }));
  }, [watchedAttributes]);
  const columns = useColumns2({ variantAxes });
  const variantData = useMemo2(() => {
    const ret = [];
    variants.forEach((v, i) => {
      if (v.should_create) {
        ret.push({ ...v, originalIndex: i });
      }
    });
    return ret;
  }, [variants]);
  const filteredVariantData = useMemo2(() => {
    const query = search.trim().toLowerCase();
    if (!query) {
      return variantData;
    }
    return variantData.filter((variant) => {
      const haystack = [
        variant.title,
        variant.sku,
        ...Object.values(variant.options ?? {})
      ];
      return haystack.some((value) => value?.toLowerCase().includes(query));
    });
  }, [variantData, search]);
  const headerContent = /* @__PURE__ */ jsx8(
    Input3,
    {
      type: "search",
      size: "small",
      autoComplete: "off",
      value: search,
      onChange: (event) => setSearch(event.target.value),
      placeholder: t(
        "products.create.variants.productVariants.searchPlaceholder"
      ),
      "data-testid": "product-create-variants-search-input"
    }
  );
  return /* @__PURE__ */ jsx8(
    "div",
    {
      className: "flex size-full flex-col divide-y overflow-hidden",
      "data-testid": "product-create-variants-form",
      children: /* @__PURE__ */ jsx8(
        "div",
        {
          className: "min-h-0 flex-1 overflow-hidden",
          "data-testid": "product-create-variants-form-datagrid",
          children: /* @__PURE__ */ jsx8(
            DataGrid,
            {
              columns,
              data: filteredVariantData,
              state: form,
              onEditingChange: (editing) => setCloseOnEscape(!editing),
              headerContent
            }
          )
        }
      )
    }
  );
};
Root4._tabMeta = defineTabMeta({
  id: "variants",
  labelKey: "products.create.tabs.variants",
  validationFields: ["variants"]
});
var ProductCreateVariantsForm = Root4;
var columnHelper2 = createDataGridHelper();
var useColumns2 = ({
  variantAxes
}) => {
  const { t } = useTranslation7();
  return useMemo2(
    () => [
      columnHelper2.column({
        id: "attributes",
        header: () => /* @__PURE__ */ jsx8("div", { className: "flex size-full items-center overflow-hidden", children: /* @__PURE__ */ jsx8("span", { className: "truncate", children: variantAxes.map((a) => a.title).join(" / ") }) }),
        cell: (context) => {
          return /* @__PURE__ */ jsx8(DataGrid.ReadonlyCell, { context, children: variantAxes.map((a) => context.row.original.options?.[a.title]).join(" / ") });
        },
        disableHiding: true
      }),
      columnHelper2.column({
        id: "title",
        name: t("fields.title"),
        header: t("fields.title"),
        field: (context) => `variants.${context.row.original.originalIndex}.title`,
        type: "text",
        cell: (context) => {
          return /* @__PURE__ */ jsx8(DataGrid.TextCell, { context });
        }
      }),
      columnHelper2.column({
        id: "sku",
        name: t("fields.sku"),
        header: t("fields.sku"),
        field: (context) => `variants.${context.row.original.originalIndex}.sku`,
        type: "text",
        cell: (context) => {
          return /* @__PURE__ */ jsx8(DataGrid.TextCell, { context });
        }
      })
    ],
    [variantAxes, t]
  );
};

// src/pages/products/create/components/product-create-form/product-create-form.tsx
import { jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
var ProductCreateForm = ({
  children,
  schema,
  defaultValues: extraDefaults
}) => {
  const { t } = useTranslation8();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      ...PRODUCT_CREATE_FORM_DEFAULTS,
      ...extraDefaults
    },
    resolver: zodResolver(schema ?? ProductCreateSchema)
  });
  const { mutateAsync, isPending } = useCreateProduct();
  const { feature_flags } = useFeatureFlags();
  const productRequestEnabled = !!feature_flags?.[import_types6.MercurFeatureFlags.PRODUCT_REQUEST];
  const watchedAttributes = useWatch2({
    control: form.control,
    name: "attributes"
  });
  useEffect3(() => {
    const currentVariants = form.getValues("variants") ?? [];
    const newVariants = generateVariantsFromAttributes(
      watchedAttributes ?? [],
      currentVariants
    );
    if (JSON.stringify(newVariants.map((v) => v.options)) !== JSON.stringify(currentVariants.map((v) => v.options))) {
      form.setValue("variants", newVariants);
    }
  }, [watchedAttributes, form]);
  const submitProduct = async (values, isDraftSubmission) => {
    const media = values.media || [];
    const payload = { ...values, media: void 0 };
    let uploadedMedia = [];
    try {
      const filesToUpload = media.map((m, i) => ({ file: m.file, isThumbnail: m.isThumbnail, index: i })).filter((m) => !!m.file);
      if (filesToUpload.length) {
        const result = await sdk.vendor.uploads.mutate({
          files: filesToUpload.map(({ file }) => file)
        });
        const uploadedFiles = result?.files ?? [];
        uploadedMedia = uploadedFiles.map((file, i) => ({
          ...file,
          isThumbnail: filesToUpload[i].isThumbnail
        }));
      }
    } catch (error) {
      if (error instanceof Error) {
        toast.error(error.message);
      }
    }
    const submittedStatus = isDraftSubmission ? "draft" : productRequestEnabled ? "proposed" : "published";
    await mutateAsync(
      normalizeProductFormValues({
        ...payload,
        media: uploadedMedia,
        status: submittedStatus
      }),
      {
        onSuccess: (data) => {
          if (submittedStatus === "proposed") {
            toast.success(t("products.create.requestSuccessToast"));
          } else {
            toast.success(
              t("products.create.successToast", {
                title: data.product.title
              })
            );
          }
          handleSuccess(`../${data.product.id}`);
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  };
  const handleSubmit = form.handleSubmit(async (values) => {
    await submitProduct(values, false);
  });
  const handleSaveAsDraft = async () => {
    const titleValid = await form.trigger("title");
    if (!titleValid) {
      return;
    }
    await submitProduct(form.getValues(), true);
  };
  const defaultTabs = useMemo3(
    () => [
      /* @__PURE__ */ jsx9(ProductCreateDetailsForm, {}, "details"),
      /* @__PURE__ */ jsx9(ProductCreateOrganizeForm, {}, "organize"),
      /* @__PURE__ */ jsx9(ProductCreateAttributesForm, {}, "attributes"),
      /* @__PURE__ */ jsx9(ProductCreateVariantsForm, {}, "variants")
    ],
    []
  );
  const hasCustomChildren = Children.count(children) > 0;
  return /* @__PURE__ */ jsx9(
    TabbedForm,
    {
      model: "product",
      zone: "create",
      form,
      onSubmit: handleSubmit,
      isLoading: isPending,
      footer: ({ isLastTab, onNext, isLoading }) => /* @__PURE__ */ jsxs7(
        "div",
        {
          className: "flex items-center justify-end gap-x-2",
          "data-testid": "product-create-form-footer-actions",
          children: [
            /* @__PURE__ */ jsx9(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx9(
              Button3,
              {
                variant: "secondary",
                size: "small",
                "data-testid": "product-create-form-cancel-button",
                children: t("actions.cancel")
              }
            ) }),
            /* @__PURE__ */ jsx9(
              Button3,
              {
                variant: "secondary",
                size: "small",
                type: "button",
                onClick: handleSaveAsDraft,
                isLoading,
                className: "whitespace-nowrap",
                "data-testid": "product-create-form-save-draft-button",
                children: t("actions.saveAsDraft")
              }
            ),
            isLastTab ? /* @__PURE__ */ jsx9(
              Button3,
              {
                "data-name": "publish-button",
                type: "submit",
                variant: "primary",
                size: "small",
                isLoading,
                "data-testid": "product-create-form-publish-button",
                children: t("actions.publish")
              },
              "submit-button"
            ) : /* @__PURE__ */ jsx9(
              Button3,
              {
                type: "button",
                variant: "primary",
                size: "small",
                onClick: () => onNext(),
                "data-testid": "product-create-form-continue-button",
                children: t("actions.continue")
              },
              "next-button"
            )
          ]
        }
      ),
      children: hasCustomChildren ? children : defaultTabs
    }
  );
};

// src/pages/products/create/product-create.tsx
import { jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
var Root5 = ({ children }) => {
  const { t } = useTranslation9();
  return /* @__PURE__ */ jsxs8(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx10(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx10("span", { className: "sr-only", children: t("products.create.title") }) }),
    /* @__PURE__ */ jsx10(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx10("span", { className: "sr-only", children: t("products.create.description") }) }),
    Children2.count(children) > 0 ? children : /* @__PURE__ */ jsx10(ProductCreateForm, {})
  ] });
};
var ProductCreate = Root5;
var ProductCreatePage = Object.assign(Root5, {
  Form: ProductCreateForm,
  DetailsTab: ProductCreateDetailsForm,
  OrganizeTab: ProductCreateOrganizeForm,
  AttributesTab: ProductCreateAttributesForm,
  VariantsTab: ProductCreateVariantsForm,
  Tab: TabbedForm.Tab
});

export {
  ProductCreate,
  ProductCreatePage
};
