import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback, Fragment } from "react";
import "./index.W70dzubm.js";
import { ak as useQueries, al as BsDatabaseDown, am as RiBracesLine, an as BsDatabase, ao as PiListNumbersLight, m as useDraftHelpers, ap as usePagePathParams, aq as validate, ar as querySchema, as as TbPlus, aj as RxCross2, at as debounce } from "./use-page-data.BgY0vKG4.js";
import { i as useModal, u as useEditorHelpers } from "./use-editor.BTqnSFNX.js";
import { g as getDatasourceIndexedFieldsWithTitles } from "./utils.Bfvth39C.js";
import { s, u as useDatasources, p, l as g, o as m, q as useDatasource, F as FieldTitle, r as u, d as C, e as u$1, h as g$1, v, y, I, t as p$1, w as l, T as TagsSelect } from "./field-factory.BeLLxyEh.js";
import { a as tx } from "./twind.DdSZmZu6.js";
import { L as LuPlus } from "./index.Dl8aD6-M.js";
import { b as FiEdit } from "./index.xEpbMg6Y.js";
import { o } from "./Editor.3ItZCyKd.js";
import { e } from "./tooltip.uLVjj809.js";
import { o as o$1 } from "./use-editable-text.CyXfLgKN.js";
function Modal() {
  const modal = useModal();
  const { hideModal } = useEditorHelpers();
  return /* @__PURE__ */ jsx(
    s,
    {
      open: !!modal,
      onOpenChange: (open) => {
        if (!open) {
          hideModal();
        }
      },
      children: modal === "queries" && /* @__PURE__ */ jsx(ModalQueriesEdtor, {})
    }
  );
}
function ModalQueriesEdtor() {
  const [editingQuery, setEditingQuery] = useState(null);
  const queries = useQueries();
  const [showCreationForm, setShowCreationForm] = useState(queries.length === 0);
  const datasources = useDatasources();
  return /* @__PURE__ */ jsxs(
    p,
    {
      "aria-describedby": "Queries management",
      maxWidth: "860px",
      minHeight: "80dvh",
      className: "overflow-y-clip flex flex-col gap-y-2",
      children: [
        /* @__PURE__ */ jsxs(g, { className: "flex items-center gap-3 pl-0 -ml-3", children: [
          /* @__PURE__ */ jsx(BsDatabaseDown, { className: "h-6 w-6 text-upstart-600" }),
          "Manage queries",
          /* @__PURE__ */ jsxs(
            o,
            {
              size: "2",
              disabled: !datasources.length || showCreationForm,
              variant: "outline",
              radius: "medium",
              className: tx("!ml-auto", showCreationForm && "!opacity-0"),
              onClick: () => {
                setEditingQuery(null);
                setShowCreationForm(true);
              },
              children: [
                /* @__PURE__ */ jsx(LuPlus, { className: "w-4 h-4" }),
                "Create Query"
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsx(m, { children: "Queries fetch data from your database. Once defined, a query can be referenced throughout your pages to loop through results and display dynamic content using placeholders." }),
        showCreationForm && /* @__PURE__ */ jsx(
          QueryCreator,
          {
            query: editingQuery,
            onClose: () => setShowCreationForm(false)
          },
          editingQuery?.alias ?? "new-query"
        ),
        queries.length === 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-2 justify-center items-center flex-1 text-center", children: /* @__PURE__ */ jsxs("span", { className: "text-base text-gray-500", children: [
          "You currently have no queries defined.",
          /* @__PURE__ */ jsx("br", {}),
          "Create a new query to get started."
        ] }) }),
        queries.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-col border border-gray-200 rounded-lg overflow-hidden -mx-1 mt-3 shadow-sm", children: queries.map((query) => /* @__PURE__ */ jsxs(
          "div",
          {
            className: "flex items-center justify-between p-4 [&:not(:last-child)]:border-b border-gray-200 ",
            children: [
              /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
                /* @__PURE__ */ jsx("div", { className: "font-medium", children: query.label }),
                /* @__PURE__ */ jsxs("div", { className: "flex gap-6 items-center justify-start text-sm  text-gray-500", children: [
                  /* @__PURE__ */ jsx(e, { content: `Alias`, children: /* @__PURE__ */ jsxs("span", { className: "inline-flex gap-1 items-center cursor-help", children: [
                    /* @__PURE__ */ jsx(RiBracesLine, { className: "text-upstart-500" }),
                    query.alias
                  ] }) }),
                  /* @__PURE__ */ jsx(e, { content: `Database`, children: /* @__PURE__ */ jsxs("span", { className: "inline-flex gap-1 items-center cursor-help", children: [
                    /* @__PURE__ */ jsx(BsDatabase, { className: "text-upstart-500" }),
                    query.datasourceId
                  ] }) }),
                  /* @__PURE__ */ jsx(e, { content: `Number of items`, children: /* @__PURE__ */ jsxs("span", { className: "inline-flex gap-1 items-center cursor-help", children: [
                    /* @__PURE__ */ jsx(PiListNumbersLight, { className: "text-upstart-500" }),
                    query.limit
                  ] }) })
                ] })
              ] }),
              /* @__PURE__ */ jsx(
                o$1,
                {
                  size: "2",
                  variant: "soft",
                  color: "violet",
                  onClick: () => {
                    setEditingQuery(query);
                    setShowCreationForm(true);
                  },
                  children: /* @__PURE__ */ jsx(FiEdit, { className: "w-4 h-4" })
                }
              )
            ]
          },
          query.alias
        )) })
      ]
    }
  );
}
function getQueryTemplate() {
  return {
    parameters: {
      op: "and",
      fields: []
    },
    sort: [{ field: "$publicationDate", direction: "desc" }],
    limit: 10
  };
}
function QueryCreator({ query: initialQuery, onClose }) {
  const [query, setQuery] = useState(initialQuery ?? getQueryTemplate());
  const reset = () => {
    setQuery(getQueryTemplate());
  };
  const { upsertQuery } = useDraftHelpers();
  const datasources = useDatasources();
  const datasource = useDatasource(query?.datasourceId);
  const pagePathParams = usePagePathParams();
  const indexedFields = datasource ? getDatasourceIndexedFieldsWithTitles(datasource) : [];
  const sortableFields = indexedFields.filter((field) => ["$id", "$slug"].includes(field.value) === false);
  const parameters = query?.parameters?.fields?.filter((f) => "field" in f) ?? [];
  const sorts = query?.sort ?? [];
  const hasFulltextParameter = () => {
    if (!datasource) return false;
    return parameters.some((param) => {
      return datasource.indexes.some(
        (index) => index.fulltext === true && index.fields.includes(param.field)
      );
    });
  };
  const showMatchSort = hasFulltextParameter();
  useEffect(() => {
    if (!showMatchSort && sorts.some((sort) => sort === "match()")) {
      setQuery((prev) => ({
        ...prev,
        sort: sorts.filter((sort) => sort !== "match()")
      }));
    }
  }, [showMatchSort, sorts]);
  const handleChange = (key, value) => {
    setQuery(
      (prev) => ({
        ...prev,
        [key]: value
      })
    );
  };
  const addSort = () => {
    const newSort = {
      field: "",
      direction: "desc"
    };
    setQuery((prev) => ({
      ...prev,
      sort: [...sorts, newSort]
    }));
  };
  const removeSort = (index) => {
    setQuery((prev) => ({
      ...prev,
      sort: sorts.filter((_, i) => i !== index)
    }));
  };
  const updateSort = (index, key, value) => {
    setQuery((prev) => {
      const newSorts = [...sorts];
      if (key === "field") {
        if (value === "random()" || value === "match()") {
          newSorts[index] = value;
        } else {
          newSorts[index] = { field: value, direction: "desc" };
        }
      } else if (key === "direction" && typeof newSorts[index] === "object") {
        newSorts[index] = {
          ...newSorts[index],
          direction: value
        };
      }
      return {
        ...prev,
        sort: newSorts
      };
    });
  };
  const getOperatorOptionsForField = (fieldName) => {
    if (!datasource) return [];
    const fieldType = getFieldType(fieldName);
    const baseOperators = [
      { value: "eq", label: "Equals" },
      { value: "ne", label: "Not equals" }
    ];
    const stringOperators = [
      { value: "contains", label: "Contains" },
      { value: "notContains", label: "Not contains" },
      { value: "startsWith", label: "Starts with" },
      { value: "notStartsWith", label: "Not starts with" },
      { value: "endsWith", label: "Ends with" },
      { value: "notEndsWith", label: "Not ends with" }
    ];
    const arrayOperators = [
      { value: "contains", label: "Contains" },
      { value: "notContains", label: "Not contains" },
      { value: "containsAll", label: "Contains all" },
      { value: "containsAny", label: "Contains any" },
      { value: "notContainsAny", label: "Not contains any" }
    ];
    const numberOperators = [
      { value: "lt", label: "Less than" },
      { value: "lte", label: "Less than or equal" },
      { value: "gt", label: "Greater than" },
      { value: "gte", label: "Greater than or equal" }
    ];
    const dateOperators = [
      { value: "before", label: "Before Date" },
      { value: "after", label: "After Date" },
      { value: "beforeNow", label: "Before Now" },
      { value: "afterNow", label: "After Now" }
    ];
    switch (fieldType) {
      case "array":
        return arrayOperators;
      case "string":
        return [...baseOperators, ...stringOperators];
      case "number":
      case "integer":
        return [...baseOperators, ...numberOperators];
      case "boolean":
        return [{ value: "eq", label: "Equals" }];
      case "date":
      case "datetime":
        return [...dateOperators, baseOperators[0]];
      default:
        return [...baseOperators, ...stringOperators, ...numberOperators, ...dateOperators];
    }
  };
  const updateParametersAtPath = (path, updater) => {
    setQuery((prev) => {
      if (!prev.parameters) return prev;
      const newParameters = JSON.parse(JSON.stringify(prev.parameters));
      let current = newParameters;
      for (let i = 0; i < path.length; i++) {
        current = current.fields[path[i]];
      }
      current.fields = updater(current.fields);
      return {
        ...prev,
        parameters: newParameters
      };
    });
  };
  const addParameter = (path = []) => {
    const newParam = {
      field: "",
      op: "eq",
      value: ""
    };
    if (path.length === 0) {
      setQuery((prev) => ({
        ...prev,
        parameters: {
          op: prev.parameters?.op || "and",
          fields: [...prev.parameters?.fields || [], newParam]
        }
      }));
    } else {
      updateParametersAtPath(path, (fields) => [...fields, newParam]);
    }
  };
  const addParameterGroup = (path = [], op = "and") => {
    const newGroup = {
      op,
      fields: [
        // Add a default empty parameter to the new group
        {
          field: "",
          op: "eq",
          value: ""
        }
      ]
    };
    if (path.length === 0) {
      setQuery((prev) => ({
        ...prev,
        parameters: {
          op: prev.parameters?.op || "and",
          fields: [...prev.parameters?.fields || [], newGroup]
        }
      }));
    } else {
      updateParametersAtPath(path, (fields) => [...fields, newGroup]);
    }
  };
  const removeParameterAtPath = (path) => {
    if (path.length === 1) {
      setQuery((prev) => ({
        ...prev,
        parameters: {
          op: prev.parameters?.op || "and",
          fields: prev.parameters?.fields.filter((_, i) => i !== path[0]) || []
        }
      }));
    } else {
      const parentPath = path.slice(0, -1);
      const index = path[path.length - 1];
      updateParametersAtPath(parentPath, (fields) => fields.filter((_, i) => i !== index));
    }
  };
  const updateParameterAtPath = (path, key, value) => {
    setQuery((prev) => {
      if (!prev.parameters) return prev;
      const newParameters = JSON.parse(JSON.stringify(prev.parameters));
      let current = newParameters;
      for (let i = 0; i < path.length - 1; i++) {
        current = current.fields[path[i]];
      }
      const index = path[path.length - 1];
      const param = current.fields[index];
      if (key === "field") {
        const op = value ? getOperatorOptionsForField(value)[0]?.value ?? "eq" : "eq";
        current.fields[index] = { field: value, op, value: "" };
      } else if (key === "op") {
        current.fields[index] = {
          ...param,
          op: value,
          value: param.value
        };
      } else {
        current.fields[index] = { ...param, [key]: value };
      }
      return {
        ...prev,
        parameters: newParameters
      };
    });
  };
  const toggleGroupOperator = (path) => {
    setQuery((prev) => {
      if (!prev.parameters) return prev;
      if (path.length === 0) {
        return {
          ...prev,
          parameters: {
            ...prev.parameters,
            op: prev.parameters.op === "and" ? "or" : "and"
          }
        };
      }
      const newParameters = JSON.parse(JSON.stringify(prev.parameters));
      let current = newParameters;
      for (let i = 0; i < path.length; i++) {
        current = current.fields[path[i]];
      }
      current.op = current.op === "and" ? "or" : "and";
      return {
        ...prev,
        parameters: newParameters
      };
    });
  };
  const getFieldType = (fieldName) => {
    if (!datasource) return "string";
    const property = datasource.schema?.items?.properties?.[fieldName];
    if (property?.type === "string" && property.format === "date") return "date";
    if (property?.type === "string" && property.format === "date-time") return "datetime";
    return property?.type ?? "string";
  };
  const handleSubmit = useCallback(
    (e2) => {
      e2.preventDefault();
      e2.stopPropagation();
      console.log("Submitting query:", query);
      try {
        const validated = validate(querySchema, query);
        upsertQuery(validated);
        onClose?.();
      } catch (error) {
        console.error("Query validation failed:", error);
      }
    },
    [query]
  );
  function validateQuery(querySchema2, query2) {
    try {
      validate(querySchema2, query2);
      return true;
    } catch (error) {
      return false;
    }
  }
  const ParameterGroupRenderer = ({
    group,
    path,
    depth = 0
  }) => {
    const isRootGroup = path.length === 0;
    const maxDepth = 3;
    const canAddGroup = depth < maxDepth - 1;
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: tx(
          "flex flex-col gap-2 rounded-lg",
          !isRootGroup && "border border-gray-300 bg-white p-3 shadow-sm"
        ),
        children: [
          !isRootGroup && /* @__PURE__ */ jsx("div", { className: "flex items-center justify-end -mb-1", children: /* @__PURE__ */ jsx(
            o$1,
            {
              size: "1",
              type: "button",
              variant: "ghost",
              className: "hover:(bg-red-100 text-red-800)",
              onClick: () => removeParameterAtPath(path),
              children: /* @__PURE__ */ jsx(RxCross2, { size: 14 })
            }
          ) }),
          /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-3", children: group.fields.map((item, index) => {
            const itemPath = [...path, index];
            if ("field" in item) {
              const param = item;
              return /* @__PURE__ */ jsxs(Fragment, { children: [
                /* @__PURE__ */ jsxs("div", { className: "flex gap-x-3 gap-y-0.5 items-center", children: [
                  /* @__PURE__ */ jsx("div", { className: "w-[200px] flex items-center gap-3 pr-1", children: /* @__PURE__ */ jsxs(
                    C,
                    {
                      value: param.field,
                      onValueChange: (value) => updateParameterAtPath(itemPath, "field", value),
                      children: [
                        /* @__PURE__ */ jsx(
                          u$1,
                          {
                            className: "!w-full",
                            radius: "medium",
                            variant: "surface",
                            placeholder: "Select a field"
                          }
                        ),
                        /* @__PURE__ */ jsx(g$1, { position: "popper", children: /* @__PURE__ */ jsx(y, { children: indexedFields.map((field) => /* @__PURE__ */ jsx(v, { value: field.value, children: field.title }, field.value)) }) })
                      ]
                    }
                  ) }),
                  /* @__PURE__ */ jsx("div", { className: tx("flex gap-2 items-center w-[120px]", !param.field && "hidden"), children: /* @__PURE__ */ jsxs(
                    C,
                    {
                      value: param.op,
                      size: "2",
                      onValueChange: (value) => updateParameterAtPath(itemPath, "op", value),
                      disabled: !param.field,
                      children: [
                        /* @__PURE__ */ jsx(
                          u$1,
                          {
                            radius: "medium",
                            variant: "ghost",
                            placeholder: "Select operator",
                            className: "!flex-1 !mr-1"
                          }
                        ),
                        /* @__PURE__ */ jsx(g$1, { position: "popper", children: /* @__PURE__ */ jsx(y, { children: getOperatorOptionsForField(param.field).map((option) => /* @__PURE__ */ jsx(v, { value: option.value, children: option.label }, option.value)) }) })
                      ]
                    },
                    `operator-${itemPath.join("-")}-${param.field}`
                  ) }),
                  renderParameterValueInput(param, itemPath),
                  /* @__PURE__ */ jsx(
                    o$1,
                    {
                      size: "1",
                      type: "button",
                      variant: "ghost",
                      className: "hover:(bg-red-100 text-red-800) !shrink-0 !ml-auto",
                      onClick: () => removeParameterAtPath(itemPath),
                      children: /* @__PURE__ */ jsx(RxCross2, { size: 14 })
                    }
                  )
                ] }),
                index < group.fields.length - 1 && /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center border-t border-dotted mx-auto w-2/3 border-gray-200 my-3 relative z-10", children: /* @__PURE__ */ jsx(
                  o,
                  {
                    type: "button",
                    size: "1",
                    variant: "soft",
                    className: "!-top-3 !absolute z-20 !opacity-100 !text-xs",
                    onClick: () => toggleGroupOperator(path),
                    children: group.op === "and" ? "And" : "Or"
                  }
                ) })
              ] }, index);
            } else {
              const nestedGroup = item;
              return /* @__PURE__ */ jsxs(Fragment, { children: [
                /* @__PURE__ */ jsx(ParameterGroupRenderer, { group: nestedGroup, path: itemPath, depth: depth + 1 }),
                index < group.fields.length - 1 && /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center border-t border-dotted mx-auto w-2/3 border-gray-200 my-3 relative z-10", children: /* @__PURE__ */ jsx(
                  o,
                  {
                    type: "button",
                    size: "1",
                    variant: "soft",
                    radius: "large",
                    className: "!-top-3 !absolute z-20 !opacity-100 !text-xs",
                    onClick: () => toggleGroupOperator(path),
                    children: group.op === "and" ? "And" : "Or"
                  }
                ) })
              ] }, index);
            }
          }) }),
          depth > 0 && /* @__PURE__ */ jsxs("div", { className: "flex gap-2 mt-2 pt-2 border-t border-gray-200 justify-end items-center", children: [
            /* @__PURE__ */ jsxs(o, { type: "button", radius: "full", variant: "surface", size: "1", onClick: () => addParameter(path), children: [
              /* @__PURE__ */ jsx(TbPlus, { className: "w-3 h-3" }),
              "Add parameter"
            ] }),
            canAddGroup && /* @__PURE__ */ jsxs(
              o,
              {
                type: "button",
                radius: "full",
                variant: "soft",
                size: "1",
                onClick: () => addParameterGroup(path, group.op === "and" ? "or" : "and"),
                children: [
                  /* @__PURE__ */ jsx(TbPlus, { className: "w-3 h-3" }),
                  "Add group"
                ]
              }
            )
          ] })
        ]
      }
    );
  };
  const renderParameterValueInput = (param, path) => {
    const fieldType = getFieldType(param.field);
    if (fieldType === "date" || fieldType === "datetime") {
      if (param.op === "before" || param.op === "after" || param.op === "eq") {
        return /* @__PURE__ */ jsx("div", { className: tx("grow flex justify-end", !param.field && "hidden"), children: /* @__PURE__ */ jsx(
          u,
          {
            size: "2",
            type: fieldType === "datetime" ? "datetime-local" : "date",
            value: String(param.value || ""),
            onChange: (e2) => updateParameterAtPath(path, "value", e2.target.value),
            disabled: !param.field,
            className: "!w-full"
          }
        ) });
      }
      return null;
    }
    return /* @__PURE__ */ jsx("div", { className: tx("grow flex justify-end", !param.field && "hidden"), children: fieldType === "number" || fieldType === "integer" ? /* @__PURE__ */ jsx(
      u,
      {
        type: "number",
        size: "2",
        value: String(param.value || ""),
        onChange: (e2) => updateParameterAtPath(path, "value", Number(e2.target.value)),
        placeholder: "Value",
        min: "1",
        disabled: !param.field,
        className: "!w-full"
      }
    ) : fieldType === "boolean" ? /* @__PURE__ */ jsxs(
      p$1,
      {
        size: "1",
        value: String(param.value || "true"),
        onValueChange: (value) => updateParameterAtPath(path, "value", value === "true"),
        className: tx("!mt-0.5 [&_.rt-SegmentedControlItemLabel]:(px-3)"),
        children: [
          /* @__PURE__ */ jsx(l, { value: "true", children: "True" }),
          /* @__PURE__ */ jsx(l, { value: "false", children: "False" })
        ]
      }
    ) : fieldType === "array" ? /* @__PURE__ */ jsx(
      TagsSelect,
      {
        options: pagePathParams.map((field) => ({
          value: field,
          label: field
        })),
        initialValue: Array.isArray(param.value) ? param.value : [],
        isMulti: true,
        onChange: (value) => updateParameterAtPath(path, "value", value ?? []),
        className: "!w-full min-w-fit max-w-full",
        placeholder: "Add parameters (e.g. Slug, Id)"
      }
    ) : /* @__PURE__ */ jsx(
      u,
      {
        disabled: !param.field,
        value: String(param.value || ""),
        onChange: debounce((e2) => updateParameterAtPath(path, "value", e2.target.value), 400),
        placeholder: "Value",
        size: "2",
        className: "!w-full max-w-full"
      }
    ) });
  };
  return /* @__PURE__ */ jsxs(
    "form",
    {
      onSubmit: handleSubmit,
      className: "text-sm border border-gray-300 bg-gray-50 p-4 rounded-lg -mx-1 mt-3 shadow-sm",
      children: [
        /* @__PURE__ */ jsxs("h3", { className: "font-bold text-[110%] mb-5", children: [
          initialQuery ? "Edit query" : "Create a new query",
          ":",
          " ",
          /* @__PURE__ */ jsx("span", { className: "text-gray-500", children: query?.label })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col text-sm flex-1 -mx-2.5 divide-y divide-gray-200", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex justify-between gap-4 flex-1 items-center p-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 flex-1", children: [
              /* @__PURE__ */ jsx(
                FieldTitle,
                {
                  withIcon: true,
                  className: "font-medium",
                  title: "Label",
                  description: "Label displayed in the Editor"
                }
              ),
              /* @__PURE__ */ jsx(
                u,
                {
                  onInput: (e2) => handleChange("label", e2.currentTarget.value),
                  defaultValue: query?.label,
                  maxLength: querySchema.properties.label.maxLength,
                  "aria-required": true,
                  placeholder: "Ex: Latest blog posts"
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 flex-1", children: [
              /* @__PURE__ */ jsx(
                FieldTitle,
                {
                  withIcon: true,
                  className: "font-medium",
                  title: "Alias",
                  description: "Unique identifier to reference this query"
                }
              ),
              /* @__PURE__ */ jsx(
                u,
                {
                  onInput: (e2) => handleChange("alias", e2.currentTarget.value),
                  pattern: "^[a-zA-Z_][a-zA-Z0-9_]*$",
                  defaultValue: query?.alias,
                  maxLength: querySchema.properties.alias.maxLength,
                  "aria-required": true,
                  placeholder: "Ex: latestBlogPosts"
                }
              )
            ] }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 flex-1", children: [
              /* @__PURE__ */ jsx(FieldTitle, { withIcon: true, className: "font-medium", title: "Database", description: "Database to query" }),
              /* @__PURE__ */ jsxs(
                C,
                {
                  "aria-required": true,
                  defaultValue: query?.datasourceId,
                  size: "2",
                  onValueChange: (value) => setQuery(
                    (prev) => ({
                      ...prev ?? {},
                      datasourceId: value,
                      parameters: {
                        op: "and",
                        fields: []
                      }
                    })
                  ),
                  children: [
                    /* @__PURE__ */ jsx(
                      u$1,
                      {
                        radius: "medium",
                        variant: "surface",
                        placeholder: "Select a database",
                        className: "!max-w-2/3 !mr-[1px]"
                      }
                    ),
                    /* @__PURE__ */ jsx(g$1, { position: "popper", children: datasources.map((ds) => /* @__PURE__ */ jsx(v, { value: ds.id, children: ds.label }, ds.id)) })
                  ]
                }
              )
            ] })
          ] }),
          indexedFields.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 flex-1 justify-between p-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-1 w-full justify-between items-center", children: [
              /* @__PURE__ */ jsx(
                FieldTitle,
                {
                  withIcon: true,
                  title: "Parameters",
                  className: "font-medium",
                  description: "Add parameters to narrow down your query"
                }
              ),
              /* @__PURE__ */ jsxs("div", { className: "flex gap-2 justify-end items-center", children: [
                /* @__PURE__ */ jsxs(o, { type: "button", radius: "full", variant: "surface", size: "1", onClick: () => addParameter(), children: [
                  /* @__PURE__ */ jsx(TbPlus, { className: "w-3 h-3" }),
                  "Add parameter"
                ] }),
                /* @__PURE__ */ jsxs(
                  o,
                  {
                    type: "button",
                    radius: "full",
                    variant: "soft",
                    size: "1",
                    onClick: () => addParameterGroup(),
                    children: [
                      /* @__PURE__ */ jsx(TbPlus, { className: "w-3 h-3" }),
                      "Add group"
                    ]
                  }
                )
              ] })
            ] }),
            query?.parameters && /* @__PURE__ */ jsx(ParameterGroupRenderer, { group: query.parameters, path: [] })
          ] }),
          query?.datasourceId && /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 flex-1 justify-between p-3", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-1 w-full justify-between items-center", children: [
              /* @__PURE__ */ jsx(
                FieldTitle,
                {
                  withIcon: true,
                  title: "Sort results by",
                  className: "font-medium",
                  description: "Add sort criteria to order your query results"
                }
              ),
              /* @__PURE__ */ jsxs(o, { type: "button", radius: "full", variant: "soft", size: "1", onClick: addSort, children: [
                /* @__PURE__ */ jsx(TbPlus, { className: "w-3 h-3" }),
                "Add sort"
              ] })
            ] }),
            sorts.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-3", children: sorts.map((sort, index) => {
              const isSpecialSort = sort === "random()" || sort === "match()";
              const sortField = typeof sort === "object" ? sort.field : sort;
              const sortDirection = typeof sort === "object" ? sort.direction : "desc";
              return /* @__PURE__ */ jsxs(Fragment, { children: [
                /* @__PURE__ */ jsxs("div", { className: "flex gap-x-3 gap-y-0.5 items-center", children: [
                  /* @__PURE__ */ jsx("div", { className: "w-[200px] flex items-center gap-3 pr-1", children: /* @__PURE__ */ jsxs(
                    C,
                    {
                      defaultValue: sortField,
                      onValueChange: (value) => updateSort(index, "field", value),
                      children: [
                        /* @__PURE__ */ jsx(
                          u$1,
                          {
                            className: "!w-full",
                            radius: "medium",
                            variant: "surface",
                            placeholder: "Select a field"
                          }
                        ),
                        /* @__PURE__ */ jsxs(g$1, { position: "popper", children: [
                          /* @__PURE__ */ jsx(y, { children: sortableFields.map((field) => /* @__PURE__ */ jsx(v, { value: field.value, children: field.title }, field.value)) }),
                          /* @__PURE__ */ jsx(I, {}),
                          /* @__PURE__ */ jsxs(y, { children: [
                            /* @__PURE__ */ jsx(v, { value: "random()", children: "Random" }),
                            showMatchSort && /* @__PURE__ */ jsx(v, { value: "match()", children: "Match (Full-text search)" })
                          ] })
                        ] })
                      ]
                    }
                  ) }),
                  /* @__PURE__ */ jsx("div", { className: tx("flex gap-2 items-center w-[120px]", isSpecialSort && "hidden"), children: /* @__PURE__ */ jsxs(
                    C,
                    {
                      defaultValue: sortDirection,
                      size: "2",
                      onValueChange: (value) => updateSort(index, "direction", value),
                      disabled: isSpecialSort,
                      children: [
                        /* @__PURE__ */ jsx(
                          u$1,
                          {
                            radius: "medium",
                            variant: "ghost",
                            placeholder: "Select direction",
                            className: "!flex-1 !mr-1"
                          }
                        ),
                        /* @__PURE__ */ jsx(g$1, { position: "popper", children: /* @__PURE__ */ jsxs(y, { children: [
                          /* @__PURE__ */ jsx(v, { value: "asc", children: "Ascending" }),
                          /* @__PURE__ */ jsx(v, { value: "desc", children: "Descending" })
                        ] }) })
                      ]
                    },
                    `direction-${index}-${sortField}`
                  ) }),
                  /* @__PURE__ */ jsx("div", { className: "grow" }),
                  /* @__PURE__ */ jsx(
                    o$1,
                    {
                      size: "1",
                      type: "button",
                      variant: "ghost",
                      className: "hover:(bg-red-100 text-red-800) !shrink-0 !ml-auto",
                      onClick: () => removeSort(index),
                      children: /* @__PURE__ */ jsx(RxCross2, { size: 14 })
                    }
                  )
                ] }),
                index < sorts.length - 1 && /* @__PURE__ */ jsx("div", { className: "border-t border-dotted mx-auto w-2/3 border-gray-200 my-2 relative", children: /* @__PURE__ */ jsx("span", { className: "absolute left-1/2 -translate-x-1/2 -top-3 bg-gray-50 rounded-full px-2 py-1 inline-block text-xs text-gray-500", children: "Then by" }) })
              ] }, index);
            }) })
          ] }),
          query?.datasourceId && indexedFields.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-1 gap-6 justify-between items-center p-3", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col flex-1 gap-2", children: [
            /* @__PURE__ */ jsx(
              FieldTitle,
              {
                className: "font-medium",
                title: "Max number of items to fetch",
                containerClassName: "!basis-0"
              }
            ),
            /* @__PURE__ */ jsx(
              u,
              {
                type: "number",
                defaultValue: query?.limit?.toString() ?? "10",
                onChange: (e2) => handleChange("limit", parseInt(e2.target.value) || 10),
                min: "1",
                max: "30",
                className: "!w-[40px]"
              }
            )
          ] }) })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2 mt-10", children: [
          /* @__PURE__ */ jsx(
            o,
            {
              type: "button",
              size: "2",
              color: "gray",
              variant: "soft",
              onClick: () => {
                reset();
                onClose?.();
              },
              children: "Cancel"
            }
          ),
          /* @__PURE__ */ jsx(o, { disabled: !validateQuery(querySchema, query), type: "submit", size: "2", children: "Save query" })
        ] })
      ]
    }
  );
}
export {
  Modal as default
};
//# sourceMappingURL=Modal.B-rOpucA.js.map
