import {
  CAMPAIGN_DETAIL_FIELDS
} from "./chunk-WQZ4ONQV.js";
import {
  DateRangeDisplay
} from "./chunk-BWGPN6XV.js";
import {
  usePromotionTableColumns,
  usePromotionTableQuery
} from "./chunk-DSNCEHLY.js";
import "./chunk-S5KWI3MM.js";
import "./chunk-JHIMVLB2.js";
import {
  usePromotionTableFilters
} from "./chunk-S2WEYEQR.js";
import "./chunk-FMFVTERD.js";
import "./chunk-DB6ANJBO.js";
import "./chunk-PHOCVOZ5.js";
import {
  currencies
} from "./chunk-IQPN4PZJ.js";
import "./chunk-ZZ4JC4WE.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 "./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 {
  campaignsQueryKeys,
  promotionsQueryKeys,
  useCampaign,
  useDeleteCampaign,
  useRemovePromotionFromCampaign
} from "./chunk-MR6REQKT.js";
import {
  queryClient
} from "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  fetchQuery
} from "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

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

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

// src/pages/campaigns/[id]/_components/campaign-budget/campaign-budget.tsx
import { ChartPie, PencilSquare } from "@medusajs/icons";
import { Container, Heading, Text } from "@medusajs/ui";
import { Trans, useTranslation } from "react-i18next";
import { DisplayExtensionZone } from "@mercurjs/dashboard-shared";
import { jsx, jsxs } from "react/jsx-runtime";
var CampaignBudget = ({ campaign }) => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsxs(Container, { className: "flex flex-col gap-y-4 px-6 py-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex-grow", children: [
        /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-base shadow-borders-base float-left flex size-7 items-center justify-center rounded-md", children: /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-component flex size-6 items-center justify-center rounded-[4px]", children: /* @__PURE__ */ jsx(ChartPie, { className: "text-ui-fg-subtle" }) }) }),
        /* @__PURE__ */ jsx(
          Heading,
          {
            className: "text-ui-fg-subtle ml-10 mt-[1.5px] font-normal",
            level: "h3",
            children: t("campaigns.fields.budget_limit")
          }
        )
      ] }),
      /* @__PURE__ */ jsx(
        ActionMenu,
        {
          groups: [
            {
              actions: [
                {
                  icon: /* @__PURE__ */ jsx(PencilSquare, {}),
                  label: t("actions.edit"),
                  to: `edit-budget`
                }
              ]
            }
          ]
        }
      )
    ] }),
    /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(
      Text,
      {
        className: "text-ui-fg-subtle border-ui-border-strong border-l-4 pl-3",
        size: "small",
        leading: "compact",
        children: /* @__PURE__ */ jsx(
          Trans,
          {
            i18nKey: "campaigns.totalSpend",
            values: {
              amount: campaign?.budget?.limit || "no limit",
              currency: campaign?.budget?.type === "spend" && campaign?.budget.limit ? campaign.budget?.currency_code : ""
            },
            components: [
              /* @__PURE__ */ jsx(
                "span",
                {
                  className: "text-ui-fg-base txt-compact-medium-plus text-lg"
                },
                "amount"
              ),
              /* @__PURE__ */ jsx(
                "span",
                {
                  className: "text-ui-fg-base txt-compact-medium-plus text-lg"
                },
                "currency"
              )
            ]
          }
        )
      }
    ) }),
    /* @__PURE__ */ jsx(DisplayExtensionZone, { model: "campaign", zone: "budget", data: campaign })
  ] });
};

// src/pages/campaigns/[id]/_components/campaign-configuration-section/campaign-configuration-section.tsx
import { Container as Container2, Heading as Heading2 } from "@medusajs/ui";
import { PencilSquare as PencilSquare2 } from "@medusajs/icons";
import { useTranslation as useTranslation2 } from "react-i18next";
import { DisplayExtensionZone as DisplayExtensionZone2 } from "@mercurjs/dashboard-shared";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var CampaignConfigurationSection = ({
  campaign
}) => {
  const { t } = useTranslation2();
  return /* @__PURE__ */ jsxs2(Container2, { className: "flex flex-col gap-y-4", children: [
    /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsx2(Heading2, { level: "h2", children: t("campaigns.configuration.header") }),
      /* @__PURE__ */ jsx2(
        ActionMenu,
        {
          groups: [
            {
              actions: [
                {
                  label: t("actions.edit"),
                  icon: /* @__PURE__ */ jsx2(PencilSquare2, {}),
                  to: "configuration"
                }
              ]
            }
          ]
        }
      )
    ] }),
    /* @__PURE__ */ jsx2(
      DateRangeDisplay,
      {
        startsAt: campaign.starts_at,
        endsAt: campaign.ends_at,
        showTime: true
      }
    ),
    /* @__PURE__ */ jsx2(
      DisplayExtensionZone2,
      {
        model: "campaign",
        zone: "configuration",
        data: campaign
      }
    )
  ] });
};

// src/pages/campaigns/[id]/_components/campaign-general-section/campaign-general-section.tsx
import { PencilSquare as PencilSquare3, Trash } from "@medusajs/icons";
import {
  Badge,
  Container as Container3,
  Heading as Heading3,
  StatusBadge,
  Text as Text2,
  toast,
  usePrompt
} from "@medusajs/ui";
import { useTranslation as useTranslation3 } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { DisplayExtensionZone as DisplayExtensionZone3, DisplayField } from "@mercurjs/dashboard-shared";

// src/pages/campaigns/common/utils/campaign-status.ts
import { isAfter, isBefore } from "date-fns";
function campaignStatus(campaign) {
  if (campaign.ends_at) {
    if (isBefore(new Date(campaign.ends_at), /* @__PURE__ */ new Date())) {
      return "expired";
    }
  }
  if (campaign.starts_at) {
    if (isAfter(new Date(campaign.starts_at), /* @__PURE__ */ new Date())) {
      return "scheduled";
    }
  }
  return "active";
}
var statusColor = (status) => {
  switch (status) {
    case "expired":
      return "red";
    case "scheduled":
      return "orange";
    case "active":
      return "green";
    default:
      return "grey";
  }
};

// src/pages/campaigns/[id]/_components/campaign-general-section/campaign-general-section.tsx
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
var CampaignGeneralSection = ({
  campaign
}) => {
  const { t } = useTranslation3();
  const prompt = usePrompt();
  const navigate = useNavigate();
  const { mutateAsync } = useDeleteCampaign(campaign.id);
  const handleDelete = async () => {
    const res = await prompt({
      title: t("campaigns.delete.title"),
      description: t("campaigns.delete.description", {
        name: campaign.name
      }),
      confirmText: t("actions.delete"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await mutateAsync(void 0, {
      onSuccess: () => {
        toast.success(
          t("campaigns.delete.successToast", {
            name: campaign.name
          })
        );
        navigate("/campaigns", { replace: true });
      },
      onError: (error) => {
        toast.error(error.message);
      }
    });
  };
  const status = campaignStatus(campaign);
  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(DisplayField, { model: "campaign", zone: "general", id: "name", data: campaign, children: /* @__PURE__ */ jsx3(Heading3, { children: campaign.name }) }),
      /* @__PURE__ */ jsxs3("div", { className: "flex items-center gap-x-4", children: [
        /* @__PURE__ */ jsx3(
          DisplayField,
          {
            model: "campaign",
            zone: "general",
            id: "status",
            data: campaign,
            children: /* @__PURE__ */ jsx3(StatusBadge, { color: statusColor(status), children: t(`campaigns.status.${status}`) })
          }
        ),
        /* @__PURE__ */ jsx3(
          ActionMenu,
          {
            groups: [
              {
                actions: [
                  {
                    icon: /* @__PURE__ */ jsx3(PencilSquare3, {}),
                    label: t("actions.edit"),
                    to: `/campaigns/${campaign.id}/edit`
                  }
                ]
              },
              {
                actions: [
                  {
                    icon: /* @__PURE__ */ jsx3(Trash, {}),
                    label: t("actions.delete"),
                    onClick: handleDelete
                  }
                ]
              }
            ]
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsx3(
      DisplayField,
      {
        model: "campaign",
        zone: "general",
        id: "campaign_identifier",
        data: campaign,
        children: /* @__PURE__ */ jsxs3("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", children: [
          /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", weight: "plus", children: t("campaigns.fields.identifier") }),
          /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", children: campaign.campaign_identifier })
        ] })
      }
    ),
    /* @__PURE__ */ jsx3(
      DisplayField,
      {
        model: "campaign",
        zone: "general",
        id: "description",
        data: campaign,
        children: /* @__PURE__ */ jsxs3("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", children: [
          /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", weight: "plus", children: t("fields.description") }),
          /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", children: campaign.description || "-" })
        ] })
      }
    ),
    campaign?.budget && campaign.budget.type === "spend" && /* @__PURE__ */ jsx3(
      DisplayField,
      {
        model: "campaign",
        zone: "general",
        id: "currency_code",
        data: campaign,
        children: /* @__PURE__ */ jsxs3("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", children: [
          /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", weight: "plus", children: t("fields.currency") }),
          /* @__PURE__ */ jsxs3("div", { children: [
            /* @__PURE__ */ jsx3(Badge, { size: "xsmall", children: campaign?.budget.currency_code }),
            /* @__PURE__ */ jsx3(Text2, { className: "inline pl-3", size: "small", leading: "compact", children: currencies[campaign?.budget.currency_code?.toUpperCase()]?.name })
          ] })
        ] })
      }
    ),
    /* @__PURE__ */ jsx3(
      DisplayExtensionZone3,
      {
        model: "campaign",
        zone: "general",
        data: campaign,
        builtInFieldIds: [
          "name",
          "status",
          "campaign_identifier",
          "description",
          "currency_code"
        ]
      }
    )
  ] });
};

// src/pages/campaigns/[id]/_components/campaign-promotion-section/campaign-promotion-section.tsx
import { PencilSquare as PencilSquare4, Trash as Trash2 } from "@medusajs/icons";
import { Button, Checkbox, Container as Container4, Heading as Heading4, usePrompt as usePrompt2 } from "@medusajs/ui";
import { createColumnHelper } from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { useTranslation as useTranslation4 } from "react-i18next";
import { Link } from "react-router-dom";
import { DisplayExtensionZone as DisplayExtensionZone4 } from "@mercurjs/dashboard-shared";
import { jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
var PAGE_SIZE = 10;
var CampaignPromotionSection = ({
  campaign
}) => {
  const [rowSelection, setRowSelection] = useState({});
  const { t } = useTranslation4();
  const prompt = usePrompt2();
  const columns = useColumns();
  const filters = usePromotionTableFilters();
  const { raw } = usePromotionTableQuery({
    pageSize: PAGE_SIZE
  });
  const promotions = campaign.promotions;
  const count = promotions?.length ?? 0;
  const { table } = useDataTable({
    data: promotions ?? [],
    columns,
    count,
    getRowId: (row) => row.id,
    enablePagination: true,
    enableRowSelection: true,
    pageSize: PAGE_SIZE,
    rowSelection: {
      state: rowSelection,
      updater: setRowSelection
    },
    meta: { campaignId: campaign.id }
  });
  const handleRemove = async () => {
    const keys = Object.keys(rowSelection);
    const res = await prompt({
      title: t("campaigns.promotions.remove.title", {
        count: keys.length
      }),
      description: t("campaigns.promotions.remove.description", {
        count: keys.length
      }),
      confirmText: t("actions.continue"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await Promise.all(
      keys.map(
        (promotionId) => fetchQuery(`/vendor/promotions/${promotionId}`, {
          method: "POST",
          body: { campaign_id: null }
        })
      )
    );
    queryClient.invalidateQueries({
      queryKey: campaignsQueryKeys.details()
    });
    queryClient.invalidateQueries({
      queryKey: promotionsQueryKeys.all
    });
    setRowSelection({});
  };
  return /* @__PURE__ */ jsxs4(Container4, { className: "divide-y p-0", children: [
    /* @__PURE__ */ jsxs4("div", { className: "flex items-center justify-between px-6 py-4", children: [
      /* @__PURE__ */ jsx4(Heading4, { level: "h2", children: t("promotions.domain") }),
      /* @__PURE__ */ jsx4(Link, { to: `/campaigns/${campaign.id}/add-promotions`, children: /* @__PURE__ */ jsx4(Button, { variant: "secondary", size: "small", children: t("general.add") }) })
    ] }),
    /* @__PURE__ */ jsx4(
      _DataTable,
      {
        table,
        columns,
        pageSize: PAGE_SIZE,
        isLoading: false,
        count,
        navigateTo: (row) => `/promotions/${row.id}`,
        filters,
        search: true,
        pagination: true,
        orderBy: [
          { key: "code", label: t("fields.code") },
          { key: "type", label: t("fields.type") },
          {
            key: "created_at",
            label: t("fields.createdAt")
          },
          {
            key: "updated_at",
            label: t("fields.updatedAt")
          }
        ],
        queryObject: raw,
        commands: [
          {
            action: handleRemove,
            label: t("actions.remove"),
            shortcut: "r"
          }
        ],
        noRecords: {
          message: t("campaigns.promotions.list.noRecordsMessage")
        }
      }
    ),
    /* @__PURE__ */ jsx4(
      DisplayExtensionZone4,
      {
        model: "campaign",
        zone: "promotions",
        data: campaign
      }
    )
  ] });
};
var PromotionActions = ({ promotion }) => {
  const { t } = useTranslation4();
  const { mutateAsync } = useRemovePromotionFromCampaign(promotion.id);
  const prompt = usePrompt2();
  const handleRemove = async () => {
    const res = await prompt({
      title: t("campaigns.promotions.remove.title", {
        count: 1
      }),
      description: t("campaigns.promotions.remove.description", {
        count: 1
      }),
      confirmText: t("actions.continue"),
      cancelText: t("actions.cancel")
    });
    if (!res) {
      return;
    }
    await mutateAsync();
  };
  return /* @__PURE__ */ jsx4(
    ActionMenu,
    {
      groups: [
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx4(PencilSquare4, {}),
              label: t("actions.edit"),
              to: `/promotions/${promotion.id}/edit`
            }
          ]
        },
        {
          actions: [
            {
              icon: /* @__PURE__ */ jsx4(Trash2, {}),
              label: t("actions.remove"),
              onClick: handleRemove
            }
          ]
        }
      ]
    }
  );
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const columns = usePromotionTableColumns();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx4(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx4(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      ...columns,
      columnHelper.display({
        id: "actions",
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx4(PromotionActions, { promotion: row.original });
        }
      })
    ],
    [columns]
  );
};

// src/pages/campaigns/[id]/_components/campaign-spend/campaign-spend.tsx
import { CurrencyDollar } from "@medusajs/icons";
import { Container as Container5, Heading as Heading5, Text as Text3 } from "@medusajs/ui";
import { Trans as Trans2, useTranslation as useTranslation5 } from "react-i18next";
import { DisplayExtensionZone as DisplayExtensionZone5 } from "@mercurjs/dashboard-shared";
import { jsx as jsx5, jsxs as jsxs5 } from "react/jsx-runtime";
var CampaignSpend = ({ campaign }) => {
  const { t } = useTranslation5();
  return /* @__PURE__ */ jsxs5(Container5, { className: "flex flex-col gap-y-4 px-6 py-4", children: [
    /* @__PURE__ */ jsxs5("div", { className: "mb-2 grid grid-cols-[28px_1fr] items-center gap-x-3", children: [
      /* @__PURE__ */ jsx5("div", { className: "bg-ui-bg-base shadow-borders-base flex size-7 items-center justify-center rounded-md", children: /* @__PURE__ */ jsx5("div", { className: "bg-ui-bg-component flex size-6 items-center justify-center rounded-[4px]", children: /* @__PURE__ */ jsx5(CurrencyDollar, { className: "text-ui-fg-subtle" }) }) }),
      /* @__PURE__ */ jsx5(Heading5, { level: "h3", className: "text-ui-fg-subtle font-normal", children: campaign.budget?.type === "spend" ? t("campaigns.fields.total_spend") : t("campaigns.fields.total_used") })
    ] }),
    /* @__PURE__ */ jsx5("div", { children: /* @__PURE__ */ jsx5(
      Text3,
      {
        className: "text-ui-fg-subtle border-ui-border-strong border-l-4 pl-3",
        size: "small",
        leading: "compact",
        children: /* @__PURE__ */ jsx5(
          Trans2,
          {
            i18nKey: "campaigns.totalSpend",
            values: {
              amount: campaign?.budget?.used || 0,
              currency: campaign?.budget?.type === "spend" ? campaign?.budget?.currency_code : ""
            },
            components: [
              /* @__PURE__ */ jsx5(
                "span",
                {
                  className: "text-ui-fg-base txt-compact-medium-plus text-lg"
                },
                "amount"
              ),
              /* @__PURE__ */ jsx5(
                "span",
                {
                  className: "text-ui-fg-base txt-compact-medium-plus text-lg"
                },
                "currency"
              )
            ]
          }
        )
      }
    ) }),
    /* @__PURE__ */ jsx5(DisplayExtensionZone5, { model: "campaign", zone: "spend", data: campaign })
  ] });
};

// src/pages/campaigns/[id]/campaign-detail-page.tsx
import { Fragment, jsx as jsx6, jsxs as jsxs6 } from "react/jsx-runtime";
var Root = ({ children }) => {
  const initialData = useLoaderData();
  const { id } = useParams();
  const { searchParams } = usePromotionTableQuery({});
  const linkQuery = useLinkQuery("campaign", CAMPAIGN_DETAIL_FIELDS);
  const { campaign, isLoading, isError, error } = useCampaign(
    id,
    { ...searchParams, ...linkQuery },
    {
      placeholderData: initialData
    }
  );
  if (isLoading || !campaign) {
    return /* @__PURE__ */ jsx6(TwoColumnPageSkeleton, { mainSections: 2, sidebarSections: 3 });
  }
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx6(Fragment, { children: Children.count(children) > 0 ? children : /* @__PURE__ */ jsxs6(TwoColumnPage, { hasOutlet: true, data: campaign, children: [
    /* @__PURE__ */ jsx6(TwoColumnPage.Main, { children: /* @__PURE__ */ jsxs6(WidgetZone, { id: "campaigns.detail.main", data: campaign, children: [
      /* @__PURE__ */ jsx6(CampaignGeneralSection, { campaign }),
      /* @__PURE__ */ jsx6(CampaignPromotionSection, { campaign })
    ] }) }),
    /* @__PURE__ */ jsx6(TwoColumnPage.Sidebar, { children: /* @__PURE__ */ jsxs6(WidgetZone, { id: "campaigns.detail.side", data: campaign, children: [
      /* @__PURE__ */ jsx6(CampaignConfigurationSection, { campaign }),
      /* @__PURE__ */ jsx6(CampaignSpend, { campaign }),
      /* @__PURE__ */ jsx6(CampaignBudget, { campaign })
    ] }) })
  ] }) });
};
var CampaignDetailPage = Object.assign(Root, {
  Main: TwoColumnPage.Main,
  Sidebar: TwoColumnPage.Sidebar,
  MainGeneralSection: CampaignGeneralSection,
  MainPromotionSection: CampaignPromotionSection,
  SidebarConfigurationSection: CampaignConfigurationSection,
  SidebarSpend: CampaignSpend,
  SidebarBudget: CampaignBudget
});
export {
  CampaignDetailPage,
  loader
};
