import { ProductTemplatesHelpers } from "@coveo/headless/commerce";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { createProductContextController } from "../product-template-component-utils/context/product-context-controller.js";
import { bindings } from "../../../decorators/bindings.js";
import { errorGuard } from "../../../decorators/error-guard.js";
import { buildCustomEvent } from "../../../utils/event-utils.js";
import { filterProtocol } from "../../../utils/xss-utils.js";
import { renderButton } from "../../common/button.js";
import "../atomic-commerce-text/atomic-commerce-text.js";
import { bindingGuard } from "../../../decorators/binding-guard.js";
import { multiClassMap, tw } from "../../../directives/multi-class-map.js";
import { LightDomMixin } from "../../../mixins/light-dom.js";
import { closest } from "../../../utils/dom-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);
}
const AMOUNT_OF_VISIBLE_CHILDREN = 5;
class AtomicProductChildren extends LightDomMixin(LitElement) {
    initialize() {
        const product = this.productController.item;
        if (product) {
            this.activeChildId = product.permanentid;
            this.childProducts = product.children ?? [];
        }
    }
    onSelectChild(child) {
        this.activeChildId = child.permanentid;
        this.dispatchEvent(buildCustomEvent('atomic/selectChildProduct', {
            child
        }));
    }
    getImageUrl(child) {
        const value = ProductTemplatesHelpers.getProductProperty(child, this.field);
        if ('string' == typeof value) return filterProtocol(value);
        if (Array.isArray(value) && 'string' == typeof value[0]) return filterProtocol(value[0]);
        return filterProtocol(this.fallback);
    }
    renderChild(child) {
        const childName = child.ec_name ?? '';
        const buttonClasses = tw({
            'product-child': true,
            'box-border rounded border border-primary': child.permanentid === this.activeChildId
        });
        return html`
      <button
        class="${multiClassMap(buttonClasses)}"
        title=${childName}
        @keypress=${(event)=>'Enter' === event.key && this.onSelectChild(child)}
        @mouseenter=${()=>this.onSelectChild(child)}
        @touchstart=${(event)=>{
            event.stopPropagation();
            event.preventDefault();
            this.onSelectChild(child);
        }}
        @click=${this.handleClick}
      >
        <img
          class="aspect-square p-1"
          src=${this.getImageUrl(child)}
          alt=${childName}
          loading="lazy"
        />
      </button>
    `;
    }
    renderLabel() {
        return html`
      <div class="text-neutral-dark my-2 font-semibold">
        <atomic-commerce-text
          .value=${this.bindings.i18n.t(this.label)}
        ></atomic-commerce-text>
      </div>
    `;
    }
    get count() {
        const hiddenChildrenCount = Math.max(0, this.childProducts.length - AMOUNT_OF_VISIBLE_CHILDREN);
        return this.productController.item?.totalNumberOfChildren - this.productController.item?.children.length + hiddenChildrenCount;
    }
    render() {
        if (0 === this.childProducts.length) return nothing;
        const visibleChildren = this.childProducts.slice(0, AMOUNT_OF_VISIBLE_CHILDREN);
        return html`
      ${'' !== this.label.trim() ? this.renderLabel() : nothing}
      <div class="flex flex-wrap">
        ${visibleChildren.map((child)=>this.renderChild(child))}
        ${this.count > 0 ? renderButton({
            props: {
                style: 'text-primary',
                class: 'product-child',
                onClick: this.handleClick
            }
        })(html`+${this.count}`) : nothing}
      </div>
    `;
    }
    constructor(...args){
        super(...args), this.productController = createProductContextController(this), this.childProducts = [], this.activeChildId = '', this.label = 'available-in', this.field = 'ec_thumbnails', this.fallback = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 50 50"%3E%3Crect width="50" height="50" fill="none" stroke="gray"%3E%3C/rect%3E%3C/svg%3E', this.handleClick = (event)=>{
            if (this.parentElement?.tagName !== 'A') closest(this, 'atomic-product').clickLinkContainer();
            else event.stopPropagation();
        };
    }
}
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof CommerceBindings ? Object : CommerceBindings)
], AtomicProductChildren.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", Array)
], AtomicProductChildren.prototype, "childProducts", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", String)
], AtomicProductChildren.prototype, "activeChildId", void 0);
_ts_decorate([
    property(),
    _ts_metadata("design:type", String)
], AtomicProductChildren.prototype, "label", void 0);
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicProductChildren.prototype, "field", void 0);
_ts_decorate([
    property({
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicProductChildren.prototype, "fallback", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicProductChildren.prototype, "render", null);
AtomicProductChildren = _ts_decorate([
    customElement('atomic-product-children'),
    bindings()
], AtomicProductChildren);
export { AtomicProductChildren };
