import { NumberValue, Schema } from "@coveo/bueno";
import { buildBreadcrumbManager, buildFacetManager } from "@coveo/headless";
import { LitElement, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { renderBreadcrumbButton } from "../../common/breadbox/breadcrumb-button.js";
import { renderBreadcrumbClearAll } from "../../common/breadbox/breadcrumb-clear-all.js";
import { renderBreadcrumbContainer } from "../../common/breadbox/breadcrumb-container.js";
import { renderBreadcrumbContent } from "../../common/breadbox/breadcrumb-content.js";
import { renderBreadcrumbShowLess } from "../../common/breadbox/breadcrumb-show-less.js";
import { renderBreadcrumbShowMore } from "../../common/breadbox/breadcrumb-show-more.js";
import { ValidatePropsController } from "../../common/validate-props-controller/validate-props-controller.js";
import { bindStateToController } from "../../../decorators/bind-state.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { withTailwindStyles } from "../../../decorators/with-tailwind-styles.js";
import { AriaLiveRegionController, FocusTargetController } from "../../../utils/accessibility-utils.js";
import { getFieldValueCaption } from "../../../utils/field-utils.js";
function _ts_decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc);
    else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function _ts_metadata(k, v) {
    if ("object" == typeof Reflect && "function" == typeof Reflect.metadata) return Reflect.metadata(k, v);
}
class AtomicBreadbox extends LitElement {
    initialize() {
        this.breadcrumbManager = buildBreadcrumbManager(this.bindings.engine);
        this.facetManager = buildFacetManager(this.bindings.engine);
        if (this.disableCollapse) this.isCollapsed = false;
        else if (window.ResizeObserver && this.parentElement) {
            this.resizeObserver = new ResizeObserver(()=>this.adaptBreadcrumbs());
            this.resizeObserver.observe(this.parentElement);
        }
        this.breadcrumbRemovedFocus = new FocusTargetController(this, this.bindings);
        this.breadcrumbShowMoreFocus = new FocusTargetController(this, this.bindings);
        this.breadcrumbShowLessFocus = new FocusTargetController(this, this.bindings);
    }
    updated() {
        this.adaptBreadcrumbs();
    }
    render() {
        const breadcrumbs = this.allBreadcrumbs;
        if (!breadcrumbs.length) return nothing;
        return html`${renderBreadcrumbContainer({
            props: {
                isCollapsed: this.isCollapsed,
                i18n: this.bindings.i18n
            }
        })(html`${this.renderBreadcrumbs(breadcrumbs)}
      ${this.disableCollapse ? nothing : html`${renderBreadcrumbShowMore({
            props: {
                refCallback: async (el)=>{
                    await this.breadcrumbShowLessFocus.setTarget(el);
                },
                onShowMore: ()=>{
                    this.firstExpandedBreadcrumbIndex = this.numberOfBreadcrumbs - this.numberOfCollapsedBreadcrumbs;
                    this.breadcrumbShowMoreFocus.focusOnNextTarget();
                    this.isCollapsed = false;
                },
                isCollapsed: this.isCollapsed,
                i18n: this.bindings.i18n,
                numberOfCollapsedBreadcrumbs: this.numberOfCollapsedBreadcrumbs,
                value: this.showMoreText,
                ariaLabel: this.bindings.i18n.t('show-n-more-filters', {
                    value: this.numberOfCollapsedBreadcrumbs
                })
            }
        })}
          ${renderBreadcrumbShowLess({
            props: {
                onShowLess: ()=>{
                    this.breadcrumbShowLessFocus.focusOnNextTarget();
                    this.isCollapsed = true;
                },
                isCollapsed: this.isCollapsed,
                i18n: this.bindings.i18n
            }
        })}`}
      ${renderBreadcrumbClearAll({
            props: {
                refCallback: async (ref)=>{
                    const isFocusTarget = this.lastRemovedBreadcrumbIndex === this.numberOfBreadcrumbs;
                    if (isFocusTarget) await this.breadcrumbRemovedFocus.setTarget(ref);
                },
                onClick: ()=>{
                    this.breadcrumbManager.deselectAll();
                    this.bindings.store.state.resultList?.focusOnFirstResultAfterNextSearch();
                },
                isCollapsed: this.isCollapsed,
                i18n: this.bindings.i18n
            }
        })} `)}`;
    }
    disconnectedCallback() {
        super.disconnectedCallback();
        this.resizeObserver?.disconnect();
    }
    get breadcrumbs() {
        return Array.from(this.shadowRoot.querySelectorAll('li.breadcrumb'));
    }
    get showMoreButton() {
        return this.shadowRoot.querySelector('button[part="show-more"]');
    }
    get showLessButton() {
        return this.shadowRoot.querySelector('button[part="show-less"]');
    }
    hide(element) {
        element.style.display = 'none';
    }
    show(element) {
        element.style.display = '';
    }
    showAllBreadcrumbs() {
        this.breadcrumbs.forEach((breadcrumb)=>this.show(breadcrumb));
    }
    adaptBreadcrumbs() {
        if (this.disableCollapse || !this.breadcrumbs.length) return;
        this.showAllBreadcrumbs();
        if (!this.isCollapsed) return void this.updateShowLessDisplay();
        this.hideOverflowingBreadcrumbs();
    }
    updateShowLessDisplay() {
        this.show(this.showLessButton);
        if (0 === this.showLessButton.offsetTop) this.hide(this.showLessButton);
    }
    hideOverflowingBreadcrumbs() {
        let hiddenBreadcrumbs = 0;
        for(let i = this.breadcrumbs.length - 1; this.isOverflowing && i >= 0; i--){
            this.hide(this.breadcrumbs[i]);
            hiddenBreadcrumbs++;
        }
        this.updateShowMoreValue(hiddenBreadcrumbs);
    }
    get isOverflowing() {
        const listElement = this.shadowRoot.querySelector('ul');
        if (!listElement) return false;
        return listElement.scrollWidth > listElement.clientWidth;
    }
    updateShowMoreValue(value) {
        this.numberOfCollapsedBreadcrumbs = value;
        if (0 === value) return void this.hide(this.showMoreButton);
        this.show(this.showMoreButton);
        this.showMoreText = `+ ${value.toLocaleString(this.bindings.i18n.language)}`;
    }
    get facetBreadcrumbs() {
        return this.breadcrumbManagerState.facetBreadcrumbs.flatMap(({ facetId, field, values })=>values.map((value)=>({
                    value,
                    facetId,
                    field
                }))).filter(({ facetId })=>this.bindings.store.state.facets[facetId]).map(({ value, facetId, field })=>({
                facetId,
                label: this.bindings.store.state.facets[facetId]?.label(),
                state: value.value.state,
                deselect: value.deselect,
                formattedValue: [
                    getFieldValueCaption(field, value.value.value, this.bindings.i18n)
                ]
            }));
    }
    get categoryFacetBreadcrumbs() {
        return this.breadcrumbManagerState.categoryFacetBreadcrumbs.map(({ facetId, field, path, deselect })=>({
                facetId,
                label: this.bindings.store.state.categoryFacets[facetId].label(),
                deselect: deselect,
                formattedValue: path.map((pathValue)=>getFieldValueCaption(field, pathValue.value, this.bindings.i18n))
            }));
    }
    get numericFacetBreadcrumbs() {
        return this.breadcrumbManagerState.numericFacetBreadcrumbs.flatMap(({ facetId, field, values })=>values.map((value)=>({
                    value,
                    facetId,
                    field
                }))).map(({ value, facetId })=>({
                facetId,
                label: this.bindings.store.state.numericFacets[facetId].label(),
                state: value.value.state,
                deselect: value.deselect,
                formattedValue: [
                    this.bindings.store.state.numericFacets[facetId].format(value.value)
                ],
                content: this.bindings.store.state.numericFacets[facetId].content?.(value.value)
            }));
    }
    get dateFacetBreadcrumbs() {
        return this.breadcrumbManagerState.dateFacetBreadcrumbs.flatMap(({ facetId, field, values })=>values.map((value)=>({
                    value,
                    facetId,
                    field
                }))).map(({ value, facetId })=>({
                facetId,
                label: this.bindings.store.state.dateFacets[facetId].label(),
                state: value.value.state,
                deselect: value.deselect,
                formattedValue: [
                    this.bindings.store.state.dateFacets[facetId].format(value.value)
                ]
            }));
    }
    get automaticFacetBreadcrumbs() {
        return this.breadcrumbManagerState.automaticFacetBreadcrumbs.flatMap(({ facetId, field, label, values })=>values.map((value)=>({
                    value,
                    facetId,
                    field,
                    label
                }))).map(({ value, facetId, field, label })=>({
                facetId,
                state: value.value.state,
                label: label ? label : field,
                deselect: value.deselect,
                formattedValue: [
                    getFieldValueCaption(field, value.value.value, this.bindings.i18n)
                ]
            }));
    }
    get allBreadcrumbs() {
        return [
            ...this.facetBreadcrumbs,
            ...this.categoryFacetBreadcrumbs,
            ...this.numericFacetBreadcrumbs,
            ...this.dateFacetBreadcrumbs,
            ...this.automaticFacetBreadcrumbs
        ];
    }
    renderBreadcrumbs(breadcrumbs) {
        const sortedBreadcrumbs = breadcrumbs.sort((a, b)=>{
            const indexA = this.facetManagerState.facetIds.indexOf(a.facetId);
            const indexB = this.facetManagerState.facetIds.indexOf(b.facetId);
            return indexA - indexB;
        });
        this.numberOfBreadcrumbs = sortedBreadcrumbs.length;
        return sortedBreadcrumbs.map((breadcrumb, index)=>{
            const isLastBreadcrumb = 1 === this.allBreadcrumbs.length;
            return html`${renderBreadcrumbButton({
                props: {
                    pathLimit: this.pathLimit,
                    breadcrumb,
                    i18n: this.bindings.i18n,
                    onSelectBreadcrumb: ()=>{
                        if (isLastBreadcrumb) this.bindings.store.state.resultList?.focusOnFirstResultAfterNextSearch();
                        else if (this.numberOfBreadcrumbs > 1) this.breadcrumbRemovedFocus.focusAfterSearch();
                        this.lastRemovedBreadcrumbIndex = index;
                        breadcrumb.deselect();
                    },
                    refCallback: async (ref)=>{
                        if (this.lastRemovedBreadcrumbIndex === index) await this.breadcrumbRemovedFocus.setTarget(ref);
                        if (this.firstExpandedBreadcrumbIndex === index) await this.breadcrumbShowMoreFocus.setTarget(ref);
                    },
                    ariaController: this.breadboxAriaMessage
                }
            })(html`${renderBreadcrumbContent({
                props: {
                    pathLimit: this.pathLimit,
                    isCollapsed: this.isCollapsed,
                    i18n: this.bindings.i18n,
                    breadcrumb
                }
            })}`)}`;
        });
    }
    constructor(){
        super(), this.lastRemovedBreadcrumbIndex = 0, this.numberOfBreadcrumbs = 0, this.numberOfCollapsedBreadcrumbs = 0, this.isCollapsed = true, this.showMoreText = '', this.disableCollapse = false, this.breadboxAriaMessage = new AriaLiveRegionController(this, 'breadbox', true), this.pathLimit = 3;
        new ValidatePropsController(this, ()=>({
                pathLimit: this.pathLimit
            }), AtomicBreadbox.propsSchema);
    }
}
AtomicBreadbox.styles = [
    css`/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */[part=breadcrumb-label].excluded,[part=breadcrumb-value].excluded{color:var(--atomic-error);text-decoration:line-through}`
];
AtomicBreadbox.propsSchema = new Schema({
    pathLimit: new NumberValue({
        default: 3,
        min: 1,
        required: false
    })
});
_ts_decorate([
    bindStateToController('breadcrumbManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof BreadcrumbManagerState ? Object : BreadcrumbManagerState)
], AtomicBreadbox.prototype, "breadcrumbManagerState", void 0);
_ts_decorate([
    bindStateToController('facetManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof FacetManagerState ? Object : FacetManagerState)
], AtomicBreadbox.prototype, "facetManagerState", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicBreadbox.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicBreadbox.prototype, "isCollapsed", void 0);
_ts_decorate([
    state()
], AtomicBreadbox.prototype, "showMoreText", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'disable-collapse'
    })
], AtomicBreadbox.prototype, "disableCollapse", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'path-limit'
    })
], AtomicBreadbox.prototype, "pathLimit", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicBreadbox.prototype, "render", null);
AtomicBreadbox = _ts_decorate([
    customElement('atomic-breadbox'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicBreadbox);
export { AtomicBreadbox };
