import { isNullOrUndefined } from "@coveo/bueno";
import { ProductTemplatesHelpers } from "@coveo/headless/commerce";
import { LitElement, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";
import { createProductContextController } from "../product-template-component-utils/context/product-context-controller.js";
import { renderImageCarousel } from "../../common/image-carousel/image-carousel.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 { filterProtocol } from "../../../utils/xss-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 AtomicProductImage extends LitElement {
    initialize() {
        if (!this.product && this.productController.item) this.product = this.productController.item;
    }
    previousImage() {
        this.currentImage = this.currentImage >= 1 ? this.currentImage - 1 : this.numberOfImages - 1;
    }
    nextImage() {
        this.currentImage = (this.currentImage + 1) % this.numberOfImages;
    }
    navigateToImage(index) {
        if (index < 0 || index >= this.numberOfImages) return;
        this.currentImage = index;
    }
    logWarning(message) {
        this.bindings.engine.logger.warn(message);
    }
    handleImageError(event) {
        const image = event.target;
        const message = `The image url "${image.src}" is not valid or could not be loaded. You might want to add a "fallback" property.`;
        if (this.fallback && image.src !== this.fallback) this.useFallback = true;
        else if (image.src === this.fallback) this.logWarning('The fallback image failed to load.');
        else this.logWarning(message);
    }
    handleMissingFallback(message) {
        if (!this.fallback) {
            this.logWarning(message);
            this.isFallbackMissing = true;
            return null;
        }
        return this.fallback;
    }
    validateUrl(url) {
        if (!url) {
            const message = `Image for ${this.product.ec_name} is missing. Please review your indexing. You might want to add a "fallback" property.`;
            return this.handleMissingFallback(message);
        }
        if ('string' != typeof url) {
            const message = `Expected "${this.field}" to be a text field. Please review your indexing. You might want to add a "fallback" property.`;
            return this.handleMissingFallback(message);
        }
        return url;
    }
    filterValidImageUrls() {
        return this.imageUrls.filter((image)=>'string' == typeof image);
    }
    getAltText(index, max, validImageAlt) {
        if ('string' == typeof validImageAlt) return validImageAlt;
        return this.bindings.i18n.t('image-alt-fallback-multiple', {
            count: index + 1,
            max,
            itemName: this.product.ec_name
        });
    }
    buildImage(url, index) {
        const finalUrl = this.useFallback ? this.fallback : url;
        this.validateUrl(finalUrl);
        const validImageAlt = this.imageAlt;
        const altText = this.getAltText(index, this.filterValidImageUrls().length, validImageAlt);
        return {
            src: filterProtocol(finalUrl),
            alt: altText
        };
    }
    get images() {
        return this.filterValidImageUrls().map((url, index)=>this.buildImage(url, index));
    }
    get imageUrls() {
        try {
            const value = ProductTemplatesHelpers.getProductProperty(this.product, this.field);
            return Array.isArray(value) ? value : [
                value
            ];
        } catch (error) {
            this.error = error;
            return [];
        }
    }
    get imageAlt() {
        if (!this.imageAltField) return null;
        const value = ProductTemplatesHelpers.getProductProperty(this.product, this.imageAltField);
        if (isNullOrUndefined(value)) return null;
        return value.trim();
    }
    get numberOfImages() {
        return this.images.length;
    }
    renderCurrentImage(image) {
        if (null === image) return nothing;
        return html`
      <img
        part="product-image"
        class="aspect-square w-full h-full object-contain"
        alt=${image.alt}
        src="${image.src}"
        @error=${(event)=>this.handleImageError(event)}
        loading="lazy"
      />
    `;
    }
    render() {
        if (null === this.product || void 0 === this.product) return nothing;
        if (this.isFallbackMissing) return nothing;
        const alt = this.imageAlt ? this.imageAlt : this.bindings.i18n.t('image-not-found-alt', {
            itemName: this.product.ec_name
        });
        return html`
      ${when(0 === this.images.length, ()=>{
            this.validateUrl(this.fallback);
            return html`
            <img
              part="product-image"
              class="aspect-square w-full h-full object-contain"
              alt=${alt}
              src="${this.fallback}"
              loading="lazy"
            />
          `;
        }, ()=>when(1 === this.images.length, ()=>this.renderCurrentImage(this.images[this.currentImage]), ()=>renderImageCarousel({
                    props: {
                        bindings: this.bindings,
                        currentImage: this.currentImage,
                        navigateToImage: (index)=>this.navigateToImage(index),
                        nextImage: ()=>this.nextImage(),
                        previousImage: ()=>this.previousImage(),
                        numberOfImages: this.numberOfImages,
                        label: this.bindings.i18n.t('image-gallery', {
                            itemName: this.product.ec_name
                        })
                    }
                })(this.renderCurrentImage(this.images[this.currentImage]))))}
    `;
    }
    constructor(...args){
        super(...args), this.productController = createProductContextController(this), this.useFallback = false, this.currentImage = 0, this.isFallbackMissing = false, 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="none"%3E%3C/rect%3E%3C/svg%3E';
    }
}
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Bindings ? Object : Bindings)
], AtomicProductImage.prototype, "bindings", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Product ? Object : Product)
], AtomicProductImage.prototype, "product", void 0);
_ts_decorate([
    state(),
    _ts_metadata("design:type", "u" < typeof Error ? Object : Error)
], AtomicProductImage.prototype, "error", void 0);
_ts_decorate([
    state()
], AtomicProductImage.prototype, "useFallback", void 0);
_ts_decorate([
    state()
], AtomicProductImage.prototype, "currentImage", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicProductImage.prototype, "field", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true,
        attribute: 'image-alt-field'
    }),
    _ts_metadata("design:type", String)
], AtomicProductImage.prototype, "imageAltField", void 0);
_ts_decorate([
    property({
        type: String,
        reflect: true
    }),
    _ts_metadata("design:type", String)
], AtomicProductImage.prototype, "fallback", void 0);
_ts_decorate([
    bindingGuard(),
    errorGuard(),
    _ts_metadata("design:type", Function),
    _ts_metadata("design:paramtypes", []),
    _ts_metadata("design:returntype", void 0)
], AtomicProductImage.prototype, "render", null);
AtomicProductImage = _ts_decorate([
    customElement('atomic-product-image'),
    bindings(),
    withTailwindStyles
], AtomicProductImage);
export { AtomicProductImage };
