import { h } from "@stencil/core";
// import Handlebars from "handlebars"
import { Carousel } from "flowbite";
import { getBotTemplate, getTemplate } from "../../../../utils/utils";
import { setItemListElement } from "../../../../utils/global-store";
import { Handlebars } from "../../../../utils/helpers";
export class ItemList {
    constructor() {
        this.inputType = "ai";
        this.customTemplate = [];
        this.isExpanded = false;
        this.currentPage = 1;
        this.currentIndex = 0;
        this.itemsPerPage = 10;
        this.emptyMessage = "No items found";
        this.buttonText = "Details";
        this.panelIndex = 0;
        this.panelName = "";
        this.items = [];
        this.scripts = ["https://cdn.jsdelivr.net/npm/flowbite@2.5.2/dist/flowbite.min.js"];
        this.styles = ["https://cdn.ai12z.net/assets/bot/v2/tailwind.min.css", "https://cdn.jsdelivr.net/npm/flowbite@2.5.2/dist/flowbite.min.css"];
    }
    async componentWillLoad() {
        var _a;
        setItemListElement(this.element);
        if (this.customSource) {
            this.itemsPerPage = this.carouselType === "custom" ? 10 : this.customSource.carousel.itemsPerPage ? this.customSource.carousel.itemsPerPage : 10;
            this.buttonText = this.customSource.carousel.buttonText;
            this.emptyMessage = (_a = this.customSource.carousel.emptyMessage) !== null && _a !== void 0 ? _a : this.customSource.message;
            this.formSettings = this.customSource.formSettings;
            this.items = this.customSource.items;
            this.theme = this.customSource.theme;
            if (this.customSource.customCss) {
                this.styles.push(this.customSource.customCss);
            }
            if (this.customSource.customJs) {
                this.scripts.push(this.customSource.customJs);
            }
        }
        if (this.customStyles) {
            this.styles.push(this.customStyles);
        }
        try {
            // Load all resources first
            await Promise.all([this.loadScripts(), this.loadStyles(), this.loadHelperScript()]);
            // Wait a bit for scripts to initialize
            await new Promise(resolve => setTimeout(resolve, 100));
            this.updateItems();
            this.renderTemplate();
        }
        catch (error) {
            console.error("Error loading resources:", error);
            // Continue anyway
            this.updateItems();
            this.renderTemplate();
        }
    }
    componentDidLoad() {
        // Wait for DOM to be ready before signaling component is ready
        requestAnimationFrame(() => {
            setTimeout(() => {
                this.element.setAttribute("data-component-ready", "true");
                this.componentReady.emit(true);
            }, 200); // Give extra time for initialization
        });
    }
    async selectByIndex(index) {
        // console.log("selectByIndex", index)
        this.panelIndex = index;
        this.panelTemplate = this.customTemplate[index].content;
    }
    async selectByName(name) {
        var _a;
        this.panelName = name;
        this.panelIndex = this.customTemplate.findIndex(item => item.name === name);
        this.panelTemplate = (_a = this.customTemplate.find(item => item.name === name)) === null || _a === void 0 ? void 0 : _a.content;
    }
    updateItems() {
        this.items = this.items.map(item => item.hideImageOnMore === undefined
            ? Object.assign(Object.assign({}, item), { hideImageOnMore: true }) : item // Keep the rest unchanged
        );
    }
    loadScripts() {
        this.scripts.forEach(script => {
            const scriptElement = document.createElement("script");
            scriptElement.src = script; // Path relative to the www root
            scriptElement.onload = () => {
                // console.log("Script loaded")
            };
            scriptElement.onerror = err => {
                console.error("Failed to load script:", err);
            };
            // document.head.appendChild(scriptElement)
            this.element.appendChild(scriptElement);
        });
    }
    async loadHelperScript() {
        if (!this.customScripts)
            return;
        return new Promise((resolve, reject) => {
            const script = document.createElement("script");
            script.src = this.customScripts;
            script.async = true;
            script.onload = () => resolve();
            script.onerror = () => reject(new Error("Failed to load helper script"));
            // document.head.appendChild(script);
            this.element.appendChild(script);
        });
    }
    loadStyles() {
        this.styles.forEach(style => {
            const styleElement = document.createElement("link");
            styleElement.rel = "stylesheet"; // Path relative to the www root
            styleElement.href = style;
            styleElement.onload = () => {
                // console.log("Style loaded")
            };
            styleElement.onerror = err => {
                console.error("Failed to load style:", err);
            };
            document.head.appendChild(styleElement);
            this.element.appendChild(styleElement);
            // this.loadModal()
        });
    }
    getCurrentPageItems() {
        const startIndex = (this.currentPage - 1) * this.itemsPerPage;
        const endIndex = startIndex + this.itemsPerPage;
        return this.items.slice(startIndex, endIndex);
    }
    totalPages() {
        return Math.ceil(this.items.length / this.itemsPerPage);
    }
    getParam(functionStr) {
        const str = functionStr;
        const start = str.indexOf('("') + 2;
        const end = str.indexOf('")');
        const param = str.substring(start, end);
        return param;
    }
    addEventListeners() {
        this.element.querySelectorAll(".read-more").forEach(readMore => {
            readMore.addEventListener("click", event => {
                // const index = (event.target as HTMLElement).getAttribute("data-index") // Get index from data-index attribute
                const card = event.target.closest(".carousel-card");
                const shortDescription = card === null || card === void 0 ? void 0 : card.querySelector(".short-description");
                const longDescription = card === null || card === void 0 ? void 0 : card.querySelector(".long-description");
                const cardImage = card === null || card === void 0 ? void 0 : card.querySelector(".card-image");
                const cardRightDiv = card === null || card === void 0 ? void 0 : card.querySelector(".card-right");
                // Toggle visibility of descriptions
                shortDescription.classList.toggle("hidden");
                longDescription.classList.toggle("hidden");
                // Update button text
                if (shortDescription.classList.contains("hidden")) {
                    cardImage.classList.add("hidden");
                    cardRightDiv.classList.add("w-full");
                    cardRightDiv.classList.remove("md:w-2/3");
                    event.target.textContent = "Show Less";
                }
                else {
                    cardImage.classList.remove("hidden");
                    cardRightDiv.classList.remove("w-full");
                    cardRightDiv.classList.add("md:w-2/3");
                    event.target.textContent = "Read More";
                }
                // Optionally, you can use the index to log or perform other actions
                // console.log(`Button clicked for card at index: ${index}`)
            });
        });
        this.element.querySelectorAll(".card-button").forEach(button => {
            button.addEventListener("click", event => {
                var _a, _b, _c;
                const btn = event.currentTarget;
                const id = btn.getAttribute("data-id"); // Get custom data-id attribute
                // console.log(`Button clicked for item with ID: ${id}`)
                // Add your logic here
                const type = btn.getAttribute("data-type"); // Get custom data-id attribute
                // console.log(`Button clicked for item with ID: ${type}`)
                const url = btn.getAttribute("data-url");
                // console.log(`Button clicked for item with ID: ${url}`)
                // Add your logic here
                // let value = (event.target as HTMLElement).getAttribute("data-item")
                // // console.log(`Button clicked for item with ID: ${value}`)
                // if (value) {
                //   value = value.replace(/&quot;/g, '"')
                // }
                // const itemObject = JSON.parse(value)
                // console.log("itemObject", itemObject)
                const clickHandler = btn.getAttribute("onClick");
                if (type === "panel") {
                    Handlebars.registerHelper("inc", function (value) {
                        return parseInt(value) + 1;
                    });
                    const templateResult = getTemplate("list")[1];
                    if (this.carouselType !== "custom") {
                        this.panelTemplate = typeof templateResult === "string" ? templateResult : templateResult.content;
                    }
                    else if (this.carouselType === "custom" && !clickHandler) {
                        this.panelIndex = Number(id) + 1;
                        this.selectByIndex(Number(id) + 1);
                    }
                    if (!this.panelTemplate) {
                        const param = this.getParam(clickHandler);
                        console.log("param", param);
                        this.panelTemplate = (_a = this.customTemplate.find(item => item.name === param)) === null || _a === void 0 ? void 0 : _a.content;
                    }
                    const cardList = this.element.querySelectorAll(".carousel-card");
                    const card = btn.closest(".carousel-card");
                    const cardIndex = card.getAttribute("data-index");
                    const compiledPanelTemplate = Handlebars.compile(this.panelTemplate);
                    // console.log("compiledPanelTemplate", panelTemplate)
                    cardList[cardIndex].innerHTML = compiledPanelTemplate({
                        form: this.items[cardIndex].panels ? (_b = this.items[cardIndex].panels[Number(id)]) === null || _b === void 0 ? void 0 : _b.form : undefined,
                        formSettings: this.formSettings,
                        buttons: this.items[cardIndex].panels ? (_c = this.items[cardIndex].panels[Number(id)]) === null || _c === void 0 ? void 0 : _c.buttons : undefined,
                        theme: this.theme,
                        item: this.items[cardIndex],
                        llm: this.llm,
                        source: this.customSource,
                        opt: {
                            isBot: this.inputType === "bot" ? true : false,
                            isExpanded: this.isExpanded,
                        },
                    });
                    setTimeout(() => {
                        this.addEventForPanel();
                    }, 1000);
                }
                if (type === "url") {
                    window.open(url, "_blank");
                }
            });
        });
    }
    addEventForPanel() {
        this.element.querySelectorAll(".panel-button").forEach(button => {
            button.addEventListener("click", event => {
                var _a, _b;
                const id = event.target.getAttribute("data-id"); // Get custom data-id attribute
                // console.log(`Button clicked for item with ID: ${id}`)
                // Add your logic here
                const type = event.target.getAttribute("data-type"); // Get custom data-id attribute
                // console.log(`Button clicked for item with ID: ${type}`)
                const clickHandler = event.target.getAttribute("onClick");
                // console.log("clickHandler", clickHandler)
                if (!clickHandler) {
                    this.panelIndex = Number(id);
                }
                // Add your logic here
                if (type === "panel" && this.panelIndex === 0) {
                    this.updateContent();
                }
                if (type === "panel" && this.panelIndex !== 0 && this.carouselType === "custom") {
                    const cardList = this.element.querySelectorAll(".carousel-card");
                    const card = event.target.closest(".carousel-card");
                    const cardIndex = card.getAttribute("data-index");
                    // console.log("cardIndex", cardIndex)
                    const compiledPanelTemplate = Handlebars.compile(this.panelTemplate);
                    // console.log("compiledPanelTemplate", panelTemplate)
                    cardList[cardIndex].innerHTML = compiledPanelTemplate({
                        form: (_a = this.items[cardIndex].panels[Number(id)]) === null || _a === void 0 ? void 0 : _a.form,
                        formSettings: this.formSettings,
                        buttons: (_b = this.items[cardIndex].panels[Number(id)]) === null || _b === void 0 ? void 0 : _b.buttons,
                        theme: this.theme,
                        item: this.items[cardIndex],
                        llm: this.llm,
                        source: this.customSource,
                        opt: {
                            isBot: this.inputType === "bot" ? true : false,
                            isExpanded: this.isExpanded,
                        },
                    });
                    setTimeout(() => {
                        this.addEventForPanel();
                        // this.addEventListeners()
                    }, 1000);
                }
            });
        });
    }
    loadList() {
        var _a, _b;
        const carouselList = {
            // itemsPerPage: this.itemsPerPage,
            // items: this.items,
            // totalItems: this.items.length,
            // totalPages: Math.ceil(this.items.length / this.itemsPerPage),
            // Handle Next
            next: () => {
                if (this.currentPage < this.totalPages()) {
                    this.currentPage++;
                }
                this.updateContent();
                this.loadImageCarousel();
            },
            // Handle Prev
            prev: () => {
                if (this.currentPage > 1) {
                    this.currentPage--;
                }
                this.updateContent();
                this.loadImageCarousel();
            },
            totalPages: () => {
                var _a;
                return Math.ceil(this.items.length / ((_a = this.customSource.carousel) === null || _a === void 0 ? void 0 : _a.itemsPerPage));
            },
        };
        (_a = this.element.querySelector(".prev-btn")) === null || _a === void 0 ? void 0 : _a.addEventListener("click", () => {
            carouselList.prev();
        });
        (_b = this.element.querySelector(".next-btn")) === null || _b === void 0 ? void 0 : _b.addEventListener("click", () => {
            carouselList.next();
        });
    }
    loadImageCarousel() {
        const pageItems = this.getCurrentPageItems();
        if (pageItems.length > 0) {
            const carouselContainers = this.element.querySelectorAll(".carousel-container");
            carouselContainers.forEach((container, idx) => {
                const carouselId = container.getAttribute("data-carousel-id");
                const carouselElement = this.element.querySelector(`#${carouselId}`);
                if (carouselElement) {
                    // Select all images within the carousel
                    const imageElement = carouselElement.querySelectorAll("[data-carousel-item]");
                    const imageList = [];
                    const imageIndicators = [];
                    imageElement.forEach((_image, index) => {
                        imageList.push({ position: index, el: this.element.querySelector(`#carousel-${idx}-item-${index}`) });
                        if (imageElement.length <= 3 && imageElement.length > 1) {
                            imageIndicators.push({
                                position: index,
                                el: this.element.querySelector(`#carousel-${idx}-indicator-${index}`),
                            });
                        }
                    });
                    const options = {
                        defaultPosition: 1,
                        interval: 3000,
                        indicators: {
                            activeClasses: "bg-gray-800 indicator-${idx}",
                            inactiveClasses: "bg-blue-500 indicator-${idx}",
                            items: imageIndicators,
                        },
                        // callback functions
                        onNext: () => {
                            // console.log("next slider item is shown")
                        },
                        onPrev: () => {
                            // console.log("previous slider item is shown")
                        },
                        onChange: () => {
                            // console.log("new slider item has been shown")
                        },
                    };
                    // Create a new instance of the Flowbite Carousel
                    const instanceOptions = {
                        id: `#${carouselId}`,
                        override: true,
                    };
                    const imageCarousel = new Carousel(carouselElement, imageList, options, instanceOptions);
                    const $prevButton = this.element.querySelector(`#carousel-${idx}-prev`);
                    const $nextButton = this.element.querySelector(`#carousel-${idx}-next`);
                    $prevButton === null || $prevButton === void 0 ? void 0 : $prevButton.addEventListener("click", () => {
                        imageCarousel.prev();
                    });
                    $nextButton === null || $nextButton === void 0 ? void 0 : $nextButton.addEventListener("click", () => {
                        imageCarousel.next();
                    });
                    // Start the carousel cycle
                    // imageCarousel.cycle()
                }
            });
        }
    }
    loadCarousel() {
        let carouselList = [];
        let carouselIndicators = [];
        const carouselElement = this.element.querySelector("#carouselExample");
        const carouselItems = this.element.querySelectorAll("div[data-carousel-item]");
        // Ensure the carouselItems array is not empty
        if (carouselItems.length > 0) {
            carouselItems.forEach((_item, index) => {
                carouselList.push({
                    position: index,
                    el: this.element.querySelector(`#carousel-item-${index}`),
                });
                if (carouselItems.length <= 5) {
                    carouselIndicators.push({
                        position: index,
                        el: this.element.querySelector(`#carousel-indicator-${index}`),
                    });
                }
            });
        }
        else {
            return;
        }
        // object options with default values
        const options = {
            defaultPosition: 1,
            interval: 3000,
            indicators: {
                activeClasses: "bg-gray-800",
                inactiveClasses: "bg-blue-500",
                items: carouselIndicators,
            },
            // callback functions
            onNext: () => {
                console.log("next slider item is shown");
            },
            onPrev: () => {
                console.log("previous slider item is shown");
            },
            onChange: () => {
                console.log("new slider item has been shown");
            },
        };
        // instance options object
        const instanceOptions = {
            id: "carouselExample",
            override: true,
        };
        const carousel = new Carousel(carouselElement, carouselList, options, instanceOptions);
        const $prevButton = this.element.querySelector("#data-carousel-prev");
        const $nextButton = this.element.querySelector("#data-carousel-next");
        $prevButton === null || $prevButton === void 0 ? void 0 : $prevButton.addEventListener("click", () => {
            carousel.prev();
        });
        $nextButton === null || $nextButton === void 0 ? void 0 : $nextButton.addEventListener("click", () => {
            carousel.next();
        });
    }
    renderTemplate() {
        Handlebars.registerHelper("lte", function (a, b) {
            return a <= b;
        });
        Handlebars.registerHelper("gte", function (a, b) {
            return a > b;
        });
        Handlebars.registerHelper("and", function (v1, v2, options) {
            if (v1 && v2) {
                return options.fn(this); // Only render if both variables are truthy
            }
        });
        const currentPageItems = this.getCurrentPageItems();
        let template = "", templateResult;
        let compiledTemplate;
        // Register Handlebars helper
        Handlebars.registerHelper("getPageCount", () => {
            return this.totalPages();
        });
        Handlebars.registerHelper("getcurrentPage", () => {
            return this.currentPage;
        });
        switch (this.carouselType) {
            case "list":
                templateResult = this.inputType === "ai" ? getTemplate(this.carouselType) : getBotTemplate(this.carouselType);
                template = Array.isArray(templateResult) ? templateResult[0].content : templateResult;
                compiledTemplate = Handlebars.compile(template);
                this.htmlTemplate = compiledTemplate({
                    items: currentPageItems,
                    hasPrev: this.currentPage > 1,
                    hasNext: (this.currentPage - 1) * this.itemsPerPage + this.itemsPerPage < this.items.length,
                    buttonText: this.buttonText,
                    llm: this.llm,
                    source: this.customSource,
                    formSettings: this.formSettings,
                    theme: this.theme,
                });
                setTimeout(() => {
                    this.loadList();
                    this.loadImageCarousel();
                    this.addEventListeners();
                }, 1000);
                break;
            case "slider":
                templateResult = getTemplate(this.carouselType);
                template = Array.isArray(templateResult) ? templateResult[0].content : templateResult;
                compiledTemplate = Handlebars.compile(template);
                this.htmlTemplate = compiledTemplate({ items: this.items, llm: this.llm, source: this.customSource });
                setTimeout(() => {
                    this.loadCarousel();
                    this.loadImageCarousel();
                    this.addEventListeners();
                }, 1000);
                break;
            case "custom":
                // Register the helper
                Handlebars.registerHelper("processArray", function (array) {
                    if (!Array.isArray(array)) {
                        return ""; // Return an empty string if the input is not an array
                    }
                    return new Handlebars.SafeString(JSON.stringify(array));
                });
                template = this.customTemplate[0].content;
                compiledTemplate = Handlebars.compile(template);
                this.htmlTemplate = compiledTemplate({
                    items: currentPageItems,
                    hasPrev: this.currentPage > 1,
                    hasNext: (this.currentPage - 1) * this.itemsPerPage + this.itemsPerPage < this.items.length,
                    buttonText: this.buttonText,
                    currentPage: this.currentPage,
                    totalPages: this.totalPages(),
                    formSettings: this.formSettings,
                    llm: this.llm,
                    source: this.customSource,
                    opt: {
                        isBot: this.inputType === "bot" ? true : false,
                        isExpanded: this.isExpanded,
                    },
                });
                setTimeout(() => {
                    this.loadList();
                    this.loadCarousel();
                    this.loadImageCarousel();
                    this.addEventListeners();
                }, 1000);
                break;
        }
        return this.htmlTemplate;
    }
    updateContent() {
        const container = this.element.querySelector("#template-container");
        if (container) {
            container.innerHTML = this.renderTemplate(); // Re-render template
        }
    }
    render() {
        // const totalPages = this.totalPages()
        if (!this.items || this.items.length === 0) {
            return h("div", null, this.emptyMessage);
        }
        return h("div", { id: "template-container", innerHTML: this.htmlTemplate });
    }
    static get is() { return "item-list"; }
    static get originalStyleUrls() {
        return {
            "$": ["item-list.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["item-list.css"]
        };
    }
    static get properties() {
        return {
            "inputType": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "input-type",
                "defaultValue": "\"ai\""
            },
            "carouselType": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "carousel-type"
            },
            "customTemplate": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "any[]",
                    "resolved": "any[]",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            },
            "customSource": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "custom-source"
            },
            "llm": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "Object",
                    "resolved": "Object",
                    "references": {
                        "Object": {
                            "location": "global",
                            "id": "global::Object"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "customStyles": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "custom-styles"
            },
            "customScripts": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "custom-scripts"
            },
            "isExpanded": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-expanded",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "currentPage": {},
            "htmlTemplate": {},
            "currentIndex": {},
            "formSettings": {},
            "itemsPerPage": {},
            "emptyMessage": {},
            "buttonText": {},
            "panelTemplate": {},
            "panelIndex": {},
            "panelName": {},
            "items": {},
            "theme": {}
        };
    }
    static get events() {
        return [{
                "method": "sendQueryToAI",
                "name": "sendQueryToAI",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                }
            }, {
                "method": "componentReady",
                "name": "componentReady",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "selectByIndex": {
                "complexType": {
                    "signature": "(index: number) => Promise<void>",
                    "parameters": [{
                            "name": "index",
                            "type": "number",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "selectByName": {
                "complexType": {
                    "signature": "(name: string) => Promise<void>",
                    "parameters": [{
                            "name": "name",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "element"; }
}
