import {
  DisplayIdCell,
  TotalCell
} from "./chunk-WG7UTTKY.mjs";
import {
  DateCell
} from "./chunk-EJWRAUTW.mjs";
import {
  getOrderFulfillmentStatus,
  getOrderPaymentStatus
} from "./chunk-NTEWUH4C.mjs";
import {
  MoneyAmountCell
} from "./chunk-INE2QCSC.mjs";
import {
  CollectionCell,
  ProductStatusCell,
  SalesChannelsCell,
  VariantCell
} from "./chunk-ZU3LA52A.mjs";
import {
  ProductCell
} from "./chunk-IQBAUTU5.mjs";
import {
  DataTable,
  SaveViewDialog,
  useViewConfiguration,
  useViewConfigurations
} from "./chunk-LIG5YESF.mjs";
import {
  useQueryParams
} from "./chunk-C76H5USB.mjs";
import {
  getCountryByIso2
} from "./chunk-DG7J63J2.mjs";
import {
  useFeatureFlag
} from "./chunk-G4BWCU5P.mjs";
import {
  useEntityColumns
} from "./chunk-3BF5SC66.mjs";

// src/components/table/configurable-data-table/configurable-data-table.tsx
import { useState as useState3 } from "react";
import { Container, Button as Button2 } from "@medusajs/ui";
import { useTranslation as useTranslation3 } from "react-i18next";

// src/components/table/configurable-data-table/save-view-dropdown.tsx
import { Button, DropdownMenu, usePrompt } from "@medusajs/ui";
import { ChevronDownMini } from "@medusajs/icons";
import { useTranslation } from "react-i18next";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var SaveViewDropdown = ({
  isDefaultView,
  currentViewId,
  currentViewName,
  onSaveAsDefault,
  onUpdateExisting,
  onSaveAsNew
}) => {
  const { t } = useTranslation();
  const prompt = usePrompt();
  const handleSaveAsDefault = async () => {
    const result = await prompt({
      title: t("views.prompts.updateDefault.title"),
      description: t("views.prompts.updateDefault.description"),
      confirmText: t("views.prompts.updateDefault.confirmText"),
      cancelText: t("views.prompts.updateDefault.cancelText")
    });
    if (result) {
      onSaveAsDefault();
    }
  };
  const handleUpdateExisting = async () => {
    const result = await prompt({
      title: t("views.prompts.updateView.title"),
      description: t("views.prompts.updateView.description", { name: currentViewName }),
      confirmText: t("views.prompts.updateView.confirmText"),
      cancelText: t("views.prompts.updateView.cancelText")
    });
    if (result) {
      onUpdateExisting();
    }
  };
  return /* @__PURE__ */ jsxs(DropdownMenu, { children: [
    /* @__PURE__ */ jsx(DropdownMenu.Trigger, { asChild: true, children: /* @__PURE__ */ jsxs(
      Button,
      {
        variant: "secondary",
        size: "small",
        type: "button",
        children: [
          t("views.save"),
          /* @__PURE__ */ jsx(ChevronDownMini, {})
        ]
      }
    ) }),
    /* @__PURE__ */ jsx(DropdownMenu.Content, { align: "end", children: isDefaultView ? /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(DropdownMenu.Item, { onClick: handleSaveAsDefault, children: t("views.updateDefaultForEveryone") }),
      /* @__PURE__ */ jsx(DropdownMenu.Item, { onClick: onSaveAsNew, children: t("views.saveAsNew") })
    ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(DropdownMenu.Item, { onClick: handleUpdateExisting, children: t("views.updateViewName") }),
      /* @__PURE__ */ jsx(DropdownMenu.Item, { onClick: onSaveAsNew, children: t("views.saveAsNew") })
    ] }) })
  ] });
};

// src/hooks/table/use-table-configuration.tsx
import { useState as useState2, useMemo as useMemo2, useCallback as useCallback2, useEffect as useEffect2 } from "react";
import { useSearchParams } from "react-router-dom";

// src/hooks/table/columns/use-column-state.ts
import { useState, useCallback, useMemo, useEffect, useRef } from "react";
function useColumnState(apiColumns, activeView) {
  const [visibleColumns, setVisibleColumns] = useState(
    () => {
      if (apiColumns?.length && activeView?.configuration) {
        const visibility = {};
        apiColumns.forEach((column) => {
          visibility[column.field] = activeView.configuration.visible_columns?.includes(column.field) || false;
        });
        return visibility;
      } else if (apiColumns?.length) {
        return getInitialColumnVisibility(apiColumns);
      }
      return {};
    }
  );
  const [columnOrder, setColumnOrder] = useState(() => {
    if (activeView?.configuration?.column_order) {
      return activeView.configuration.column_order;
    } else if (apiColumns?.length) {
      return getInitialColumnOrder(apiColumns);
    }
    return [];
  });
  const columnState = useMemo(
    () => ({
      visibility: visibleColumns,
      order: columnOrder
    }),
    [visibleColumns, columnOrder]
  );
  const currentColumns = useMemo(() => {
    const visible = Object.entries(visibleColumns).filter(([_, isVisible]) => isVisible).map(([field]) => field);
    return {
      visible,
      order: columnOrder
    };
  }, [visibleColumns, columnOrder]);
  const handleColumnVisibilityChange = useCallback(
    (visibility) => {
      setVisibleColumns(visibility);
    },
    []
  );
  const handleViewChange = useCallback(
    (view, apiColumns2) => {
      if (view?.configuration) {
        const newVisibility = {};
        apiColumns2.forEach((column) => {
          newVisibility[column.field] = view.configuration.visible_columns?.includes(column.field) || false;
        });
        setVisibleColumns(newVisibility);
        setColumnOrder(view.configuration.column_order || []);
      } else {
        setVisibleColumns(getInitialColumnVisibility(apiColumns2));
        setColumnOrder(getInitialColumnOrder(apiColumns2));
      }
    },
    []
  );
  const initializeColumns = useCallback(
    (apiColumns2) => {
      if (Object.keys(visibleColumns).length === 0) {
        setVisibleColumns(getInitialColumnVisibility(apiColumns2));
      }
      if (columnOrder.length === 0) {
        setColumnOrder(getInitialColumnOrder(apiColumns2));
      }
    },
    []
  );
  const prevActiveViewRef = useRef();
  useEffect(() => {
    if (apiColumns?.length) {
      const viewChanged = prevActiveViewRef.current?.id !== activeView?.id;
      const viewUpdated = activeView && prevActiveViewRef.current?.id === activeView.id && prevActiveViewRef.current.updated_at !== activeView.updated_at;
      if (viewChanged || viewUpdated) {
        if (activeView?.configuration) {
          const newVisibility = {};
          apiColumns.forEach((column) => {
            newVisibility[column.field] = activeView.configuration?.visible_columns?.includes(
              column.field
            ) || false;
          });
          setVisibleColumns(newVisibility);
          setColumnOrder(activeView.configuration?.column_order || []);
        } else {
          setVisibleColumns(getInitialColumnVisibility(apiColumns));
          setColumnOrder(getInitialColumnOrder(apiColumns));
        }
      }
    }
    prevActiveViewRef.current = activeView;
  }, [activeView, apiColumns]);
  return {
    visibleColumns,
    columnOrder,
    columnState,
    currentColumns,
    setVisibleColumns,
    setColumnOrder,
    handleColumnVisibilityChange,
    handleViewChange,
    initializeColumns
  };
}
var DEFAULT_COLUMN_ORDER = 500;
function getInitialColumnVisibility(apiColumns) {
  if (!apiColumns || apiColumns.length === 0) {
    return {};
  }
  const visibility = {};
  apiColumns.forEach((column) => {
    visibility[column.field] = column.default_visible ?? true;
  });
  return visibility;
}
function getInitialColumnOrder(apiColumns) {
  if (!apiColumns || apiColumns.length === 0) {
    return [];
  }
  const sortedColumns = [...apiColumns].sort((a, b) => {
    const orderA = a.default_order ?? DEFAULT_COLUMN_ORDER;
    const orderB = b.default_order ?? DEFAULT_COLUMN_ORDER;
    return orderA - orderB;
  });
  return sortedColumns.map((col) => col.field);
}

// src/lib/table/entity-defaults.ts
var ENTITY_DEFAULT_FIELDS = {
  orders: {
    properties: [
      "id",
      "status",
      "created_at",
      "email",
      "display_id",
      "payment_status",
      "fulfillment_status",
      "total",
      "currency_code"
    ],
    relations: ["*customer", "*sales_channel"]
  },
  products: {
    properties: ["id", "title", "handle", "status", "thumbnail"],
    relations: ["collection.title", "*sales_channels", "*variants"]
  },
  customers: {
    properties: [
      "id",
      "email",
      "first_name",
      "last_name",
      "created_at",
      "updated_at",
      "has_account"
    ],
    relations: ["*groups"]
  },
  inventory: {
    properties: [
      "id",
      "sku",
      "title",
      "description",
      "stocked_quantity",
      "reserved_quantity",
      "created_at",
      "updated_at"
    ],
    relations: ["*location_levels"]
  },
  // Default configuration for entities without specific defaults
  default: {
    properties: ["id", "created_at", "updated_at"],
    relations: []
  }
};
function getEntityDefaultFields(entity) {
  const config = ENTITY_DEFAULT_FIELDS[entity] || ENTITY_DEFAULT_FIELDS.default;
  return {
    properties: config.properties,
    relations: config.relations,
    formatted: [...config.properties, ...config.relations].join(",")
  };
}

// src/lib/table/field-utils.ts
function calculateRequiredFields(entity, apiColumns, visibleColumns) {
  const defaults = getEntityDefaultFields(entity);
  const defaultFields = defaults.formatted;
  if (!apiColumns?.length) {
    return defaultFields;
  }
  const visibleColumnObjects = apiColumns.filter((column) => {
    if (Object.keys(visibleColumns).length > 0) {
      return visibleColumns[column.field] === true;
    }
    return column.default_visible;
  });
  const requiredFieldsSet = /* @__PURE__ */ new Set();
  visibleColumnObjects.forEach((column) => {
    if (column.computed) {
      column.computed.required_fields?.forEach((field) => requiredFieldsSet.add(field));
      column.computed.optional_fields?.forEach((field) => requiredFieldsSet.add(field));
    } else if (!column.field.includes(".")) {
      requiredFieldsSet.add(column.field);
    } else {
      requiredFieldsSet.add(column.field);
    }
  });
  const allRequiredFields = Array.from(requiredFieldsSet);
  const visibleRelationshipFields = allRequiredFields.filter((field) => field.includes("."));
  const visibleDirectFields = allRequiredFields.filter((field) => !field.includes("."));
  const additionalRelationshipFields = visibleRelationshipFields.filter((field) => {
    const [relationName] = field.split(".");
    const isAlreadyCovered = defaults.relations.some(
      (rel) => rel === `*${relationName}` || rel === relationName
    );
    return !isAlreadyCovered;
  });
  const additionalDirectFields = visibleDirectFields.filter((field) => {
    const isAlreadyIncluded = defaults.properties.includes(field);
    return !isAlreadyIncluded;
  });
  const additionalFields = [...additionalRelationshipFields, ...additionalDirectFields];
  if (additionalFields.length > 0) {
    return `${defaultFields},${additionalFields.join(",")}`;
  }
  return defaultFields;
}

// src/hooks/table/use-table-configuration.tsx
function parseSortingState(value) {
  return value.startsWith("-") ? { id: value.slice(1), desc: true } : { id: value, desc: false };
}
function useTableConfiguration({
  entity,
  queryPrefix = "",
  filters = []
}) {
  const isViewConfigEnabled = useFeatureFlag("view_configurations");
  const [_, setSearchParams] = useSearchParams();
  const { activeView, createView } = useViewConfigurations(entity);
  const currentActiveView = activeView?.view_configuration || null;
  const { updateView } = useViewConfiguration(entity, currentActiveView?.id || "");
  const { columns: apiColumns, isLoading: isLoadingColumns } = useEntityColumns(entity, {
    enabled: isViewConfigEnabled
  });
  const queryParams = useQueryParams(
    ["q", "order", "offset", "limit", ...filters.map((f) => f.id)],
    queryPrefix
  );
  const {
    visibleColumns,
    columnOrder,
    currentColumns,
    setColumnOrder,
    handleColumnVisibilityChange,
    handleViewChange: originalHandleViewChange
  } = useColumnState(apiColumns, currentActiveView);
  useEffect2(() => {
    if (!apiColumns) return;
    originalHandleViewChange(currentActiveView, apiColumns);
    setSearchParams((prev) => {
      const keysToDelete = Array.from(prev.keys()).filter(
        (key) => key.startsWith(queryPrefix + "_") || key === queryPrefix + "_q" || key === queryPrefix + "_order"
      );
      keysToDelete.forEach((key) => prev.delete(key));
      if (currentActiveView) {
        const viewConfig = currentActiveView.configuration;
        if (viewConfig.filters) {
          Object.entries(viewConfig.filters).forEach(([key, value]) => {
            prev.set(`${queryPrefix}_${key}`, JSON.stringify(value));
          });
        }
        if (viewConfig.sorting) {
          const sortValue = viewConfig.sorting.desc ? `-${viewConfig.sorting.id}` : viewConfig.sorting.id;
          prev.set(`${queryPrefix}_order`, sortValue);
        }
        if (viewConfig.search) {
          prev.set(`${queryPrefix}_q`, viewConfig.search);
        }
      }
      return prev;
    });
  }, [currentActiveView, apiColumns]);
  const currentConfiguration = useMemo2(() => {
    const currentFilters = {};
    filters.forEach((filter) => {
      if (queryParams[filter.id] !== void 0) {
        currentFilters[filter.id] = JSON.parse(queryParams[filter.id] || "");
      }
    });
    return {
      filters: currentFilters,
      sorting: queryParams.order ? parseSortingState(queryParams.order) : null,
      search: queryParams.q || ""
    };
  }, [filters, queryParams]);
  const [debouncedHasConfigChanged, setDebouncedHasConfigChanged] = useState2(false);
  const hasConfigurationChanged = useMemo2(() => {
    const currentFilters = currentConfiguration.filters;
    const currentSorting = currentConfiguration.sorting;
    const currentSearch = currentConfiguration.search;
    const currentVisibleColumns = Object.entries(visibleColumns).filter(([_2, isVisible]) => isVisible).map(([field]) => field).sort();
    if (currentActiveView) {
      const viewFilters = currentActiveView.configuration.filters || {};
      const viewSorting = currentActiveView.configuration.sorting;
      const viewSearch = currentActiveView.configuration.search || "";
      const viewVisibleColumns = [...currentActiveView.configuration.visible_columns || []].sort();
      const viewColumnOrder = currentActiveView.configuration.column_order || [];
      const filterKeys = /* @__PURE__ */ new Set([...Object.keys(currentFilters), ...Object.keys(viewFilters)]);
      for (const key of filterKeys) {
        if (JSON.stringify(currentFilters[key]) !== JSON.stringify(viewFilters[key])) {
          return true;
        }
      }
      const normalizedCurrentSorting = currentSorting || void 0;
      const normalizedViewSorting = viewSorting || void 0;
      if (JSON.stringify(normalizedCurrentSorting) !== JSON.stringify(normalizedViewSorting)) {
        return true;
      }
      if (currentSearch !== viewSearch) {
        return true;
      }
      if (JSON.stringify(currentVisibleColumns) !== JSON.stringify(viewVisibleColumns)) {
        return true;
      }
      if (JSON.stringify(columnOrder) !== JSON.stringify(viewColumnOrder)) {
        return true;
      }
    } else {
      if (Object.keys(currentFilters).length > 0) return true;
      if (currentSorting !== null) return true;
      if (currentSearch !== "") return true;
      if (apiColumns) {
        const currentVisibleSet = new Set(currentVisibleColumns);
        const defaultVisibleSet = new Set(
          apiColumns.filter((col) => col.default_visible).map((col) => col.field)
        );
        if (currentVisibleSet.size !== defaultVisibleSet.size || [...currentVisibleSet].some((field) => !defaultVisibleSet.has(field))) {
          return true;
        }
        const defaultOrder = apiColumns.sort((a, b) => (a.default_order ?? 500) - (b.default_order ?? 500)).map((col) => col.field);
        if (JSON.stringify(columnOrder) !== JSON.stringify(defaultOrder)) {
          return true;
        }
      }
    }
    return false;
  }, [currentActiveView, visibleColumns, columnOrder, currentConfiguration, apiColumns]);
  useEffect2(() => {
    const timer = setTimeout(() => {
      setDebouncedHasConfigChanged(hasConfigurationChanged);
    }, 50);
    return () => clearTimeout(timer);
  }, [hasConfigurationChanged]);
  const handleClearConfiguration = useCallback2(() => {
    if (apiColumns) {
      originalHandleViewChange(currentActiveView, apiColumns);
    }
    setSearchParams((prev) => {
      const keysToDelete = Array.from(prev.keys()).filter(
        (key) => key.startsWith(queryPrefix + "_") || key === queryPrefix + "_q" || key === queryPrefix + "_order"
      );
      keysToDelete.forEach((key) => prev.delete(key));
      if (currentActiveView?.configuration) {
        const viewConfig = currentActiveView.configuration;
        if (viewConfig.filters) {
          Object.entries(viewConfig.filters).forEach(([key, value]) => {
            prev.set(`${queryPrefix}_${key}`, JSON.stringify(value));
          });
        }
        if (viewConfig.sorting) {
          const sortValue = viewConfig.sorting.desc ? `-${viewConfig.sorting.id}` : viewConfig.sorting.id;
          prev.set(`${queryPrefix}_order`, sortValue);
        }
        if (viewConfig.search) {
          prev.set(`${queryPrefix}_q`, viewConfig.search);
        }
      }
      return prev;
    });
  }, [currentActiveView, apiColumns, queryPrefix]);
  const requiredFields = useMemo2(() => {
    return calculateRequiredFields(entity, apiColumns, visibleColumns);
  }, [entity, apiColumns, visibleColumns]);
  return {
    activeView: currentActiveView,
    createView,
    updateView,
    isViewConfigEnabled,
    visibleColumns,
    columnOrder,
    currentColumns,
    setColumnOrder,
    handleColumnVisibilityChange,
    currentConfiguration,
    hasConfigurationChanged: debouncedHasConfigChanged,
    handleClearConfiguration,
    apiColumns,
    isLoadingColumns,
    queryParams,
    requiredFields
  };
}

// src/hooks/table/columns/use-configurable-table-columns.tsx
import { useMemo as useMemo3 } from "react";
import { createDataTableColumnHelper } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/lib/table/cell-renderers.tsx
import { Badge, StatusBadge, Tooltip } from "@medusajs/ui";
import ReactCountryFlag from "react-country-flag";
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var cellRenderers = /* @__PURE__ */ new Map();
var getNestedValue = (obj, path) => {
  return path.split(".").reduce((current, key) => current?.[key], obj);
};
var TextRenderer = (value, _row, _column, _t) => {
  if (value === null || value === void 0) return "-";
  return String(value);
};
var CountRenderer = (value, _row, _column, t) => {
  const items = value || [];
  const count = Array.isArray(items) ? items.length : 0;
  return t("general.items", { count });
};
var StatusRenderer = (value, row, column, t) => {
  if (!value) return "-";
  if (column.field === "status" && row.status && (row.handle || row.is_giftcard !== void 0)) {
    return /* @__PURE__ */ jsx2(ProductStatusCell, { status: row.status });
  }
  if (column.context === "payment" && t) {
    const { label, color } = getOrderPaymentStatus(t, value);
    return /* @__PURE__ */ jsx2(StatusBadge, { color, children: label });
  }
  if (column.context === "fulfillment" && t) {
    const { label, color } = getOrderFulfillmentStatus(t, value);
    return /* @__PURE__ */ jsx2(StatusBadge, { color, children: label });
  }
  const getStatusColor = (status) => {
    switch (status?.toLowerCase()) {
      case "active":
      case "published":
      case "fulfilled":
      case "paid":
        return "green";
      case "pending":
      case "proposed":
      case "processing":
        return "orange";
      case "draft":
        return "grey";
      case "rejected":
      case "failed":
      case "canceled":
        return "red";
      default:
        return "grey";
    }
  };
  const getTranslatedStatus = (status) => {
    if (!t) return status;
    const lowerStatus = status.toLowerCase();
    switch (lowerStatus) {
      case "active":
        return t("general.active", "Active");
      case "published":
        return t("products.productStatus.published", "Published");
      case "draft":
        return t("orders.status.draft", "Draft");
      case "pending":
        return t("orders.status.pending", "Pending");
      case "canceled":
        return t("orders.status.canceled", "Canceled");
      default:
        return t(`status.${lowerStatus}`, status);
    }
  };
  const translatedValue = getTranslatedStatus(value);
  return /* @__PURE__ */ jsx2(StatusBadge, { color: getStatusColor(value), children: translatedValue });
};
var BadgeListRenderer = (value, row, column, t) => {
  if (column.field === "sales_channels_display" || column.field === "sales_channels") {
    return /* @__PURE__ */ jsx2(SalesChannelsCell, { salesChannels: row.sales_channels });
  }
  if (!Array.isArray(value)) return "-";
  const items = value.slice(0, 2);
  const remaining = value.length - 2;
  return /* @__PURE__ */ jsxs2("div", { className: "flex gap-1", children: [
    items.map((item, index) => /* @__PURE__ */ jsx2(Badge, { size: "xsmall", children: typeof item === "string" ? item : item.name || item.title || "-" }, index)),
    remaining > 0 && /* @__PURE__ */ jsx2(Badge, { size: "xsmall", color: "grey", children: t ? t("general.plusCountMore", "+ {{count}} more", {
      count: remaining
    }) : `+${remaining}` })
  ] });
};
var ProductInfoRenderer = (_, row, _column, _t) => {
  return /* @__PURE__ */ jsx2(ProductCell, { product: row });
};
var CollectionRenderer = (_, row, _column, _t) => {
  return /* @__PURE__ */ jsx2(CollectionCell, { collection: row.collection });
};
var VariantsRenderer = (_, row, _column, _t) => {
  return /* @__PURE__ */ jsx2(VariantCell, { variants: row.variants });
};
var CustomerNameRenderer = (_, row, _column, t) => {
  if (row.customer?.first_name || row.customer?.last_name) {
    const fullName = `${row.customer.first_name || ""} ${row.customer.last_name || ""}`.trim();
    if (fullName) return fullName;
  }
  if (row.customer?.email) {
    return row.customer.email;
  }
  if (row.customer?.phone) {
    return row.customer.phone;
  }
  return t ? t("customers.guest", "Guest") : "Guest";
};
var AddressSummaryRenderer = (_, row, column, _t) => {
  let address = null;
  if (column.field === "shipping_address_display") {
    address = row.shipping_address;
  } else if (column.field === "billing_address_display") {
    address = row.billing_address;
  } else {
    address = row.shipping_address || row.billing_address;
  }
  if (!address) return "-";
  const parts = [];
  if (address.address_1) {
    parts.push(address.address_1);
  }
  const locationParts = [];
  if (address.city) locationParts.push(address.city);
  if (address.province) locationParts.push(address.province);
  if (address.postal_code) locationParts.push(address.postal_code);
  if (locationParts.length > 0) {
    parts.push(locationParts.join(", "));
  }
  if (address.country_code) {
    parts.push(address.country_code.toUpperCase());
  }
  return parts.join(" \u2022 ") || "-";
};
var CountryCodeRenderer = (_, row, _column, _t) => {
  const countryCode = row.shipping_address?.country_code;
  if (!countryCode) return /* @__PURE__ */ jsx2("div", { className: "flex w-full justify-center", children: "-" });
  const country = getCountryByIso2(countryCode);
  const displayName = country?.display_name || countryCode.toUpperCase();
  return /* @__PURE__ */ jsx2("div", { className: "flex w-full items-center justify-center", children: /* @__PURE__ */ jsx2(Tooltip, { content: displayName, children: /* @__PURE__ */ jsx2("div", { className: "flex size-4 items-center justify-center overflow-hidden rounded-sm", children: /* @__PURE__ */ jsx2(
    ReactCountryFlag,
    {
      countryCode: countryCode.toUpperCase(),
      svg: true,
      style: {
        width: "16px",
        height: "16px"
      },
      "aria-label": displayName
    }
  ) }) }) });
};
var DateRenderer = (value, _row, _column, _t) => {
  return /* @__PURE__ */ jsx2(DateCell, { date: value });
};
var DisplayIdRenderer = (value, _row, _column, _t) => {
  return /* @__PURE__ */ jsx2(DisplayIdCell, { displayId: value });
};
var CurrencyRenderer = (value, row, _column, _t) => {
  const currencyCode = row.currency_code || "USD";
  return /* @__PURE__ */ jsx2(MoneyAmountCell, { currencyCode, amount: value, align: "right" });
};
var TotalRenderer = (value, row, _column, _t) => {
  const currencyCode = row.currency_code || "USD";
  return /* @__PURE__ */ jsx2(TotalCell, { currencyCode, total: value });
};
cellRenderers.set("text", TextRenderer);
cellRenderers.set("count", CountRenderer);
cellRenderers.set("status", StatusRenderer);
cellRenderers.set("badge_list", BadgeListRenderer);
cellRenderers.set("date", DateRenderer);
cellRenderers.set("timestamp", DateRenderer);
cellRenderers.set("currency", CurrencyRenderer);
cellRenderers.set("total", TotalRenderer);
cellRenderers.set("product_info", ProductInfoRenderer);
cellRenderers.set("collection", CollectionRenderer);
cellRenderers.set("variants", VariantsRenderer);
cellRenderers.set("sales_channels_list", BadgeListRenderer);
cellRenderers.set("customer_name", CustomerNameRenderer);
cellRenderers.set("address_summary", AddressSummaryRenderer);
cellRenderers.set("country_code", CountryCodeRenderer);
cellRenderers.set("display_id", DisplayIdRenderer);
function getCellRenderer(renderType, dataType) {
  if (renderType && cellRenderers.has(renderType)) {
    return cellRenderers.get(renderType);
  }
  switch (dataType) {
    case "number":
    case "string":
      return TextRenderer;
    case "date":
      return DateRenderer;
    case "boolean":
      return (value, _row, _column, t) => {
        if (t) {
          return value ? t("fields.yes", "Yes") : t("fields.no", "No");
        }
        return value ? "Yes" : "No";
      };
    case "enum":
      return StatusRenderer;
    case "currency":
      return CurrencyRenderer;
    default:
      return TextRenderer;
  }
}
function getColumnValue(row, column) {
  if (column.computed) {
    return row;
  }
  return getNestedValue(row, column.field);
}

// src/hooks/table/columns/use-configurable-table-columns.tsx
function useConfigurableTableColumns(entity, apiColumns, adapter) {
  const columnHelper = createDataTableColumnHelper();
  const { t } = useTranslation2();
  return useMemo3(() => {
    if (!apiColumns?.length) {
      return [];
    }
    return apiColumns.map((apiColumn) => {
      let renderType = apiColumn.computed?.type;
      if (!renderType) {
        if (apiColumn.semantic_type === "timestamp") {
          renderType = "timestamp";
        } else if (apiColumn.field === "display_id") {
          renderType = "display_id";
        } else if (apiColumn.field === "total") {
          renderType = "total";
        } else if (apiColumn.semantic_type === "currency") {
          renderType = "currency";
        }
      }
      const renderer = getCellRenderer(
        renderType,
        apiColumn.data_type
      );
      const headerAlign = adapter?.getColumnAlignment ? adapter.getColumnAlignment(apiColumn) : getDefaultColumnAlignment(apiColumn);
      const accessor = (row) => getColumnValue(row, apiColumn);
      return columnHelper.accessor(accessor, {
        id: apiColumn.field,
        header: () => apiColumn.name,
        cell: ({ getValue, row }) => {
          const value = getValue();
          if (adapter?.transformCellValue) {
            const transformed = adapter.transformCellValue(value, row.original, apiColumn);
            if (transformed !== null) {
              return transformed;
            }
          }
          return renderer(value, row.original, apiColumn, t);
        },
        meta: {
          name: apiColumn.name,
          column: apiColumn
          // Store column metadata for future use
        },
        enableHiding: apiColumn.hideable,
        enableSorting: apiColumn.sortable,
        headerAlign
        // Pass the header alignment to the DataTable
      });
    });
  }, [entity, apiColumns, adapter, t]);
}
function getDefaultColumnAlignment(column) {
  if (column.semantic_type === "currency" || column.data_type === "currency") {
    return "right";
  }
  if (column.data_type === "number" && column.context !== "identifier") {
    return "right";
  }
  if (column.field.includes("total") || column.field.includes("amount") || column.field.includes("price") || column.field.includes("quantity") || column.field.includes("count")) {
    return "right";
  }
  if (column.semantic_type === "status") {
    return "center";
  }
  if (column.computed?.type === "country_code" || column.field === "country" || column.field.includes("country_code")) {
    return "center";
  }
  return "left";
}

// src/lib/table/entity-adapters.tsx
var orderColumnAdapter = {
  getColumnAlignment: (column) => {
    if (column.semantic_type === "currency") {
      return "right";
    }
    if (column.semantic_type === "status") {
      return "center";
    }
    if (column.computed?.type === "country_code") {
      return "center";
    }
    return "left";
  }
};
var productColumnAdapter = {
  getColumnAlignment: (column) => {
    if (column.field === "product_display") {
      return "left";
    }
    if (column.field === "collection.title") {
      return "left";
    }
    if (column.field === "sales_channels_display") {
      return "left";
    }
    if (column.field === "variants_count") {
      return "left";
    }
    if (column.field === "sku") {
      return "center";
    }
    if (column.field === "stock") {
      return "right";
    }
    if (column.semantic_type === "currency") {
      return "right";
    }
    if (column.semantic_type === "status") {
      return "left";
    }
    if (column.computed?.type === "product_info") {
      return "left";
    }
    if (column.computed?.type === "count") {
      return "left";
    }
    if (column.computed?.type === "sales_channels_list") {
      return "left";
    }
    return "left";
  },
  transformCellValue: (_value, row, column) => {
    if (column.field === "variants_count" || column.computed?.type === "count") {
      const count = Array.isArray(row.variants) ? row.variants.length : 0;
      return `${count} ${count === 1 ? "variant" : "variants"}`;
    }
    if (column.field === "product_display" || column.computed?.type === "product_info") {
      return null;
    }
    if (column.field === "sales_channels_display" || column.computed?.type === "sales_channels_list") {
      return null;
    }
    if (column.field === "status") {
      return null;
    }
    return null;
  }
};
var customerColumnAdapter = {
  getColumnAlignment: (column) => {
    if (column.field === "orders_count") {
      return "right";
    }
    if (column.semantic_type === "currency") {
      return "right";
    }
    if (column.semantic_type === "status") {
      return "center";
    }
    return "left";
  },
  transformCellValue: (_value, row, column) => {
    if (column.field === "name") {
      const { first_name, last_name } = row;
      if (first_name || last_name) {
        return `${first_name || ""} ${last_name || ""}`.trim();
      }
      return "-";
    }
    return null;
  }
};
var inventoryColumnAdapter = {
  getColumnAlignment: (column) => {
    if (column.field === "stocked_quantity") {
      return "right";
    }
    if (column.field === "reserved_quantity") {
      return "right";
    }
    if (column.field === "available_quantity") {
      return "right";
    }
    if (column.semantic_type === "status") {
      return "center";
    }
    return "left";
  }
};
var entityAdapters = {
  orders: orderColumnAdapter,
  products: productColumnAdapter,
  customers: customerColumnAdapter,
  inventory: inventoryColumnAdapter
};
function getEntityAdapter(entity) {
  return entityAdapters[entity];
}

// src/components/table/configurable-data-table/configurable-data-table.tsx
import { Fragment as Fragment2, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
function ConfigurableDataTable({
  adapter,
  heading,
  subHeading,
  pageSize: pageSizeProp,
  queryPrefix: queryPrefixProp,
  layout = "fill",
  actions
}) {
  const { t } = useTranslation3();
  const [saveDialogOpen, setSaveDialogOpen] = useState3(false);
  const [editingView, setEditingView] = useState3(null);
  const entity = adapter.entity;
  const entityName = adapter.entityName;
  const rawFilters = adapter.filters || [];
  const filters = rawFilters.map((filter) => {
    if (filter.key && !filter.id) {
      return { ...filter, id: filter.key };
    }
    return filter;
  });
  const pageSize = pageSizeProp || adapter.pageSize || 20;
  const queryPrefix = queryPrefixProp || adapter.queryPrefix || "";
  const {
    activeView,
    createView,
    updateView,
    isViewConfigEnabled,
    visibleColumns,
    columnOrder,
    currentColumns,
    setColumnOrder,
    handleColumnVisibilityChange,
    currentConfiguration,
    hasConfigurationChanged,
    handleClearConfiguration,
    isLoadingColumns,
    apiColumns,
    requiredFields,
    queryParams
  } = useTableConfiguration({
    entity,
    pageSize,
    queryPrefix,
    filters
  });
  const parsedQueryParams = { ...queryParams };
  filters.forEach((filter) => {
    const filterKey = filter.id;
    if (filterKey && parsedQueryParams[filterKey] !== void 0) {
      try {
        parsedQueryParams[filterKey] = JSON.parse(parsedQueryParams[filterKey]);
      } catch {
      }
    }
  });
  const searchParams = {
    ...parsedQueryParams,
    fields: requiredFields,
    limit: pageSize,
    offset: parsedQueryParams.offset ? Number(parsedQueryParams.offset) : 0
  };
  const fetchResult = adapter.useData(requiredFields, searchParams);
  const columnAdapter = adapter.columnAdapter || getEntityAdapter(entity);
  const generatedColumns = useConfigurableTableColumns(entity, apiColumns || [], columnAdapter);
  const columns = adapter.getColumns && apiColumns ? adapter.getColumns(apiColumns) : generatedColumns;
  if (fetchResult.isError) {
    throw fetchResult.error;
  }
  const handleSaveAsDefault = async () => {
    try {
      if (activeView?.is_system_default) {
        await updateView.mutateAsync({
          name: activeView.name || null,
          configuration: {
            visible_columns: currentColumns.visible,
            column_order: currentColumns.order,
            filters: currentConfiguration.filters || {},
            sorting: currentConfiguration.sorting || null,
            search: currentConfiguration.search || ""
          }
        });
      } else {
        await createView.mutateAsync({
          name: "Default",
          is_system_default: true,
          set_active: true,
          configuration: {
            visible_columns: currentColumns.visible,
            column_order: currentColumns.order,
            filters: currentConfiguration.filters || {},
            sorting: currentConfiguration.sorting || null,
            search: currentConfiguration.search || ""
          }
        });
      }
    } catch (_) {
    }
  };
  const handleUpdateExisting = async () => {
    if (!activeView) return;
    try {
      await updateView.mutateAsync({
        name: activeView.name,
        configuration: {
          visible_columns: currentColumns.visible,
          column_order: currentColumns.order,
          filters: currentConfiguration.filters || {},
          sorting: currentConfiguration.sorting || null,
          search: currentConfiguration.search || ""
        }
      });
    } catch (_) {
    }
  };
  const handleSaveAsNew = () => {
    setSaveDialogOpen(true);
    setEditingView(null);
  };
  const filterBarContent = hasConfigurationChanged ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
    /* @__PURE__ */ jsx3(
      Button2,
      {
        variant: "secondary",
        size: "small",
        type: "button",
        onClick: handleClearConfiguration,
        children: t("actions.clear")
      }
    ),
    /* @__PURE__ */ jsx3(
      SaveViewDropdown,
      {
        isDefaultView: activeView?.is_system_default || !activeView,
        currentViewId: activeView?.id,
        currentViewName: activeView?.name,
        onSaveAsDefault: handleSaveAsDefault,
        onUpdateExisting: handleUpdateExisting,
        onSaveAsNew: handleSaveAsNew
      }
    )
  ] }) : null;
  return /* @__PURE__ */ jsxs3(Container, { className: "divide-y p-0", children: [
    /* @__PURE__ */ jsx3(
      DataTable,
      {
        data: fetchResult.data || [],
        columns,
        filters,
        getRowId: adapter.getRowId || ((row) => row.id),
        rowCount: fetchResult.count,
        enablePagination: true,
        enableSearch: true,
        pageSize,
        isLoading: fetchResult.isLoading || isLoadingColumns,
        layout,
        heading: heading || entityName || (entity ? t(`${entity}.domain`) : ""),
        subHeading,
        enableColumnVisibility: isViewConfigEnabled,
        initialColumnVisibility: visibleColumns,
        onColumnVisibilityChange: handleColumnVisibilityChange,
        columnOrder,
        onColumnOrderChange: setColumnOrder,
        enableViewSelector: isViewConfigEnabled,
        entity,
        currentColumns,
        filterBarContent,
        rowHref: adapter.getRowHref,
        emptyState: adapter.emptyState || {
          empty: {
            heading: t(`${entity}.list.noRecordsMessage`)
          }
        },
        prefix: queryPrefix,
        actions,
        enableFilterMenu: false
      }
    ),
    saveDialogOpen && /* @__PURE__ */ jsx3(
      SaveViewDialog,
      {
        entity,
        currentColumns,
        currentConfiguration,
        editingView,
        onClose: () => {
          setSaveDialogOpen(false);
          setEditingView(null);
        },
        onSaved: () => {
          setSaveDialogOpen(false);
          setEditingView(null);
        }
      }
    )
  ] });
}

// src/lib/table/table-adapters.ts
function createTableAdapter(adapter) {
  return {
    // Provide smart defaults
    getRowId: (row) => row.id,
    pageSize: 20,
    queryPrefix: "",
    ...adapter
  };
}

export {
  orderColumnAdapter,
  productColumnAdapter,
  ConfigurableDataTable,
  createTableAdapter
};
