import { NumberValue, Schema } from "@coveo/bueno";
import { buildContext, buildProductListing, buildSearch } from "@coveo/headless/commerce";
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 { formatHumanReadable } from "../../common/facets/numeric-facet/formatter.js";
import { defaultCurrencyFormatter, defaultNumberFormatter } from "../../common/formats/format-common.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 { parseDate } from "../../../utils/date-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 AtomicCommerceBreadbox extends LitElement {
    initialize() {
        if ('product-listing' === this.bindings.interfaceElement.type) this.searchOrListing = buildProductListing(this.bindings.engine);
        else this.searchOrListing = buildSearch(this.bindings.engine);
        this.context = buildContext(this.bindings.engine);
        this.breadcrumbManager = this.searchOrListing.breadcrumbManager();
        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();
    }
    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)}`;
    }
    getNumberFormatter(field) {
        if ('ec_price' === field || 'ec_promo_price' === field) return defaultCurrencyFormatter(this.contextState.currency);
        return defaultNumberFormatter;
    }
    buildBreadcrumb(breadcrumb) {
        return breadcrumb.values.map((value)=>({
                facetId: breadcrumb.facetId,
                label: breadcrumb.facetDisplayName ?? this.bindings.i18n.t('no-label'),
                deselect: value.deselect,
                formattedValue: this.valueForFacetType(breadcrumb.type, breadcrumb.facetId, value)
            }));
    }
    renderBreadcrumbs(breadcrumbs) {
        this.numberOfBreadcrumbs = breadcrumbs.length;
        return breadcrumbs.map((breadcrumb, index)=>{
            const isLastBreadcrumb = 1 === breadcrumbs.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
                }
            })}`)}`;
        });
    }
    render() {
        const breadcrumbs = this.breadcrumbManagerState.facetBreadcrumbs.flatMap((breadcrumb)=>this.buildBreadcrumb(breadcrumb));
        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
            }
        })} `)}`;
    }
    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, this.valueForFacetType = (type, field, value)=>{
            switch(type){
                case 'numericalRange':
                    return [
                        formatHumanReadable({
                            facetValue: value.value,
                            logger: this.bindings.engine.logger,
                            i18n: this.bindings.i18n,
                            field: field,
                            manualRanges: [],
                            formatter: this.getNumberFormatter(field)
                        })
                    ];
                case 'dateRange':
                    return [
                        this.bindings.i18n.t('to', {
                            start: parseDate(value.value.start).format('YYYY-MM-DD'),
                            end: parseDate(value.value.end).format('YYYY-MM-DD')
                        })
                    ];
                case 'hierarchical':
                    return value.value.path.map((pathValue)=>getFieldValueCaption(field, pathValue, this.bindings.i18n));
                case 'regular':
                    return [
                        getFieldValueCaption(field, value.value.value, this.bindings.i18n)
                    ];
                default:
                    this.bindings.engine.logger.warn('Unexpected breadcrumb type.');
                    return [];
            }
        };
        new ValidatePropsController(this, ()=>({
                pathLimit: this.pathLimit
            }), AtomicCommerceBreadbox.propsSchema);
    }
}
AtomicCommerceBreadbox.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}[part=breadcrumb-value]:before{content:" "}`
];
AtomicCommerceBreadbox.propsSchema = new Schema({
    pathLimit: new NumberValue({
        default: 3,
        min: 1,
        required: false
    })
});
_ts_decorate([
    bindStateToController('context'),
    state(),
    _ts_metadata("design:type", "u" < typeof ContextState ? Object : ContextState)
], AtomicCommerceBreadbox.prototype, "contextState", void 0);
_ts_decorate([
    bindStateToController('breadcrumbManager'),
    state(),
    _ts_metadata("design:type", "u" < typeof BreadcrumbManagerState ? Object : BreadcrumbManagerState)
], AtomicCommerceBreadbox.prototype, "breadcrumbManagerState", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicCommerceBreadbox.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicCommerceBreadbox.prototype, "isCollapsed", void 0);
_ts_decorate([
    state()
], AtomicCommerceBreadbox.prototype, "showMoreText", void 0);
_ts_decorate([
    property({
        type: Boolean,
        attribute: 'disable-collapse'
    })
], AtomicCommerceBreadbox.prototype, "disableCollapse", void 0);
_ts_decorate([
    property({
        type: Number,
        attribute: 'path-limit'
    })
], AtomicCommerceBreadbox.prototype, "pathLimit", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicCommerceBreadbox.prototype, "render", null);
AtomicCommerceBreadbox = _ts_decorate([
    customElement('atomic-commerce-breadbox'),
    bindings(),
    withTailwindStyles,
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", [])
], AtomicCommerceBreadbox);
export { AtomicCommerceBreadbox };
