import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import * as React from "react";
import { createContext, forwardRef, useState, Children, useEffect, useMemo, isValidElement, useContext } from "react";
import { S as StClose } from "../../StClose-BQuYK7Le.js";
import { c as cn } from "../../cn-FAaWYZ6x.js";
import { Badge } from "../badge/badge.js";
import { Button } from "../button/button.js";
import { Input } from "../input/input.js";
import { Popover, PopoverTrigger, PopoverContent } from "../popover/popover.js";
import { Checkbox } from "../checkbox/checkbox.js";
const StFilter2 = ({ width = 24, height = 24, color, style, ...otherProps }) => /* @__PURE__ */ jsxs("svg", { id: "icon_StFilter2", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg", width, height, style: {
  ...color && {
    "--stroke-color": color,
    "--stroke-fg-color": color
  },
  ...style
}, ...otherProps, children: [
  /* @__PURE__ */ jsx("line", { x1: 3.75, y1: 6.25, x2: 20.25, y2: 6.25, stroke: "var(--stroke-color, currentColor)", strokeWidth: "var(--stroke-width, 1.5)", strokeLinecap: "square" }),
  /* @__PURE__ */ jsx("line", { x1: 6.75, y1: 12.25, x2: 17.25, y2: 12.25, stroke: "var(--stroke-color, currentColor)", strokeWidth: "var(--stroke-width, 1.5)", strokeLinecap: "square" }),
  /* @__PURE__ */ jsx("line", { x1: 10.75, y1: 18.25, x2: 13.25, y2: 18.25, stroke: "var(--stroke-color, currentColor)", strokeWidth: "var(--stroke-width, 1.5)", strokeLinecap: "square" })
] });
StFilter2.displayName = "StFilter2";
function useIsMobile(breakpoint = 768) {
  const [isMobile, setIsMobile] = React.useState(
    void 0
  );
  React.useEffect(() => {
    const mql = window.matchMedia(`(max-width: ${breakpoint - 1}px)`);
    const onChange = () => {
      setIsMobile(window.innerWidth < breakpoint);
    };
    mql.addEventListener("change", onChange);
    setIsMobile(window.innerWidth < breakpoint);
    return () => mql.removeEventListener("change", onChange);
  }, [breakpoint]);
  return !!isMobile;
}
const CollectionToolbarContext = createContext(void 0);
const useCollectionToolbar = () => {
  const context = useContext(CollectionToolbarContext);
  if (context === void 0) {
    throw new Error(
      "useCollectionToolbar must be used within CollectionToolbar"
    );
  }
  return context;
};
function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);
  return debouncedValue;
}
const FilterCountBadge = ({ count }) => /* @__PURE__ */ jsx(Badge, { className: "h-4 min-w-[16px] flex items-center justify-center p-0", children: count });
const EmptyFilterState = ({
  message = "No options available"
}) => /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: message });
const CollectionToolbar = forwardRef(({ className, children, ...props }, ref) => {
  const [activeFilters, setActiveFilters] = useState(
    /* @__PURE__ */ new Map()
  );
  const isMobile = useIsMobile();
  const contextValue = {
    isMobile,
    activeFilters,
    setActiveFilters
  };
  const childArray = Children.toArray(children);
  const firstChild = childArray[0];
  const restChildren = childArray.slice(1);
  return /* @__PURE__ */ jsx(CollectionToolbarContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxs(
    "div",
    {
      ref,
      role: "toolbar",
      className: cn(
        // Mobile: Stack vertically
        "flex flex-col gap-4",
        // Desktop: Horizontal layout - title on left, controls on right
        "md:flex-row md:items-center md:justify-between md:gap-4",
        className
      ),
      ...props,
      children: [
        firstChild,
        restChildren.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2 flex-wrap", children: restChildren })
      ]
    }
  ) });
});
CollectionToolbar.displayName = "CollectionToolbar";
const CollectionTitle = forwardRef(
  ({ className, children, ...props }, ref) => {
    return /* @__PURE__ */ jsx(
      "div",
      {
        ref,
        className: cn("flex items-center gap-2", className),
        ...props,
        children: /* @__PURE__ */ jsx("h2", { className: "headline-md line-clamp-1", children })
      }
    );
  }
);
CollectionTitle.displayName = "CollectionTitle";
const CollectionSearch = forwardRef(
  ({
    onSearch,
    debounceMs = 300,
    className,
    placeholder = "Search...",
    width,
    ...props
  }, ref) => {
    const [value, setValue] = useState("");
    const debouncedValue = useDebounce(value, debounceMs);
    const { isMobile } = useCollectionToolbar();
    useEffect(() => {
      onSearch?.(debouncedValue);
    }, [debouncedValue, onSearch]);
    const containerClassName = useMemo(() => {
      if (typeof width === "string") return width;
      if (typeof width === "number") return `w-[${width}px]`;
      return isMobile ? "w-full" : "w-[180px]";
    }, [isMobile, width]);
    return /* @__PURE__ */ jsx("div", { className: cn("relative", containerClassName), children: /* @__PURE__ */ jsx(
      Input,
      {
        ref,
        type: "search",
        role: "searchbox",
        "aria-label": "Search",
        value,
        onChange: (e) => setValue(e.target.value),
        placeholder,
        className: cn("h-8 pl-8 pr-2 w-full", className),
        ...props
      }
    ) });
  }
);
CollectionSearch.displayName = "CollectionSearch";
const CollectionFilters = forwardRef(({ activeCount, onClearAll, className, children, ...props }, ref) => {
  const { isMobile } = useCollectionToolbar();
  const [popoverOpen, setPopoverOpen] = useState(false);
  const childFilterCount = useMemo(() => {
    let count = 0;
    Children.forEach(children, (child) => {
      if (isValidElement(child) && isCollectionFilter(child)) {
        const value = child.props.value;
        if (Array.isArray(value)) {
          count += value.length;
        }
      }
    });
    return count;
  }, [children]);
  const totalFilterCount = activeCount ?? childFilterCount;
  if (isMobile) {
    return /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(CollectionToolbarAnnouncer, { filterCount: totalFilterCount }),
      /* @__PURE__ */ jsxs(Popover, { open: popoverOpen, onOpenChange: setPopoverOpen, children: [
        /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
          Button,
          {
            variant: "ghost",
            size: "sm",
            "aria-expanded": popoverOpen,
            "aria-label": `Filter${totalFilterCount > 0 ? ` (${totalFilterCount} active)` : ""}`,
            className: "px-3",
            leftIcon: totalFilterCount > 0 ? /* @__PURE__ */ jsx(FilterCountBadge, { count: totalFilterCount }) : /* @__PURE__ */ jsx(StFilter2, { className: "h-4 w-4" }),
            children: "Filter"
          }
        ) }),
        /* @__PURE__ */ jsx(
          PopoverContent,
          {
            className: cn("w-[320px]", "max-h-[400px]", "overflow-y-auto"),
            align: "start",
            children: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
              children,
              totalFilterCount > 0 && onClearAll && /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "ghost",
                  onClick: onClearAll,
                  className: "w-full",
                  leftIcon: /* @__PURE__ */ jsx(StClose, { className: "h-4 w-4" }),
                  children: "Clear"
                }
              )
            ] })
          }
        )
      ] })
    ] });
  }
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(CollectionToolbarAnnouncer, { filterCount: totalFilterCount }),
    /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn("flex items-center gap-1", className),
        ...props,
        children: [
          totalFilterCount > 0 && onClearAll && /* @__PURE__ */ jsx(
            Button,
            {
              variant: "ghost",
              size: "sm",
              onClick: onClearAll,
              "aria-label": "Clear all filters",
              leftIcon: /* @__PURE__ */ jsx(StClose, { className: "h-4 w-4" }),
              children: "Clear"
            }
          ),
          children
        ]
      }
    )
  ] });
});
CollectionFilters.displayName = "CollectionFilters";
const CollectionFilter = forwardRef(({ label, options, value, onChange, multiple = true }, ref) => {
  const { isMobile } = useCollectionToolbar();
  const [open, setOpen] = useState(false);
  const handleSelect = (optionValue) => {
    if (multiple) {
      const newValue = value.includes(optionValue) ? value.filter((v) => v !== optionValue) : [...value, optionValue];
      onChange(newValue);
    } else {
      onChange([optionValue]);
      setOpen(false);
    }
  };
  if (isMobile) {
    return /* @__PURE__ */ jsxs("div", { ref, className: "space-y-3", children: [
      /* @__PURE__ */ jsx("h3", { className: "font-medium", children: label }),
      options.length === 0 ? /* @__PURE__ */ jsx(EmptyFilterState, {}) : /* @__PURE__ */ jsx("div", { role: "listbox", "aria-label": label, children: options.map((option) => /* @__PURE__ */ jsxs(
        "label",
        {
          className: "flex items-center gap-2 cursor-pointer hover:bg-subtle p-2 rounded-md",
          children: [
            /* @__PURE__ */ jsx(
              Checkbox,
              {
                checked: value.includes(option.value),
                onCheckedChange: () => handleSelect(option.value),
                "aria-label": `Select ${option.label}`
              }
            ),
            /* @__PURE__ */ jsx("span", { className: "flex-1", children: option.label })
          ]
        },
        option.value
      )) })
    ] });
  }
  return /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpen, children: [
    /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
      Button,
      {
        variant: "ghost",
        size: "sm",
        role: "button",
        "aria-expanded": open,
        "aria-label": `${label} filter${value.length > 0 ? ` (${value.length} selected)` : ""}`,
        className: "whitespace-nowrap h-8",
        leftIcon: value.length > 0 ? /* @__PURE__ */ jsx(FilterCountBadge, { count: value.length }) : /* @__PURE__ */ jsx(StFilter2, { className: "h-4 w-4" }),
        children: label
      }
    ) }),
    /* @__PURE__ */ jsx(PopoverContent, { className: "w-56 p-0", align: "start", children: options.length === 0 ? /* @__PURE__ */ jsx("div", { className: "p-3", children: /* @__PURE__ */ jsx(EmptyFilterState, {}) }) : /* @__PURE__ */ jsx(
      "div",
      {
        className: cn("max-h-[300px]", "overflow-y-auto"),
        role: "listbox",
        "aria-label": label,
        children: options.map((option) => /* @__PURE__ */ jsxs(
          "div",
          {
            onClick: () => handleSelect(option.value),
            className: cn(
              "flex w-full items-center gap-2 px-3 py-2 hover:bg-subtle cursor-pointer",
              value.includes(option.value) && "bg-accent/10"
            ),
            role: "option",
            "aria-selected": value.includes(option.value),
            children: [
              multiple && /* @__PURE__ */ jsx(
                Checkbox,
                {
                  checked: value.includes(option.value),
                  className: "pointer-events-none",
                  tabIndex: -1
                }
              ),
              /* @__PURE__ */ jsx("span", { className: "flex-1 text-left", children: option.label })
            ]
          },
          option.value
        ))
      }
    ) })
  ] });
});
CollectionFilter.displayName = "CollectionFilter";
function isCollectionFilter(child) {
  if (!isValidElement(child)) return false;
  const type = child.type;
  return (typeof type === "function" || typeof type === "object" && type !== null) && "displayName" in type && type.displayName === "CollectionFilter";
}
const CollectionActions = forwardRef(({ className, children, ...props }, ref) => {
  return /* @__PURE__ */ jsx(
    "div",
    {
      ref,
      className: cn("flex items-center gap-2", className),
      ...props,
      children
    }
  );
});
CollectionActions.displayName = "CollectionActions";
const CollectionAction = forwardRef(
  ({
    priority = "secondary",
    className,
    children,
    leftIcon,
    rightIcon,
    ...props
  }, ref) => {
    return /* @__PURE__ */ jsx(
      Button,
      {
        ref,
        variant: priority === "primary" ? "default" : "secondary",
        size: "sm",
        "data-priority": priority,
        className,
        leftIcon,
        rightIcon,
        ...props,
        children
      }
    );
  }
);
CollectionAction.displayName = "CollectionAction";
const CollectionToolbarAnnouncer = ({
  filterCount
}) => {
  const [announcement, setAnnouncement] = useState("");
  useEffect(() => {
    if (filterCount > 0) {
      setAnnouncement(
        `${filterCount} filter${filterCount === 1 ? "" : "s"} applied`
      );
    } else {
      setAnnouncement("No filters applied");
    }
  }, [filterCount]);
  return /* @__PURE__ */ jsx(
    "div",
    {
      role: "status",
      "aria-live": "polite",
      "aria-atomic": "true",
      className: "sr-only",
      children: announcement
    }
  );
};
export {
  CollectionAction,
  CollectionActions,
  CollectionFilter,
  CollectionFilters,
  CollectionSearch,
  CollectionTitle,
  CollectionToolbar,
  CollectionToolbarAnnouncer
};
