import {
  CategoryCell,
  CategoryHeader,
  ProductStatusCell,
  ProductStatusHeader
} from "./chunk-G64YUZSL.js";
import {
  useProductTableQuery
} from "./chunk-BEPAXQMU.js";
import {
  ProductCell,
  ProductHeader
} from "./chunk-FWPGOIFA.js";
import {
  useProductTableFilters
} from "./chunk-LFX6R456.js";
import "./chunk-DB6ANJBO.js";
import {
  PlaceholderCell
} from "./chunk-PHOCVOZ5.js";
import {
  defineTabMeta
} from "./chunk-LEWA4BPH.js";
import {
  DataGrid,
  createDataGridHelper,
  createDataGridLocationStockColumns,
  createDataGridPriceColumns
} from "./chunk-5FBQOAXU.js";
import "./chunk-IQPN4PZJ.js";
import {
  TabbedForm
} from "./chunk-WJ5EU3KW.js";
import "./chunk-TKGWSUEI.js";
import "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import "./chunk-3QSRE5LS.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import "./chunk-YN3FGNJM.js";
import "./chunk-KCHYLLVG.js";
import "./chunk-CVXKASWV.js";
import "./chunk-THHRRYRS.js";
import "./chunk-LRD242C7.js";
import "./chunk-52KJSIHS.js";
import {
  Thumbnail
} from "./chunk-WIYFXWRI.js";
import "./chunk-INNFZYX2.js";
import "./chunk-LAVHRER2.js";
import "./chunk-QHQWEERJ.js";
import "./chunk-Y7QKP6QU.js";
import "./chunk-RLRWDHME.js";
import "./chunk-K5324KIX.js";
import "./chunk-FV76G2D7.js";
import "./chunk-GHDLST2P.js";
import "./chunk-YVYYOBAE.js";
import "./chunk-L2NJPDUD.js";
import "./chunk-P7UBW2EI.js";
import "./chunk-MR6REQKT.js";
import {
  useShippingProfiles
} from "./chunk-EPSDO2MJ.js";
import {
  usePricePreferences
} from "./chunk-BHEU34FL.js";
import {
  useCurrentSeller
} from "./chunk-W34KDYZA.js";
import "./chunk-II3CLUXA.js";
import "./chunk-XKEYHWBS.js";
import "./chunk-J2XUEO2E.js";
import "./chunk-656G74I2.js";
import "./chunk-VWPNMEOE.js";
import {
  useStockLocations
} from "./chunk-O72AIZUN.js";
import "./chunk-VUWAOX7H.js";
import {
  useBulkCreateOffers
} from "./chunk-5DKUSZQ7.js";
import "./chunk-DIAWPVYS.js";
import "./chunk-4U2BLH45.js";
import {
  useProducts
} from "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/offers/create/offer-create-page.tsx
import { useTranslation as useTranslation4 } from "react-i18next";

// src/pages/offers/create/create-offer-form/create-offer-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, toast } from "@medusajs/ui";
import { useEffect, useMemo as useMemo3, useState as useState2 } from "react";
import { useForm } from "react-hook-form";
import { useTranslation as useTranslation3 } from "react-i18next";

// src/pages/offers/create/create-offer-form/create-offer-catalogue.tsx
import { Checkbox, Text } from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import {
  createColumnHelper
} from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { useFormContext } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var PAGE_SIZE = 10;
var FIELDS = [
  "id",
  "title",
  "handle",
  "status",
  "thumbnail",
  "*collection",
  "categories.id",
  "categories.name",
  "variants.id"
].join(",");
var Root = () => {
  const { t } = useTranslation();
  const form = useFormContext();
  const initialSelection = (form.getValues("selected_product_ids") ?? []).reduce(
    (acc, id) => {
      acc[id] = true;
      return acc;
    },
    {}
  );
  const [rowSelection, setRowSelection] = useState(initialSelection);
  const updater = (fn) => {
    const next = typeof fn === "function" ? fn(rowSelection) : fn;
    const nextIds = Object.keys(next);
    const currentIds = Object.keys(rowSelection);
    const unchanged = nextIds.length === currentIds.length && nextIds.every((id) => rowSelection[id]);
    if (unchanged) {
      return;
    }
    setRowSelection(next);
    form.setValue("selected_product_ids", nextIds, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true
    });
  };
  const { searchParams, raw } = useProductTableQuery({ pageSize: PAGE_SIZE });
  const { products, count, isLoading, isError, error } = useProducts(
    { ...searchParams, fields: FIELDS },
    { placeholderData: keepPreviousData }
  );
  const filters = useProductTableFilters();
  const columns = useColumns();
  const { table } = useDataTable({
    data: products ?? [],
    columns,
    enablePagination: true,
    enableRowSelection: true,
    getRowId: (row) => row.id,
    pageSize: PAGE_SIZE,
    count,
    rowSelection: {
      state: rowSelection,
      updater
    }
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: "flex size-full flex-col",
      "data-testid": "offer-create-tab-catalogue",
      children: [
        /* @__PURE__ */ jsx(
          _DataTable,
          {
            table,
            count,
            columns,
            pageSize: PAGE_SIZE,
            isLoading,
            filters,
            orderBy: [
              { key: "title", label: t("fields.title") },
              { key: "created_at", label: t("fields.createdAt") },
              { key: "updated_at", label: t("fields.updatedAt") }
            ],
            defaultOrderBy: "title",
            queryObject: raw,
            layout: "fill",
            pagination: true,
            search: "autofocus"
          }
        ),
        /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-subtle border-t px-6 py-4", children: /* @__PURE__ */ jsxs("p", { className: "border-ui-border-strong txt-small text-ui-fg-subtle border-l-2 pl-3", children: [
          /* @__PURE__ */ jsx("span", { className: "text-ui-fg-base font-medium", children: t("offers.create.tipLabel") }),
          " ",
          t("offers.create.tip")
        ] }) })
      ]
    }
  );
};
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),
            "data-testid": "offer-create-catalogue-select-all-checkbox"
          }
        ),
        cell: ({ row }) => /* @__PURE__ */ jsx(
          Checkbox,
          {
            checked: row.getIsSelected(),
            onCheckedChange: (value) => row.toggleSelected(!!value),
            onClick: (e) => e.stopPropagation(),
            "data-testid": `offer-create-catalogue-select-checkbox-${row.original.id}`
          }
        )
      }),
      columnHelper.display({
        id: "product",
        header: () => /* @__PURE__ */ jsx(ProductHeader, {}),
        cell: ({ row }) => /* @__PURE__ */ jsx(
          ProductCell,
          {
            product: {
              title: row.original.title ?? "",
              thumbnail: row.original.thumbnail ?? null
            }
          }
        )
      }),
      columnHelper.display({
        id: "categories",
        header: () => /* @__PURE__ */ jsx(CategoryHeader, {}),
        cell: ({ row }) => /* @__PURE__ */ jsx(CategoryCell, { categories: row.original.categories })
      }),
      columnHelper.display({
        id: "collection",
        header: t("fields.collection"),
        cell: ({ row }) => {
          const title = row.original.collection?.title;
          if (!title) return /* @__PURE__ */ jsx(PlaceholderCell, {});
          return /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "truncate", children: title });
        }
      }),
      columnHelper.display({
        id: "variants",
        header: t("offers.fields.variants"),
        cell: ({ row }) => /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", className: "truncate", children: t("offers.fields.variantsCount", {
          count: row.original.variants?.length ?? 0
        }) })
      }),
      columnHelper.display({
        id: "status",
        header: () => /* @__PURE__ */ jsx(ProductStatusHeader, {}),
        cell: ({ row }) => {
          const status = row.original.status;
          if (!status) return /* @__PURE__ */ jsx(PlaceholderCell, {});
          return /* @__PURE__ */ jsx(ProductStatusCell, { status });
        }
      })
    ],
    [t]
  );
};
Root._tabMeta = defineTabMeta({
  id: "catalogue",
  labelKey: "offers.create.tabs.catalogue",
  validationFields: ["selected_product_ids"]
});
var CreateOfferCatalogueTab = Root;

// src/pages/offers/create/create-offer-form/create-offer-stock-levels-and-prices.tsx
import { useMemo as useMemo2 } from "react";
import { useFormContext as useFormContext2, useWatch } from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var isGroup = (row) => row.__group === true;
var Root2 = () => {
  const form = useFormContext2();
  const { setCloseOnEscape } = useRouteModal();
  const { currency_code } = useCurrentSeller();
  const { stock_locations } = useStockLocations({ limit: 100 });
  const { shipping_profiles } = useShippingProfiles({ limit: 100 });
  const { price_preferences: pricePreferences } = usePricePreferences({});
  const variants = useWatch({
    control: form.control,
    name: "variants"
  });
  const gridData = useMemo2(() => {
    const rows = [];
    let lastProductId;
    (variants ?? []).forEach((variant, index) => {
      if (variant.product_id !== lastProductId) {
        rows.push({
          __group: true,
          id: `group-${variant.product_id}`,
          product_title: variant.product_title
        });
        lastProductId = variant.product_id;
      }
      rows.push({ ...variant, __group: false, __formIndex: index });
    });
    return rows;
  }, [variants]);
  const columns = useColumns2({
    currencyCode: currency_code,
    stockLocations: stock_locations,
    shippingProfiles: shipping_profiles ?? [],
    pricePreferences
  });
  return /* @__PURE__ */ jsx2(
    "div",
    {
      className: "flex size-full flex-col overflow-hidden",
      "data-testid": "offer-create-tab-stockLevelsAndPrices",
      children: /* @__PURE__ */ jsx2(
        DataGrid,
        {
          columns,
          data: gridData,
          state: form,
          onEditingChange: (editing) => setCloseOnEscape(!editing)
        }
      )
    }
  );
};
var columnHelper2 = createDataGridHelper();
var useColumns2 = ({
  currencyCode,
  stockLocations = [],
  shippingProfiles = [],
  pricePreferences = []
}) => {
  const { t } = useTranslation2();
  return useMemo2(() => {
    const shippingProfileOptions = shippingProfiles.map((p) => ({
      value: p.id,
      label: p.name ?? p.id
    }));
    const currencies = currencyCode ? [currencyCode] : [];
    return [
      columnHelper2.column({
        id: "title",
        header: t("fields.title"),
        cell: (context) => {
          const row = context.row.original;
          if (isGroup(row)) {
            return /* @__PURE__ */ jsx2(DataGrid.ReadonlyCell, { context, children: /* @__PURE__ */ jsx2(
              "span",
              {
                className: "text-ui-fg-subtle truncate font-medium",
                title: row.product_title,
                children: row.product_title
              }
            ) });
          }
          const title = row.variant_title || "";
          return /* @__PURE__ */ jsx2(DataGrid.ReadonlyCell, { context, children: /* @__PURE__ */ jsxs2("div", { className: "flex h-full w-full items-center gap-x-2 overflow-hidden", children: [
            /* @__PURE__ */ jsx2(Thumbnail, { src: row.product_thumbnail ?? null }),
            /* @__PURE__ */ jsx2("span", { className: "truncate", title, children: title })
          ] }) });
        },
        disableHiding: true
      }),
      columnHelper2.column({
        id: "sku",
        name: t("fields.sku"),
        header: t("fields.sku"),
        field: (context) => {
          const row = context.row.original;
          return isGroup(row) ? null : `variants.${row.__formIndex}.sku`;
        },
        type: "text",
        cell: (context) => isGroup(context.row.original) ? /* @__PURE__ */ jsx2(DataGrid.ReadonlyCell, { context }) : /* @__PURE__ */ jsx2(DataGrid.TextCell, { context })
      }),
      columnHelper2.column({
        id: "shipping_profile",
        name: t("offers.fields.shippingProfile"),
        header: t("offers.fields.shippingProfile"),
        field: (context) => {
          const row = context.row.original;
          return isGroup(row) ? null : `variants.${row.__formIndex}.shipping_profile_id`;
        },
        type: "select",
        cell: (context) => isGroup(context.row.original) ? /* @__PURE__ */ jsx2(DataGrid.ReadonlyCell, { context }) : /* @__PURE__ */ jsx2(
          DataGrid.SelectCell,
          {
            context,
            options: shippingProfileOptions,
            placeholder: ""
          }
        )
      }),
      ...createDataGridLocationStockColumns({
        stockLocations,
        isReadyOnly: (context) => isGroup(context.row.original),
        getFieldName: (context, index) => {
          const row = context.row.original;
          if (isGroup(row)) return null;
          const location = stockLocations[index];
          if (!location) return null;
          return `variants.${row.__formIndex}.inventory.${location.id}`;
        },
        t
      }),
      ...createDataGridPriceColumns({
        currencies,
        pricePreferences,
        isReadyOnly: (context) => isGroup(context.row.original),
        getFieldName: (context, value) => {
          const row = context.row.original;
          if (isGroup(row)) return null;
          if (context.column.id?.startsWith("currency_prices")) {
            return `variants.${row.__formIndex}.prices.${value}`;
          }
          return null;
        },
        t
      })
    ];
  }, [t, currencyCode, stockLocations, shippingProfiles, pricePreferences]);
};
Root2._tabMeta = defineTabMeta({
  id: "stockLevelsAndPrices",
  labelKey: "offers.create.tabs.stockLevelsAndPrices"
});
var CreateOfferStockLevelsAndPricesTab = Root2;

// src/pages/offers/create/create-offer-form/schema.ts
import { z } from "zod";
var VariantRowSchema = z.object({
  variant_id: z.string().min(1),
  product_id: z.string().min(1),
  product_title: z.string(),
  variant_title: z.string(),
  product_thumbnail: z.string().nullish(),
  variant_sku: z.string().nullish(),
  sku: z.string().max(64).default(""),
  shipping_profile_id: z.string().default(""),
  prices: z.record(z.string(), z.union([z.coerce.number().min(0), z.literal("")])).default({}),
  inventory: z.record(
    z.string(),
    z.object({
      checked: z.boolean().default(false),
      quantity: z.union([z.coerce.number().min(0), z.literal("")]).default(""),
      disabledToggle: z.boolean().optional()
    })
  ).default({})
});
var CreateOfferSchema = z.object({
  // The catalogue tab selects whole products (SPEC-009); the stock &
  // prices tab fans them out to their variants.
  selected_product_ids: z.array(z.string().min(1)).min(1),
  variants: z.array(VariantRowSchema).min(1)
});

// src/pages/offers/create/create-offer-form/create-offer-form.tsx
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var DEFAULTS = {
  selected_product_ids: [],
  variants: []
};
var numericOrZero = (v) => {
  if (v === "" || v === null || v === void 0) return 0;
  return Number(v) || 0;
};
var attachErrorToRow = (message, rows, form) => {
  const variantMatch = message.match(/variant[^a-z0-9]*(?:with id[^a-z0-9]*)?['"`]?(var(?:iant)?_[A-Za-z0-9]+)/i);
  if (variantMatch) {
    const target = rows.find((r) => r.row.variant_id === variantMatch[1]);
    if (target) {
      form.setError(`variants.${target.index}.sku`, { type: "manual", message });
      return true;
    }
  }
  const skuMatch = message.match(/sku\s+['"`]([^'"`]+)['"`]/i) || message.match(/duplicate[^']*['"`]([^'"`]+)['"`]/i);
  if (skuMatch) {
    const target = rows.find((r) => r.sku === skuMatch[1]);
    if (target) {
      form.setError(`variants.${target.index}.sku`, { type: "manual", message });
      return true;
    }
  }
  return false;
};
var CreateOfferForm = () => {
  const { t } = useTranslation3();
  const { handleSuccess } = useRouteModal();
  const [isSubmitting, setIsSubmitting] = useState2(false);
  const form = useForm({
    defaultValues: DEFAULTS,
    resolver: zodResolver(CreateOfferSchema)
  });
  const { mutateAsync: bulkCreateOffers } = useBulkCreateOffers();
  const { currency_code } = useCurrentSeller();
  const { stock_locations } = useStockLocations({ limit: 100 });
  const locationIds = (stock_locations ?? []).map((l) => l.id);
  const selectedProductIds = form.watch("selected_product_ids") ?? [];
  const selectedProductIdsKey = selectedProductIds.join(",");
  const locationsKey = locationIds.join(",");
  const { products: fetchedProducts } = useProducts(
    {
      id: selectedProductIds,
      limit: selectedProductIds.length || 1,
      fields: "id,title,thumbnail,variants.id,variants.title,variants.sku"
    },
    { enabled: selectedProductIds.length > 0 }
  );
  useEffect(() => {
    const locIds = locationsKey ? locationsKey.split(",") : [];
    const emptyPrices = currency_code ? { [currency_code]: "" } : {};
    const emptyInventory = locIds.reduce((acc, locId) => {
      acc[locId] = { checked: false, quantity: "", disabledToggle: false };
      return acc;
    }, {});
    const existing = form.getValues("variants") ?? [];
    const existingByVariantId = new Map(
      existing.map((row) => [row.variant_id, row])
    );
    const next = [];
    for (const product of fetchedProducts ?? []) {
      for (const variant of product.variants ?? []) {
        const previous = existingByVariantId.get(variant.id);
        if (previous) {
          next.push({
            ...previous,
            prices: { ...emptyPrices, ...previous.prices ?? {} },
            inventory: { ...emptyInventory, ...previous.inventory ?? {} }
          });
          continue;
        }
        next.push({
          variant_id: variant.id,
          product_id: product.id ?? "",
          product_title: product.title ?? "",
          variant_title: variant.title ?? variant.id,
          product_thumbnail: product.thumbnail ?? null,
          variant_sku: variant.sku ?? null,
          sku: variant.sku ?? "",
          shipping_profile_id: "",
          prices: { ...emptyPrices },
          inventory: { ...emptyInventory }
        });
      }
    }
    const prev = form.getValues("variants") ?? [];
    if (JSON.stringify(prev) !== JSON.stringify(next)) {
      form.setValue("variants", next, { shouldDirty: false });
    }
  }, [
    selectedProductIdsKey,
    fetchedProducts,
    currency_code,
    locationsKey,
    form
  ]);
  const handleSubmit = form.handleSubmit(async (values) => {
    const variants = values.variants ?? [];
    if (variants.length === 0) {
      return;
    }
    let hasValidationError = false;
    const skuSeen = /* @__PURE__ */ new Map();
    for (let i = 0; i < variants.length; i++) {
      const row = variants[i];
      const sku = (row.sku ?? "").trim();
      if (!sku) {
        form.setError(`variants.${i}.sku`, {
          type: "manual",
          message: t("offers.validation.skuRequired")
        });
        hasValidationError = true;
      } else if (skuSeen.has(sku)) {
        form.setError(`variants.${i}.sku`, {
          type: "manual",
          message: t("offers.validation.duplicateSku")
        });
        hasValidationError = true;
      } else {
        skuSeen.set(sku, i);
      }
      if (!row.shipping_profile_id) {
        form.setError(`variants.${i}.shipping_profile_id`, {
          type: "manual",
          message: t("offers.validation.shippingProfileRequired")
        });
        hasValidationError = true;
      }
    }
    if (hasValidationError) return;
    setIsSubmitting(true);
    const rows = variants.map((row, index) => ({
      row,
      index,
      sku: (row.sku ?? "").trim()
    }));
    const payloadOffers = rows.map(({ row, sku }) => {
      const prices = [];
      if (currency_code) {
        prices.push({
          amount: numericOrZero(row.prices?.[currency_code]),
          currency_code
        });
      }
      const stock_levels = [];
      for (const [locationId, level] of Object.entries(row.inventory ?? {})) {
        if (!level?.checked) continue;
        stock_levels.push({
          location_id: locationId,
          stocked_quantity: numericOrZero(level.quantity)
        });
      }
      return {
        sku,
        variant_id: row.variant_id,
        shipping_profile_id: row.shipping_profile_id,
        prices,
        inventory_items: [
          {
            title: row.variant_title,
            stock_levels
          }
        ]
      };
    });
    try {
      await bulkCreateOffers({ offers: payloadOffers });
      toast.success(t("offers.create.successToast"));
      handleSuccess("/offers");
    } catch (err) {
      const message = err instanceof Error ? err.message : t("general.unknownError");
      const attributed = attachErrorToRow(message, rows, form);
      if (!attributed) {
        toast.error(message);
      }
    } finally {
      setIsSubmitting(false);
    }
  });
  const tabs = useMemo3(
    () => [
      /* @__PURE__ */ jsx3(CreateOfferCatalogueTab, {}, "catalogue"),
      /* @__PURE__ */ jsx3(CreateOfferStockLevelsAndPricesTab, {}, "stockLevelsAndPrices")
    ],
    []
  );
  return /* @__PURE__ */ jsx3(
    TabbedForm,
    {
      model: "offer",
      zone: "create",
      form,
      onSubmit: handleSubmit,
      isLoading: isSubmitting,
      footer: ({ isLastTab, onNext, isLoading }) => /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-end gap-x-2", children: [
        /* @__PURE__ */ jsx3(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx3(Button, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
        isLastTab ? /* @__PURE__ */ jsx3(
          Button,
          {
            type: "submit",
            variant: "primary",
            size: "small",
            isLoading,
            "data-testid": "offer-create-publish",
            children: t("offers.create.publish")
          },
          "publish-button"
        ) : /* @__PURE__ */ jsx3(
          Button,
          {
            type: "button",
            variant: "primary",
            size: "small",
            onClick: () => onNext(),
            disabled: (form.watch("selected_product_ids")?.length ?? 0) === 0,
            children: t("actions.continue")
          },
          "next-button"
        )
      ] }),
      children: tabs
    }
  );
};

// src/pages/offers/create/offer-create-page.tsx
import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
var OfferCreatePage = () => {
  const { t } = useTranslation4();
  return /* @__PURE__ */ jsxs4(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx4(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx4("span", { className: "sr-only", children: t("offers.create.header") }) }),
    /* @__PURE__ */ jsx4(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx4("span", { className: "sr-only", children: t("offers.create.description") }) }),
    /* @__PURE__ */ jsx4(CreateOfferForm, {})
  ] });
};
var Component = OfferCreatePage;
export {
  Component,
  OfferCreatePage
};
