import {
  HandleInput
} from "./chunk-HJ56YXBU.js";
import {
  currencies
} from "./chunk-IQPN4PZJ.js";
import {
  FileUpload,
  MediaSchema
} from "./chunk-UWU6VSO4.js";
import "./chunk-AJLGY3LQ.js";
import "./chunk-SMQT3ZNO.js";
import "./chunk-ZZ4JC4WE.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import "./chunk-52KJSIHS.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 "./chunk-EPSDO2MJ.js";
import "./chunk-BHEU34FL.js";
import {
  useMe,
  useSeller,
  useUpdateSeller
} 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 "./chunk-O72AIZUN.js";
import "./chunk-VUWAOX7H.js";
import "./chunk-5DKUSZQ7.js";
import "./chunk-DIAWPVYS.js";
import "./chunk-4U2BLH45.js";
import "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  sdk
} from "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/settings/store/edit/index.tsx
import { Heading as Heading2 } from "@medusajs/ui";
import { useLinkQuery } from "@mercurjs/dashboard-shared";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/settings/store/edit/_components/edit-store-form.tsx
import i18n from "i18next";
import {
  Button,
  Heading,
  Hint,
  Input,
  Select,
  Textarea,
  toast
} from "@medusajs/ui";
import { useFieldArray } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { useCallback } from "react";
import {
  FormExtensionZone,
  useExtendableForm
} from "@mercurjs/dashboard-shared";
import { jsx, jsxs } from "react/jsx-runtime";
var EditStoreSchema = zod.object({
  name: zod.string().min(1, { message: i18n.t("store.validation.nameRequired") }),
  handle: zod.string().optional().or(zod.literal("")),
  email: zod.string().min(1, { message: i18n.t("store.validation.emailRequired") }).email({ message: i18n.t("store.validation.emailInvalid") }),
  phone: zod.string().optional().or(zod.literal("")),
  description: zod.string().optional().or(zod.literal("")),
  website_url: zod.string().optional().or(zod.literal("")),
  media: zod.array(MediaSchema).optional(),
  bannerMedia: zod.array(MediaSchema).optional()
});
var SUPPORTED_FORMATS = [
  "image/jpeg",
  "image/png",
  "image/gif",
  "image/webp",
  "image/heic",
  "image/svg+xml"
];
var SUPPORTED_FORMATS_FILE_EXTENSIONS = [
  ".jpeg",
  ".png",
  ".gif",
  ".webp",
  ".heic",
  ".svg"
];
var stripWebsiteProtocol = (url) => url ? url.replace(/^https?:\/\//i, "") : "";
var getFileNameFromUrl = (url) => {
  if (!url || url.startsWith("blob:")) return void 0;
  try {
    const pathname = new URL(url).pathname;
    const last = pathname.split("/").filter(Boolean).pop();
    return last ? decodeURIComponent(last) : void 0;
  } catch {
    const last = url.split("?")[0].split("/").filter(Boolean).pop();
    return last ? decodeURIComponent(last) : void 0;
  }
};
var ensureWebsiteProtocol = (url) => {
  const trimmed = url.trim();
  if (!trimmed) return null;
  if (/^https?:\/\//i.test(trimmed)) return trimmed;
  return `https://${trimmed}`;
};
var EditStoreForm = ({ seller }) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const form = useExtendableForm({
    schema: EditStoreSchema,
    model: "seller",
    zone: "edit",
    data: seller,
    defaultValues: {
      name: seller.name ?? "",
      handle: seller.handle ?? "",
      email: seller.email ?? "",
      phone: seller.phone ?? "",
      description: seller.description ?? "",
      website_url: stripWebsiteProtocol(seller.website_url),
      media: seller.logo ? [
        {
          id: "existing-logo",
          url: seller.logo,
          isThumbnail: false,
          file: null
        }
      ] : [],
      bannerMedia: seller.banner ? [
        {
          id: "existing-banner",
          url: seller.banner,
          isThumbnail: false,
          file: null
        }
      ] : []
    }
  });
  const { fields: logoFields } = useFieldArray({
    name: "media",
    control: form.control,
    keyName: "field_id"
  });
  const { fields: bannerFields } = useFieldArray({
    name: "bannerMedia",
    control: form.control,
    keyName: "field_id"
  });
  const { mutateAsync, isPending } = useUpdateSeller(seller.id);
  const handleSubmit = form.handleSubmit(async (values) => {
    let logoUrl = null;
    let bannerUrl = null;
    const newLogoFile = values.media?.find((m) => m.file);
    const newBannerFile = values.bannerMedia?.find((m) => m.file);
    try {
      if (newLogoFile) {
        const uploaded = await sdk.vendor.uploads.mutate({
          files: [newLogoFile.file]
        });
        logoUrl = uploaded.files?.[0]?.url || null;
      } else if (values.media?.length) {
        logoUrl = values.media[0].url;
      }
      if (newBannerFile) {
        const uploaded = await sdk.vendor.uploads.mutate({
          files: [newBannerFile.file]
        });
        bannerUrl = uploaded.files?.[0]?.url || null;
      } else if (values.bannerMedia?.length) {
        bannerUrl = values.bannerMedia[0].url;
      }
    } catch (error) {
      if (error instanceof Error) {
        toast.error(error.message);
      }
      return;
    }
    await mutateAsync(
      {
        name: values.name,
        handle: values.handle || void 0,
        email: values.email || void 0,
        phone: values.phone || null,
        description: values.description || null,
        website_url: ensureWebsiteProtocol(values.website_url),
        logo: logoUrl,
        banner: bannerUrl,
        additional_data: values.additional_data
      },
      {
        onSuccess: () => {
          toast.success(t("store.toast.update"));
          handleSuccess();
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  const hasInvalidFiles = useCallback(
    (fileList, fieldName) => {
      const invalidFile = fileList.find(
        (f) => !SUPPORTED_FORMATS.includes(f.file.type)
      );
      if (invalidFile) {
        form.setError(fieldName, {
          type: "invalid_file",
          message: t("products.media.invalidFileType", {
            name: invalidFile.file.name,
            types: SUPPORTED_FORMATS_FILE_EXTENSIONS.join(", ")
          })
        });
        return true;
      }
      return false;
    },
    [form, t]
  );
  const onLogoUploaded = (files) => {
    form.clearErrors("media");
    if (hasInvalidFiles(files, "media")) {
      return;
    }
    form.setValue("media", [{ ...files[0], isThumbnail: false }]);
  };
  const onBannerUploaded = (files) => {
    form.clearErrors("bannerMedia");
    if (hasInvalidFiles(files, "bannerMedia")) {
      return;
    }
    form.setValue("bannerMedia", [{ ...files[0], isThumbnail: false }]);
  };
  const currencyCode = seller.currency_code?.toUpperCase() ?? "";
  const currencyName = currencies[currencyCode]?.name ?? currencyCode;
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex flex-1 flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsxs(RouteDrawer.Body, { className: "flex flex-col gap-y-8 overflow-y-auto", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "name",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("fields.name") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "description",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.description") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Textarea, { ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "handle",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { optional: true, tooltip: t("store.handleTooltip"), children: t("fields.handle") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(HandleInput, { ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "email",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { children: t("fields.email") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { type: "email", ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "phone",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.phone") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { type: "tel", ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "website_url",
                render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                  /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.website") }),
                  /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(HandleInput, { prefix: "https://", ...field }) }),
                  /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                ] })
              }
            ),
            /* @__PURE__ */ jsxs(Form.Item, { children: [
              /* @__PURE__ */ jsx(Form.Label, { children: t("fields.currency") }),
              /* @__PURE__ */ jsxs(Select, { value: currencyCode, disabled: true, children: [
                /* @__PURE__ */ jsx(Select.Trigger, { children: /* @__PURE__ */ jsx(Select.Value, { placeholder: currencyName, children: currencyName }) }),
                /* @__PURE__ */ jsx(Select.Content, { children: /* @__PURE__ */ jsx(Select.Item, { value: currencyCode, children: currencyName }) })
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "border-ui-border-base border-t" }),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsx(Heading, { level: "h2", children: t("store.edit.mediaHeading") }),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                name: "media",
                control: form.control,
                render: () => {
                  const logoFile = logoFields[0];
                  const previewUrl = logoFile?.url || null;
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("store.logo") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                      FileUpload,
                      {
                        uploadedImage: previewUrl,
                        fileName: logoFile?.file?.name ?? getFileNameFromUrl(logoFile?.url),
                        fileSize: logoFile?.file?.size,
                        multiple: false,
                        label: t("store.edit.uploadLogoLabel"),
                        hint: t("store.edit.uploadLogoHint"),
                        hasError: !!form.formState.errors.media,
                        formats: SUPPORTED_FORMATS,
                        onUploaded: onLogoUploaded,
                        onRemove: () => form.setValue("media", [])
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                name: "bannerMedia",
                control: form.control,
                render: () => {
                  const bannerFile = bannerFields[0];
                  const previewUrl = bannerFile?.url || null;
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("store.banner") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                      FileUpload,
                      {
                        uploadedImage: previewUrl,
                        fileName: bannerFile?.file?.name ?? getFileNameFromUrl(bannerFile?.url),
                        fileSize: bannerFile?.file?.size,
                        multiple: false,
                        label: t("store.edit.uploadBannerLabel"),
                        hint: t("store.edit.uploadBannerHint"),
                        hasError: !!form.formState.errors.bannerMedia,
                        formats: SUPPORTED_FORMATS,
                        onUploaded: onBannerUploaded,
                        onRemove: () => form.setValue("bannerMedia", [])
                      }
                    ) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(Hint, { children: t("store.edit.mediaTipBody") })
          ] }),
          /* @__PURE__ */ jsx(
            FormExtensionZone,
            {
              model: "seller",
              zone: "edit",
              control: form.control,
              data: seller
            }
          )
        ] }),
        /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isPending, children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};

// src/pages/settings/store/edit/index.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var StoreEdit = () => {
  const { t } = useTranslation2();
  const { seller_member, isPending, isError, error } = useMe();
  const meSeller = seller_member?.seller;
  const query = useLinkQuery("seller");
  const needsLinks = !!query.fields;
  const { seller: linkedSeller, isPending: linkedPending } = useSeller(
    meSeller?.id ?? "",
    query,
    { enabled: needsLinks && !!meSeller?.id }
  );
  const seller = needsLinks ? linkedSeller : meSeller;
  const ready = !isPending && !!seller && (!needsLinks || !linkedPending);
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs2(RouteDrawer, { children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { children: /* @__PURE__ */ jsx2(Heading2, { className: "capitalize", children: t("app.menus.store.editStore") }) }),
    ready && /* @__PURE__ */ jsx2(EditStoreForm, { seller })
  ] });
};
var Component = StoreEdit;
export {
  Component
};
