"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { createPortal } from "react-dom";
import { Plus, Trash2, X, GripVertical, ChevronDown } from "lucide-react";
import {
  DndContext,
  DragOverlay,
  PointerSensor,
  KeyboardSensor,
  useSensor,
  useSensors,
  closestCenter
} from "@dnd-kit/core";
import {
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Button } from "../../primitives/button.js";
import { IconButton } from "../../primitives/icon-button.js";
import { Input } from "../../primitives/input.js";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../../primitives/select.js";
import { Popover, PopoverContent, PopoverTrigger } from "../../primitives/popover.js";
import { Checkbox } from "../../primitives/checkbox.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import {
  OPERATORS_BY_FIELD_TYPE,
  getDefaultOperator,
  isValuelessOperator
} from "@open-mercato/shared/lib/query/advanced-filter";
import {
  TREE_LIMITS
} from "@open-mercato/shared/lib/query/advanced-filter-tree";
import { treeReducer, canAddRule, canAddGroup } from "./treeReducer.js";
import { FilterFieldPicker } from "./FilterFieldPicker.js";
const OPERATOR_LABELS = {
  is: "is",
  is_not: "is not",
  contains: "contains",
  does_not_contain: "does not contain",
  starts_with: "starts with",
  ends_with: "ends with",
  is_empty: "is empty",
  is_not_empty: "is not empty",
  equals: "equals",
  not_equals: "not equals",
  greater_than: "greater than",
  less_than: "less than",
  greater_or_equal: "greater or equal",
  less_or_equal: "less or equal",
  between: "between",
  is_before: "is before",
  is_after: "is after",
  is_any_of: "is any of",
  is_none_of: "is none of",
  is_true: "is true",
  is_false: "is false",
  has_any_of: "has any of",
  has_all_of: "has all of",
  has_none_of: "has none of"
};
function getFieldType(fields, fieldKey) {
  return fields.find((f) => f.key === fieldKey)?.type ?? "text";
}
const MULTI_VALUE_OPS = /* @__PURE__ */ new Set([
  "is_any_of",
  "is_none_of",
  "has_any_of",
  "has_all_of",
  "has_none_of"
]);
function getOperatorShape(op) {
  if (isValuelessOperator(op)) return "valueless";
  if (MULTI_VALUE_OPS.has(op)) return "multi";
  if (op === "between") return "range";
  return "single";
}
function AdvancedFilterBuilder({
  fields,
  value,
  onChange,
  onApply,
  onClear,
  pendingErrors
}) {
  const t = useT();
  const dispatch = React.useCallback((action) => {
    onChange(treeReducer(value, action));
  }, [onChange, value]);
  React.useEffect(() => {
    function onKey(e) {
      if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
        e.preventDefault();
        onApply();
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onApply]);
  const errorByRuleId = React.useMemo(() => {
    const m = /* @__PURE__ */ new Map();
    for (const e of pendingErrors ?? []) m.set(e.ruleId, t(e.messageKey, e.message));
    return m;
  }, [pendingErrors, t]);
  const empty = value.root.children.length === 0;
  const defaultField = fields.length > 0 ? fields[0].key : void 0;
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  );
  const [activeDrag, setActiveDrag] = React.useState(null);
  const findNode = React.useCallback((id) => locateInTree(value.root, id), [value]);
  const handleDragStart = React.useCallback((e) => {
    const found = findNode(String(e.active.id));
    if (found) setActiveDrag(found);
  }, [findNode]);
  const handleDragEnd = React.useCallback((e) => {
    setActiveDrag(null);
    const { active, over } = e;
    if (!over || active.id === over.id) return;
    const from = findNode(String(active.id));
    const to = findNode(String(over.id));
    if (!from || !to) return;
    if (from.parent.id !== to.parent.id) return;
    const fromIdx = from.parent.children.findIndex((c) => c.id === active.id);
    const toIdx = to.parent.children.findIndex((c) => c.id === over.id);
    if (fromIdx < 0 || toIdx < 0) return;
    dispatch({ type: "reorderChildren", groupId: from.parent.id, fromIdx, toIdx });
  }, [dispatch, findNode]);
  const handleDragCancel = React.useCallback(() => setActiveDrag(null), []);
  return /* @__PURE__ */ jsxs(
    DndContext,
    {
      sensors,
      collisionDetection: closestCenter,
      onDragStart: handleDragStart,
      onDragEnd: handleDragEnd,
      onDragCancel: handleDragCancel,
      children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 p-3", children: [
          !empty ? /* @__PURE__ */ jsx(
            GroupView,
            {
              group: value.root,
              level: 1,
              fields,
              tree: value,
              dispatch,
              defaultField,
              errorByRuleId,
              t
            }
          ) : null,
          !empty ? /* @__PURE__ */ jsx("div", { className: "flex items-center gap-3 pt-2 border-t border-border", children: /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "ghost",
              size: "sm",
              className: "h-auto px-0 py-0 text-base text-muted-foreground hover:bg-transparent hover:text-foreground",
              onClick: onClear,
              children: [
                /* @__PURE__ */ jsx(X, { className: "size-4" }),
                t("ui.advancedFilter.clearAll", "Clear all")
              ]
            }
          ) }) : null
        ] }),
        typeof document !== "undefined" ? createPortal(
          // dnd-kit's DragOverlay sets its own inline z-index, so a Tailwind
          // utility class would be overridden — read the DS token via CSS var.
          /* @__PURE__ */ jsx(DragOverlay, { dropAnimation: null, style: { zIndex: "var(--z-index-modal-elevated, 55)" }, children: activeDrag ? /* @__PURE__ */ jsx(DragGhost, { node: activeDrag.node, parent: activeDrag.parent, fields, t }) : null }),
          document.body
        ) : null
      ]
    }
  );
}
function locateInTree(root, id) {
  for (const child of root.children) {
    if (child.id === id) return { node: child, parent: root };
    if (child.type === "group") {
      const found = locateInTree(child, id);
      if (found) return found;
    }
  }
  return null;
}
function DragGhost({
  node,
  parent,
  fields,
  t
}) {
  const isGroup = node.type === "group";
  const labelParts = [];
  if (isGroup) {
    const ruleCount = countRulesIn(node);
    labelParts.push(t("ui.advancedFilter.dragGhost.group", "Group"));
    labelParts.push(`(${ruleCount})`);
  } else {
    const def = fields.find((f) => f.key === node.field);
    labelParts.push(def?.label ?? (node.field || t("ui.advancedFilter.dragGhost.unsetField", "Unset field")));
    labelParts.push(OPERATOR_LABELS[node.operator] ?? node.operator);
    if (typeof node.value === "string" && node.value) labelParts.push(`"${node.value}"`);
  }
  return /* @__PURE__ */ jsxs("div", { className: "inline-flex items-center gap-2 rounded-md border border-border bg-popover px-3 py-1.5 text-sm shadow-md cursor-grabbing", children: [
    /* @__PURE__ */ jsx(GripVertical, { className: "size-4 text-muted-foreground" }),
    /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: parent.combinator === "and" ? t("ui.advancedFilter.connector.and", "and") : t("ui.advancedFilter.connector.or", "or") }),
    /* @__PURE__ */ jsx("span", { className: "font-medium", children: labelParts.join(" ") })
  ] });
}
function countRulesIn(group) {
  let n = 0;
  for (const c of group.children) {
    if (c.type === "rule") n += 1;
    else n += countRulesIn(c);
  }
  return n;
}
function GroupView({
  group,
  level,
  fields,
  tree,
  dispatch,
  defaultField,
  errorByRuleId,
  t
}) {
  const isRoot = level === 1;
  const containerClass = isRoot ? "space-y-3" : "space-y-3 rounded-lg border border-border bg-muted/30 p-3";
  return /* @__PURE__ */ jsxs("div", { className: containerClass, children: [
    /* @__PURE__ */ jsx(
      GroupToolbar,
      {
        group,
        level,
        tree,
        dispatch,
        defaultField,
        fields,
        isRoot,
        t
      }
    ),
    /* @__PURE__ */ jsx(
      SortableChildrenList,
      {
        group,
        level,
        fields,
        tree,
        dispatch,
        defaultField,
        errorByRuleId,
        t
      }
    )
  ] });
}
function AndOrToggle({
  combinator,
  onChange,
  t
}) {
  const andLabel = t("ui.advancedFilter.combinator.and", "And");
  const orLabel = t("ui.advancedFilter.combinator.or", "Or");
  const baseBtn = "h-8 px-3 text-sm font-medium outline-none focus-visible:shadow-focus disabled:cursor-not-allowed";
  const selBtn = "bg-brand-violet text-white hover:bg-brand-violet/90";
  const unselBtn = "bg-background text-foreground hover:bg-accent";
  return /* @__PURE__ */ jsxs(
    "div",
    {
      role: "group",
      "aria-label": t("ui.advancedFilter.combinator.label", "Group combinator"),
      className: "inline-flex rounded-md border border-input overflow-hidden shrink-0",
      "data-testid": "advanced-filter-combinator-toggle",
      "data-combinator": combinator,
      children: [
        /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            "aria-pressed": combinator === "and",
            onClick: () => combinator !== "and" && onChange("and"),
            className: `${baseBtn} ${combinator === "and" ? selBtn : unselBtn}`,
            children: andLabel
          }
        ),
        /* @__PURE__ */ jsx(
          "button",
          {
            type: "button",
            "aria-pressed": combinator === "or",
            onClick: () => combinator !== "or" && onChange("or"),
            className: `${baseBtn} border-l border-input ${combinator === "or" ? selBtn : unselBtn}`,
            children: orLabel
          }
        )
      ]
    }
  );
}
function SortableChildrenList({
  group,
  level,
  fields,
  tree,
  dispatch,
  defaultField,
  errorByRuleId,
  t
}) {
  return /* @__PURE__ */ jsx(SortableContext, { items: group.children.map((c) => c.id), strategy: verticalListSortingStrategy, children: group.children.map((child, idx) => /* @__PURE__ */ jsx(
    SortableRow,
    {
      child,
      idx,
      parent: group,
      level,
      fields,
      tree,
      dispatch,
      defaultField,
      errorByRuleId,
      t
    },
    child.id
  )) });
}
function SortableRow({
  child,
  idx,
  parent,
  level,
  fields,
  tree,
  dispatch,
  defaultField,
  errorByRuleId,
  t
}) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: child.id
  });
  const style = isDragging ? { visibility: "hidden" } : { transform: CSS.Transform.toString(transform), transition };
  const dragHandleProps = { ...attributes, ...listeners };
  return /* @__PURE__ */ jsx("div", { ref: setNodeRef, style, "data-testid": "filter-rule-row", "data-filter-node-id": child.id, children: child.type === "rule" ? /* @__PURE__ */ jsx(
    RuleRow,
    {
      rule: child,
      fields,
      dispatch,
      errorByRuleId,
      dragHandleProps,
      t
    }
  ) : /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2", children: [
    /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        ...dragHandleProps,
        "data-testid": "filter-drag-handle",
        className: "mt-1 text-muted-foreground/60 hover:text-muted-foreground cursor-grab outline-none focus-visible:shadow-focus rounded-sm",
        "aria-label": t("ui.advancedFilter.dragHandle", "Drag to reorder"),
        children: /* @__PURE__ */ jsx(GripVertical, { className: "size-4" })
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
      GroupView,
      {
        group: child,
        level: level + 1,
        fields,
        tree,
        dispatch,
        defaultField,
        errorByRuleId,
        t
      }
    ) })
  ] }) });
}
function RuleRow({
  rule,
  fields,
  dispatch,
  errorByRuleId,
  dragHandleProps,
  t
}) {
  const fieldType = getFieldType(fields, rule.field);
  const operators = OPERATORS_BY_FIELD_TYPE[fieldType] ?? OPERATORS_BY_FIELD_TYPE.text;
  const valueless = isValuelessOperator(rule.operator);
  const errorMsg = errorByRuleId.get(rule.id);
  const fieldDef = fields.find((f) => f.key === rule.field);
  const [pickerOpen, setPickerOpen] = React.useState(false);
  const fieldBtnRef = React.useRef(null);
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", "data-testid": "filter-rule", "data-filter-rule-id": rule.id, children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-start gap-2", children: [
      /* @__PURE__ */ jsx(
        "button",
        {
          type: "button",
          ...dragHandleProps,
          "data-testid": "filter-drag-handle",
          className: "mt-1 text-muted-foreground/60 hover:text-muted-foreground cursor-grab outline-none focus-visible:shadow-focus rounded-sm",
          "aria-label": t("ui.advancedFilter.dragHandle", "Drag to reorder"),
          children: /* @__PURE__ */ jsx(GripVertical, { className: "size-4" })
        }
      ),
      /* @__PURE__ */ jsx(
        Button,
        {
          ref: fieldBtnRef,
          type: "button",
          variant: "outline",
          size: "sm",
          onClick: () => setPickerOpen(true),
          className: "min-w-[140px] justify-start",
          children: fieldDef?.label ?? t("ui.advancedFilter.selectField", "Select field")
        }
      ),
      /* @__PURE__ */ jsx(
        FilterFieldPicker,
        {
          fields,
          open: pickerOpen,
          onOpenChange: setPickerOpen,
          onSelect: (f) => {
            const nextType = getFieldType(fields, f.key);
            dispatch({
              type: "updateRule",
              ruleId: rule.id,
              updates: { field: f.key, operator: getDefaultOperator(nextType), value: "" }
            });
          },
          triggerRef: fieldBtnRef
        }
      ),
      /* @__PURE__ */ jsxs(
        Select,
        {
          value: rule.operator,
          onValueChange: (next) => {
            const nextOp = next;
            const sameShape = getOperatorShape(rule.operator) === getOperatorShape(nextOp);
            const updates = sameShape ? { operator: nextOp } : { operator: nextOp, value: getOperatorShape(nextOp) === "multi" || getOperatorShape(nextOp) === "range" ? [] : "" };
            dispatch({ type: "updateRule", ruleId: rule.id, updates });
          },
          children: [
            /* @__PURE__ */ jsx(
              SelectTrigger,
              {
                size: "sm",
                className: "w-auto min-w-[140px]",
                "aria-label": t("ui.advancedFilter.selectOperator", "Select operator"),
                children: /* @__PURE__ */ jsx(SelectValue, {})
              }
            ),
            /* @__PURE__ */ jsx(SelectContent, { "data-advanced-filter-portal": "", children: operators.map((op) => /* @__PURE__ */ jsx(SelectItem, { value: op, children: t(`ui.advancedFilter.operator.${op}`, OPERATOR_LABELS[op]) }, op)) })
          ]
        }
      ),
      !valueless ? /* @__PURE__ */ jsx(
        ValueInput,
        {
          rule,
          fields,
          fieldType,
          dispatch,
          hasError: !!errorMsg,
          t
        }
      ) : null,
      /* @__PURE__ */ jsx(
        IconButton,
        {
          variant: "ghost",
          size: "sm",
          type: "button",
          onClick: () => dispatch({ type: "removeNode", nodeId: rule.id }),
          "aria-label": t("ui.advancedFilter.removeCondition", "Remove condition"),
          title: t("ui.advancedFilter.removeCondition", "Remove condition"),
          children: /* @__PURE__ */ jsx(Trash2, { className: "size-4 text-muted-foreground" })
        }
      )
    ] }),
    errorMsg ? /* @__PURE__ */ jsx("div", { className: "ml-6 pl-12 text-xs text-status-error-text", children: errorMsg }) : null
  ] });
}
function ValueInput({
  rule,
  fields,
  fieldType,
  dispatch,
  hasError,
  t
}) {
  const fieldDef = fields.find((f) => f.key === rule.field);
  const value = rule.value;
  const errorClass = hasError ? "border-status-error-border ring-1 ring-status-error-border focus-visible:border-status-error-border focus-within:border-status-error-border" : "";
  if (fieldType === "select" && fieldDef?.options) {
    if (getOperatorShape(rule.operator) === "multi") {
      return /* @__PURE__ */ jsx(
        MultiValuePicker,
        {
          rule,
          options: fieldDef.options,
          dispatch,
          errorClass,
          t
        }
      );
    }
    return /* @__PURE__ */ jsxs(
      Select,
      {
        value: typeof value === "string" && value.length ? value : void 0,
        onValueChange: (next) => dispatch({ type: "updateRule", ruleId: rule.id, updates: { value: next ?? "" } }),
        children: [
          /* @__PURE__ */ jsx(
            SelectTrigger,
            {
              size: "sm",
              className: `w-auto min-w-[160px] ${errorClass}`,
              "aria-label": t("ui.advancedFilter.selectValue", "Select value"),
              children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("ui.advancedFilter.selectValuePlaceholder", "Select...") })
            }
          ),
          /* @__PURE__ */ jsx(SelectContent, { "data-advanced-filter-portal": "", children: fieldDef.options.map((opt) => /* @__PURE__ */ jsx(SelectItem, { value: opt.value, children: opt.tone ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
            /* @__PURE__ */ jsx("span", { className: toneDotClass(opt.tone), "aria-hidden": "true" }),
            opt.label
          ] }) : opt.label }, opt.value)) })
        ]
      }
    );
  }
  if (rule.operator === "between" && (fieldType === "number" || fieldType === "date")) {
    return /* @__PURE__ */ jsx(
      BetweenInput,
      {
        rule,
        fieldType,
        dispatch,
        errorClass,
        t
      }
    );
  }
  if (fieldType === "date") {
    return /* @__PURE__ */ jsx(
      Input,
      {
        type: "date",
        size: "sm",
        className: `w-auto min-w-[160px] ${errorClass}`,
        value: typeof value === "string" ? value : "",
        onChange: (e) => dispatch({ type: "updateRule", ruleId: rule.id, updates: { value: e.target.value } }),
        "aria-label": t("ui.advancedFilter.dateValue", "Date value")
      }
    );
  }
  if (fieldType === "number") {
    return /* @__PURE__ */ jsx(
      Input,
      {
        type: "number",
        size: "sm",
        className: `w-[120px] ${errorClass}`,
        value: typeof value === "number" ? value : typeof value === "string" ? value : "",
        onChange: (e) => dispatch({ type: "updateRule", ruleId: rule.id, updates: { value: e.target.value } }),
        placeholder: t("ui.advancedFilter.numberPlaceholder", "Value"),
        "aria-label": t("ui.advancedFilter.numberValue", "Number value")
      }
    );
  }
  return /* @__PURE__ */ jsx(
    Input,
    {
      type: "text",
      size: "sm",
      className: `w-auto min-w-[160px] ${errorClass}`,
      value: typeof value === "string" ? value : "",
      onChange: (e) => dispatch({ type: "updateRule", ruleId: rule.id, updates: { value: e.target.value } }),
      placeholder: t("ui.advancedFilter.textPlaceholder", "Value..."),
      "aria-label": t("ui.advancedFilter.textValue", "Text value")
    }
  );
}
function BetweenInput({
  rule,
  fieldType,
  dispatch,
  errorClass,
  t
}) {
  const pair = Array.isArray(rule.value) ? rule.value : [];
  const start = typeof pair[0] === "string" || typeof pair[0] === "number" ? String(pair[0] ?? "") : "";
  const end = typeof pair[1] === "string" || typeof pair[1] === "number" ? String(pair[1] ?? "") : "";
  const update = (which, next) => {
    const value = which === "start" ? [next, end] : [start, next];
    dispatch({ type: "updateRule", ruleId: rule.id, updates: { value } });
  };
  const inputType = fieldType === "date" ? "date" : "number";
  const inputWidth = fieldType === "date" ? "w-auto min-w-[140px]" : "w-[110px]";
  return /* @__PURE__ */ jsxs("div", { className: "inline-flex items-center gap-1", children: [
    /* @__PURE__ */ jsx(
      Input,
      {
        type: inputType,
        size: "sm",
        className: `${inputWidth} ${errorClass}`,
        value: start,
        onChange: (e) => update("start", e.target.value),
        placeholder: fieldType === "number" ? t("ui.advancedFilter.numberPlaceholder", "Value") : void 0,
        "aria-label": t("ui.advancedFilter.betweenStart", "Start")
      }
    ),
    /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("ui.advancedFilter.and", "and") }),
    /* @__PURE__ */ jsx(
      Input,
      {
        type: inputType,
        size: "sm",
        className: `${inputWidth} ${errorClass}`,
        value: end,
        onChange: (e) => update("end", e.target.value),
        placeholder: fieldType === "number" ? t("ui.advancedFilter.numberPlaceholder", "Value") : void 0,
        "aria-label": t("ui.advancedFilter.betweenEnd", "End")
      }
    )
  ] });
}
function MultiValuePicker({
  rule,
  options,
  dispatch,
  errorClass,
  t
}) {
  const selected = Array.isArray(rule.value) ? rule.value.map((v) => String(v)).filter((v) => v.length > 0) : [];
  const selectedLabel = (() => {
    if (selected.length === 0) return t("ui.advancedFilter.selectValuePlaceholder", "Select...");
    const firstOpt = options.find((o) => o.value === selected[0]);
    const head = firstOpt?.label ?? selected[0];
    const more = selected.length - 1;
    return more > 0 ? `${head} +${more}` : head;
  })();
  const toggle = (val) => {
    const next = selected.includes(val) ? selected.filter((v) => v !== val) : [...selected, val];
    dispatch({ type: "updateRule", ruleId: rule.id, updates: { value: next } });
  };
  return /* @__PURE__ */ jsxs(Popover, { children: [
    /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
      "button",
      {
        type: "button",
        className: `inline-flex h-8 items-center justify-between gap-2 rounded-md border border-input bg-background px-2.5 text-xs shadow-xs transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:shadow-focus focus-visible:border-foreground w-auto min-w-[160px] ${errorClass}`,
        "aria-label": t("ui.advancedFilter.selectValue", "Select value"),
        "data-testid": "multi-value-trigger",
        children: [
          /* @__PURE__ */ jsx("span", { className: selected.length === 0 ? "text-muted-foreground" : "", children: selectedLabel }),
          /* @__PURE__ */ jsx(ChevronDown, { className: "size-3 text-muted-foreground" })
        ]
      }
    ) }),
    /* @__PURE__ */ jsx(PopoverContent, { className: "w-64 p-1", align: "start", "data-advanced-filter-portal": "", children: /* @__PURE__ */ jsx("div", { className: "max-h-64 overflow-y-auto", role: "listbox", "aria-multiselectable": "true", children: options.map((opt) => {
      const isOn = selected.includes(opt.value);
      return (
        // Raw <button>: needs `role="option"` + `aria-selected`; <Button> would override role.
        /* @__PURE__ */ jsxs(
          "button",
          {
            type: "button",
            role: "option",
            "aria-selected": isOn,
            onClick: () => toggle(opt.value),
            className: "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-accent focus-visible:bg-accent focus-visible:outline-none",
            children: [
              /* @__PURE__ */ jsx(Checkbox, { checked: isOn, "aria-hidden": "true", tabIndex: -1, className: "pointer-events-none" }),
              opt.tone ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
                /* @__PURE__ */ jsx("span", { className: toneDotClass(opt.tone), "aria-hidden": "true" }),
                opt.label
              ] }) : /* @__PURE__ */ jsx("span", { children: opt.label })
            ]
          },
          opt.value
        )
      );
    }) }) })
  ] });
}
function toneDotClass(tone) {
  const base = "inline-block size-2 rounded-full shrink-0";
  switch (tone) {
    case "success":
      return `${base} bg-status-success-icon`;
    case "error":
      return `${base} bg-status-error-icon`;
    case "warning":
      return `${base} bg-status-warning-icon`;
    case "info":
      return `${base} bg-status-info-icon`;
    case "neutral":
      return `${base} bg-status-neutral-icon`;
    case "pink":
      return `${base} bg-status-pink-icon`;
    case "brand":
      return `${base} bg-brand-violet`;
    default:
      return `${base} bg-muted-foreground/40`;
  }
}
function GroupToolbar({
  group,
  level,
  tree,
  dispatch,
  defaultField,
  fields,
  isRoot,
  t
}) {
  const [pickerOpen, setPickerOpen] = React.useState(false);
  const addBtnRef = React.useRef(null);
  const addRuleEnabled = canAddRule(tree, group.id);
  const addGroupEnabled = canAddGroup(tree, group.id);
  const widthCapHit = group.children.length >= TREE_LIMITS.maxChildrenPerGroup;
  const depthCapHit = level >= TREE_LIMITS.maxGroupLevel;
  const addRuleTitle = !addRuleEnabled ? widthCapHit ? t("ui.advancedFilter.limitWidthReached", "Maximum {max} conditions per group", {
    max: TREE_LIMITS.maxChildrenPerGroup
  }) : t("ui.advancedFilter.limitTotalReached", "Maximum {max} conditions reached", {
    max: TREE_LIMITS.maxTotalRules
  }) : void 0;
  const addGroupTitle = !addGroupEnabled ? depthCapHit ? t("ui.advancedFilter.limitDepthReached", "Maximum nesting depth reached") : widthCapHit ? t("ui.advancedFilter.limitWidthReached", "Maximum {max} conditions per group", {
    max: TREE_LIMITS.maxChildrenPerGroup
  }) : t("ui.advancedFilter.limitTotalReached", "Maximum {max} conditions reached", {
    max: TREE_LIMITS.maxTotalRules
  }) : void 0;
  const addGroupLabel = level === 1 ? t("ui.advancedFilter.addGroup", "Add group") : t("ui.advancedFilter.addSubgroup", "Add subgroup");
  const ctaClass = "text-brand-violet hover:text-brand-violet/80 hover:bg-transparent px-0 disabled:text-muted-foreground/50 disabled:hover:text-muted-foreground/50";
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
      /* @__PURE__ */ jsx(
        AndOrToggle,
        {
          combinator: group.combinator,
          onChange: (c) => dispatch({ type: "updateGroupCombinator", groupId: group.id, combinator: c }),
          t
        }
      ),
      /* @__PURE__ */ jsxs(
        Button,
        {
          ref: addBtnRef,
          type: "button",
          variant: "ghost",
          size: "sm",
          disabled: !addRuleEnabled,
          title: addRuleTitle,
          onClick: () => setPickerOpen(true),
          className: ctaClass,
          children: [
            /* @__PURE__ */ jsx(Plus, { className: "size-4" }),
            t("ui.advancedFilter.addCondition", "Add condition")
          ]
        }
      ),
      /* @__PURE__ */ jsx(
        FilterFieldPicker,
        {
          fields,
          open: pickerOpen,
          onOpenChange: setPickerOpen,
          onSelect: (f) => dispatch({
            type: "addRule",
            groupId: group.id,
            defaultField: f.key,
            defaultOperator: getDefaultOperator(f.type)
          }),
          triggerRef: addBtnRef
        }
      ),
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          disabled: !addGroupEnabled,
          title: addGroupTitle,
          onClick: () => dispatch({ type: "addGroup", groupId: group.id, defaultField }),
          className: ctaClass,
          children: [
            /* @__PURE__ */ jsx(Plus, { className: "size-4" }),
            addGroupLabel
          ]
        }
      ),
      !isRoot ? /* @__PURE__ */ jsx(
        IconButton,
        {
          variant: "ghost",
          size: "sm",
          type: "button",
          onClick: () => dispatch({ type: "removeNode", nodeId: group.id }),
          "aria-label": t("ui.advancedFilter.deleteGroup", "Delete group"),
          title: t("ui.advancedFilter.deleteGroup", "Delete group"),
          className: "ml-auto",
          children: /* @__PURE__ */ jsx(X, { className: "size-4 text-muted-foreground" })
        }
      ) : null
    ] }),
    !addGroupEnabled && depthCapHit ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", "data-testid": "filter-depth-limit-hint", children: t("ui.advancedFilter.limitDepthHint", "You've reached the maximum nesting depth ({max} levels). Switch this group's combinator with the toggle above instead of nesting deeper.", {
      max: TREE_LIMITS.maxGroupLevel
    }) }) : null
  ] });
}
export {
  AdvancedFilterBuilder
};
//# sourceMappingURL=AdvancedFilterBuilder.js.map
