"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Button } from "../primitives/button.js";
import { FilterOverlay } from "./FilterOverlay.js";
import { useT } from "@open-mercato/shared/lib/i18n/context";
function FilterBar({
  searchValue,
  onSearchChange,
  searchPlaceholder,
  searchAlign = "left",
  filters = [],
  values = {},
  onApply,
  onClear,
  className,
  leadingItems,
  trailingItems,
  layout = "stacked",
  filtersExtraContent
}) {
  const t = useT();
  const resolvedSearchPlaceholder = searchPlaceholder ?? t("ui.filterBar.searchPlaceholder", "Search");
  const [open, setOpen] = React.useState(false);
  const [searchDraft, setSearchDraft] = React.useState(searchValue ?? "");
  const lastAppliedSearchRef = React.useRef(searchValue ?? "");
  React.useEffect(() => {
    const next = searchValue ?? "";
    lastAppliedSearchRef.current = next;
    setSearchDraft((prev) => prev === next ? prev : next);
  }, [searchValue]);
  React.useEffect(() => {
    if (!onSearchChange) return;
    const handle = window.setTimeout(() => {
      if (lastAppliedSearchRef.current === searchDraft) return;
      lastAppliedSearchRef.current = searchDraft;
      onSearchChange(searchDraft);
    }, 1e3);
    return () => {
      window.clearTimeout(handle);
    };
  }, [searchDraft, onSearchChange]);
  const activeCount = React.useMemo(() => {
    const isActive = (v) => {
      if (v == null) return false;
      if (typeof v === "string") return v.trim() !== "";
      if (Array.isArray(v)) return v.length > 0;
      if (typeof v === "object") return Object.values(v).some((x) => x != null && x !== "");
      return Boolean(v);
    };
    return Object.values(values).filter(isActive).length;
  }, [values]);
  const containerClass = `flex flex-col ${layout === "inline" ? "gap-1 sm:gap-2" : "gap-2"} w-full`;
  const searchInput = onSearchChange ? /* @__PURE__ */ jsxs("div", { className: `relative w-full sm:w-auto sm:min-w-[180px] sm:max-w-[240px] ${searchAlign === "right" ? "sm:ml-auto" : ""}`, children: [
    /* @__PURE__ */ jsx(
      "input",
      {
        value: searchDraft,
        onChange: (e) => setSearchDraft(e.target.value),
        placeholder: resolvedSearchPlaceholder,
        className: "h-9 w-full rounded border pl-8 pr-2 text-sm",
        suppressHydrationWarning: true
      }
    ),
    /* @__PURE__ */ jsx("span", { className: "absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground", children: "\u{1F50D}" })
  ] }) : null;
  const controls = /* @__PURE__ */ jsxs("div", { className: `flex flex-wrap items-center gap-2 ${searchAlign === "left" && searchInput ? "sm:ml-auto" : ""}`, children: [
    filters.length > 0 && /* @__PURE__ */ jsxs(Button, { variant: "outline", className: "h-9", onClick: () => setOpen(true), children: [
      /* @__PURE__ */ jsxs("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", "aria-hidden": "true", className: "opacity-80", children: [
        /* @__PURE__ */ jsx("path", { d: "M3 4h18" }),
        /* @__PURE__ */ jsx("path", { d: "M6 8h12l-3 8H9L6 8z" })
      ] }),
      activeCount ? t("ui.filterBar.filtersWithCount", "Filters {count}", { count: activeCount }) : t("ui.filterBar.filters", "Filters")
    ] }),
    leadingItems,
    trailingItems
  ] });
  return /* @__PURE__ */ jsxs("div", { className: `${containerClass} ${className ?? ""}`, children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2 w-full", children: [
      searchAlign === "left" ? searchInput : null,
      controls,
      searchAlign === "right" ? searchInput : null
    ] }),
    filters.length > 0 && activeCount > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-1", children: filters.map((f) => {
      const v = values[f.id];
      if (v == null || v === "" || Array.isArray(v) && v.length === 0) return null;
      const toLabel = (val) => {
        if (typeof f.formatValue === "function" && (typeof val === "string" || typeof val === "number")) {
          const formatted = f.formatValue(String(val));
          if (formatted) return formatted;
        }
        if (f.type === "select" && f.options) {
          const o = f.options.find((o2) => o2.value === val);
          return o ? o.label : String(val);
        }
        if (typeof val === "object" && val.from == null && val.to == null) return null;
        if (typeof val === "object") {
          const from = val.from ?? "";
          const to = val.to ? ` \u2192 ${val.to}` : "";
          return `${from}${to}`.trim();
        }
        if (val === true) return t("common.yes", "Yes");
        if (val === false) return t("common.no", "No");
        return String(val);
      };
      const removeValue = (val) => {
        const next = { ...values || {} };
        if (Array.isArray(v) && val !== void 0) next[f.id] = v.filter((x) => x !== val);
        else delete next[f.id];
        onApply?.(next);
      };
      if (Array.isArray(v)) {
        return v.map((item) => /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", className: "max-w-[calc(100vw-4rem)] truncate", onClick: () => removeValue(item), children: [
          f.label,
          ": ",
          toLabel(item),
          " \xD7"
        ] }, `${f.id}:${item}`));
      }
      const label = toLabel(v);
      if (!label) return null;
      return /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", className: "max-w-[calc(100vw-4rem)] truncate", onClick: () => removeValue(), children: [
        f.label,
        ": ",
        label,
        " \xD7"
      ] }, f.id);
    }) }),
    /* @__PURE__ */ jsx(
      FilterOverlay,
      {
        title: t("ui.filterOverlay.title", "Filters"),
        filters,
        initialValues: values,
        open,
        onOpenChange: setOpen,
        onApply: (v) => onApply?.(v),
        onClear,
        extraContent: filtersExtraContent
      }
    )
  ] });
}
export {
  FilterBar
};
//# sourceMappingURL=FilterBar.js.map
