import {
  DeprecatedPercentageInput
} from "./chunk-MAEP2UCK.js";
import {
  AddCampaignPromotionFields
} from "./chunk-MNYDJXTM.js";
import {
  RulesFormField
} from "./chunk-Y3FXVIJO.js";
import {
  CreateCampaignSchema,
  DEFAULT_CAMPAIGN_VALUES
} from "./chunk-7QWLLYOY.js";
import {
  currencies,
  getCurrencySymbol
} from "./chunk-IQPN4PZJ.js";
import {
  TabbedForm,
  defineTabMeta,
  useTabbedForm
} from "./chunk-4LXBQTFN.js";
import {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useCreatePromotion
} from "./chunk-ZN7LWXVC.js";

// src/pages/promotions/promotion-create/components/create-promotion-form/form-schema.ts
import { z } from "zod";
var RuleSchema = z.array(
  z.object({
    id: z.string().optional(),
    attribute: z.string().min(1, { message: "Required field" }),
    operator: z.string().min(1, { message: "Required field" }),
    values: z.union([
      z.number().min(1, { message: "Required field" }),
      z.string().min(1, { message: "Required field" }),
      z.array(z.string()).min(1, { message: "Required field" })
    ]),
    required: z.boolean().optional(),
    disguised: z.boolean().optional(),
    field_type: z.string().optional()
  })
);
var CreatePromotionSchema = z.object({
  template_id: z.string().optional(),
  campaign_id: z.string().optional(),
  campaign_choice: z.enum(["none", "existing", "new"]).optional(),
  is_automatic: z.string().toLowerCase(),
  code: z.string().min(1),
  type: z.enum(["buyget", "standard"]),
  status: z.enum(["draft", "active", "inactive"]),
  rules: RuleSchema,
  is_tax_inclusive: z.boolean().optional(),
  application_method: z.object({
    allocation: z.enum(["each", "across", "once"]),
    value: z.number().min(0).or(z.string().min(1)),
    currency_code: z.string().optional(),
    max_quantity: z.number().optional().nullable(),
    target_rules: RuleSchema,
    buy_rules: RuleSchema,
    type: z.enum(["fixed", "percentage"]),
    target_type: z.enum(["order", "shipping_methods", "items"])
  }),
  campaign: CreateCampaignSchema.optional()
}).refine(
  (data) => {
    if (data.application_method.allocation === "across") {
      return true;
    }
    return typeof data.application_method.max_quantity === "number";
  },
  {
    path: ["application_method.max_quantity"],
    message: `required field`
  }
);

// src/pages/promotions/promotion-create/promotion-create.tsx
import { Children as Children2 } from "react";

// src/pages/promotions/promotion-create/components/create-promotion-form/create-promotion-form.tsx
import { Children, useEffect as useEffect2, useMemo } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "@medusajs/ui";
import { useForm, useWatch as useWatch3 } from "react-hook-form";
import { useTranslation as useTranslation3 } from "react-i18next";

// src/pages/promotions/promotion-create/components/create-promotion-form/promotion-campaign-tab.tsx
import { useWatch } from "react-hook-form";
import { jsx } from "react/jsx-runtime";
var Root = () => {
  const form = useTabbedForm();
  const currencyCode = useWatch({
    control: form.control,
    name: "application_method.currency_code"
  });
  return /* @__PURE__ */ jsx("div", { className: "flex flex-col items-center", children: /* @__PURE__ */ jsx("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8 py-16", children: /* @__PURE__ */ jsx(
    AddCampaignPromotionFields,
    {
      form,
      promotionCurrencyCode: currencyCode
    }
  ) }) });
};
Root._tabMeta = defineTabMeta({
  id: "campaign",
  labelKey: "promotions.tabs.campaign",
  validationFields: ["campaign_id", "campaign_choice", "campaign"]
});
var PromotionCampaignTab = Root;

// src/pages/promotions/promotion-create/components/create-promotion-form/promotion-details-tab.tsx
import { useEffect, useState } from "react";
import {
  Alert,
  Badge,
  clx,
  CurrencyInput,
  Divider,
  Heading,
  Input,
  RadioGroup,
  Switch,
  Text
} from "@medusajs/ui";
import { useWatch as useWatch2 } from "react-hook-form";
import { Trans, useTranslation } from "react-i18next";
import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
var Root2 = ({ currentTemplate }) => {
  const { t } = useTranslation();
  const direction = useDocumentDirection();
  const form = useTabbedForm();
  const { setValue } = form;
  const [allocationMode, setAllocationMode] = useState("each");
  const watchValueType = useWatch2({
    control: form.control,
    name: "application_method.type"
  });
  const isFixedValueType = watchValueType === "fixed";
  const watchAllocation = useWatch2({
    control: form.control,
    name: "application_method.allocation"
  });
  useEffect(() => {
    if (watchAllocation) {
      setAllocationMode(watchAllocation);
    }
  }, [watchAllocation]);
  const watchType = useWatch2({
    control: form.control,
    name: "type"
  });
  const isTypeStandard = watchType === "standard";
  const isTypeBuyGet = watchType === "buyget";
  const targetType = useWatch2({
    control: form.control,
    name: "application_method.target_type"
  });
  const isTargetTypeOrder = targetType === "order";
  return /* @__PURE__ */ jsx2("div", { className: "flex size-full flex-col items-center", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8 py-16", children: [
    /* @__PURE__ */ jsxs(
      Heading,
      {
        level: "h1",
        className: "text-fg-base",
        "data-testid": "promotion-create-form-promotion-heading",
        children: [
          t(`promotions.sections.details`),
          currentTemplate?.title && /* @__PURE__ */ jsx2(
            Badge,
            {
              className: "ml-2 align-middle",
              color: "grey",
              size: "2xsmall",
              rounded: "full",
              "data-testid": "promotion-create-form-promotion-template-badge",
              children: currentTemplate?.title
            }
          )
        ]
      }
    ),
    form.formState.errors.root && /* @__PURE__ */ jsx2(
      Alert,
      {
        variant: "error",
        dismissible: false,
        className: "text-balance",
        "data-testid": "promotion-create-form-promotion-error-alert",
        children: form.formState.errors.root.message
      }
    ),
    /* @__PURE__ */ jsx2(
      Form.Field,
      {
        control: form.control,
        name: "is_automatic",
        render: ({ field }) => {
          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-create-form-method-item", children: [
            /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "promotion-create-form-method-label", children: t("promotions.form.method.label") }),
            /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "promotion-create-form-method-control", children: /* @__PURE__ */ jsxs(
              RadioGroup,
              {
                dir: direction,
                className: "flex gap-y-3",
                ...field,
                value: field.value,
                onValueChange: field.onChange,
                "data-testid": "promotion-create-form-method-radio-group",
                children: [
                  /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "false",
                      label: t("promotions.form.method.code.title"),
                      description: t("promotions.form.method.code.description"),
                      className: clx("basis-1/2"),
                      "data-testid": "promotion-create-form-method-option-code"
                    }
                  ),
                  /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "true",
                      label: t("promotions.form.method.automatic.title"),
                      description: t(
                        "promotions.form.method.automatic.description"
                      ),
                      className: clx("basis-1/2"),
                      "data-testid": "promotion-create-form-method-option-automatic"
                    }
                  )
                ]
              }
            ) }),
            /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-create-form-method-error" })
          ] });
        }
      }
    ),
    /* @__PURE__ */ jsx2(
      Form.Field,
      {
        control: form.control,
        name: "status",
        render: ({ field }) => {
          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-create-form-status-item", children: [
            /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "promotion-create-form-status-label", children: t("promotions.form.status.label") }),
            /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "promotion-create-form-status-control", children: /* @__PURE__ */ jsxs(
              RadioGroup,
              {
                dir: direction,
                className: "flex gap-y-3",
                ...field,
                value: field.value,
                onValueChange: field.onChange,
                "data-testid": "promotion-create-form-status-radio-group",
                children: [
                  /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "draft",
                      label: t("promotions.form.status.draft.title"),
                      description: t(
                        "promotions.form.status.draft.description"
                      ),
                      className: clx("basis-1/2"),
                      "data-testid": "promotion-create-form-status-option-draft"
                    }
                  ),
                  /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "active",
                      label: t("promotions.form.status.active.title"),
                      description: t(
                        "promotions.form.status.active.description"
                      ),
                      className: clx("basis-1/2"),
                      "data-testid": "promotion-create-form-status-option-active"
                    }
                  )
                ]
              }
            ) }),
            /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-create-form-status-error" })
          ] });
        }
      }
    ),
    /* @__PURE__ */ jsx2("div", { className: "flex gap-y-4", children: /* @__PURE__ */ jsx2(
      Form.Field,
      {
        control: form.control,
        name: "code",
        render: ({ field }) => {
          return /* @__PURE__ */ jsxs(
            Form.Item,
            {
              className: "basis-1/2",
              "data-testid": "promotion-create-form-code-item",
              children: [
                /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "promotion-create-form-code-label", children: t("promotions.form.code.title") }),
                /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "promotion-create-form-code-control", children: /* @__PURE__ */ jsx2(
                  Input,
                  {
                    ...field,
                    placeholder: "SUMMER15",
                    "data-testid": "promotion-create-form-code-input"
                  }
                ) }),
                /* @__PURE__ */ jsx2(
                  Text,
                  {
                    size: "small",
                    leading: "compact",
                    className: "text-ui-fg-subtle",
                    "data-testid": "promotion-create-form-code-description",
                    children: /* @__PURE__ */ jsx2(
                      Trans,
                      {
                        t,
                        i18nKey: "promotions.form.code.description",
                        components: [/* @__PURE__ */ jsx2("br", {}, "break")]
                      }
                    )
                  }
                ),
                /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-create-form-code-error" })
              ]
            }
          );
        }
      }
    ) }),
    !currentTemplate?.hiddenFields?.includes("is_tax_inclusive") && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx2(Divider, {}),
      /* @__PURE__ */ jsx2("div", { className: "flex gap-x-2 gap-y-4", children: /* @__PURE__ */ jsx2(
        Form.Field,
        {
          control: form.control,
          name: "is_tax_inclusive",
          render: ({ field: { onChange, value, ...field } }) => {
            return /* @__PURE__ */ jsxs(
              Form.Item,
              {
                className: "basis-full",
                "data-testid": "promotion-create-form-tax-inclusive-item",
                children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
                    /* @__PURE__ */ jsxs("div", { className: "block", children: [
                      /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "promotion-create-form-tax-inclusive-label", children: t("promotions.form.taxInclusive.title") }),
                      /* @__PURE__ */ jsx2(
                        Form.Hint,
                        {
                          className: "!mt-1",
                          "data-testid": "promotion-create-form-tax-inclusive-hint",
                          children: t("promotions.form.taxInclusive.description")
                        }
                      )
                    ] }),
                    /* @__PURE__ */ jsx2(
                      Form.Control,
                      {
                        className: "mr-2 self-center",
                        "data-testid": "promotion-create-form-tax-inclusive-control",
                        children: /* @__PURE__ */ jsx2(
                          Switch,
                          {
                            dir: "ltr",
                            className: "mt-[2px] rtl:rotate-180",
                            checked: !!value,
                            onCheckedChange: onChange,
                            ...field,
                            "data-testid": "promotion-create-form-tax-inclusive-switch"
                          }
                        )
                      }
                    )
                  ] }),
                  /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-create-form-tax-inclusive-error" })
                ]
              }
            );
          }
        }
      ) })
    ] }),
    !currentTemplate?.hiddenFields?.includes("type") && /* @__PURE__ */ jsx2(
      Form.Field,
      {
        control: form.control,
        name: "type",
        render: ({ field }) => {
          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-create-form-type-item", children: [
            /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "promotion-create-form-type-label", children: t("promotions.fields.type") }),
            /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "promotion-create-form-type-control", children: /* @__PURE__ */ jsxs(
              RadioGroup,
              {
                dir: direction,
                className: "flex gap-y-3",
                ...field,
                onValueChange: field.onChange,
                "data-testid": "promotion-create-form-type-radio-group",
                children: [
                  /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "standard",
                      label: t("promotions.form.type.standard.title"),
                      description: t(
                        "promotions.form.type.standard.description"
                      ),
                      className: clx("basis-1/2"),
                      "data-testid": "promotion-create-form-type-option-standard"
                    }
                  ),
                  /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "buyget",
                      label: t("promotions.form.type.buyget.title"),
                      description: t(
                        "promotions.form.type.buyget.description"
                      ),
                      className: clx("basis-1/2"),
                      "data-testid": "promotion-create-form-type-option-buyget"
                    }
                  )
                ]
              }
            ) }),
            /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-create-form-type-error" })
          ] });
        }
      }
    ),
    /* @__PURE__ */ jsx2(Divider, {}),
    /* @__PURE__ */ jsx2(RulesFormField, { form, ruleType: "rules" }),
    !currentTemplate?.hiddenFields?.includes("application_method.type") && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx2(Divider, {}),
      /* @__PURE__ */ jsx2(
        Form.Field,
        {
          control: form.control,
          name: "application_method.type",
          render: ({ field }) => {
            return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-create-form-value-type-item", children: [
              /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "promotion-create-form-value-type-label", children: t("promotions.fields.value_type") }),
              /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "promotion-create-form-value-type-control", children: /* @__PURE__ */ jsxs(
                RadioGroup,
                {
                  dir: direction,
                  className: "flex gap-y-3",
                  ...field,
                  onValueChange: field.onChange,
                  "data-testid": "promotion-create-form-value-type-radio-group",
                  children: [
                    /* @__PURE__ */ jsx2(
                      RadioGroup.ChoiceBox,
                      {
                        value: "fixed",
                        label: t(
                          "promotions.form.value_type.fixed.title"
                        ),
                        description: t(
                          "promotions.form.value_type.fixed.description"
                        ),
                        className: clx("basis-1/2"),
                        "data-testid": "promotion-create-form-value-type-option-fixed"
                      }
                    ),
                    /* @__PURE__ */ jsx2(
                      RadioGroup.ChoiceBox,
                      {
                        value: "percentage",
                        label: t(
                          "promotions.form.value_type.percentage.title"
                        ),
                        description: t(
                          "promotions.form.value_type.percentage.description"
                        ),
                        className: clx("basis-1/2"),
                        "data-testid": "promotion-create-form-value-type-option-percentage"
                      }
                    )
                  ]
                }
              ) }),
              /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-create-form-value-type-error" })
            ] });
          }
        }
      )
    ] }),
    !currentTemplate?.hiddenFields?.includes(
      "application_method.value"
    ) && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx2(Divider, {}),
      /* @__PURE__ */ jsx2(
        Form.Field,
        {
          control: form.control,
          name: "application_method.value",
          render: ({ field: { onChange, value, ...field } }) => {
            const currencyCode = form.getValues().application_method.currency_code;
            const currencyInfo = currencies[currencyCode?.toUpperCase() || "USD"];
            return /* @__PURE__ */ jsxs(
              Form.Item,
              {
                className: "basis-1/2",
                "data-testid": "promotion-create-form-value-item",
                children: [
                  /* @__PURE__ */ jsx2(
                    Form.Label,
                    {
                      tooltip: currencyCode || !isFixedValueType ? void 0 : t("promotions.fields.amount.tooltip"),
                      "data-testid": "promotion-create-form-value-label",
                      children: t("promotions.form.value.title")
                    }
                  ),
                  /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "promotion-create-form-value-control", children: isFixedValueType ? /* @__PURE__ */ jsx2(
                    CurrencyInput,
                    {
                      ...field,
                      min: 0,
                      code: currencyCode || "USD",
                      onValueChange: (_value, _name, values) => onChange(values?.value),
                      decimalScale: currencyInfo?.decimal_digits ?? 2,
                      decimalsLimit: currencyInfo?.decimal_digits ?? 2,
                      symbol: currencyCode ? getCurrencySymbol(currencyCode) : "$",
                      value,
                      disabled: !currencyCode,
                      "data-testid": "promotion-create-form-value-currency-input"
                    }
                  ) : /* @__PURE__ */ jsx2(
                    DeprecatedPercentageInput,
                    {
                      className: "text-right",
                      min: 0,
                      max: 100,
                      ...field,
                      value,
                      onChange: (e) => {
                        onChange(
                          e.target.value === "" ? null : parseFloat(e.target.value)
                        );
                      },
                      "data-testid": "promotion-create-form-value-percentage-input"
                    },
                    "amount"
                  ) }),
                  /* @__PURE__ */ jsx2(
                    Text,
                    {
                      size: "small",
                      leading: "compact",
                      className: "text-ui-fg-subtle",
                      "data-testid": "promotion-create-form-value-description",
                      children: /* @__PURE__ */ jsx2(
                        Trans,
                        {
                          t,
                          i18nKey: isFixedValueType ? "promotions.form.value_type.fixed.description" : "promotions.form.value_type.percentage.description",
                          components: [/* @__PURE__ */ jsx2("br", {}, "break")]
                        }
                      )
                    }
                  ),
                  /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-create-form-value-error" })
                ]
              }
            );
          }
        }
      )
    ] }),
    (isTypeStandard || isTypeBuyGet) && allocationMode !== "across" && /* @__PURE__ */ jsxs(Fragment, { children: [
      isTypeBuyGet && /* @__PURE__ */ jsx2(Fragment, { children: /* @__PURE__ */ jsx2(Divider, {}) }),
      /* @__PURE__ */ jsx2(
        Form.Field,
        {
          control: form.control,
          name: "application_method.max_quantity",
          render: () => {
            return /* @__PURE__ */ jsxs(
              Form.Item,
              {
                className: "basis-1/2",
                "data-testid": "promotion-create-form-max-quantity-item",
                children: [
                  /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "promotion-create-form-max-quantity-label", children: t("promotions.form.max_quantity.title") }),
                  /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "promotion-create-form-max-quantity-control", children: /* @__PURE__ */ jsx2(
                    Input,
                    {
                      ...form.register("application_method.max_quantity", {
                        valueAsNumber: true
                      }),
                      type: "number",
                      min: 1,
                      placeholder: "3",
                      "data-testid": "promotion-create-form-max-quantity-input"
                    }
                  ) }),
                  /* @__PURE__ */ jsx2(
                    Text,
                    {
                      size: "small",
                      leading: "compact",
                      className: "text-ui-fg-subtle",
                      "data-testid": "promotion-create-form-max-quantity-description",
                      children: /* @__PURE__ */ jsx2(
                        Trans,
                        {
                          t,
                          i18nKey: "promotions.form.max_quantity.description",
                          components: [/* @__PURE__ */ jsx2("br", {}, "break")]
                        }
                      )
                    }
                  ),
                  /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-create-form-max-quantity-error" })
                ]
              }
            );
          }
        }
      )
    ] }),
    !currentTemplate?.hiddenFields?.includes(
      "application_method.allocation"
    ) && /* @__PURE__ */ jsx2(
      Form.Field,
      {
        control: form.control,
        name: "application_method.allocation",
        render: ({ field }) => {
          const handleAllocationChange = (value) => {
            setAllocationMode(value);
            setValue(
              "application_method.allocation",
              value
            );
            field.onChange(value);
            if (value === "once") {
              setValue("application_method.max_quantity", 1);
            }
          };
          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "promotion-create-form-allocation-item", children: [
            /* @__PURE__ */ jsx2(Form.Label, { "data-testid": "promotion-create-form-allocation-label", children: t("promotions.fields.allocation") }),
            /* @__PURE__ */ jsx2(Form.Control, { "data-testid": "promotion-create-form-allocation-control", children: /* @__PURE__ */ jsxs(
              RadioGroup,
              {
                dir: direction,
                className: "flex gap-y-3",
                value: allocationMode,
                onValueChange: (val) => handleAllocationChange(val),
                "data-testid": "promotion-create-form-allocation-radio-group",
                children: [
                  /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "each",
                      label: t("promotions.form.allocation.each.title"),
                      description: t(
                        "promotions.form.allocation.each.description"
                      ),
                      className: clx("basis-1/2"),
                      "data-testid": "promotion-create-form-allocation-option-each"
                    }
                  ),
                  /* @__PURE__ */ jsx2(
                    RadioGroup.ChoiceBox,
                    {
                      value: "once",
                      label: t("promotions.form.allocation.once.title", {
                        defaultValue: "Once"
                      }),
                      description: t(
                        "promotions.form.allocation.once.description",
                        {
                          defaultValue: "Limit discount to max quantity"
                        }
                      ),
                      className: clx("basis-1/2"),
                      "data-testid": "promotion-create-form-allocation-option-once"
                    }
                  )
                ]
              }
            ) }),
            /* @__PURE__ */ jsx2(Form.ErrorMessage, { "data-testid": "promotion-create-form-allocation-error" })
          ] });
        }
      }
    ),
    !isTypeStandard && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx2(Divider, {}),
      /* @__PURE__ */ jsx2(
        RulesFormField,
        {
          form,
          ruleType: "buy-rules",
          scope: "application_method.buy_rules"
        }
      )
    ] }),
    !isTargetTypeOrder && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx2(Divider, {}),
      /* @__PURE__ */ jsx2(
        RulesFormField,
        {
          form,
          ruleType: "target-rules",
          scope: "application_method.target_rules"
        }
      )
    ] })
  ] }) });
};
Root2._tabMeta = defineTabMeta({
  id: "promotion",
  labelKey: "promotions.tabs.details",
  validationFields: [
    "is_automatic",
    "code",
    "type",
    "status",
    "rules",
    "is_tax_inclusive",
    "application_method"
  ]
});
var PromotionDetailsTab = Root2;

// src/pages/promotions/promotion-create/components/create-promotion-form/promotion-template-tab.tsx
import { RadioGroup as RadioGroup2 } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/promotions/promotion-create/components/create-promotion-form/templates.ts
var commonHiddenFields = [
  "type",
  "application_method.type"
];
var amountOfOrderHiddenFields = [...commonHiddenFields];
var amountOfProductHiddenFields = [...commonHiddenFields];
var percentageOfOrderHiddenFields = [
  ...commonHiddenFields,
  "is_tax_inclusive"
];
var percentageOfProductHiddenFields = [
  ...commonHiddenFields,
  "is_tax_inclusive"
];
var buyGetHiddenFields = [
  ...commonHiddenFields,
  "application_method.value",
  "is_tax_inclusive"
];
var freeShippingHiddenFields = [
  ...commonHiddenFields,
  "application_method.value",
  "application_method.allocation",
  "is_tax_inclusive"
];
var templates = [
  {
    id: "amount_off_products",
    type: "standard",
    title: "Amount off products",
    description: "Discount specific products or collection of products",
    hiddenFields: amountOfProductHiddenFields,
    defaults: {
      is_automatic: "false",
      type: "standard",
      application_method: {
        allocation: "each",
        target_type: "items",
        type: "fixed"
      }
    }
  },
  {
    id: "amount_off_order",
    type: "standard",
    title: "Amount off order",
    description: "Discounts the total order amount",
    hiddenFields: amountOfOrderHiddenFields,
    defaults: {
      is_automatic: "false",
      type: "standard",
      application_method: {
        allocation: "across",
        target_type: "order",
        type: "fixed"
      }
    }
  },
  {
    id: "percentage_off_product",
    type: "standard",
    title: "Percentage off product",
    description: "Discounts a percentage off selected products",
    hiddenFields: percentageOfProductHiddenFields,
    defaults: {
      is_automatic: "false",
      type: "standard",
      application_method: {
        allocation: "each",
        target_type: "items",
        type: "percentage"
      }
    }
  },
  {
    id: "percentage_off_order",
    type: "standard",
    title: "Percentage off order",
    description: "Discounts a percentage of the total order amount",
    hiddenFields: percentageOfOrderHiddenFields,
    defaults: {
      is_automatic: "false",
      type: "standard",
      application_method: {
        allocation: "across",
        target_type: "order",
        type: "percentage"
      }
    }
  },
  {
    id: "buy_get",
    type: "buy_get",
    title: "Buy X Get Y",
    description: "Buy X product(s), get Y product(s)",
    hiddenFields: buyGetHiddenFields,
    defaults: {
      is_automatic: "false",
      type: "buyget",
      application_method: {
        type: "percentage",
        value: 100,
        apply_to_quantity: 1,
        max_quantity: 1
      }
    }
  },
  {
    id: "shipping_discount",
    type: "standard",
    title: "Free shipping",
    description: "Applies a 100% discount to shipping fees",
    hiddenFields: freeShippingHiddenFields,
    defaults: {
      is_automatic: "false",
      type: "standard",
      application_method: {
        allocation: "across",
        target_type: "shipping_methods",
        type: "percentage",
        value: 100
      }
    }
  }
];

// src/pages/promotions/promotion-create/components/create-promotion-form/promotion-template-tab.tsx
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
var Root3 = () => {
  const { t } = useTranslation2();
  const direction = useDocumentDirection();
  const form = useTabbedForm();
  return /* @__PURE__ */ jsx3("div", { className: "flex size-full flex-col items-center", children: /* @__PURE__ */ jsx3("div", { className: "w-full max-w-[720px] py-16", children: /* @__PURE__ */ jsx3(
    Form.Field,
    {
      control: form.control,
      name: "template_id",
      render: ({ field }) => {
        return /* @__PURE__ */ jsxs2(Form.Item, { "data-testid": "promotion-create-form-template-item", children: [
          /* @__PURE__ */ jsx3(Form.Label, { "data-testid": "promotion-create-form-template-label", children: t("promotions.fields.type") }),
          /* @__PURE__ */ jsx3(Form.Control, { "data-testid": "promotion-create-form-template-control", children: /* @__PURE__ */ jsx3(
            RadioGroup2,
            {
              dir: direction,
              className: "flex-col gap-y-3",
              ...field,
              onValueChange: field.onChange,
              "data-testid": "promotion-create-form-template-radio-group",
              children: templates.map((template) => {
                return /* @__PURE__ */ jsx3(
                  RadioGroup2.ChoiceBox,
                  {
                    value: template.id,
                    label: template.title,
                    description: template.description,
                    "data-testid": `promotion-create-form-template-option-${template.id}`
                  },
                  template.id
                );
              })
            },
            "template_id"
          ) }),
          /* @__PURE__ */ jsx3(Form.ErrorMessage, { "data-testid": "promotion-create-form-template-error" })
        ] });
      }
    }
  ) }) });
};
Root3._tabMeta = defineTabMeta({
  id: "type",
  labelKey: "promotions.tabs.template",
  validationFields: ["template_id"]
});
var PromotionTemplateTab = Root3;

// src/pages/promotions/promotion-create/components/create-promotion-form/create-promotion-form.tsx
import { jsx as jsx4 } from "react/jsx-runtime";
var PROMOTION_CREATE_DEFAULTS = {
  campaign_id: void 0,
  template_id: templates[0].id,
  campaign_choice: "none",
  is_automatic: "false",
  code: "",
  type: "standard",
  status: "draft",
  rules: [],
  is_tax_inclusive: false,
  application_method: {
    allocation: "each",
    type: "fixed",
    target_type: "items",
    max_quantity: 1,
    target_rules: [],
    buy_rules: []
  },
  campaign: void 0
};
function CreatePromotionForm({
  children,
  schema,
  defaultValues: extraDefaults
}) {
  const { t } = useTranslation3();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      ...PROMOTION_CREATE_DEFAULTS,
      ...extraDefaults
    },
    resolver: zodResolver(schema ?? CreatePromotionSchema)
  });
  const { setValue, reset, getValues } = form;
  const { mutateAsync: createPromotion, isPending: isLoading } = useCreatePromotion();
  const handleSubmit = form.handleSubmit(
    async (data) => {
      if (data.campaign_choice === "existing" && !data.campaign_id) {
        form.setError("campaign_id", {
          message: t("promotions.errors.requiredField")
        });
        return;
      }
      const {
        campaign_choice: _campaignChoice,
        is_automatic,
        is_tax_inclusive,
        template_id: _templateId,
        application_method,
        rules,
        ...promotionData
      } = data;
      const {
        target_rules: targetRulesData = [],
        buy_rules: buyRulesData = [],
        ...applicationMethodData
      } = application_method;
      const allocationTyped = applicationMethodData.allocation;
      const disguisedRules = [
        ...targetRulesData.filter((r) => !!r.disguised),
        ...buyRulesData.filter((r) => !!r.disguised),
        ...rules.filter((r) => !!r.disguised)
      ];
      const applicationMethodRuleData = {};
      for (const rule of disguisedRules) {
        applicationMethodRuleData[rule.attribute] = rule.field_type === "number" ? parseInt(rule.values) : rule.values;
      }
      const buildRulesData = (rules2) => {
        return rules2.filter((r) => !r.disguised).map((rule) => ({
          operator: rule.operator,
          attribute: rule.attribute,
          values: rule.values
        }));
      };
      if (data.campaign) {
        data.campaign.budget.attribute = data.campaign.budget.attribute || null;
        data.campaign.budget.type = data.campaign.budget.attribute ? "use_by_attribute" : data.campaign.budget.type;
      }
      await createPromotion(
        {
          ...promotionData,
          rules: buildRulesData(rules),
          application_method: {
            ...applicationMethodData,
            allocation: allocationTyped,
            ...applicationMethodRuleData,
            value: parseFloat(applicationMethodData.value),
            target_rules: buildRulesData(targetRulesData),
            buy_rules: buildRulesData(buyRulesData),
            max_quantity: allocationTyped === "across" ? void 0 : applicationMethodData.max_quantity
          },
          is_tax_inclusive,
          is_automatic: is_automatic === "true"
        },
        {
          onSuccess: ({ promotion }) => {
            toast.success(
              t("promotions.toasts.promotionCreateSuccess", {
                code: promotion.code
              })
            );
            handleSuccess(`/promotions/${promotion.id}`);
          },
          onError: (e) => {
            toast.error(e.message);
          }
        }
      );
    },
    async (error) => {
      const { campaign: _campaign, ...rest } = error || {};
      const errorInPromotionTab = !!Object.keys(rest || {}).length;
      if (errorInPromotionTab) {
        toast.error(t("promotions.errors.promotionTabError"));
      }
    }
  );
  const watchTemplateId = useWatch3({
    control: form.control,
    name: "template_id"
  });
  const currentTemplate = useMemo(() => {
    const currentTemplate2 = templates.find(
      (template) => template.id === watchTemplateId
    );
    if (!currentTemplate2) {
      return;
    }
    reset({
      ...PROMOTION_CREATE_DEFAULTS,
      ...extraDefaults,
      template_id: watchTemplateId
    });
    for (const [key, value] of Object.entries(currentTemplate2.defaults)) {
      if (typeof value === "object") {
        for (const [subKey, subValue] of Object.entries(
          value
        )) {
          setValue(`application_method.${subKey}`, subValue);
        }
      } else {
        setValue(key, value);
      }
    }
    return currentTemplate2;
  }, [watchTemplateId, setValue, reset]);
  const watchCampaignChoice = useWatch3({
    control: form.control,
    name: "campaign_choice"
  });
  useEffect2(() => {
    const formData = getValues();
    if (watchCampaignChoice !== "existing") {
      setValue("campaign_id", void 0);
      form.clearErrors("campaign_id");
    }
    if (watchCampaignChoice !== "new") {
      setValue("campaign", void 0);
    }
    if (watchCampaignChoice === "new") {
      if (!formData.campaign || !formData.campaign?.budget?.type) {
        setValue("campaign", {
          ...DEFAULT_CAMPAIGN_VALUES,
          budget: {
            ...DEFAULT_CAMPAIGN_VALUES.budget,
            type: DEFAULT_CAMPAIGN_VALUES.budget.type,
            currency_code: formData.application_method.currency_code
          }
        });
      }
    }
  }, [watchCampaignChoice, getValues, setValue, form]);
  const watchRules = useWatch3({
    control: form.control,
    name: "rules"
  });
  const watchCurrencyRule = watchRules.find(
    (rule) => rule.attribute === "currency_code"
  );
  if (watchCurrencyRule) {
    const formData = form.getValues();
    const currencyCode = formData.application_method.currency_code;
    const ruleValue = watchCurrencyRule.values;
    if (!Array.isArray(ruleValue) && currencyCode !== ruleValue) {
      form.setValue("application_method.currency_code", ruleValue);
    }
  }
  const defaultTabs = useMemo(
    () => [
      /* @__PURE__ */ jsx4(PromotionTemplateTab, {}, "type"),
      /* @__PURE__ */ jsx4(PromotionDetailsTab, { currentTemplate }, "promotion"),
      /* @__PURE__ */ jsx4(PromotionCampaignTab, {}, "campaign")
    ],
    [currentTemplate]
  );
  const hasCustomChildren = Children.count(children) > 0;
  return /* @__PURE__ */ jsx4(
    TabbedForm,
    {
      form,
      onSubmit: handleSubmit,
      isLoading,
      children: hasCustomChildren ? children : defaultTabs
    }
  );
}

// src/pages/promotions/promotion-create/promotion-create.tsx
import { jsx as jsx5 } from "react/jsx-runtime";
var Root4 = ({ children }) => {
  return /* @__PURE__ */ jsx5(RouteFocusModal, { "data-testid": "promotion-create-modal", children: Children2.count(children) > 0 ? children : /* @__PURE__ */ jsx5(CreatePromotionForm, {}) });
};
var PromotionCreatePage = Object.assign(Root4, {
  Form: CreatePromotionForm,
  TemplateTab: PromotionTemplateTab,
  DetailsTab: PromotionDetailsTab,
  CampaignTab: PromotionCampaignTab,
  Tab: TabbedForm.Tab
});
var PromotionCreate = Root4;

export {
  CreatePromotionSchema,
  PromotionCreatePage,
  PromotionCreate
};
