import { jsxs, Fragment, jsx } from 'react/jsx-runtime';
import * as React from 'react';
import { useState, useEffect, useContext, useRef, useCallback, useMemo, forwardRef } from 'react';
import { S as SvgClose } from './close-DZj38AEh.js';
import { F as FilterGroupContext, g as getActiveFilters, h as hasFilterSelectionChanged, c as cloneFiltersWithItemRefs, u as updateSingleFilter, a as checkActiveFilters, b as getAdapter, s as styles, D as DateListDialog, r as resetFilters, p as preserveFilterState, d as FilterItemWrapper } from './filter-state-DKXF5MeW.js';
import { B as Button } from './Button-BNzCI47m.js';
import { F as Flex } from './Flex-Bb3iHExM.js';
import { B as ButtonToggle } from './ButtonToggle-DBGc7dIn.js';
import { C as Chip } from './Chip-CxgryK86.js';
import { D as Drawer } from './Drawer-DzvM9MRB.js';
import { u as useToolbarSize, a as updateToolbarItemsTabIndex, g as getToolbarElements, h as handleToolbarKeyDown, b as ToolbarContext } from './ToolbarButtonToggle-3xbnm1Qr.js';
import { c as cx } from './index-De1g9FRV.js';
import { d as BreakpointSm, c as BreakpointMd, b as BreakpointLg, a as BreakpointXl, B as BreakpointXxl } from './primitive-BXgYQTTw.js';
import { u as useLayoutPropsUtil } from './useLayoutPropsUtil-DjqeAJZ9.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';

function containerBreakpoint(containerWidth, name, min, max) {
  if ((min == null || containerWidth >= min) && (max == null || containerWidth < max)) {
    return {
      name,
      min,
      max,
      containerWidth,
      containerHeight: 0
      // Will be updated with actual height
    };
  }
  return void 0;
}
const getContainerBreakpoint = (containerWidth, containerHeight) => {
  if (!BreakpointSm) return;
  if (!BreakpointMd) return;
  if (!BreakpointLg) return;
  if (!BreakpointXl) return;
  if (!BreakpointXxl) return;
  const sm = parseInt(BreakpointSm.value);
  const md = parseInt(BreakpointMd.value);
  const lg = parseInt(BreakpointLg.value);
  const xl = parseInt(BreakpointXl.value);
  const xxl = parseInt(BreakpointXxl.value);
  const result = containerBreakpoint(containerWidth, "xs", void 0, sm) ?? containerBreakpoint(containerWidth, "sm", sm, md) ?? containerBreakpoint(containerWidth, "md", md, lg) ?? containerBreakpoint(containerWidth, "lg", lg, xl) ?? containerBreakpoint(containerWidth, "xl", xl, xxl) ?? containerBreakpoint(containerWidth, "xxl", xxl, void 0);
  return result ? { ...result, containerHeight } : void 0;
};
const useContainerQuery = (containerRef, props) => {
  const [size, setSize] = useState(
    void 0
  );
  useEffect(() => {
    if (!containerRef.current) return;
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { width, height } = entry.contentRect;
        const breakpoint = getContainerBreakpoint(width, height);
        setSize(breakpoint);
      }
    });
    resizeObserver.observe(containerRef.current);
    const rect = containerRef.current.getBoundingClientRect();
    setSize(getContainerBreakpoint(rect.width, rect.height));
    return () => {
      resizeObserver.disconnect();
    };
  }, [containerRef, props?.disable]);
  return size;
};

const SvgTune = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: "1em", height: "1em", viewBox: "0 0 24 24", ...props }, /* @__PURE__ */ React.createElement("path", { d: "M3 18c0 .55.45 1 1 1h5v-2H4c-.55 0-1 .45-1 1zM3 6c0 .55.45 1 1 1h9V5H4c-.55 0-1 .45-1 1zm10 14v-1h7c.55 0 1-.45 1-1s-.45-1-1-1h-7v-1c0-.55-.45-1-1-1s-1 .45-1 1v4c0 .55.45 1 1 1s1-.45 1-1zM7 10v1H4c-.55 0-1 .45-1 1s.45 1 1 1h3v1c0 .55.45 1 1 1s1-.45 1-1v-4c0-.55-.45-1-1-1s-1 .45-1 1zm14 2c0-.55-.45-1-1-1h-9v2h9c.55 0 1-.45 1-1zm-5-3c.55 0 1-.45 1-1V7h3c.55 0 1-.45 1-1s-.45-1-1-1h-3V4c0-.55-.45-1-1-1s-1 .45-1 1v4c0 .55.45 1 1 1z" }));

const FilterDrawer = () => {
  const [open, setOpen] = useState(false);
  const {
    filters,
    updateFilter,
    onFilterChange,
    drawerOnlyFilters,
    showInlineFilters
  } = useContext(FilterGroupContext);
  const toolbarSize = useToolbarSize();
  const [draftFilters, setDraftFilters] = useState(filters);
  const [dateListDialogState, setDateListDialogState] = useState(null);
  const filtersNotInToolbar = showInlineFilters ? drawerOnlyFilters : filters;
  const activeFiltersCount = getActiveFilters(filtersNotInToolbar).length;
  const prevOpenRef = useRef(open);
  const prevFiltersRef = useRef(filters);
  useEffect(() => {
    const justOpened = open && !prevOpenRef.current;
    prevOpenRef.current = open;
    if (open) {
      const anySelectionChanged = prevFiltersRef.current.some(
        (prevFilter, index) => {
          const newFilter = filters[index];
          return newFilter && hasFilterSelectionChanged(prevFilter, newFilter);
        }
      );
      const shouldSync = justOpened || anySelectionChanged;
      if (shouldSync) {
        setDraftFilters(cloneFiltersWithItemRefs(filters));
      }
      prevFiltersRef.current = filters;
    }
  }, [open, filters]);
  const handleDraftChange = useCallback((filterId, value) => {
    setDraftFilters((draft) => updateSingleFilter(draft, filterId, value));
  }, []);
  const clearDraftFilters = () => {
    setDraftFilters(resetFilters(draftFilters));
  };
  const hasActiveDraftFilters = checkActiveFilters(draftFilters);
  const requestDateListDialog = useCallback(
    (filterId, libraryId) => {
      setDateListDialogState({ filterId, libraryId });
    },
    []
  );
  const filterForm = useMemo(
    () => draftFilters.map((draftFilter) => {
      const originalFilter = filters.find((f) => f.id === draftFilter.id);
      if (!originalFilter) return null;
      return getAdapter(draftFilter).renderDrawer({
        originalFilter,
        draftFilter,
        onDraftChange: handleDraftChange,
        requestDateListDialog
      });
    }),
    [draftFilters, filters, handleDraftChange, requestDateListDialog]
  );
  const applyFiltering = () => {
    draftFilters.forEach((draftFilter) => {
      const value = getAdapter(draftFilter).getValue(draftFilter);
      updateFilter(draftFilter.id, value, false);
    });
    onFilterChange?.(draftFilters);
    setOpen(false);
  };
  const handleCancel = () => {
    setOpen(false);
  };
  const hasHiddenActiveFilters = activeFiltersCount > 0;
  const triggerClasses = cx(
    styles["filter-button-trigger"],
    styles["filter-drawer-trigger"],
    {
      [styles["filter-drawer-trigger--chipped"]]: hasHiddenActiveFilters
    }
  );
  const dateListDialogTarget = dateListDialogState ? draftFilters.find(
    (f) => f.id === dateListDialogState.filterId && f.type === "dateList"
  ) : void 0;
  const dateListDialogSelected = dateListDialogTarget?.selectedOption;
  const dateListDialogInitialValue = dateListDialogSelected && dateListDialogSelected.id === dateListDialogState?.libraryId && dateListDialogSelected.value !== null ? dateListDialogSelected.value : void 0;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs(
      ButtonToggle,
      {
        "data-anv": "filter-group-drawer-trigger",
        icon: { before: SvgTune },
        onClick: () => setOpen(true),
        className: triggerClasses,
        checked: open,
        size: toolbarSize,
        children: [
          "Filters",
          hasHiddenActiveFilters && /* @__PURE__ */ jsx(
            Chip,
            {
              size: "small",
              color: "#0265DC",
              label: activeFiltersCount.toString()
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ jsxs(
      Drawer,
      {
        "data-anv": "filter-group-drawer",
        "data-testid": "filter-group-drawer",
        open,
        onClose: () => setOpen(false),
        children: [
          /* @__PURE__ */ jsx(Drawer.Content, { children: /* @__PURE__ */ jsx(Flex, { direction: "column", gap: 6, grow: 1, children: filterForm }) }),
          /* @__PURE__ */ jsx(Drawer.Footer, { children: /* @__PURE__ */ jsxs(
            Flex,
            {
              justifyContent: hasActiveDraftFilters ? "space-between" : "flex-end",
              grow: 1,
              children: [
                hasActiveDraftFilters && /* @__PURE__ */ jsx(
                  Button,
                  {
                    appearance: "ghost",
                    icon: { before: SvgClose },
                    onClick: clearDraftFilters,
                    children: "Clear All Filters"
                  }
                ),
                /* @__PURE__ */ jsxs(Flex, { gap: "3", children: [
                  /* @__PURE__ */ jsx(Button, { onClick: handleCancel, children: "Cancel" }),
                  /* @__PURE__ */ jsx(Button, { appearance: "primary", onClick: applyFiltering, children: "Apply" })
                ] })
              ]
            }
          ) })
        ]
      }
    ),
    /* @__PURE__ */ jsx(
      DateListDialog,
      {
        libraryId: dateListDialogState?.libraryId ?? null,
        parentFilterId: dateListDialogState?.filterId ?? "",
        initialValue: dateListDialogInitialValue,
        mode: dateListDialogTarget?.mode,
        dialogCtaLabel: "Save",
        onCommit: (option) => {
          if (dateListDialogState) {
            handleDraftChange(dateListDialogState.filterId, option);
          }
          setDateListDialogState(null);
        },
        onCancel: () => setDateListDialogState(null)
      }
    )
  ] });
};

const FilterBar = forwardRef(
  function FilterBarInner(props, ref) {
    const { layoutStyles, componentProps } = useLayoutPropsUtil(props);
    const {
      filters: initialFilters,
      onFilterChange,
      controlledFiltering = false,
      associatedContent,
      size = "xsmall",
      disableCollapse = false,
      className,
      style,
      onKeyDown,
      ...rest
    } = componentProps;
    const [filters, setFilters] = useState(initialFilters);
    const filterBarRef = useRef(null);
    const containerQuery = useContainerQuery(filterBarRef);
    const showInlineFilters = disableCollapse || !!(containerQuery && containerQuery.name !== "xs");
    useEffect(() => {
      setFilters((prevFilters) => {
        const existingFiltersMap = new Map(prevFilters.map((f) => [f.id, f]));
        return initialFilters.map((newFilter) => {
          const existingFilter = existingFiltersMap.get(newFilter.id);
          if (!existingFilter) {
            return newFilter;
          }
          if (!hasFilterSelectionChanged(existingFilter, newFilter)) {
            return preserveFilterState(newFilter, existingFilter);
          }
          return newFilter;
        });
      });
    }, [initialFilters]);
    const updateFilter = useCallback(
      (filterId, value, submit) => {
        setFilters((prevFilters) => {
          const updatedFilters = updateSingleFilter(
            prevFilters,
            filterId,
            value
          );
          if (submit) {
            onFilterChange?.(updatedFilters);
          }
          return updatedFilters;
        });
      },
      [onFilterChange]
    );
    const clearAllFilters = () => {
      const resetAllFilters = resetFilters(filters);
      setFilters(resetAllFilters);
      onFilterChange?.(resetAllFilters);
      requestAnimationFrame(() => {
        if (filterBarRef.current) {
          const firstFocusable = filterBarRef.current.querySelector(
            'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
          );
          if (firstFocusable) {
            firstFocusable.focus();
          }
        }
      });
    };
    const hasActiveFilters = checkActiveFilters(filters);
    const { inlineFilters, drawerOnlyFilters } = useMemo(() => {
      const inline = [];
      const drawer = [];
      for (const f of filters) {
        (f.drawerOnly ? drawer : inline).push(f);
      }
      const searchFilter = inline.find((f) => f.type === "search");
      const orderedInline = searchFilter ? [searchFilter, ...inline.filter((f) => f !== searchFilter)] : inline;
      return { inlineFilters: orderedInline, drawerOnlyFilters: drawer };
    }, [filters]);
    const shouldShowDrawer = !showInlineFilters || drawerOnlyFilters.length > 0;
    const filterGroupControls = inlineFilters.map(
      (filter) => getAdapter(filter).renderBarControl({
        filter,
        updateFilter,
        controlledFiltering
      })
    );
    const toolbarContextValue = useMemo(
      () => ({
        overflowItems: [],
        addItem: () => {
        },
        removeItem: () => {
        },
        toolbarRef: filterBarRef,
        size
      }),
      [size]
    );
    const filterGroupContextValue = useMemo(
      () => ({
        filterGroupRef: filterBarRef,
        filters,
        updateFilter,
        onFilterChange,
        controlledFiltering,
        associatedContent,
        showInlineFilters,
        drawerOnlyFilters
      }),
      [
        filterBarRef,
        filters,
        updateFilter,
        onFilterChange,
        controlledFiltering,
        associatedContent,
        showInlineFilters,
        drawerOnlyFilters
      ]
    );
    useEffect(() => {
      if (filterBarRef.current) {
        updateToolbarItemsTabIndex(filterBarRef.current);
      }
    }, [filters]);
    const handleKeyDown = useCallback(
      (event) => {
        if (filterBarRef.current) {
          const searchInput = filterBarRef.current.querySelector(
            '[data-anv="filter-search-field"] input'
          );
          if (searchInput) {
            const items = getToolbarElements(filterBarRef.current);
            const activeElement = event.target;
            const activeItem = items.find(
              (item) => item === activeElement || Array.from(item.children).some(
                (child) => child === activeElement
              )
            );
            const activeIndex = activeItem ? items.indexOf(activeItem) : -1;
            if (event.code === "ArrowLeft" && activeIndex === 0 || event.code === "ArrowRight" && activeIndex === items.length - 1) {
              event.preventDefault();
              searchInput.focus();
              onKeyDown?.(event);
              return;
            }
          }
          handleToolbarKeyDown(event, filterBarRef.current);
        }
        onKeyDown?.(event);
      },
      [onKeyDown]
    );
    const styleCombined = {
      ...style,
      ...layoutStyles
    };
    return /* @__PURE__ */ jsx(ToolbarContext.Provider, { value: toolbarContextValue, children: /* @__PURE__ */ jsx(FilterGroupContext.Provider, { value: filterGroupContextValue, children: /* @__PURE__ */ jsx(
      Flex,
      {
        ref: useMergeRefs([filterBarRef, ref]),
        role: "toolbar",
        "aria-label": `Filters for ${associatedContent}. Use arrow keys to navigate through filter controls.`,
        "aria-orientation": "horizontal",
        tabIndex: -1,
        onKeyDown: handleKeyDown,
        alignItems: "center",
        gap: 1,
        wrap: "wrap",
        className,
        style: styleCombined,
        "data-anv": "filter-bar",
        ...rest,
        children: /* @__PURE__ */ jsxs(
          Flex,
          {
            alignItems: "center",
            gap: 1,
            wrap: "wrap",
            grow: 1,
            "data-anv": "toolbar-content",
            children: [
              showInlineFilters && filterGroupControls,
              shouldShowDrawer && /* @__PURE__ */ jsx(FilterDrawer, {}),
              showInlineFilters && hasActiveFilters && /* @__PURE__ */ jsx(FilterItemWrapper, { children: /* @__PURE__ */ jsx(
                Button,
                {
                  appearance: "ghost",
                  size,
                  className: styles["filter-button-trigger"],
                  icon: {
                    before: SvgClose
                  },
                  onClick: clearAllFilters,
                  children: "Clear Filters"
                }
              ) })
            ]
          }
        )
      }
    ) }) });
  }
);
FilterBar.displayName = "FilterBar";

export { FilterBar as F };
//# sourceMappingURL=FilterBar-DBVW3LL3.js.map
