/*!
 * Crafted with ❤ by Salla
 */
import { proxyCustomElement, HTMLElement, h } from '@stencil/core/internal/client';
import { a as anime } from './anime.es.js';
import { H as Helper } from './Helper.js';
import { d as defineCustomElement$a } from './salla-button2.js';
import { d as defineCustomElement$9 } from './salla-comment-form2.js';
import { d as defineCustomElement$8 } from './salla-comment-item2.js';
import { d as defineCustomElement$7 } from './salla-loading2.js';
import { d as defineCustomElement$6 } from './salla-modal2.js';
import { d as defineCustomElement$5 } from './salla-progress-bar2.js';
import { d as defineCustomElement$4 } from './salla-rating-stars2.js';
import { d as defineCustomElement$3 } from './salla-reviews-summary2.js';
import { d as defineCustomElement$2 } from './salla-slider2.js';

var CommentType;
(function (CommentType) {
    CommentType["PAGE"] = "page";
    CommentType["PRODUCT"] = "product";
    CommentType["BLOG"] = "blog";
})(CommentType || (CommentType = {}));

var ChatBubbles = `<!-- Generated by IcoMoon.io -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
<title>chat-bubbles</title>
<path d="M15.333 17.333c4.779 0 8.667-3.888 8.667-8.667s-3.888-8.667-8.667-8.667h-6.667c-4.779 0-8.667 3.888-8.667 8.667 0 2.985 1.513 5.712 4 7.297v4.703c0 0.497 0.277 0.953 0.717 1.183 0.195 0.1 0.405 0.151 0.616 0.151 0.269 0 0.536-0.081 0.764-0.241l6.323-4.425zM11.236 14.908l-4.569 3.199v-2.913c0-0.5-0.28-0.959-0.725-1.187-2.020-1.035-3.275-3.080-3.275-5.34 0-3.308 2.692-6 6-6h6.667c3.308 0 6 2.692 6 6s-2.692 6-6 6h-3.333c-0.273 0-0.54 0.084-0.764 0.241zM29.196 12.964c-0.543-0.5-1.388-0.464-1.884 0.077-0.5 0.541-0.465 1.385 0.077 1.884 1.253 1.156 1.944 2.72 1.944 4.408 0 2.26-1.255 4.305-3.275 5.339-0.445 0.228-0.725 0.687-0.725 1.188v2.572l-5.441-2.939c-0.195-0.104-0.412-0.16-0.633-0.16h-2.592c-1.688 0-3.309-0.724-4.451-1.988-0.492-0.545-1.335-0.591-1.883-0.096-0.547 0.493-0.589 1.336-0.096 1.883 1.644 1.823 3.988 2.868 6.429 2.868h2.255l7.111 3.84c0.199 0.107 0.417 0.16 0.635 0.16 0.236 0 0.472-0.063 0.683-0.188 0.404-0.241 0.651-0.676 0.651-1.145v-4.036c2.487-1.585 4-4.311 4-7.297 0-2.407-1.023-4.727-2.804-6.369z"></path>
</svg>
`;

const sallaCommentsCss = ":host{display:block}";

const SallaComments$1 = /*@__PURE__*/ proxyCustomElement(class SallaComments extends HTMLElement {
    constructor() {
        super();
        this.__registerHost();
        /**
         * Comment Type
         */
        this.type = CommentType.PAGE;
        /**
         * Show or hide avatar
         */
        this.showFormAvatar = false;
        /**
       * Hide Bought
       */
        this.hideBought = false;
        /**
         * Determines if the comments are testimonials
         */
        this.testimonials = false;
        this.customerId = null;
        // Translations
        this.noComments = salla.lang.get('blocks.comments.no_comments');
        this.comment_title = salla.lang.get('blocks.comments.title');
        this.comment_name = salla.lang.get('blocks.comments.comment');
        this.showRatingSummary = salla.config.get('store.settings.rating.show_rating_summary');
        this.allowLikes = salla.config.get('store.settings.rating.allow_likes');
        salla.onReady(() => {
            this.allowLikes = salla.config.get('store.settings.rating.allow_likes');
            this.showRatingSummary = salla.config.get('store.settings.rating.show_rating_summary');
        });
        salla.lang.onLoaded(() => {
            this.comment_title = salla.lang.get('blocks.comments.title');
            this.comment_name = salla.lang.get('blocks.comments.comment');
            this.noComments = salla.lang.get('pages.rating.no_ratings');
            const setNestedAsync = (lang, key, value) => {
                return new Promise((resolve) => {
                    salla.helpers.setNested(salla.lang.messages[lang], key, value);
                    resolve(true);
                });
            };
            const setTranslations = async () => {
                await setNestedAsync('ar.trans', 'blocks.comments.most_helpful', 'الأكثر إفادة');
                await setNestedAsync('en.trans', 'blocks.comments.most_helpful', 'Most helpful');
                this.mostHelpfulLabel = salla.lang.get('blocks.comments.most_helpful');
                this.comment_title = salla.lang.get('blocks.comments.title');
                this.comment_name = salla.lang.get('blocks.comments.comment');
                this.noComments = salla.lang.get('pages.rating.no_ratings');
            };
            setTranslations();
        });
    }
    // TOOD: it's a good idea to move this into lang.js
    // Pluralize a string based on the count
    pluralize(phrases, count) {
        const options = phrases.split('|');
        const conditions = [
            { condition: count === 0, index: 0 },
            { condition: count === 1, index: 1 },
            { condition: count === 2, index: 2 },
            { condition: count > 2 && count <= 10, index: 3 },
            { condition: count >= 11, index: 4 }
        ];
        const { index } = conditions.find(({ condition }) => condition) || { index: options.length - 1 };
        const selectedOption = options[index];
        return selectedOption.replace(':count', salla.helpers.number(count.toString()))
            .replace(/\{[0-9]+\}/g, '')
            .replace(/\[\d+,\d+\]|\[11,\*\]/g, '');
    }
    wrapConsoleError() {
        if (Salla.infiniteScroll.errorWrapped) {
            return;
        }
        (() => {
            const orig = console.error.bind(console);
            console.error = (...args) => {
                const msg = args[0];
                // only rewrite the noisy one
                if (typeof msg === 'string' && msg.toLowerCase().replace(/\s/g, '').includes('infinitescroll')) {
                    return console.log(...args); // downgrade to log
                }
                return orig(...args); // keep real errors
            };
        })();
        Salla.infiniteScroll.errorWrapped = true;
    }
    // Preserve sort and private_comments params in next page URL for infinite scroll
    patchNextPageUrl() {
        if (!this.nextPage)
            return;
        try {
            const url = new URL(this.nextPage, window.location.origin);
            if (this.sort && !url.searchParams.get('sort')) {
                url.searchParams.set('sort', this.sort);
            }
            if (this.customerId && !url.searchParams.get('private_comments')) {
                url.searchParams.set('private_comments', this.customerId);
            }
            this.nextPage = url.toString();
        }
        catch (_e) {
            // fallback for relative next links
            const hasQuery = this.nextPage.includes('?');
            if (this.sort && !/[?&]sort=/.test(this.nextPage)) {
                this.nextPage = this.nextPage + (hasQuery ? '&' : '?') + `sort=${this.sort}`;
            }
            if (this.customerId && !/[?&]private_comments=/.test(this.nextPage)) {
                const sep = this.nextPage.includes('?') ? '&' : '?';
                this.nextPage = this.nextPage + sep + `private_comments=${this.customerId}`;
            }
        }
    }
    // Initiate infinite scroll
    initiateInfiniteScroll() {
        if (!this.wrapper) {
            console.error('Wrapper is undefined. Cannot initiate infinite scroll.');
            return;
        }
        this.wrapConsoleError();
        this.infiniteScroll = salla.infiniteScroll.initiate(this.wrapper, this.wrapper, {
            path: () => this.nextPage,
            history: false,
            nextPage: this.nextPage,
            scrollThreshold: false,
        }, true);
        this.infiniteScroll?.on('request', _response => {
            this.loading();
        });
        this.infiniteScroll?.on('load', response => {
            this.pagination = response.pagination;
            this.nextPage = typeof response.pagination.links === 'object' && !!response.pagination.links.next ? response.pagination.links.next : null;
            this.patchNextPageUrl();
            for (const card of this.handleResponse(response)) {
                this.wrapper.append(card);
            }
            const items = this.host.querySelectorAll('salla-comment-item:not(.animated):not(.s-comments-item-admin)');
            this.animateItems(items);
            this.loading(false);
        });
        this.infiniteScroll?.on('error', (e) => {
            salla.console.error('Error loading more comments:', e);
        });
    }
    // Show/hide loading
    loading(isLoading = true) {
        const btnText = this.status?.querySelector('.s-button-text');
        if (btnText) {
            Helper.toggleElementClassIf(btnText, 's-button-hide', 's-button-show', () => isLoading);
            this.btnLoader.style.display = isLoading ? 'inherit' : 'none';
        }
    }
    // Animate newly added items
    animateItems(items) {
        anime({
            targets: items,
            opacity: [0, 1],
            duration: 1200,
            translateY: [20, 0],
            delay: (_el, i) => i * 100,
            easing: 'easeOutExpo',
            complete: (_anim) => {
                for (const item of items) {
                    item.classList.add('animated');
                }
            }
        });
    }
    /**
     * Reloads the comments data from the server
     */
    async reload() {
        this.showPlaceholder = false;
        if (this.wrapper) {
            this.wrapper.innerHTML = "";
            const loading = document.createElement('salla-loading');
            this.wrapper.append(loading);
        }
        this.nextPage = null;
        this.loadInitialData();
    }
    // Get comment item HTML
    getCommentHTML(comment) {
        const commentItem = document.createElement('salla-comment-item');
        commentItem.comment = comment;
        commentItem.hideBought = this.hideBought;
        return commentItem;
    }
    // Parse response and return an array of comment items to be appended to the wrapper
    handleResponse(response) {
        return response.data?.map(comment => this.getCommentHTML(comment)) || [];
    }
    componentWillLoad() {
        return salla.onReady()
            .then(() => {
            this.showRatingSummary = salla.config.get('store.settings.rating.show_rating_summary');
        })
            .then(() => this.loading())
            .then(() => {
            this.hideTitle = this.hideTitle || this.testimonials;
            this.hideForm = this.hideForm || this.testimonials;
            return this.loadInitialData();
        });
    }
    /**
     * Catch the commentAdded event emitted by salla-comment-form and instantly render it
     */
    onCommentAdded(event) {
        const comment = event.detail;
        if (!comment)
            return;
        // If comments were empty, clear the placeholder and initialize the list
        if (this.showPlaceholder || !this.total) {
            this.showPlaceholder = false;
            this.total = (this.total || 0) + 1;
            this.comments = this.comments || [];
        }
        else {
            this.total = (this.total || 0) + 1;
        }
        // Wait for next render tick so wrapper is available if placeholder was just removed
        setTimeout(() => {
            if (!this.wrapper)
                return;
            const commentItem = this.getCommentHTML(comment);
            this.wrapper.prepend(commentItem);
            this.animateItems([commentItem]);
        }, 0);
    }
    // Load initial data
    async loadInitialData() {
        try {
            let resp = { data: [], pagination: {} };
            const searchParams = new URLSearchParams(window.location.search);
            if (searchParams.has('sort')) {
                this.sort = searchParams.get('sort');
            }
            if (this.testimonials) {
                const params = {
                    sort: this.sort,
                    type: "store"
                };
                resp = await salla.api.request('reviews', { params }, 'get');
            }
            else {
                const showPrivateComments = searchParams.get('private_comments');
                this.customerId = (showPrivateComments && Salla.config.get('user.type') === 'user' && Salla.config.get('user.id'))
                    ? Salla.config.get('user.id')
                    : null;
                resp = await salla.api.comment.getComments(this.type, this.itemId, 1, 5, this.sort, this.customerId);
            }
            if (!resp.data || !resp.data.length) {
                this.showPlaceholder = false;
                this.loading(false);
                return;
            }
            if (this.wrapper) {
                this.wrapper.innerHTML = "";
            }
            this.comments = resp.data;
            this.pagination = resp.pagination;
            this.total = resp.pagination.total;
            this.nextPage = typeof resp.pagination.links === 'object' && !!resp.pagination.links.next ? resp.pagination.links.next : null;
            this.patchNextPageUrl();
            setTimeout(() => {
                for (const card of this.handleResponse(resp)) {
                    this.wrapper.append(card);
                }
                this.initiateInfiniteScroll(); // Initiate infinite scroll after the initial data is loaded
                const items = this.wrapper.querySelectorAll('salla-comment-item:not(.animated)');
                this.animateItems(items);
            }, 100);
        }
        catch (error) {
            console.error('Error loading initial data:', error);
            this.showPlaceholder = true;
            this.loading(false);
        }
    }
    // Get next page
    async loadMore() {
        this.infiniteScroll?.loadNextPage();
    }
    render() {
        // We should show a different placeholder for pages and products (WIP)
        if (this.showPlaceholder) {
            return (h("div", null, !!this.total && !this.hideTitle ? h("h2", { class: "s-comments-title" }, this.blockTitle ? this.blockTitle : this.comment_title) : '', !this.hideForm && !this.testimonials ? h("salla-comment-form", { showAvatar: this.showFormAvatar, type: this.type, "item-id": this.itemId }) : '', h("div", { class: "s-comments-placeholder" }, h("span", { innerHTML: ChatBubbles }), h("p", null, this.noComments))));
        }
        return (h("div", { class: `s-comments s-comments-${this.testimonials ? 'testimonials' : this.type}` }, h("div", { class: `${this.type === CommentType.PAGE ? "s-comments-page-container" : "s-comments-container"}` }, !!this.total && !this.hideTitle ? h("h2", { class: "s-comments-title" }, this.blockTitle ? this.blockTitle : this.comment_title) : '', !this.hideForm && h("salla-comment-form", { showAvatar: this.showFormAvatar, type: this.type, "item-id": this.itemId }), salla.url.is_page('product.single') ? h("salla-reviews-summary", { itemId: this.itemId }) : '', h("div", { class: `s-comments-header ${this.total ? "has-total" : ""}` }, !!this.total && h("span", { class: "s-comments-count-label", innerHTML: this.pluralize(this.comment_name, this.total) }), !!this.total && !this.testimonials && this.type !== CommentType.BLOG ?
            h("div", { class: "s-comments-filter-wrapper" }, h("label", { class: "s-comments-filter-label", htmlFor: "comments-filter" }, salla.lang.get('pages.categories.sorting')), h("select", { id: "comments-filter", "aria-label": salla.lang.get('pages.categories.sorting'), class: "s-form-control s-comments-sort-input", onChange: (e) => {
                    this.sort = e.target.value;
                    this.reload();
                } }, h("option", { value: "latest", selected: true }, salla.lang.get("pages.testimonials.sort_by_date_desc")), h("option", { value: "oldest" }, salla.lang.get("pages.testimonials.sort_by_date_asc")), this.allowLikes && h("option", { value: "most_helpful" }, this.mostHelpfulLabel)))
            : ''), h("div", { ref: wrapper => {
                this.wrapper = wrapper;
            } }), this.nextPage && (h("div", { class: "s-infinite-scroll-wrapper", ref: status => {
                this.status = status;
            } }, h("button", { onClick: () => this.loadMore(), class: "s-infinite-scroll-btn s-button-btn s-button-primary", type: "button" }, h("span", { class: "s-button-text s-infinite-scroll-btn-text" }, this.loadMoreText ? this.loadMoreText : salla.lang.get('common.elements.load_more')), h("span", { class: "s-button-loader s-button-loader-center s-infinite-scroll-btn-loader", ref: btnLoader => {
                this.btnLoader = btnLoader;
            }, style: { "display": "none" } })))))));
    }
    get host() { return this; }
    static get style() { return sallaCommentsCss; }
}, [0, "salla-comments", {
        "itemId": [2, "item-id"],
        "loadMoreText": [1, "load-more-text"],
        "hideForm": [4, "hide-form"],
        "blockTitle": [1, "block-title"],
        "hideTitle": [4, "hide-title"],
        "type": [1],
        "showFormAvatar": [4, "show-form-avatar"],
        "hideBought": [4, "hide-bought"],
        "sort": [1],
        "testimonials": [4],
        "comments": [32],
        "pagination": [32],
        "total": [32],
        "showPlaceholder": [32],
        "nextPage": [32],
        "mostHelpfulLabel": [32],
        "noComments": [32],
        "comment_title": [32],
        "comment_name": [32],
        "placeholder_text": [32],
        "showRatingSummary": [32],
        "allowLikes": [32],
        "reload": [64]
    }, [[0, "commentAdded", "onCommentAdded"]]]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["salla-comments", "salla-button", "salla-comment-form", "salla-comment-item", "salla-loading", "salla-modal", "salla-progress-bar", "salla-rating-stars", "salla-reviews-summary", "salla-slider"];
    components.forEach(tagName => { switch (tagName) {
        case "salla-comments":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, SallaComments$1);
            }
            break;
        case "salla-button":
            if (!customElements.get(tagName)) {
                defineCustomElement$a();
            }
            break;
        case "salla-comment-form":
            if (!customElements.get(tagName)) {
                defineCustomElement$9();
            }
            break;
        case "salla-comment-item":
            if (!customElements.get(tagName)) {
                defineCustomElement$8();
            }
            break;
        case "salla-loading":
            if (!customElements.get(tagName)) {
                defineCustomElement$7();
            }
            break;
        case "salla-modal":
            if (!customElements.get(tagName)) {
                defineCustomElement$6();
            }
            break;
        case "salla-progress-bar":
            if (!customElements.get(tagName)) {
                defineCustomElement$5();
            }
            break;
        case "salla-rating-stars":
            if (!customElements.get(tagName)) {
                defineCustomElement$4();
            }
            break;
        case "salla-reviews-summary":
            if (!customElements.get(tagName)) {
                defineCustomElement$3();
            }
            break;
        case "salla-slider":
            if (!customElements.get(tagName)) {
                defineCustomElement$2();
            }
            break;
    } });
}
defineCustomElement$1();

const SallaComments = SallaComments$1;
const defineCustomElement = defineCustomElement$1;

export { SallaComments, defineCustomElement };
