"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { ListFilter } from "lucide-react";
import { Button } from "../primitives/button.js";
import { SearchInput } from "../primitives/search-input.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,
  searchTrailing,
  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 searchBlock = onSearchChange ? /* @__PURE__ */ jsxs("div", { className: `flex items-center gap-2 ${searchAlign === "right" ? "sm:ml-auto" : ""}`, children: [
    /* @__PURE__ */ jsx("div", { className: "w-full sm:w-72 lg:w-80", children: /* @__PURE__ */ jsx(
      SearchInput,
      {
        value: searchDraft,
        onChange: setSearchDraft,
        placeholder: resolvedSearchPlaceholder,
        suppressHydrationWarning: true
      }
    ) }),
    searchTrailing ? /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: searchTrailing }) : null
  ] }) : null;
  const controls = /* @__PURE__ */ jsxs("div", { className: `flex flex-wrap items-center gap-2 ${searchAlign === "left" && searchBlock ? "sm:ml-auto" : ""}`, children: [
    filters.length > 0 && /* @__PURE__ */ jsxs(Button, { variant: "outline", onClick: () => setOpen(true), children: [
      /* @__PURE__ */ jsx(ListFilter, { "aria-hidden": "true", className: "size-4 opacity-80" }),
      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" ? searchBlock : null,
      controls,
      searchAlign === "right" ? searchBlock : 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
