import {
  useCustomerGroupTableQuery
} from "./chunk-VKOE5J66.js";
import {
  TextCell,
  TextHeader
} from "./chunk-JHIMVLB2.js";
import {
  useOrderTableColumns
} from "./chunk-HRUO43BZ.js";
import {
  useOrderTableQuery
} from "./chunk-XBKWFLJG.js";
import {
  useOrderTableFilters
} from "./chunk-5ALC4Z2H.js";
import {
  useCustomerGroupTableFilters
} from "./chunk-CMHI2RPL.js";
import "./chunk-HB3BP55W.js";
import "./chunk-SYNUA6LQ.js";
import "./chunk-5YZ3G5EZ.js";
import "./chunk-T35QBLG7.js";
import "./chunk-XCHKUSUU.js";
import {
  getCountryByIso2
} from "./chunk-JRTZWK77.js";
import "./chunk-DB6ANJBO.js";
import "./chunk-PHOCVOZ5.js";
import "./chunk-IQPN4PZJ.js";
import {
  TwoColumnPage
} from "./chunk-YV6MK4PZ.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import "./chunk-YN3FGNJM.js";
import "./chunk-KCHYLLVG.js";
import {
  NoRecords
} from "./chunk-CVXKASWV.js";
import "./chunk-THHRRYRS.js";
import "./chunk-LRD242C7.js";
import {
  TwoColumnPageSkeleton
} from "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.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 "./chunk-EPSDO2MJ.js";
import "./chunk-BHEU34FL.js";
import "./chunk-W34KDYZA.js";
import {
  customersQueryKeys,
  useBatchCustomerCustomerGroups,
  useCustomer,
  useCustomerGroups,
  useRemoveCustomersFromGroup
} from "./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 {
  useOrders
} from "./chunk-DIAWPVYS.js";
import "./chunk-4U2BLH45.js";
import "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import {
  queryClient
} from "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  fetchQuery
} from "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/customers/[id]/loader.tsx
import { getLinkQuery } from "@mercurjs/dashboard-shared";
var customerDetailQuery = (id) => {
  const query = getLinkQuery("customer", "*groups, *groups.customers");
  return {
    queryKey: customersQueryKeys.detail(id, query),
    queryFn: async () => fetchQuery(`/vendor/customers/${id}`, {
      method: "GET",
      query
    })
  };
};
var loader = async ({ params }) => {
  const id = params.id;
  const query = customerDetailQuery(id);
  return queryClient.ensureQueryData(query);
};

// src/pages/customers/[id]/customer-detail-page.tsx
import { Children } from "react";
import { useLoaderData, useParams } from "react-router-dom";
import { WidgetZone, useLinkQuery } from "@mercurjs/dashboard-shared";

// src/pages/customers/[id]/_components/customer-address-section/customer-address-section.tsx
import { Container, Heading, Text } from "@medusajs/ui";
import { DisplayExtensionZone } from "@mercurjs/dashboard-shared";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var getAddressLabel = (address) => {
  if (address.address_name) {
    return address.address_name;
  }
  const name = [address.first_name, address.last_name].filter(Boolean).join(" ");
  return name || "Address";
};
var CustomerAddressSection = ({
  customer
}) => {
  const { t: t2 } = useTranslation();
  const addresses = customer.addresses ?? [];
  return /* @__PURE__ */ jsxs(Container, { className: "divide-y p-0", "data-testid": "customer-address-section", children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        className: "flex items-center justify-between px-6 py-4",
        "data-testid": "customer-address-section-header",
        children: /* @__PURE__ */ jsx(Heading, { level: "h2", "data-testid": "customer-address-section-heading", children: t2("customers.addresses.title") })
      }
    ),
    addresses.length === 0 ? /* @__PURE__ */ jsx("div", { "data-testid": "customer-address-section-empty", children: /* @__PURE__ */ jsx(
      NoRecords,
      {
        className: "flex h-full flex-col overflow-hidden p-6",
        icon: null,
        title: t2("customers.addresses.emptyTitle"),
        message: t2("customers.addresses.emptyMessage")
      }
    ) }) : /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-2 p-3", children: addresses.map((address) => {
      const country = getCountryByIso2(address.country_code)?.display_name ?? address.country_code?.toUpperCase();
      const cityLine = [address.city, address.postal_code].filter(Boolean).join(", ");
      return /* @__PURE__ */ jsxs(
        "div",
        {
          className: "bg-ui-bg-subtle border-ui-border-base flex flex-col gap-y-1 rounded-lg border px-3 py-2",
          "data-testid": `customer-address-section-address-${address.id}`,
          children: [
            /* @__PURE__ */ jsx(Text, { size: "small", weight: "plus", leading: "compact", children: getAddressLabel(address) }),
            address.address_1 && /* @__PURE__ */ jsx(
              Text,
              {
                size: "small",
                leading: "compact",
                className: "text-ui-fg-subtle",
                children: address.address_1
              }
            ),
            address.address_2 && /* @__PURE__ */ jsx(
              Text,
              {
                size: "small",
                leading: "compact",
                className: "text-ui-fg-subtle",
                children: address.address_2
              }
            ),
            cityLine && /* @__PURE__ */ jsx(
              Text,
              {
                size: "small",
                leading: "compact",
                className: "text-ui-fg-subtle",
                children: cityLine
              }
            ),
            country && /* @__PURE__ */ jsx(
              Text,
              {
                size: "small",
                leading: "compact",
                className: "text-ui-fg-subtle",
                children: country
              }
            )
          ]
        },
        address.id
      );
    }) }),
    /* @__PURE__ */ jsx(DisplayExtensionZone, { model: "customer", zone: "addresses", data: customer })
  ] });
};

// src/pages/customers/[id]/_components/customer-general-section/customer-general-section.tsx
import { Container as Container2, Heading as Heading2, StatusBadge, Text as Text2 } from "@medusajs/ui";
import { DisplayExtensionZone as DisplayExtensionZone2, DisplayField } from "@mercurjs/dashboard-shared";
import { useTranslation as useTranslation2 } from "react-i18next";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var CustomerGeneralSection = ({
  customer
}) => {
  const { t: t2 } = useTranslation2();
  const name = [customer.first_name, customer.last_name].filter(Boolean).join(" ");
  const statusColor = customer.has_account ? "green" : "orange";
  const statusText = customer.has_account ? t2("customers.fields.registered") : t2("customers.fields.guest");
  return /* @__PURE__ */ jsxs2(Container2, { className: "divide-y p-0", children: [
    /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between px-6 py-4", children: [
      /* @__PURE__ */ jsx2(DisplayField, { model: "customer", zone: "general", id: "email", data: customer, children: /* @__PURE__ */ jsx2(Heading2, { children: customer.email }) }),
      /* @__PURE__ */ jsx2("div", { className: "flex items-center gap-x-2", children: /* @__PURE__ */ jsx2(
        DisplayField,
        {
          model: "customer",
          zone: "general",
          id: "status",
          data: customer,
          children: /* @__PURE__ */ jsx2(StatusBadge, { color: statusColor, children: statusText })
        }
      ) })
    ] }),
    /* @__PURE__ */ jsx2(DisplayField, { model: "customer", zone: "general", id: "name", data: customer, children: /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", children: [
      /* @__PURE__ */ jsx2(Text2, { size: "small", leading: "compact", weight: "plus", children: t2("fields.name") }),
      /* @__PURE__ */ jsx2(Text2, { size: "small", leading: "compact", children: name || "-" })
    ] }) }),
    /* @__PURE__ */ jsx2(
      DisplayField,
      {
        model: "customer",
        zone: "general",
        id: "company_name",
        data: customer,
        children: /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", children: [
          /* @__PURE__ */ jsx2(Text2, { size: "small", leading: "compact", weight: "plus", children: t2("fields.company") }),
          /* @__PURE__ */ jsx2(Text2, { size: "small", leading: "compact", children: customer.company_name || "-" })
        ] })
      }
    ),
    /* @__PURE__ */ jsx2(DisplayField, { model: "customer", zone: "general", id: "phone", data: customer, children: /* @__PURE__ */ jsxs2("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", children: [
      /* @__PURE__ */ jsx2(Text2, { size: "small", leading: "compact", weight: "plus", children: t2("fields.phone") }),
      /* @__PURE__ */ jsx2(Text2, { size: "small", leading: "compact", children: customer.phone || "-" })
    ] }) }),
    /* @__PURE__ */ jsx2(
      DisplayExtensionZone2,
      {
        model: "customer",
        zone: "general",
        data: customer,
        builtInFieldIds: ["email", "status", "name", "company_name", "phone"]
      }
    )
  ] });
};

// src/pages/customers/[id]/_components/customer-group-section/customer-group-section.tsx
import { DisplayExtensionZone as DisplayExtensionZone3 } from "@mercurjs/dashboard-shared";
import {
  Button,
  Checkbox,
  Container as Container3,
  Heading as Heading3,
  toast,
  usePrompt
} from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import { createColumnHelper } from "@tanstack/react-table";
import { t } from "i18next";
import { useMemo, useState } from "react";
import { PencilSquare, Trash } from "@medusajs/icons";
import { useTranslation as useTranslation3 } from "react-i18next";
import { Link } from "react-router-dom";
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var PAGE_SIZE = 10;
var PREFIX = "cusgr";
var DEFAULT_ORDER = "-created_at";
var CustomerGroupSection = ({
  customer
}) => {
  const prompt = usePrompt();
  const [rowSelection, setRowSelection] = useState({});
  const { searchParams, raw } = useCustomerGroupTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const flatCustomerGroups = customer.groups ?? [];
  const groupIds = useMemo(
    () => (customer.groups ?? []).map((g) => g.id),
    [customer.groups]
  );
  const {
    customer_groups: customerGroups = [],
    count = 0,
    isLoading,
    isError,
    error
  } = useCustomerGroups(
    {
      ...searchParams,
      id: groupIds,
      order: searchParams.order || DEFAULT_ORDER,
      fields: "id,name,created_at,updated_at,customers.id"
    },
    {
      enabled: groupIds.length > 0,
      placeholderData: keepPreviousData
    }
  );
  if (isError) {
    throw error;
  }
  const customerCountByGroup = {};
  for (const g of customerGroups) {
    customerCountByGroup[g.id] = g.customers?.length ?? 0;
  }
  const { mutateAsync: batchCustomerCustomerGroups } = useBatchCustomerCustomerGroups(customer.id);
  const filters = useCustomerGroupTableFilters();
  const columns = useColumns(customer.id, customerCountByGroup);
  const { table } = useDataTable({
    data: customerGroups,
    columns,
    count,
    getRowId: (row) => row.id,
    enablePagination: true,
    enableRowSelection: true,
    pageSize: PAGE_SIZE,
    prefix: PREFIX,
    rowSelection: {
      state: rowSelection,
      updater: setRowSelection
    }
  });
  const handleRemove = async () => {
    const selectedIds = Object.keys(rowSelection);
    const selectedGroups = flatCustomerGroups.filter(
      (g) => selectedIds.includes(g.id)
    );
    const names = selectedGroups.map((g) => g.name);
    const isSingle = selectedGroups.length === 1;
    const res = await prompt({
      title: t("customers.groups.removeTitle"),
      description: isSingle ? t("customers.groups.remove", { name: names[0] }) : t("customers.groups.removeMany", { groups: names.join(", ") }),
      confirmText: t("actions.remove"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    const customerGroupIds = selectedGroups.map((g) => g.id);
    await batchCustomerCustomerGroups(
      { remove: customerGroupIds, add: [] },
      {
        onSuccess: () => {
          toast.success(
            isSingle ? t("customers.groups.removed.successOne", { groups: names[0] }) : t("customers.groups.removed.successMany", {
              groups: names.join(", ")
            })
          );
        },
        onError: (e) => {
          toast.error(e.message);
        }
      }
    );
  };
  return /* @__PURE__ */ jsxs3(Container3, { className: "divide-y p-0", children: [
    /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-between px-6 py-4", children: [
      /* @__PURE__ */ jsx3(Heading3, { level: "h2", children: t("customerGroups.domain") }),
      /* @__PURE__ */ jsx3(Link, { to: `/customers/${customer.id}/add-customer-groups`, children: /* @__PURE__ */ jsx3(Button, { variant: "secondary", size: "small", children: t("general.add") }) })
    ] }),
    /* @__PURE__ */ jsx3(
      _DataTable,
      {
        table,
        columns,
        pageSize: PAGE_SIZE,
        isLoading,
        count,
        prefix: PREFIX,
        navigateTo: (row) => `/customer-groups/${row.original.id}`,
        filters,
        search: true,
        pagination: true,
        orderBy: [
          { key: "name", label: t("fields.name") },
          { key: "created_at", label: t("fields.createdAt") },
          { key: "updated_at", label: t("fields.updatedAt") }
        ],
        defaultOrderBy: DEFAULT_ORDER,
        commands: [
          {
            action: handleRemove,
            label: t("actions.remove"),
            shortcut: "r"
          }
        ],
        queryObject: raw,
        noRecords: {
          title: t("customers.groups.list.emptyTitle"),
          message: t("customers.groups.list.noRecordsMessage"),
          icon: null
        }
      }
    ),
    /* @__PURE__ */ jsx3(DisplayExtensionZone3, { model: "customer", zone: "groups", data: customer })
  ] });
};
var CustomerGroupRowActions = ({
  group,
  customerId
}) => {
  const prompt = usePrompt();
  const { t: t2 } = useTranslation3();
  const { mutateAsync } = useRemoveCustomersFromGroup(group.id);
  const onRemove = async () => {
    const res = await prompt({
      title: t2("customers.groups.removeTitle"),
      description: t2("customers.groups.remove", {
        name: group.name
      }),
      confirmText: t2("actions.remove"),
      cancelText: t2("actions.cancel")
    });
    if (!res) {
      return;
    }
    await mutateAsync([customerId], {
      onSuccess: () => {
        toast.success(
          t2("customers.groups.removed.successOne", { groups: group.name })
        );
      },
      onError: (error) => {
        toast.error(error.message);
      }
    });
  };
  return /* @__PURE__ */ jsx3(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              label: t2("actions.edit"),
              icon: /* @__PURE__ */ jsx3(PencilSquare, {}),
              to: `/customer-groups/${group.id}/edit`
            },
            {
              label: t2("actions.remove"),
              onClick: onRemove,
              icon: /* @__PURE__ */ jsx3(Trash, {})
            }
          ]
        }
      ]
    }
  );
};
var columnHelper = createColumnHelper();
var useColumns = (customerId, customerCountByGroup = {}) => {
  const { t: t2 } = useTranslation3();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx3(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx3(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      columnHelper.accessor("name", {
        header: () => /* @__PURE__ */ jsx3(TextHeader, { text: t2("fields.name") }),
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx3(TextCell, { text: row.original?.name || "-" });
        }
      }),
      columnHelper.display({
        id: "customers",
        header: () => /* @__PURE__ */ jsx3(TextHeader, { text: t2("customers.domain") }),
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx3(TextCell, { text: `${customerCountByGroup[row.original.id] ?? 0}` });
        }
      }),
      columnHelper.display({
        id: "actions",
        cell: ({ row }) => /* @__PURE__ */ jsx3(
          CustomerGroupRowActions,
          {
            group: row.original,
            customerId
          }
        )
      })
    ],
    [customerId, t2, customerCountByGroup]
  );
};

// src/pages/customers/[id]/_components/customer-order-section/customer-order-section.tsx
import { Container as Container4, Heading as Heading4 } from "@medusajs/ui";
import { DisplayExtensionZone as DisplayExtensionZone4 } from "@mercurjs/dashboard-shared";
import { useMemo as useMemo2 } from "react";
import { useTranslation as useTranslation4 } from "react-i18next";
import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
var PREFIX2 = "cusord";
var PAGE_SIZE2 = 10;
var DEFAULT_RELATIONS = "*customer,*items,*sales_channel";
var DEFAULT_FIELDS = "id,status,display_id,created_at,updated_at,email,fulfillment_status,payment_status,total,currency_code";
var CustomerOrderSection = ({
  customer
}) => {
  const { t: t2 } = useTranslation4();
  const { searchParams, raw } = useOrderTableQuery({
    pageSize: PAGE_SIZE2,
    prefix: PREFIX2
  });
  const { orders, count, isLoading, isError, error } = useOrders({
    fields: DEFAULT_FIELDS + "," + DEFAULT_RELATIONS,
    ...searchParams,
    customer_id: customer.id
  });
  const columns = useColumns2();
  const filters = useOrderTableFilters();
  const { table } = useDataTable({
    data: orders ?? [],
    columns,
    enablePagination: true,
    count,
    pageSize: PAGE_SIZE2,
    prefix: PREFIX2
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs4(Container4, { className: "divide-y p-0", children: [
    /* @__PURE__ */ jsx4("div", { className: "flex items-center justify-between px-6 py-4", children: /* @__PURE__ */ jsx4(Heading4, { level: "h2", children: t2("orders.domain") }) }),
    /* @__PURE__ */ jsx4(
      _DataTable,
      {
        columns,
        table,
        pagination: true,
        search: true,
        navigateTo: (row) => `/orders/${row.original.id}`,
        filters,
        count,
        isLoading,
        pageSize: PAGE_SIZE2,
        orderBy: [
          {
            key: "display_id",
            label: t2("orders.fields.displayId")
          },
          {
            key: "created_at",
            label: t2("fields.createdAt")
          },
          {
            key: "updated_at",
            label: t2("fields.updatedAt")
          }
        ],
        defaultOrderBy: "-display_id",
        queryObject: raw,
        prefix: PREFIX2
      }
    ),
    /* @__PURE__ */ jsx4(DisplayExtensionZone4, { model: "customer", zone: "orders", data: customer })
  ] });
};
var useColumns2 = () => {
  const base = useOrderTableColumns({
    exclude: ["customer"]
  });
  return useMemo2(() => [...base], [base]);
};

// src/pages/customers/[id]/customer-detail-page.tsx
import { Fragment, jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
var Root = ({ children }) => {
  const { id } = useParams();
  const initialData = useLoaderData();
  const query = useLinkQuery("customer", "*groups, *groups.customers");
  const { customer, isLoading, isError, error } = useCustomer(id, query, {
    initialData
  });
  if (isLoading || !customer) {
    return /* @__PURE__ */ jsx5(TwoColumnPageSkeleton, { mainSections: 3, sidebarSections: 1 });
  }
  if (isError) throw error;
  return /* @__PURE__ */ jsx5(Fragment, { children: Children.count(children) > 0 ? children : /* @__PURE__ */ jsxs5(TwoColumnPage, { data: customer, showJSON: true, hasOutlet: true, children: [
    /* @__PURE__ */ jsx5(TwoColumnPage.Main, { children: /* @__PURE__ */ jsxs5(WidgetZone, { id: "customers.detail.main", data: customer, children: [
      /* @__PURE__ */ jsx5(CustomerGeneralSection, { customer }),
      /* @__PURE__ */ jsx5(CustomerOrderSection, { customer }),
      /* @__PURE__ */ jsx5(CustomerGroupSection, { customer })
    ] }) }),
    /* @__PURE__ */ jsx5(TwoColumnPage.Sidebar, { children: /* @__PURE__ */ jsx5(WidgetZone, { id: "customers.detail.side", data: customer, children: /* @__PURE__ */ jsx5(CustomerAddressSection, { customer }) }) })
  ] }) });
};
var CustomerDetailPage = Object.assign(Root, {
  Main: TwoColumnPage.Main,
  Sidebar: TwoColumnPage.Sidebar,
  GeneralSection: CustomerGeneralSection,
  OrderSection: CustomerOrderSection,
  GroupSection: CustomerGroupSection,
  AddressSection: CustomerAddressSection
});
export {
  CustomerDetailPage,
  loader
};
