"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const jsxRuntime = require("react/jsx-runtime");
const React = require("react");
const designSystem = require("@strapi/design-system");
const Icons = require("@strapi/icons");
const isEqual = require("lodash/isEqual");
const index_H1ljeG8 = require("./index--h1ljeG8-TLddt1Eo.js");
const Helmet = require("./Helmet-d9JljxUo.js");
const reactIntl = require("react-intl");
const reactRouterDom = require("react-router-dom");
const styled = require("styled-components");
const useSyncRbacOd0wrAnD = require("./useSyncRbac-Od0wrAnD-_nmioRwh.js");
const isEmpty = require("lodash/isEmpty");
const toString = require("lodash/toString");
const v2 = require("@strapi/design-system/v2");
const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
function _interopNamespace(e) {
  if (e && e.__esModule)
    return e;
  const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
  if (e) {
    for (const k in e) {
      if (k !== "default") {
        const d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: () => e[k]
        });
      }
    }
  }
  n.default = e;
  return Object.freeze(n);
}
const React__namespace = /* @__PURE__ */ _interopNamespace(React);
const isEqual__default = /* @__PURE__ */ _interopDefault(isEqual);
const styled__default = /* @__PURE__ */ _interopDefault(styled);
const isEmpty__default = /* @__PURE__ */ _interopDefault(isEmpty);
const toString__default = /* @__PURE__ */ _interopDefault(toString);
function parseISO(argument, options) {
  var _options$additionalDi;
  index_H1ljeG8.requiredArgs(1, arguments);
  var additionalDigits = index_H1ljeG8.toInteger((_options$additionalDi = options === null || options === void 0 ? void 0 : options.additionalDigits) !== null && _options$additionalDi !== void 0 ? _options$additionalDi : 2);
  if (additionalDigits !== 2 && additionalDigits !== 1 && additionalDigits !== 0) {
    throw new RangeError("additionalDigits must be 0, 1 or 2");
  }
  if (!(typeof argument === "string" || Object.prototype.toString.call(argument) === "[object String]")) {
    return /* @__PURE__ */ new Date(NaN);
  }
  var dateStrings = splitDateString(argument);
  var date;
  if (dateStrings.date) {
    var parseYearResult = parseYear(dateStrings.date, additionalDigits);
    date = parseDate(parseYearResult.restDateString, parseYearResult.year);
  }
  if (!date || isNaN(date.getTime())) {
    return /* @__PURE__ */ new Date(NaN);
  }
  var timestamp = date.getTime();
  var time = 0;
  var offset;
  if (dateStrings.time) {
    time = parseTime(dateStrings.time);
    if (isNaN(time)) {
      return /* @__PURE__ */ new Date(NaN);
    }
  }
  if (dateStrings.timezone) {
    offset = parseTimezone(dateStrings.timezone);
    if (isNaN(offset)) {
      return /* @__PURE__ */ new Date(NaN);
    }
  } else {
    var dirtyDate = new Date(timestamp + time);
    var result = /* @__PURE__ */ new Date(0);
    result.setFullYear(dirtyDate.getUTCFullYear(), dirtyDate.getUTCMonth(), dirtyDate.getUTCDate());
    result.setHours(dirtyDate.getUTCHours(), dirtyDate.getUTCMinutes(), dirtyDate.getUTCSeconds(), dirtyDate.getUTCMilliseconds());
    return result;
  }
  return new Date(timestamp + time + offset);
}
var patterns = {
  dateTimeDelimiter: /[T ]/,
  timeZoneDelimiter: /[Z ]/i,
  timezone: /([Z+-].*)$/
};
var dateRegex = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/;
var timeRegex = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/;
var timezoneRegex = /^([+-])(\d{2})(?::?(\d{2}))?$/;
function splitDateString(dateString) {
  var dateStrings = {};
  var array = dateString.split(patterns.dateTimeDelimiter);
  var timeString;
  if (array.length > 2) {
    return dateStrings;
  }
  if (/:/.test(array[0])) {
    timeString = array[0];
  } else {
    dateStrings.date = array[0];
    timeString = array[1];
    if (patterns.timeZoneDelimiter.test(dateStrings.date)) {
      dateStrings.date = dateString.split(patterns.timeZoneDelimiter)[0];
      timeString = dateString.substr(dateStrings.date.length, dateString.length);
    }
  }
  if (timeString) {
    var token = patterns.timezone.exec(timeString);
    if (token) {
      dateStrings.time = timeString.replace(token[1], "");
      dateStrings.timezone = token[1];
    } else {
      dateStrings.time = timeString;
    }
  }
  return dateStrings;
}
function parseYear(dateString, additionalDigits) {
  var regex = new RegExp("^(?:(\\d{4}|[+-]\\d{" + (4 + additionalDigits) + "})|(\\d{2}|[+-]\\d{" + (2 + additionalDigits) + "})$)");
  var captures = dateString.match(regex);
  if (!captures)
    return {
      year: NaN,
      restDateString: ""
    };
  var year = captures[1] ? parseInt(captures[1]) : null;
  var century = captures[2] ? parseInt(captures[2]) : null;
  return {
    year: century === null ? year : century * 100,
    restDateString: dateString.slice((captures[1] || captures[2]).length)
  };
}
function parseDate(dateString, year) {
  if (year === null)
    return /* @__PURE__ */ new Date(NaN);
  var captures = dateString.match(dateRegex);
  if (!captures)
    return /* @__PURE__ */ new Date(NaN);
  var isWeekDate = !!captures[4];
  var dayOfYear = parseDateUnit(captures[1]);
  var month = parseDateUnit(captures[2]) - 1;
  var day = parseDateUnit(captures[3]);
  var week = parseDateUnit(captures[4]);
  var dayOfWeek = parseDateUnit(captures[5]) - 1;
  if (isWeekDate) {
    if (!validateWeekDate(year, week, dayOfWeek)) {
      return /* @__PURE__ */ new Date(NaN);
    }
    return dayOfISOWeekYear(year, week, dayOfWeek);
  } else {
    var date = /* @__PURE__ */ new Date(0);
    if (!validateDate(year, month, day) || !validateDayOfYearDate(year, dayOfYear)) {
      return /* @__PURE__ */ new Date(NaN);
    }
    date.setUTCFullYear(year, month, Math.max(dayOfYear, day));
    return date;
  }
}
function parseDateUnit(value) {
  return value ? parseInt(value) : 1;
}
function parseTime(timeString) {
  var captures = timeString.match(timeRegex);
  if (!captures)
    return NaN;
  var hours = parseTimeUnit(captures[1]);
  var minutes = parseTimeUnit(captures[2]);
  var seconds = parseTimeUnit(captures[3]);
  if (!validateTime(hours, minutes, seconds)) {
    return NaN;
  }
  return hours * index_H1ljeG8.millisecondsInHour + minutes * index_H1ljeG8.millisecondsInMinute + seconds * 1e3;
}
function parseTimeUnit(value) {
  return value && parseFloat(value.replace(",", ".")) || 0;
}
function parseTimezone(timezoneString) {
  if (timezoneString === "Z")
    return 0;
  var captures = timezoneString.match(timezoneRegex);
  if (!captures)
    return 0;
  var sign = captures[1] === "+" ? -1 : 1;
  var hours = parseInt(captures[2]);
  var minutes = captures[3] && parseInt(captures[3]) || 0;
  if (!validateTimezone(hours, minutes)) {
    return NaN;
  }
  return sign * (hours * index_H1ljeG8.millisecondsInHour + minutes * index_H1ljeG8.millisecondsInMinute);
}
function dayOfISOWeekYear(isoWeekYear, week, day) {
  var date = /* @__PURE__ */ new Date(0);
  date.setUTCFullYear(isoWeekYear, 0, 4);
  var fourthOfJanuaryDay = date.getUTCDay() || 7;
  var diff = (week - 1) * 7 + day + 1 - fourthOfJanuaryDay;
  date.setUTCDate(date.getUTCDate() + diff);
  return date;
}
var daysInMonths = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function isLeapYearIndex(year) {
  return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;
}
function validateDate(year, month, date) {
  return month >= 0 && month <= 11 && date >= 1 && date <= (daysInMonths[month] || (isLeapYearIndex(year) ? 29 : 28));
}
function validateDayOfYearDate(year, dayOfYear) {
  return dayOfYear >= 1 && dayOfYear <= (isLeapYearIndex(year) ? 366 : 365);
}
function validateWeekDate(_year, week, day) {
  return week >= 1 && week <= 53 && day >= 0 && day <= 6;
}
function validateTime(hours, minutes, seconds) {
  if (hours === 24) {
    return minutes === 0 && seconds === 0;
  }
  return seconds >= 0 && seconds < 60 && minutes >= 0 && minutes < 60 && hours >= 0 && hours < 25;
}
function validateTimezone(_hours, minutes) {
  return minutes >= 0 && minutes <= 59;
}
const BASE_FILTERS = [
  {
    label: { id: "components.FilterOptions.FILTER_TYPES.$eq", defaultMessage: "is" },
    value: "$eq"
  },
  {
    label: { id: "components.FilterOptions.FILTER_TYPES.$ne", defaultMessage: "is not" },
    value: "$ne"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$null",
      defaultMessage: "is null"
    },
    value: "$null"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$notNull",
      defaultMessage: "is not null"
    },
    value: "$notNull"
  }
];
const NUMERIC_FILTERS = [
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$gt",
      defaultMessage: "is greater than"
    },
    value: "$gt"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$gte",
      defaultMessage: "is greater than or equal to"
    },
    value: "$gte"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$lt",
      defaultMessage: "is less than"
    },
    value: "$lt"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$lte",
      defaultMessage: "is less than or equal to"
    },
    value: "$lte"
  }
];
const IS_SENSITIVE_FILTERS = [
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$eqi",
      defaultMessage: "is (case insensitive)"
    },
    value: "$eqi"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$nei",
      defaultMessage: "is not (case insensitive)"
    },
    value: "$nei"
  }
];
const CONTAINS_FILTERS = [
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$contains",
      defaultMessage: "contains"
    },
    value: "$contains"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$containsi",
      defaultMessage: "contains (case insensitive)"
    },
    value: "$containsi"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$notContains",
      defaultMessage: "not contains"
    },
    value: "$notContains"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$notContainsi",
      defaultMessage: "not contains (case insensitive)"
    },
    value: "$notContainsi"
  }
];
const STRING_PARSE_FILTERS = [
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$startsWith",
      defaultMessage: "starts with"
    },
    value: "$startsWith"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$startsWithi",
      defaultMessage: "starts with (case insensitive)"
    },
    value: "$startsWithi"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$endsWith",
      defaultMessage: "ends with"
    },
    value: "$endsWith"
  },
  {
    label: {
      id: "components.FilterOptions.FILTER_TYPES.$endsWithi",
      defaultMessage: "ends with (case insensitive)"
    },
    value: "$endsWithi"
  }
];
const [FiltersProvider, useFilters] = index_H1ljeG8.createContext("Filters");
const Root = ({
  children,
  disabled = false,
  onChange,
  onOpenChange,
  open: openProp,
  defaultOpen,
  options = []
}) => {
  const [triggerNode, setTriggerNode] = React__namespace.useState(null);
  const [open = false, setOpen] = index_H1ljeG8.useControllableState({
    prop: openProp,
    defaultProp: defaultOpen,
    onChange: onOpenChange
  });
  const handleChange = (data) => {
    if (onChange) {
      onChange(data);
    }
  };
  return /* @__PURE__ */ jsxRuntime.jsx(
    FiltersProvider,
    {
      disabled,
      onChange: handleChange,
      open,
      options,
      setOpen,
      setTriggerNode,
      triggerNode,
      children
    }
  );
};
const Trigger = React__namespace.forwardRef(
  ({ label }, forwardedRef) => {
    const { formatMessage } = reactIntl.useIntl();
    const { setTriggerNode, setOpen } = useFilters("Trigger", ({ setTriggerNode: setTriggerNode2, setOpen: setOpen2 }) => ({
      setTriggerNode: setTriggerNode2,
      setOpen: setOpen2
    }));
    const disabled = useFilters("Trigger", ({ disabled: disabled2 }) => disabled2);
    const open = useFilters("Trigger", ({ open: open2 }) => open2);
    const composedRefs = designSystem.useComposedRefs(forwardedRef, setTriggerNode);
    const handleClick = () => setOpen(!open);
    return /* @__PURE__ */ jsxRuntime.jsx(
      designSystem.Button,
      {
        variant: "tertiary",
        ref: composedRefs,
        startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Filter, {}),
        onClick: handleClick,
        size: "S",
        disabled,
        children: label || formatMessage({ id: "app.utils.filters", defaultMessage: "Filters" })
      }
    );
  }
);
const PopoverImpl = () => {
  const [{ query }, setQuery] = index_H1ljeG8.useQueryParams();
  const { formatMessage } = reactIntl.useIntl();
  const open = useFilters("Popover", ({ open: open2 }) => open2);
  const options = useFilters("Popover", ({ options: options2 }) => options2);
  const triggerNode = useFilters("Popover", ({ triggerNode: triggerNode2 }) => triggerNode2);
  const setOpen = useFilters("Popover", ({ setOpen: setOpen2 }) => setOpen2);
  const onChange = useFilters("Popover", ({ onChange: onChange2 }) => onChange2);
  if (!open || options.length === 0 || !triggerNode) {
    return null;
  }
  const handleSubmit = (data) => {
    if (!data.value) {
      return;
    }
    if (onChange) {
      onChange(data);
    }
    const filterType = options.find((filter) => filter.name === data.name).type;
    const operatorValuePairing = {
      [data.filter]: data.value
    };
    const newFilterQuery = {
      ...query.filters,
      $and: [
        ...query.filters?.$and ?? [],
        {
          [data.name]: filterType === "relation" ? {
            id: operatorValuePairing
          } : operatorValuePairing
        }
      ]
    };
    setQuery({ filters: newFilterQuery, page: 1 });
    setOpen(false);
  };
  return /* @__PURE__ */ jsxRuntime.jsx(
    designSystem.PopoverPrimitives.Content,
    {
      source: { current: triggerNode },
      onDismiss: () => setOpen(false),
      padding: 3,
      spacing: 4,
      maxHeight: "unset",
      children: /* @__PURE__ */ jsxRuntime.jsx(
        index_H1ljeG8.Form,
        {
          method: "POST",
          initialValues: {
            name: options[0]?.name,
            filter: BASE_FILTERS[0].value
          },
          onSubmit: handleSubmit,
          children: ({ values: formValues, modified, isSubmitting }) => {
            const filter = options.find((filter2) => filter2.name === formValues.name);
            const Input = filter?.input || index_H1ljeG8.InputRenderer;
            return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", alignItems: "stretch", gap: 2, style: { minWidth: 184 }, children: [
              [
                {
                  ["aria-label"]: formatMessage({
                    id: "app.utils.select-field",
                    defaultMessage: "Select field"
                  }),
                  name: "name",
                  options: options.map((filter2) => ({
                    label: filter2.label,
                    value: filter2.name
                  })),
                  placholder: formatMessage({
                    id: "app.utils.select-field",
                    defaultMessage: "Select field"
                  }),
                  type: "enumeration"
                },
                {
                  ["aria-label"]: formatMessage({
                    id: "app.utils.select-filter",
                    defaultMessage: "Select filter"
                  }),
                  name: "filter",
                  options: filter?.operators || getFilterList(filter).map((opt) => ({
                    label: formatMessage(opt.label),
                    value: opt.value
                  })),
                  placeholder: formatMessage({
                    id: "app.utils.select-filter",
                    defaultMessage: "Select filter"
                  }),
                  type: "enumeration"
                }
              ].map((field) => /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.InputRenderer, { ...field }, field.name)),
              filter && formValues.filter && formValues.filter !== "$null" && formValues.filter !== "$notNull" ? /* @__PURE__ */ jsxRuntime.jsx(
                Input,
                {
                  ...filter,
                  label: null,
                  "aria-label": filter.label,
                  name: "value",
                  type: filter.mainField?.type ?? filter.type
                }
              ) : null,
              /* @__PURE__ */ jsxRuntime.jsx(
                designSystem.Button,
                {
                  disabled: !modified || isSubmitting,
                  size: "L",
                  variant: "secondary",
                  startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Plus, {}),
                  type: "submit",
                  fullWidth: true,
                  children: formatMessage({ id: "app.utils.add-filter", defaultMessage: "Add filter" })
                }
              )
            ] });
          }
        }
      )
    }
  );
};
const getFilterList = (filter) => {
  if (!filter) {
    return [];
  }
  const type = filter.mainField?.type ? filter.mainField.type : filter.type;
  switch (type) {
    case "email":
    case "text":
    case "enumeration":
    case "string": {
      return [
        ...BASE_FILTERS,
        ...IS_SENSITIVE_FILTERS,
        ...CONTAINS_FILTERS,
        ...STRING_PARSE_FILTERS
      ];
    }
    case "float":
    case "integer":
    case "biginteger":
    case "decimal": {
      return [...BASE_FILTERS, ...NUMERIC_FILTERS];
    }
    case "time":
    case "date": {
      return [...BASE_FILTERS, ...NUMERIC_FILTERS, ...CONTAINS_FILTERS];
    }
    case "datetime": {
      return [...BASE_FILTERS, ...NUMERIC_FILTERS];
    }
    default:
      return [...BASE_FILTERS, ...IS_SENSITIVE_FILTERS];
  }
};
const List = () => {
  const [{ query }, setQuery] = index_H1ljeG8.useQueryParams();
  const options = useFilters("List", ({ options: options2 }) => options2);
  const handleClick = (data) => {
    const nextFilters = (query?.filters?.$and ?? []).filter((filter) => {
      const [attributeName] = Object.keys(filter);
      if (attributeName !== data.name) {
        return true;
      }
      const { type, mainField } = options.find(({ name }) => name === attributeName);
      if (type === "relation") {
        const filterObj = filter[attributeName][mainField?.name ?? "id"];
        if (typeof filterObj === "object") {
          const [operator] = Object.keys(filterObj);
          const value = filterObj[operator];
          return !(operator === data.filter && value === data.value);
        }
        return true;
      } else {
        const filterObj = filter[attributeName];
        const [operator] = Object.keys(filterObj);
        const value = filterObj[operator];
        return !(operator === data.filter && value === data.value);
      }
    });
    setQuery({ filters: { $and: nextFilters }, page: 1 });
  };
  if (!query?.filters?.$and?.length) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: query?.filters?.$and?.map((queryFilter) => {
    const [attributeName] = Object.keys(queryFilter);
    const filter = options.find(({ name }) => name === attributeName);
    const filterObj = queryFilter[attributeName];
    if (!filter || typeof filterObj !== "object" || filterObj === null) {
      return null;
    }
    if (filter.type === "relation") {
      const modelFilter = filterObj[filter.mainField?.name ?? "id"];
      if (typeof modelFilter === "object") {
        const [operator] = Object.keys(modelFilter);
        const value = modelFilter[operator];
        return /* @__PURE__ */ jsxRuntime.jsx(
          AttributeTag,
          {
            ...filter,
            onClick: handleClick,
            operator,
            value
          },
          `${attributeName}-${operator}-${value}`
        );
      }
      return null;
    } else {
      const [operator] = Object.keys(filterObj);
      const value = filterObj[operator];
      if (typeof value === "object") {
        return null;
      }
      return /* @__PURE__ */ jsxRuntime.jsx(
        AttributeTag,
        {
          ...filter,
          onClick: handleClick,
          operator,
          value
        },
        `${attributeName}-${operator}-${value}`
      );
    }
  }) });
};
const AttributeTag = ({
  input,
  label,
  mainField,
  name,
  onClick,
  operator,
  options,
  value,
  ...filter
}) => {
  const { formatMessage, formatDate, formatTime, formatNumber } = reactIntl.useIntl();
  const handleClick = () => {
    onClick({ name, value, filter: operator });
  };
  const type = mainField?.type ? mainField.type : filter.type;
  let formattedValue = value;
  switch (type) {
    case "date":
      formattedValue = formatDate(value, { dateStyle: "full" });
      break;
    case "datetime":
      formattedValue = formatDate(value, { dateStyle: "full", timeStyle: "short" });
      break;
    case "time":
      const [hour, minute] = value.split(":");
      const date = /* @__PURE__ */ new Date();
      date.setHours(Number(hour));
      date.setMinutes(Number(minute));
      formattedValue = formatTime(date, {
        hour: "numeric",
        minute: "numeric"
      });
      break;
    case "float":
    case "integer":
    case "biginteger":
    case "decimal":
      formattedValue = formatNumber(Number(value));
      break;
  }
  if (input && options) {
    const selectedOption = options.find((option) => {
      return (typeof option === "string" ? option : option.value) === value;
    });
    formattedValue = selectedOption ? typeof selectedOption === "string" ? selectedOption : selectedOption.label ?? selectedOption.value : value;
  }
  const content = `${label} ${formatMessage({
    id: `components.FilterOptions.FILTER_TYPES.${operator}`,
    defaultMessage: operator
  })} ${operator !== "$null" && operator !== "$notNull" ? formattedValue : ""}`;
  return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tag, { padding: 1, onClick: handleClick, icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Cross, {}), children: content });
};
const Filters = {
  List,
  Popover: PopoverImpl,
  Root,
  Trigger
};
const REVIEW_WORKFLOW_FILTER_CE = [];
const NOT_ALLOWED_FILTERS = [
  "json",
  "component",
  "media",
  "richtext",
  "dynamiczone",
  "password",
  "blocks"
];
const DEFAULT_ALLOWED_FILTERS = ["createdAt", "updatedAt"];
const USER_FILTER_ATTRIBUTES = [...index_H1ljeG8.CREATOR_FIELDS, "strapi_assignee"];
const FiltersImpl = ({ disabled, schema }) => {
  const { attributes, uid: model, options } = schema;
  const { formatMessage, locale } = reactIntl.useIntl();
  const { trackUsage } = index_H1ljeG8.useTracking();
  const allPermissions = index_H1ljeG8.useAuth("FiltersImpl", (state) => state.permissions);
  const [{ query }] = index_H1ljeG8.useQueryParams();
  const { schemas } = index_H1ljeG8.useContentTypeSchema();
  const canReadAdminUsers = React__namespace.useMemo(
    () => allPermissions.filter(
      (permission) => permission.action === "admin::users.read" && permission.subject === null
    ).length > 0,
    [allPermissions]
  );
  const selectedUserIds = (query?.filters?.$and ?? []).reduce((acc, filter) => {
    const [key, value] = Object.entries(filter)[0];
    if (typeof value.id !== "object") {
      return acc;
    }
    const id = value.id.$eq || value.id.$ne;
    if (id && USER_FILTER_ATTRIBUTES.includes(key) && !acc.includes(id)) {
      acc.push(id);
    }
    return acc;
  }, []);
  const { data: userData, isLoading: isLoadingAdminUsers } = index_H1ljeG8.useAdminUsers(
    { filters: { id: { $in: selectedUserIds } } },
    {
      // fetch the list of admin users only if the filter contains users and the
      // current user has permissions to display users
      skip: selectedUserIds.length === 0 || !canReadAdminUsers
    }
  );
  const { users = [] } = userData ?? {};
  const { metadata } = index_H1ljeG8.useGetContentTypeConfigurationQuery(model, {
    selectFromResult: ({ data }) => ({ metadata: data?.contentType.metadatas ?? {} })
  });
  const formatter = designSystem.useCollator(locale, {
    sensitivity: "base"
  });
  const displayedAttributeFilters = React__namespace.useMemo(() => {
    const [{ properties: { fields = [] } = { fields: [] } }] = allPermissions.filter(
      (permission) => permission.action === "plugin::content-manager.explorer.read" && permission.subject === model
    );
    const allowedFields = fields.filter((field) => {
      const attribute = attributes[field] ?? {};
      return attribute.type && !NOT_ALLOWED_FILTERS.includes(attribute.type);
    });
    return [
      "id",
      ...allowedFields,
      ...DEFAULT_ALLOWED_FILTERS,
      ...canReadAdminUsers ? index_H1ljeG8.CREATOR_FIELDS : []
    ].map((name) => {
      const attribute = attributes[name];
      if (NOT_ALLOWED_FILTERS.includes(attribute.type)) {
        return null;
      }
      const { mainField: mainFieldName = "", label } = metadata[name].list;
      let filter = {
        name,
        label: label ?? "",
        mainField: index_H1ljeG8.getMainField(attribute, mainFieldName, { schemas, components: {} }),
        // @ts-expect-error – TODO: this is filtered out above in the `allowedFields` call but TS complains, is there a better way to solve this?
        type: attribute.type
      };
      if (attribute.type === "relation" && "target" in attribute && attribute.target === "admin::user") {
        filter = {
          ...filter,
          input: AdminUsersFilter,
          options: users.map((user) => ({
            label: index_H1ljeG8.getDisplayName(user, formatMessage),
            value: user.id.toString()
          })),
          operators: [
            {
              label: formatMessage({
                id: "components.FilterOptions.FILTER_TYPES.$eq",
                defaultMessage: "is"
              }),
              value: "$eq"
            },
            {
              label: formatMessage({
                id: "components.FilterOptions.FILTER_TYPES.$ne",
                defaultMessage: "is not"
              }),
              value: "$ne"
            }
          ],
          mainField: {
            name: "id",
            type: "integer"
          }
        };
      }
      return filter;
    }).filter(Boolean);
  }, [
    allPermissions,
    model,
    canReadAdminUsers,
    attributes,
    metadata,
    schemas,
    users,
    formatMessage
  ]);
  const reviewWorkflowFilter = index_H1ljeG8.useEnterprise(
    REVIEW_WORKFLOW_FILTER_CE,
    async () => (await Promise.resolve().then(() => require("./constants-VMWcn5Dg-AljxaBIG.js"))).REVIEW_WORKFLOW_FILTERS,
    {
      combine(ceFilters, eeFilters) {
        return [
          ...ceFilters,
          ...eeFilters.filter((eeFilter) => {
            if (eeFilter.name === "strapi_assignee") {
              return canReadAdminUsers;
            }
            return true;
          }).map((eeFilter) => ({
            ...eeFilter,
            "aria-label": formatMessage(eeFilter.label),
            options: (
              // TODO: strapi_assignee should not be in here and rather defined
              // in the ee directory.
              eeFilter.name === "strapi_assignee" ? users.map((user) => ({
                label: index_H1ljeG8.getDisplayName(user, formatMessage),
                value: user.id.toString()
              })) : void 0
            )
          }))
        ];
      },
      defaultValue: [],
      // we have to wait for admin users to be fully loaded, because otherwise
      // combine is called to early and does not contain the latest state of
      // the users array
      enabled: !!options?.reviewWorkflows && !isLoadingAdminUsers
    }
    /**
     * this is cast because the data returns MessageDescriptor
     * as `metadatas.label` _then_ we turn it to a string.
     */
  );
  const onOpenChange = (isOpen) => {
    if (isOpen) {
      trackUsage("willFilterEntries");
    }
  };
  const displayedFilters = [...displayedAttributeFilters, ...reviewWorkflowFilter].sort(
    (a, b) => formatter.compare(a.label, b.label)
  );
  const handleFilterChange = (data) => {
    const attribute = attributes[data.name];
    if (attribute) {
      trackUsage("didFilterEntries", {
        useRelation: attribute.type === "relation"
      });
    }
  };
  return /* @__PURE__ */ jsxRuntime.jsxs(
    Filters.Root,
    {
      disabled,
      options: displayedFilters,
      onOpenChange,
      onChange: handleFilterChange,
      children: [
        /* @__PURE__ */ jsxRuntime.jsx(Filters.Trigger, {}),
        /* @__PURE__ */ jsxRuntime.jsx(Filters.Popover, {}),
        /* @__PURE__ */ jsxRuntime.jsx(Filters.List, {})
      ]
    }
  );
};
const AdminUsersFilter = ({ name }) => {
  const [page, setPage] = React__namespace.useState(1);
  const { formatMessage } = reactIntl.useIntl();
  const { data, isLoading } = index_H1ljeG8.useAdminUsers({
    page
  });
  const field = index_H1ljeG8.useField(name);
  const handleOpenChange = (isOpen) => {
    if (!isOpen) {
      setPage(1);
    }
  };
  const users = data?.users || [];
  return /* @__PURE__ */ jsxRuntime.jsx(
    designSystem.Combobox,
    {
      value: field.value,
      "aria-label": formatMessage({
        id: "content-manager.components.Filters.usersSelect.label",
        defaultMessage: "Search and select a user to filter"
      }),
      onOpenChange: handleOpenChange,
      onChange: (value) => field.onChange(name, value),
      loading: isLoading,
      onLoadMore: () => setPage((prev) => prev + 1),
      children: users.map((user) => {
        return /* @__PURE__ */ jsxRuntime.jsx(designSystem.ComboboxOption, { value: user.id.toString(), children: index_H1ljeG8.getDisplayName(user, formatMessage) }, user.id);
      })
    }
  );
};
const CellValue = ({ type, value }) => {
  const { formatDate, formatTime, formatNumber } = reactIntl.useIntl();
  let formattedValue = value;
  if (type === "date") {
    formattedValue = formatDate(parseISO(value), { dateStyle: "full" });
  }
  if (type === "datetime") {
    formattedValue = formatDate(value, { dateStyle: "full", timeStyle: "short" });
  }
  if (type === "time") {
    const [hour, minute, second] = value.split(":");
    const date = /* @__PURE__ */ new Date();
    date.setHours(hour);
    date.setMinutes(minute);
    date.setSeconds(second);
    formattedValue = formatTime(date, {
      timeStyle: "short"
    });
  }
  if (["float", "decimal"].includes(type)) {
    formattedValue = formatNumber(value, {
      // Should be kept in sync with the corresponding value
      // in the design-system/NumberInput: https://github.com/strapi/design-system/blob/main/packages/strapi-design-system/src/NumberInput/NumberInput.js#L53
      maximumFractionDigits: 20
    });
  }
  if (["integer", "biginteger"].includes(type)) {
    formattedValue = formatNumber(value, { maximumFractionDigits: 0 });
  }
  return toString__default.default(formattedValue);
};
const SingleComponent = ({ content, mainField }) => {
  if (!mainField) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tooltip, { label: content[mainField.name], children: /* @__PURE__ */ jsxRuntime.jsx(SingleComponentTypography, { textColor: "neutral800", ellipsis: true, children: /* @__PURE__ */ jsxRuntime.jsx(CellValue, { type: mainField.type, value: content[mainField.name] }) }) });
};
const SingleComponentTypography = styled__default.default(designSystem.Typography)`
  max-width: 250px;
`;
const RepeatableComponent = ({ content, mainField }) => {
  const { formatMessage } = reactIntl.useIntl();
  if (!mainField) {
    return null;
  }
  return /* @__PURE__ */ jsxRuntime.jsxs(v2.Menu.Root, { children: [
    /* @__PURE__ */ jsxRuntime.jsxs(MenuTrigger$1, { onClick: (e) => e.stopPropagation(), children: [
      /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { children: content.length }),
      " ",
      formatMessage(
        {
          id: "content-manager.containers.list.items",
          defaultMessage: "{number, plural, =0 {items} one {item} other {items}}"
        },
        { number: content.length }
      )
    ] }),
    /* @__PURE__ */ jsxRuntime.jsx(v2.Menu.Content, { children: content.map((item) => /* @__PURE__ */ jsxRuntime.jsx(v2.Menu.Item, { disabled: true, children: /* @__PURE__ */ jsxRuntime.jsx(RepeatableComponentTypography, { ellipsis: true, children: /* @__PURE__ */ jsxRuntime.jsx(CellValue, { type: mainField.type, value: item[mainField.name] }) }) }, item.id)) })
  ] });
};
const RepeatableComponentTypography = styled__default.default(designSystem.Typography)`
  max-width: 500px;
`;
const MenuTrigger$1 = styled__default.default(v2.Menu.Trigger)`
  svg {
    width: ${6 / 16}rem;
    height: ${4 / 16}rem;
  }
`;
const getFileExtension = (ext) => ext && ext[0] === "." ? ext.substring(1) : ext;
const MediaSingle = ({ url, mime, alternativeText, name, ext, formats }) => {
  const fileURL = index_H1ljeG8.prefixFileUrlWithBackendUrl(url);
  if (mime.includes("image")) {
    const thumbnail = formats?.thumbnail?.url;
    const mediaURL = index_H1ljeG8.prefixFileUrlWithBackendUrl(thumbnail) || fileURL;
    return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Avatar, { src: mediaURL, alt: alternativeText || name, preview: true });
  }
  const fileExtension = getFileExtension(ext);
  const fileName = name.length > 100 ? `${name.substring(0, 100)}...` : name;
  return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tooltip, { description: fileName, children: /* @__PURE__ */ jsxRuntime.jsx(FileWrapper, { children: fileExtension }) });
};
const FileWrapper = ({ children }) => {
  return /* @__PURE__ */ jsxRuntime.jsx(
    designSystem.Flex,
    {
      as: "span",
      position: "relative",
      borderRadius: "50%",
      width: "26px",
      height: "26px",
      borderColor: "neutral200",
      background: "neutral150",
      paddingLeft: "1px",
      justifyContent: "center",
      alignItems: "center",
      children: /* @__PURE__ */ jsxRuntime.jsx(FileTypography, { variant: "sigma", textColor: "neutral600", children })
    }
  );
};
const FileTypography = styled__default.default(designSystem.Typography)`
  font-size: 0.6rem;
  line-height: 0.6rem;
`;
const MediaMultiple = ({ content }) => {
  return /* @__PURE__ */ jsxRuntime.jsx(designSystem.AvatarGroup, { children: content.map((file, index) => {
    const key = `${file.id}${index}`;
    if (index === 3) {
      const remainingFiles = `+${content.length - 3}`;
      return /* @__PURE__ */ jsxRuntime.jsx(FileWrapper, { children: remainingFiles }, key);
    }
    if (index > 3) {
      return null;
    }
    return /* @__PURE__ */ jsxRuntime.jsx(MediaSingle, { ...file }, key);
  }) });
};
const RelationSingle = ({ mainField, content }) => {
  return /* @__PURE__ */ jsxRuntime.jsx(TypographyMaxWidth$1, { textColor: "neutral800", ellipsis: true, children: index_H1ljeG8.getRelationLabel(content, mainField) });
};
const TypographyMaxWidth$1 = styled__default.default(designSystem.Typography)`
  max-width: 500px;
`;
const RelationMultiple = ({ mainField, content, rowId, name }) => {
  const { model } = index_H1ljeG8.useDoc();
  const { formatMessage } = reactIntl.useIntl();
  const { notifyStatus } = designSystem.useNotifyAT();
  const [isOpen, setIsOpen] = React__namespace.useState(false);
  const [targetField] = name.split(".");
  const { data, isLoading } = index_H1ljeG8.useGetRelationsQuery(
    {
      model,
      id: rowId,
      targetField
    },
    {
      skip: !isOpen,
      refetchOnMountOrArgChange: true
    }
  );
  React__namespace.useEffect(() => {
    if (data) {
      notifyStatus(
        formatMessage({
          id: index_H1ljeG8.getTranslation("DynamicTable.relation-loaded"),
          defaultMessage: "Relations have been loaded"
        })
      );
    }
  }, [data, formatMessage, notifyStatus]);
  return /* @__PURE__ */ jsxRuntime.jsxs(v2.Menu.Root, { onOpenChange: (isOpen2) => setIsOpen(isOpen2), children: [
    /* @__PURE__ */ jsxRuntime.jsx(MenuTrigger, { onClick: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, wrap: "nowrap", children: [
      /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { children: content.count }),
      formatMessage(
        {
          id: "content-manager.containers.list.items",
          defaultMessage: "{number, plural, =0 {items} one {item} other {items}}"
        },
        { number: content.count }
      )
    ] }) }),
    /* @__PURE__ */ jsxRuntime.jsxs(v2.Menu.Content, { children: [
      isLoading && /* @__PURE__ */ jsxRuntime.jsx(v2.Menu.Item, { disabled: true, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Loader, { small: true, children: formatMessage({
        id: index_H1ljeG8.getTranslation("ListViewTable.relation-loading"),
        defaultMessage: "Relations are loading"
      }) }) }),
      data?.results && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
        data.results.map((entry) => /* @__PURE__ */ jsxRuntime.jsx(v2.Menu.Item, { disabled: true, children: /* @__PURE__ */ jsxRuntime.jsx(TypographyMaxWidth$1, { ellipsis: true, children: index_H1ljeG8.getRelationLabel(entry, mainField) }) }, entry.documentId)),
        data?.pagination && data?.pagination.total > 10 && /* @__PURE__ */ jsxRuntime.jsx(
          v2.Menu.Item,
          {
            "aria-disabled": true,
            "aria-label": formatMessage({
              id: index_H1ljeG8.getTranslation("ListViewTable.relation-more"),
              defaultMessage: "This relation contains more entities than displayed"
            }),
            children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { children: "…" })
          }
        )
      ] })
    ] })
  ] });
};
const MenuTrigger = styled__default.default(v2.Menu.Trigger)`
  svg {
    width: ${6 / 16}rem;
    height: ${4 / 16}rem;
  }
`;
const CellContent = ({ content, mainField, attribute, rowId, name }) => {
  if (!hasContent(content, mainField, attribute)) {
    return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral800", children: "-" });
  }
  switch (attribute.type) {
    case "media":
      if (!attribute.multiple) {
        return /* @__PURE__ */ jsxRuntime.jsx(MediaSingle, { ...content });
      }
      return /* @__PURE__ */ jsxRuntime.jsx(MediaMultiple, { content });
    case "relation": {
      if (isSingleRelation(attribute.relation)) {
        return /* @__PURE__ */ jsxRuntime.jsx(RelationSingle, { mainField, content });
      }
      return /* @__PURE__ */ jsxRuntime.jsx(RelationMultiple, { rowId, mainField, content, name });
    }
    case "component":
      if (attribute.repeatable) {
        return /* @__PURE__ */ jsxRuntime.jsx(RepeatableComponent, { mainField, content });
      }
      return /* @__PURE__ */ jsxRuntime.jsx(SingleComponent, { mainField, content });
    case "string":
      return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tooltip, { description: content, children: /* @__PURE__ */ jsxRuntime.jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: /* @__PURE__ */ jsxRuntime.jsx(CellValue, { type: attribute.type, value: content }) }) });
    default:
      return /* @__PURE__ */ jsxRuntime.jsx(TypographyMaxWidth, { ellipsis: true, textColor: "neutral800", children: /* @__PURE__ */ jsxRuntime.jsx(CellValue, { type: attribute.type, value: content }) });
  }
};
const TypographyMaxWidth = styled__default.default(designSystem.Typography)`
  max-width: 300px;
`;
const hasContent = (content, mainField, attribute) => {
  if (attribute.type === "component") {
    if (attribute.repeatable || !mainField) {
      return content?.length > 0;
    }
    const value = content?.[mainField.name];
    if (mainField.name === "id" && ![void 0, null].includes(value)) {
      return true;
    }
    return !isEmpty__default.default(value);
  }
  if (attribute.type === "relation") {
    if (isSingleRelation(attribute.relation)) {
      return !isEmpty__default.default(content);
    }
    return content?.count > 0;
  }
  if (["integer", "decimal", "float", "number"].includes(attribute.type)) {
    return typeof content === "number";
  }
  if (attribute.type === "boolean") {
    return content !== null;
  }
  return !isEmpty__default.default(content);
};
const isSingleRelation = (type) => ["oneToOne", "manyToOne", "oneToOneMorph"].includes(type);
const ViewSettingsMenu = (props) => {
  const [isVisible, setIsVisible] = React__namespace.useState(false);
  const cogButtonRef = React__namespace.useRef(null);
  const permissions = index_H1ljeG8.useTypedSelector(
    (state) => state.admin_app.permissions.contentManager?.collectionTypesConfigurations ?? []
  );
  const [{ query }] = index_H1ljeG8.useQueryParams();
  const { formatMessage } = reactIntl.useIntl();
  const {
    allowedActions: { canViewConfiguration }
  } = index_H1ljeG8.useRBAC({
    viewConfiguration: permissions
  });
  const handleToggle = () => {
    setIsVisible((prev) => !prev);
  };
  return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(
      designSystem.IconButton,
      {
        icon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Cog, {}),
        label: formatMessage({
          id: "components.ViewSettings.tooltip",
          defaultMessage: "View Settings"
        }),
        ref: cogButtonRef,
        onClick: handleToggle
      }
    ),
    isVisible && /* @__PURE__ */ jsxRuntime.jsx(
      designSystem.Popover,
      {
        placement: "bottom-end",
        source: cogButtonRef,
        onDismiss: handleToggle,
        spacing: 4,
        padding: 3,
        children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { alignItems: "stretch", direction: "column", gap: 3, children: [
          canViewConfiguration ? /* @__PURE__ */ jsxRuntime.jsx(
            v2.LinkButton,
            {
              size: "S",
              startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Layer, {}),
              variant: "secondary",
              as: reactRouterDom.NavLink,
              to: {
                pathname: "configurations/list",
                search: query.plugins ? index_H1ljeG8.lib.stringify({ plugins: query.plugins }, { encode: false }) : ""
              },
              children: formatMessage({
                id: "app.links.configure-view",
                defaultMessage: "Configure the view"
              })
            }
          ) : null,
          /* @__PURE__ */ jsxRuntime.jsx(FieldPicker, { ...props })
        ] })
      }
    )
  ] });
};
const FieldPicker = ({ headers = [], resetHeaders, setHeaders }) => {
  const { trackUsage } = index_H1ljeG8.useTracking();
  const { formatMessage, locale } = reactIntl.useIntl();
  const { schema, model } = index_H1ljeG8.useDoc();
  const { list } = index_H1ljeG8.useDocumentLayout(model);
  const formatter = designSystem.useCollator(locale, {
    sensitivity: "base"
  });
  const attributes = schema?.attributes ?? {};
  const columns = Object.keys(attributes).filter((name) => index_H1ljeG8.checkIfAttributeIsDisplayable(attributes[name])).map((name) => ({
    name,
    label: list.metadatas[name]?.label ?? ""
  })).sort((a, b) => formatter.compare(a.label, b.label));
  const handleChange = (name) => {
    trackUsage("didChangeDisplayedFields");
    const newHeaders = headers.includes(name) ? headers.filter((header) => header !== name) : [...headers, name];
    setHeaders(newHeaders);
  };
  const handleReset = () => {
    resetHeaders();
  };
  return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { as: "fieldset", direction: "column", alignItems: "stretch", gap: 3, children: [
    /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", children: [
      /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { as: "legend", variant: "pi", fontWeight: "bold", children: formatMessage({
        id: "containers.list.displayedFields",
        defaultMessage: "Displayed fields"
      }) }),
      /* @__PURE__ */ jsxRuntime.jsx(designSystem.TextButton, { onClick: handleReset, children: formatMessage({
        id: "app.components.Button.reset",
        defaultMessage: "Reset"
      }) })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { direction: "column", alignItems: "stretch", children: columns.map((header) => {
      const isActive = headers.includes(header.name);
      return /* @__PURE__ */ jsxRuntime.jsxs(
        ChackboxWrapper,
        {
          wrap: "wrap",
          gap: 2,
          as: "label",
          background: isActive ? "primary100" : "transparent",
          hasRadius: true,
          padding: 2,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx(
              designSystem.BaseCheckbox,
              {
                onChange: () => handleChange(header.name),
                value: isActive,
                name: header.name
              }
            ),
            /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontSize: 1, children: header.label })
          ]
        },
        header.name
      );
    }) })
  ] });
};
const ChackboxWrapper = styled__default.default(designSystem.Flex)`
  :hover {
    background-color: ${(props) => props.theme.colors.primary100};
  }
`;
const { INJECT_COLUMN_IN_TABLE } = index_H1ljeG8.HOOKS;
const REVIEW_WORKFLOW_COLUMNS_CE = null;
const REVIEW_WORKFLOW_COLUMNS_CELL_CE = {
  ReviewWorkflowsStageEE: () => null,
  ReviewWorkflowsAssigneeEE: () => null
};
const ListViewPage = () => {
  const { trackUsage } = index_H1ljeG8.useTracking();
  const navigate = reactRouterDom.useNavigate();
  const { formatMessage } = reactIntl.useIntl();
  const { toggleNotification } = index_H1ljeG8.useNotification();
  const { _unstableFormatAPIError: formatAPIError } = index_H1ljeG8.useAPIErrorHandler(index_H1ljeG8.getTranslation);
  const { collectionType, model, schema } = index_H1ljeG8.useDoc();
  const { list } = index_H1ljeG8.useDocumentLayout(model);
  const [displayedHeaders, setDisplayedHeaders] = React__namespace.useState([]);
  const listLayout = index_H1ljeG8.usePrev(list.layout);
  React__namespace.useEffect(() => {
    if (!isEqual__default.default(listLayout, list.layout)) {
      setDisplayedHeaders(list.layout);
    }
  }, [list.layout, listLayout]);
  const handleSetHeaders = (headers) => {
    setDisplayedHeaders(
      index_H1ljeG8.convertListLayoutToFieldLayouts(headers, schema.attributes, list.metadatas)
    );
  };
  const [{ query }] = index_H1ljeG8.useQueryParams({
    page: "1",
    pageSize: list.settings.pageSize.toString(),
    sort: list.settings.defaultSortBy ? `${list.settings.defaultSortBy}:${list.settings.defaultSortOrder}` : ""
  });
  const params = React__namespace.useMemo(() => index_H1ljeG8.buildValidParams(query), [query]);
  const { data, error, isLoading } = index_H1ljeG8.useGetAllDocumentsQuery({
    model,
    params
  });
  React__namespace.useEffect(() => {
    if (error) {
      toggleNotification({
        type: "danger",
        message: formatAPIError(error)
      });
    }
  }, [error, formatAPIError, toggleNotification]);
  const { results = [], pagination } = data ?? {};
  React__namespace.useEffect(() => {
    if (pagination && pagination.pageCount > 0 && pagination.page > pagination.pageCount) {
      navigate(
        {
          search: index_H1ljeG8.lib.stringify({
            ...query,
            page: pagination.pageCount
          })
        },
        { replace: true }
      );
    }
  }, [pagination, formatMessage, query, navigate]);
  const { canCreate } = index_H1ljeG8.useDocumentRBAC("ListViewPage", ({ canCreate: canCreate2 }) => ({
    canCreate: canCreate2
  }));
  const reviewWorkflowColumns = index_H1ljeG8.useEnterprise(
    REVIEW_WORKFLOW_COLUMNS_CE,
    async () => (await Promise.resolve().then(() => require("./constants-VMWcn5Dg-AljxaBIG.js"))).REVIEW_WORKFLOW_COLUMNS_EE,
    {
      enabled: !!schema?.options?.reviewWorkflows
    }
  );
  const ReviewWorkflowsColumns = index_H1ljeG8.useEnterprise(
    REVIEW_WORKFLOW_COLUMNS_CELL_CE,
    async () => {
      const { ReviewWorkflowsStageEE, ReviewWorkflowsAssigneeEE } = await Promise.resolve().then(() => require("./ReviewWorkflowsColumn-6zZJluSU-kgZGsgKW.js"));
      return { ReviewWorkflowsStageEE, ReviewWorkflowsAssigneeEE };
    },
    {
      enabled: !!schema?.options?.reviewWorkflows
    }
  );
  const runHookWaterfall = index_H1ljeG8.useStrapiApp("ListViewPage", ({ runHookWaterfall: runHookWaterfall2 }) => runHookWaterfall2);
  const tableHeaders = React__namespace.useMemo(() => {
    const headers = runHookWaterfall(INJECT_COLUMN_IN_TABLE, {
      displayedHeaders,
      layout: list
    });
    const formattedHeaders = headers.displayedHeaders.map((header) => {
      return {
        ...header,
        label: typeof header.label === "string" ? header.label : formatMessage(header.label),
        name: `${header.name}${header.mainField ? `.${header.mainField}` : ""}`
      };
    });
    if (schema?.options?.draftAndPublish) {
      formattedHeaders.push({
        attribute: {
          type: "custom"
        },
        name: "status",
        label: formatMessage({
          id: index_H1ljeG8.getTranslation(`containers.list.table-headers.status`),
          defaultMessage: "status"
        }),
        searchable: false,
        sortable: false
      });
    }
    if (reviewWorkflowColumns) {
      formattedHeaders.push(
        ...reviewWorkflowColumns.map((column) => ({
          ...column,
          label: formatMessage(column.label)
        }))
      );
    }
    return formattedHeaders;
  }, [
    displayedHeaders,
    formatMessage,
    list,
    reviewWorkflowColumns,
    runHookWaterfall,
    schema?.options?.draftAndPublish
  ]);
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Page.Loading, {});
  }
  if (error) {
    return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Page.Error, {});
  }
  const contentTypeTitle = schema?.info.displayName ?? "Untitled";
  const handleRowClick = (id) => () => {
    trackUsage("willEditEntryFromList");
    navigate({
      pathname: id.toString(),
      search: index_H1ljeG8.lib.stringify({ plugins: query.plugins })
    });
  };
  return /* @__PURE__ */ jsxRuntime.jsxs(index_H1ljeG8.Page.Main, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(Helmet.HelmetExport, { title: `${contentTypeTitle} | Strapi` }),
    /* @__PURE__ */ jsxRuntime.jsx(
      designSystem.HeaderLayout,
      {
        primaryAction: canCreate ? /* @__PURE__ */ jsxRuntime.jsx(CreateButton, {}) : null,
        subtitle: formatMessage(
          {
            id: index_H1ljeG8.getTranslation("pages.ListView.header-subtitle"),
            defaultMessage: "{number, plural, =0 {# entries} one {# entry} other {# entries}} found"
          },
          { number: pagination?.total }
        ),
        title: contentTypeTitle,
        navigationAction: /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.BackButton, {})
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(
      designSystem.ActionLayout,
      {
        endActions: /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
          /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.InjectionZone, { area: "contentManager.listView.actions" }),
          /* @__PURE__ */ jsxRuntime.jsx(
            ViewSettingsMenu,
            {
              setHeaders: handleSetHeaders,
              resetHeaders: () => setDisplayedHeaders(list.layout),
              headers: displayedHeaders.map((header) => header.name)
            }
          )
        ] }),
        startActions: /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
          list.settings.searchable && /* @__PURE__ */ jsxRuntime.jsx(
            index_H1ljeG8.SearchInput,
            {
              disabled: results.length === 0,
              label: formatMessage(
                { id: "app.component.search.label", defaultMessage: "Search for {target}" },
                { target: contentTypeTitle }
              ),
              placeholder: formatMessage({
                id: "global.search",
                defaultMessage: "Search"
              }),
              trackedEvent: "didSearch"
            }
          ),
          list.settings.filterable && schema ? /* @__PURE__ */ jsxRuntime.jsx(FiltersImpl, { disabled: results.length === 0, schema }) : null
        ] })
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx(designSystem.ContentLayout, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 4, direction: "column", alignItems: "stretch", children: [
      /* @__PURE__ */ jsxRuntime.jsxs(index_H1ljeG8.Table.Root, { rows: results, headers: tableHeaders, isLoading, children: [
        /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.ActionBar, {}),
        /* @__PURE__ */ jsxRuntime.jsxs(index_H1ljeG8.Table.Content, { children: [
          /* @__PURE__ */ jsxRuntime.jsxs(index_H1ljeG8.Table.Head, { children: [
            /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.HeaderCheckboxCell, {}),
            tableHeaders.map((header) => /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.HeaderCell, { ...header }, header.name))
          ] }),
          /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.Loading, {}),
          /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.Empty, { action: canCreate ? /* @__PURE__ */ jsxRuntime.jsx(CreateButton, { variant: "secondary" }) : null }),
          /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.Body, { children: results.map((row) => {
            return /* @__PURE__ */ jsxRuntime.jsxs(
              index_H1ljeG8.Table.Row,
              {
                cursor: "pointer",
                onClick: handleRowClick(row.documentId),
                children: [
                  /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.CheckboxCell, { id: row.id }),
                  tableHeaders.map(({ cellFormatter, ...header }) => {
                    if (header.name === "status") {
                      const { status } = row;
                      return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.DocumentStatus, { status, maxWidth: "min-content" }) }, header.name);
                    }
                    if (schema?.options?.reviewWorkflows) {
                      if (header.name === "strapi_stage") {
                        return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.Cell, { children: row.strapi_stage ? /* @__PURE__ */ jsxRuntime.jsx(
                          ReviewWorkflowsColumns.ReviewWorkflowsStageEE,
                          {
                            color: row.strapi_stage.color ?? designSystem.lightTheme.colors.primary600,
                            name: row.strapi_stage.name
                          }
                        ) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral800", children: "-" }) }, header.name);
                      }
                      if (header.name === "strapi_assignee") {
                        return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.Cell, { children: row.strapi_assignee ? /* @__PURE__ */ jsxRuntime.jsx(
                          ReviewWorkflowsColumns.ReviewWorkflowsAssigneeEE,
                          {
                            user: row.strapi_assignee
                          }
                        ) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral800", children: "-" }) }, header.name);
                      }
                    }
                    if (["createdBy", "updatedBy"].includes(header.name.split(".")[0])) {
                      return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral800", children: row[header.name.split(".")[0]] ? index_H1ljeG8.getDisplayName(row[header.name.split(".")[0]], formatMessage) : "-" }) }, header.name);
                    }
                    if (typeof cellFormatter === "function") {
                      return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.Cell, { children: cellFormatter(row, header, { collectionType, model }) }, header.name);
                    }
                    return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Table.Cell, { children: /* @__PURE__ */ jsxRuntime.jsx(
                      CellContent,
                      {
                        content: row[header.name.split(".")[0]],
                        rowId: row.documentId,
                        ...header
                      }
                    ) }, header.name);
                  }),
                  /* @__PURE__ */ jsxRuntime.jsx(ActionsCell, { onClick: (e) => e.stopPropagation(), children: /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.TableActions, { document: row }) })
                ]
              },
              row.id
            );
          }) })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntime.jsxs(
        index_H1ljeG8.Pagination.Root,
        {
          ...pagination,
          onPageSizeChange: () => trackUsage("willChangeNumberOfEntriesPerPage"),
          children: [
            /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Pagination.PageSize, {}),
            /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Pagination.Links, {})
          ]
        }
      )
    ] }) })
  ] });
};
const ActionsCell = styled__default.default(index_H1ljeG8.Table.Cell)`
  display: flex;
  justify-content: flex-end;
`;
const CreateButton = ({ variant }) => {
  const { formatMessage } = reactIntl.useIntl();
  const { trackUsage } = index_H1ljeG8.useTracking();
  const [{ query }] = index_H1ljeG8.useQueryParams();
  return /* @__PURE__ */ jsxRuntime.jsx(
    designSystem.Button,
    {
      variant,
      forwardedAs: reactRouterDom.Link,
      onClick: () => {
        trackUsage("willCreateEntry", { status: "draft" });
      },
      startIcon: /* @__PURE__ */ jsxRuntime.jsx(Icons.Plus, {}),
      style: { textDecoration: "none" },
      to: {
        pathname: "create",
        search: index_H1ljeG8.lib.stringify({ plugins: query.plugins })
      },
      children: formatMessage({
        id: index_H1ljeG8.getTranslation("HeaderLayout.button.label-add-entry"),
        defaultMessage: "Create new entry"
      })
    }
  );
};
const ProtectedListViewPage = () => {
  const { model } = index_H1ljeG8.useDoc();
  const [{ query }] = index_H1ljeG8.useQueryParams();
  const { permissions = [], isLoading, isError } = useSyncRbacOd0wrAnD.useSyncRbac(model, query, "editView");
  if (isLoading) {
    return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Page.Loading, {});
  }
  if (isError) {
    return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Page.Error, {});
  }
  return /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.Page.Protect, { permissions, children: ({ permissions: permissions2 }) => /* @__PURE__ */ jsxRuntime.jsx(index_H1ljeG8.DocumentRBAC, { permissions: permissions2, children: /* @__PURE__ */ jsxRuntime.jsx(ListViewPage, {}) }) });
};
exports.ListViewPage = ListViewPage;
exports.ProtectedListViewPage = ProtectedListViewPage;
//# sourceMappingURL=ListViewPage-TJbHzMdV-02M2sPzu.js.map
