"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { X } from "lucide-react";
import { Tag } from "../../primitives/tag.js";
import { IconButton } from "../../primitives/icon-button.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { isValuelessOperator } from "@open-mercato/shared/lib/query/advanced-filter";
import { validateTreeForApply } from "./filterValidation.js";
const MAX_LABEL = 24;
function truncate(s) {
  if (s.length <= MAX_LABEL) return s;
  return s.slice(0, MAX_LABEL) + "\u2026";
}
function getOption(field, value) {
  if (!field?.options) return void 0;
  return field.options.find((o) => o.value === value);
}
function valueText(field, value) {
  if (Array.isArray(value)) {
    if (value.length === 0) return { text: "" };
    const first = String(value[0]);
    const opt2 = getOption(field, first);
    const display = opt2?.label ?? first;
    const more = value.length - 1;
    return {
      text: more > 0 ? `${truncate(display)} +${more}` : truncate(display),
      tone: opt2?.tone
    };
  }
  if (value == null || value === "") return { text: "" };
  const str = String(value);
  const opt = getOption(field, str);
  return { text: truncate(opt?.label ?? str), tone: opt?.tone };
}
const VALUELESS_OPERATOR_LABEL = {
  is_empty: "is empty",
  is_not_empty: "is not empty",
  is_true: "is true",
  is_false: "is false"
};
function ruleChip(rule, fields, t) {
  const field = fields.find((f) => f.key === rule.field);
  const fieldLabel = field?.label ?? rule.field;
  if (isValuelessOperator(rule.operator)) {
    const fallback = VALUELESS_OPERATOR_LABEL[rule.operator] ?? rule.operator;
    const opLabel = t(`ui.advancedFilter.operator.${rule.operator}`, fallback);
    return { label: `${fieldLabel} ${opLabel}` };
  }
  if (rule.operator === "between" && Array.isArray(rule.value)) {
    const [start, end] = rule.value;
    const startStr = start == null ? "" : String(start);
    const endStr = end == null ? "" : String(end);
    return { label: `${fieldLabel}: ${truncate(startStr)} \u2013 ${truncate(endStr)}` };
  }
  const v = valueText(field, rule.value);
  return { label: `${fieldLabel}: ${v.text}`, tone: v.tone };
}
function groupChip(group, fields, invalidRuleIds, t) {
  const ruleChildren = [];
  for (const c of group.children) if (c.type === "rule" && !invalidRuleIds.has(c.id)) ruleChildren.push(c);
  if (!ruleChildren.length) return { label: "", remaining: 0 };
  const firstChip = ruleChip(ruleChildren[0], fields, t);
  const remaining = ruleChildren.length - 1;
  return {
    label: remaining > 0 ? `${firstChip.label} +${remaining}` : firstChip.label,
    tone: firstChip.tone,
    remaining
  };
}
function isNodeFullyInvalid(node, invalidRuleIds) {
  if (node.type === "rule") return invalidRuleIds.has(node.id);
  if (!node.children.length) return true;
  return node.children.every((c) => isNodeFullyInvalid(c, invalidRuleIds));
}
function ActiveFilterChips({ tree, fields, popoverOpen, onRemoveNode, onOpen }) {
  const t = useT();
  const invalidRuleIds = React.useMemo(() => {
    const result = validateTreeForApply(tree, fields);
    if (result.ok) return /* @__PURE__ */ new Set();
    return new Set(result.errors.map((e) => e.ruleId));
  }, [tree, fields]);
  const visibleChildren = React.useMemo(
    () => tree.root.children.filter((child) => !isNodeFullyInvalid(child, invalidRuleIds)),
    [tree.root.children, invalidRuleIds]
  );
  if (popoverOpen) return null;
  if (!visibleChildren.length) return null;
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: "flex items-center gap-2 px-4 py-2 overflow-x-auto bg-background border-b border-border",
      "data-testid": "active-filter-chips",
      children: visibleChildren.map((child) => {
        if (child.type === "rule") {
          const c2 = ruleChip(child, fields, t);
          return /* @__PURE__ */ jsx(
            ChipWithRemove,
            {
              label: c2.label,
              tone: c2.tone,
              onClick: () => onOpen(child.id),
              onRemove: () => onRemoveNode(child.id),
              removeLabel: t("ui.advancedFilter.chips.remove", "Remove filter")
            },
            child.id
          );
        }
        const c = groupChip(child, fields, invalidRuleIds, t);
        return /* @__PURE__ */ jsx(
          ChipWithRemove,
          {
            label: c.label,
            tone: c.tone,
            onClick: () => onOpen(child.id),
            onRemove: () => onRemoveNode(child.id),
            removeLabel: t("ui.advancedFilter.chips.removeGroup", "Remove filter group")
          },
          child.id
        );
      })
    }
  );
}
function ChipWithRemove({ label, tone, onClick, onRemove, removeLabel }) {
  return /* @__PURE__ */ jsxs("div", { className: "inline-flex items-center gap-1", "data-testid": "active-filter-chip", "aria-label": label, children: [
    /* @__PURE__ */ jsx(
      "button",
      {
        type: "button",
        onClick,
        className: "inline-flex rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
        children: /* @__PURE__ */ jsx(Tag, { variant: tone ?? "default", dot: tone != null, children: label })
      }
    ),
    /* @__PURE__ */ jsx(IconButton, { type: "button", variant: "ghost", size: "xs", "aria-label": removeLabel, onClick: onRemove, children: /* @__PURE__ */ jsx(X, { className: "size-3" }) })
  ] });
}
export {
  ActiveFilterChips
};
//# sourceMappingURL=ActiveFilterChips.js.map
