import { ProductTemplatesHelpers, buildProductListing, buildSearch } from "@coveo/headless/commerce";
import { LitElement, html, nothing } from "lit";
import { customElement, property as decorators_js_property, state } from "lit/decorators.js";
import { createProductContextController } from "../product-template-component-utils/context/product-context-controller.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 { getFieldValueCaption } from "../../../utils/field-utils.js";
import { titleToKebab } from "../../../utils/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 AtomicProductMultiValueText extends LitElement {
    initialize() {
        const searchOrListing = 'product-listing' === this.bindings.interfaceElement.type ? buildProductListing(this.bindings.engine) : buildSearch(this.bindings.engine);
        this.breadcrumbManager = searchOrListing.breadcrumbManager();
        this.values = this.initializeValues();
    }
    initializeValues() {
        const product = this.productController.item;
        if (!product) return [];
        const property = ProductTemplatesHelpers.getProductProperty(product, this.field);
        if (null === property) return [];
        if (Array.isArray(property)) return property.map((v)=>`${v}`.trim());
        if ('string' != typeof property || '' === property.trim()) {
            this.error = new Error(`Could not parse "${property}" from field "${this.field}" as a string array.`);
            return [];
        }
        return this.delimiter ? property.split(this.delimiter).map((value)=>value.trim()) : [
            property
        ];
    }
    get facetSelectedValues() {
        return this.breadcrumbManager.state.facetBreadcrumbs.reduce((values, facet)=>{
            if (facet.field !== this.field) return values;
            return values.concat(facet.values.map(({ value })=>value.value));
        }, []);
    }
    get sortedValues() {
        const firstValues = this.facetSelectedValues.filter((value)=>this.values.includes(value));
        return Array.from(new Set([
            ...firstValues,
            ...this.values
        ]));
    }
    get shouldDisplayLabel() {
        return this.maxValuesToDisplay > 0 && this.sortedValues.length > this.maxValuesToDisplay;
    }
    get numberOfValuesToDisplay() {
        return Math.min(this.sortedValues.length, this.maxValuesToDisplay);
    }
    renderValue(value) {
        const label = getFieldValueCaption(this.field, value, this.bindings.i18n);
        const kebabValue = titleToKebab(value);
        return html`
      <li part="product-multi-value-text-value" class="inline-block">
        <slot name=${`product-multi-value-text-value-${kebabValue}`}>
          ${label}
        </slot>
      </li>
    `;
    }
    renderSeparator() {
        return html`
      <li
        aria-hidden="true"
        part="product-multi-value-text-separator"
        class="${String.raw`inline-block before:inline before:content-[',\00a0']`}"
      ></li>
    `;
    }
    renderMoreLabel(value) {
        return html`
      <li part="product-multi-value-text-value-more" class="inline-block">
        ${this.bindings.i18n.t('n-more', {
            value
        })}
      </li>
    `;
    }
    renderListItems(values) {
        const templates = [];
        templates.push(this.renderValue(values[0]));
        for(let i = 1; i < this.numberOfValuesToDisplay; i++){
            templates.push(this.renderSeparator());
            templates.push(this.renderValue(values[i]));
        }
        if (this.shouldDisplayLabel) {
            templates.push(this.renderSeparator());
            templates.push(this.renderMoreLabel(values.length - this.numberOfValuesToDisplay));
        }
        return templates;
    }
    render() {
        if (0 === this.sortedValues.length) return nothing;
        return html`
      <ul
        part="product-multi-value-text-list"
        class="m-0 flex list-none p-0 set-font-size-sm"
      >
        ${this.renderListItems(this.sortedValues)}
      </ul>
    `;
    }
    constructor(...args){
        super(...args), this.productController = createProductContextController(this), this.maxValuesToDisplay = 3, this.delimiter = null, this.values = [];
    }
}
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicProductMultiValueText.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicProductMultiValueText.prototype, "error", void 0);
_ts_decorate([
    decorators_js_property({
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicProductMultiValueText.prototype, "field", void 0);
_ts_decorate([
    decorators_js_property({
        reflect: true,
        type: Number,
        attribute: 'max-values-to-display'
    })
], AtomicProductMultiValueText.prototype, "maxValuesToDisplay", void 0);
_ts_decorate([
    decorators_js_property({
        reflect: true
    }),
    _ts_metadata("design:type", Object)
], AtomicProductMultiValueText.prototype, "delimiter", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", Array)
], AtomicProductMultiValueText.prototype, "values", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicProductMultiValueText.prototype, "render", null);
AtomicProductMultiValueText = _ts_decorate([
    customElement('atomic-product-multi-value-text'),
    bindings(),
    withTailwindStyles
], AtomicProductMultiValueText);
export { AtomicProductMultiValueText };
