import {
  usePromotionTableColumns,
  usePromotionTableQuery
} from "./chunk-UYKWOC5A.js";
import {
  DateRangeDisplay
} from "./chunk-RK5N3XIX.js";
import {
  TwoColumnPage
} from "./chunk-V5J73NPW.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-ULJ3OMWU.js";
import {
  currencies
} from "./chunk-IQPN4PZJ.js";
import {
  TwoColumnPageSkeleton
} from "./chunk-INNFZYX2.js";
import {
  ActionMenu
} from "./chunk-BDGZ4EQO.js";
import {
  usePromotionTableFilters
} from "./chunk-S2WEYEQR.js";
import {
  useAddOrRemoveCampaignPromotions,
  useCampaign,
  useDeleteCampaign,
  usePromotions
} from "./chunk-HAFZQK53.js";

// src/pages/campaigns/campaign-detail/campaign-detail.tsx
import { Children } from "react";
import { useLoaderData, useParams } from "react-router-dom";

// src/pages/campaigns/campaign-detail/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 { 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", "data-testid": "campaign-budget-container", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex justify-between", "data-testid": "campaign-budget-header", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex-grow", children: [
        /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-base shadow-borders-base float-start flex size-7 items-center justify-center rounded-md", "data-testid": "campaign-budget-icon-container", 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 ms-10 mt-[1.5px] font-normal",
            level: "h3",
            "data-testid": "campaign-budget-heading",
            children: campaign.budget?.type === "use_by_attribute" ? t("campaigns.budget.fields.totalUsedByAttribute", {
              attribute: campaign.budget?.attribute
            }) : t("campaigns.fields.budget_limit")
          }
        )
      ] }),
      /* @__PURE__ */ jsx(
        ActionMenu,
        {
          groups: [
            {
              actions: [
                {
                  icon: /* @__PURE__ */ jsx(PencilSquare, {}),
                  label: t("actions.edit"),
                  to: `edit-budget`
                }
              ]
            }
          ],
          "data-testid": "campaign-budget-action-menu"
        }
      )
    ] }),
    /* @__PURE__ */ jsx("div", { "data-testid": "campaign-budget-limit", children: /* @__PURE__ */ jsx(
      Text,
      {
        className: "text-ui-fg-subtle border-ui-border-strong border-l-4 ps-3",
        size: "small",
        leading: "compact",
        "data-testid": "campaign-budget-limit-text",
        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",
                  "data-testid": "campaign-budget-limit-amount"
                },
                "amount"
              ),
              /* @__PURE__ */ jsx(
                "span",
                {
                  className: "text-ui-fg-base txt-compact-medium-plus text-lg",
                  "data-testid": "campaign-budget-limit-currency"
                },
                "currency"
              )
            ]
          }
        )
      }
    ) })
  ] });
};

// src/pages/campaigns/campaign-detail/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 { 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", "data-testid": "campaign-configuration-section-container", children: [
    /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between", "data-testid": "campaign-configuration-section-header", children: [
      /* @__PURE__ */ jsx2(Heading2, { level: "h2", "data-testid": "campaign-configuration-section-heading", children: t("campaigns.configuration.header") }),
      /* @__PURE__ */ jsx2(
        ActionMenu,
        {
          groups: [
            {
              actions: [
                {
                  label: t("actions.edit"),
                  icon: /* @__PURE__ */ jsx2(PencilSquare2, {}),
                  to: "configuration"
                }
              ]
            }
          ],
          "data-testid": "campaign-configuration-section-action-menu"
        }
      )
    ] }),
    /* @__PURE__ */ jsx2(
      DateRangeDisplay,
      {
        startsAt: campaign.starts_at,
        endsAt: campaign.ends_at,
        showTime: true,
        "data-testid": "campaign-configuration-section-date-range"
      }
    )
  ] });
};

// src/pages/campaigns/campaign-detail/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";

// 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/campaign-detail/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", "data-testid": "campaign-general-section-container", children: [
    /* @__PURE__ */ jsxs3("div", { className: "flex items-center justify-between px-6 py-4", "data-testid": "campaign-general-section-header", children: [
      /* @__PURE__ */ jsx3(Heading3, { "data-testid": "campaign-general-section-name", children: campaign.name }),
      /* @__PURE__ */ jsxs3("div", { className: "flex items-center gap-x-4", children: [
        /* @__PURE__ */ jsx3(StatusBadge, { color: statusColor(status), "data-testid": "campaign-general-section-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
                  }
                ]
              }
            ],
            "data-testid": "campaign-general-section-action-menu"
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ jsxs3("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": "campaign-general-section-identifier", children: [
      /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", weight: "plus", "data-testid": "campaign-general-section-identifier-label", children: t("campaigns.fields.identifier") }),
      /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", "data-testid": "campaign-general-section-identifier-value", children: campaign.campaign_identifier })
    ] }),
    /* @__PURE__ */ jsxs3("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": "campaign-general-section-description", children: [
      /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", weight: "plus", "data-testid": "campaign-general-section-description-label", children: t("fields.description") }),
      /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", "data-testid": "campaign-general-section-description-value", children: campaign.description || "-" })
    ] }),
    campaign?.budget && campaign.budget.type === "spend" && /* @__PURE__ */ jsxs3("div", { className: "text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4", "data-testid": "campaign-general-section-currency", children: [
      /* @__PURE__ */ jsx3(Text2, { size: "small", leading: "compact", weight: "plus", "data-testid": "campaign-general-section-currency-label", children: t("fields.currency") }),
      /* @__PURE__ */ jsxs3("div", { "data-testid": "campaign-general-section-currency-value", children: [
        /* @__PURE__ */ jsx3(Badge, { size: "xsmall", "data-testid": "campaign-general-section-currency-badge", children: campaign?.budget.currency_code }),
        /* @__PURE__ */ jsx3(Text2, { className: "inline pl-3", size: "small", leading: "compact", "data-testid": "campaign-general-section-currency-name", children: currencies[campaign?.budget.currency_code?.toUpperCase()]?.name })
      ] })
    ] })
  ] });
};

// src/pages/campaigns/campaign-detail/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 { 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 { searchParams, raw } = usePromotionTableQuery({ pageSize: PAGE_SIZE });
  const { promotions, count, isLoading, isError, error } = usePromotions({
    ...searchParams,
    campaign_id: campaign.id
  });
  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 }
  });
  if (isError) {
    throw error;
  }
  const { mutateAsync } = useAddOrRemoveCampaignPromotions(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 mutateAsync(
      { remove: keys },
      { onSuccess: () => setRowSelection({}) }
    );
  };
  return /* @__PURE__ */ jsxs4(Container4, { className: "divide-y p-0", "data-testid": "campaign-promotion-section-container", children: [
    /* @__PURE__ */ jsxs4("div", { className: "flex items-center justify-between px-6 py-4", "data-testid": "campaign-promotion-section-header", children: [
      /* @__PURE__ */ jsx4(Heading4, { level: "h2", "data-testid": "campaign-promotion-section-heading", children: t("promotions.domain") }),
      /* @__PURE__ */ jsx4(Link, { to: `/campaigns/${campaign.id}/add-promotions`, children: /* @__PURE__ */ jsx4(Button, { variant: "secondary", size: "small", "data-testid": "campaign-promotion-section-add-button", children: t("general.add") }) })
    ] }),
    /* @__PURE__ */ jsx4(
      _DataTable,
      {
        table,
        columns,
        pageSize: PAGE_SIZE,
        isLoading,
        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")
        },
        "data-testid": "campaign-promotion-section-table"
      }
    )
  ] });
};
var PromotionActions = ({
  promotion,
  campaignId
}) => {
  const { t } = useTranslation4();
  const { mutateAsync } = useAddOrRemoveCampaignPromotions(campaignId);
  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({
      remove: [promotion.id]
    });
  };
  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
            }
          ]
        }
      ],
      "data-testid": `campaign-promotion-section-action-menu-${promotion.id}`
    }
  );
};
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),
              "data-testid": "campaign-promotion-section-select-all-checkbox"
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx4(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              },
              "data-testid": `campaign-promotion-section-select-checkbox-${row.original.id}`
            }
          );
        }
      }),
      ...columns,
      columnHelper.display({
        id: "actions",
        cell: ({ row, table }) => {
          const { campaignId } = table.options.meta;
          return /* @__PURE__ */ jsx4(
            PromotionActions,
            {
              promotion: row.original,
              campaignId
            }
          );
        }
      })
    ],
    [columns]
  );
};

// src/pages/campaigns/campaign-detail/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 { 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", "data-testid": "campaign-spend-container", children: [
    /* @__PURE__ */ jsxs5("div", { className: "mb-2 grid grid-cols-[28px_1fr] items-center gap-x-3", "data-testid": "campaign-spend-header", children: [
      /* @__PURE__ */ jsx5("div", { className: "bg-ui-bg-base shadow-borders-base flex size-7 items-center justify-center rounded-md", "data-testid": "campaign-spend-icon-container", 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", "data-testid": "campaign-spend-heading", children: campaign.budget?.type === "use_by_attribute" ? t("campaigns.fields.totalUsedByAttribute") : campaign.budget?.type === "spend" ? t("campaigns.fields.total_spend") : t("campaigns.fields.total_used") })
    ] }),
    /* @__PURE__ */ jsx5("div", { "data-testid": "campaign-spend-value", children: /* @__PURE__ */ jsx5(
      Text3,
      {
        className: "text-ui-fg-subtle border-ui-border-strong border-l-4 pl-3",
        size: "small",
        leading: "compact",
        "data-testid": "campaign-spend-value-text",
        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",
                  "data-testid": "campaign-spend-value-amount"
                },
                "amount"
              ),
              /* @__PURE__ */ jsx5(
                "span",
                {
                  className: "text-ui-fg-base txt-compact-medium-plus text-lg",
                  "data-testid": "campaign-spend-value-currency"
                },
                "currency"
              )
            ]
          }
        )
      }
    ) })
  ] });
};

// src/pages/campaigns/campaign-detail/constants.ts
var CAMPAIGN_DETAIL_FIELDS = "+promotions.id";

// src/pages/campaigns/campaign-detail/campaign-detail.tsx
import { jsx as jsx6, jsxs as jsxs6 } from "react/jsx-runtime";
var Root = ({ children }) => {
  const initialData = useLoaderData();
  const { id } = useParams();
  const { campaign, isLoading, isError, error } = useCampaign(
    id,
    { fields: CAMPAIGN_DETAIL_FIELDS },
    { initialData }
  );
  if (isLoading || !campaign) {
    return /* @__PURE__ */ jsx6(
      TwoColumnPageSkeleton,
      {
        mainSections: 2,
        sidebarSections: 3,
        showJSON: true,
        showMetadata: true
      }
    );
  }
  if (isError) {
    throw error;
  }
  return Children.count(children) > 0 ? /* @__PURE__ */ jsx6(TwoColumnPage, { hasOutlet: true, showJSON: true, showMetadata: true, data: campaign, "data-testid": "campaign-detail-page", children }) : /* @__PURE__ */ jsxs6(TwoColumnPage, { hasOutlet: true, showJSON: true, showMetadata: true, data: campaign, "data-testid": "campaign-detail-page", children: [
    /* @__PURE__ */ jsxs6(TwoColumnPage.Main, { children: [
      /* @__PURE__ */ jsx6(CampaignGeneralSection, { campaign }),
      /* @__PURE__ */ jsx6(CampaignPromotionSection, { campaign })
    ] }),
    /* @__PURE__ */ jsxs6(TwoColumnPage.Sidebar, { 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,
  SidebarSpendSection: CampaignSpend,
  SidebarBudgetSection: CampaignBudget
});

export {
  CAMPAIGN_DETAIL_FIELDS,
  CampaignDetailPage
};
