'use strict';

var index = require('./index-pX0sBY0-.js');

const filterBarCss = () => `:host{display:block;width:100%}.search-container{display:flex;width:calc(100% - 48px);padding-left:24px;padding-right:24px;flex-direction:row;align-items:flex-start;margin-bottom:16px}.components-container{display:flex;width:calc(100% - 48px);padding-left:24px;padding-right:24px;flex-direction:row;align-items:flex-end;align-content:flex-end;flex-wrap:wrap;gap:16px}.filter-slot-wrapper{flex-grow:1;flex-basis:100%;max-width:100%}@media (max-width: 1024px){.filter-buttons-wrapper{order:3;width:100%;display:flex;justify-content:center;padding-top:16px;}}@media (min-width: 720px) and (max-width: 1024px){.filter-slot-wrapper{flex-basis:calc((100% - 16px) / 2);max-width:calc((100% - 16px) / 2)}}@media (min-width: 1025px){.filter-slot-wrapper{flex-basis:auto;max-width:200px}::slotted([slot=filter-search]){max-width:828px}}::slotted([slot=filter-search]){flex-grow:1;flex-basis:100%;width:100%}`;

const FilterBar = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.ifxTopbarFilterChange = index.createEvent(this, "ifxTopbarFilterChange", 7);
    }
    get el() { return index.getElement(this); }
    selectedOptions = [];
    /** Emitted when a topbar filter changes */
    ifxTopbarFilterChange;
    showAllFilters = false;
    /** Maximum number of filters to show in the topbar before collapsing */
    maxShownFilters = 4; // Default to 4, can be overridden by parent component
    visibleSlots;
    /** Controls "More / Less filters" Buttons */
    async showMoreFilters(showMore) {
        this.showAllFilters = showMore;
        this.updateVisibleSlots();
    }
    /* If the component is ever removed and then reattached to the DOM,
    connectedCallback ensures that the event listeners are properly set up again */
    connectedCallback() {
        this.el.addEventListener("ifxFilterSelect", this.handleTopbarFilterChange);
        this.el.addEventListener("ifxFilterSearchChange", this.handleSearchChange);
        window.addEventListener("ifxResetFiltersEvent", this.handleResetEvent);
    }
    disconnectedCallback() {
        this.el.removeEventListener("ifxFilterSelect", this.handleTopbarFilterChange);
        this.el.removeEventListener("ifxFilterSearchChange", this.handleSearchChange);
        window.removeEventListener("ifxResetFiltersEvent", this.handleResetEvent);
    }
    componentWillLoad() {
        this.updateVisibleSlots();
    }
    // Modify updateVisibleSlots to use showAllFilters to determine the number of slots
    updateVisibleSlots() {
        this.visibleSlots = this.showAllFilters
            ? Number.MAX_SAFE_INTEGER
            : this.maxShownFilters;
    }
    handleFilterButtonsClick = (all) => {
        this.showMoreFilters(all);
    };
    handleResetEvent = () => {
        const filterSearchSlot = this.el.shadowRoot?.querySelector('slot[name="filter-search"]');
        if (filterSearchSlot instanceof HTMLSlotElement) {
            // Ensure it's treated as HTMLSlotElement
            const filterSearchSlottedElements = filterSearchSlot.assignedElements({
                flatten: true,
            });
            filterSearchSlottedElements.forEach((filterSearchWrapper) => {
                const filterSearch = filterSearchWrapper.querySelector("ifx-filter-search");
                const searchField = filterSearch.shadowRoot.querySelectorAll("ifx-search-field");
                if (searchField.length > 0) {
                    searchField.forEach((searchFieldElement) => {
                        searchFieldElement.value = "";
                    });
                }
            });
        }
        this.selectedOptions = [];
        // Emit the change to inform any parent components that the filters have been reset
        this.ifxTopbarFilterChange.emit(this.selectedOptions);
    };
    handleSearchChange = (event) => {
        this.handleTopbarFilterChange(event);
    };
    handleTopbarFilterChange = (event) => {
        const newSelectedOptions = [...this.selectedOptions];
        if (event.type === "ifxFilterSearchChange") {
            const { filterName, filterValue } = event.detail;
            const existingOptionIndex = newSelectedOptions.findIndex((option) => option.filterName === filterName);
            if (existingOptionIndex !== -1) {
                // If an existing filter is found, update its value
                newSelectedOptions[existingOptionIndex].filterValues = [filterValue];
            }
            else {
                newSelectedOptions.push({
                    filterName: filterName,
                    filterValues: [filterValue],
                    type: "text",
                });
            }
        }
        else if (event.type === "ifxFilterSelect") {
            const { filterName, filterValues, type } = event.detail;
            const existingOptionIndex = newSelectedOptions.findIndex((option) => option.filterName === filterName);
            if (existingOptionIndex !== -1) {
                newSelectedOptions[existingOptionIndex].filterValues = filterValues;
                newSelectedOptions[existingOptionIndex].type = type; // Update type based on the number of selected items
            }
            else {
                newSelectedOptions.push({
                    filterName: filterName,
                    filterValues: filterValues,
                    type: type,
                });
            }
        }
        this.selectedOptions = newSelectedOptions;
        this.ifxTopbarFilterChange.emit(this.selectedOptions);
    };
    render() {
        const safeVisibleSlots = Math.max(0, this.visibleSlots);
        const actualNumberOfComponents = this.el.querySelectorAll("ifx-set-filter").length;
        // Calculate slotsToShow safely
        const slotsToShow = Math.min(safeVisibleSlots, actualNumberOfComponents, Number.MAX_SAFE_INTEGER);
        const slots = Array.from({ length: slotsToShow }, (_, i) => (index.h("div", { class: "filter-slot-wrapper" }, index.h("slot", { name: `filter-component-${i + 1}` }))));
        return (index.h(index.Host, { key: 'ffe2a8fb921554af84679eb8653d79b13f86c8b1' }, index.h("div", { key: 'ff836ffc5399fc087dc4aab78ef6521fdf9c919d', class: "search-container" }, index.h("slot", { key: '8490ebe5747f37ed476adcc3f63b406435778376', name: "filter-search" }), " "), index.h("div", { key: '4d3960b70ebfbcf0e65df544b1bc22006447d3ef', class: "components-container" }, slots.length > 0 ? slots : index.h("slot", { name: "filter-component" }), this.showMoreFilters && (index.h("div", { key: '9265bc7f1d60b341be4cc997023e7fa671c73c8e', class: "filter-buttons-wrapper", onClick: () => this.handleFilterButtonsClick(!this.showAllFilters) }, index.h("ifx-button", { key: 'a5fad6269fc27513177b172dfb668d56bf32ddab', type: "button", disabled: false, variant: "tertiary", size: "m", target: "_blank", theme: "default", "full-width": "false" }, index.h("ifx-icon", { key: '3287ca74ece70905d275f41a74cb54f9a30a8162', icon: "filter-16" }), this.showAllFilters ? "Less filters" : "More filters"))))));
    }
};
FilterBar.style = filterBarCss();

exports.ifx_filter_bar = FilterBar;
