import { Host, h } from "@stencil/core";
export class SpwSlider {
    constructor() {
        /** Affiche les flèches de navigation */
        this.showArrows = true;
        /** Affiche les dots de navigation */
        this.showDots = true;
        /** Affiche le toggle de défilement automatique */
        this.showAutoplayToggle = false;
        /** Intervalle de défilement automatique en millisecondes */
        this.autoplayInterval = 5000;
        /** Active le défilement automatique par défaut */
        this.autoplayEnabled = false;
        /** Label du toggle de défilement automatique */
        this.autoplayText = 'Défilement automatique';
        /** Position des flèches gauche/droite */
        this.arrowsPosition = 'inside';
        /** Position des dots de navigation */
        this.dotsPosition = 'inside';
        /** Texte aria-label pour la slide suivante */
        this.nextSlideText = 'Slide suivante';
        /** Texte aria-label du slider */
        this.accAriaLabel = 'Slider de contenu';
        /** Texte aria-label pour la slide précédente */
        this.previousSlideText = 'Slide précédente';
        /** Fixe la hauteur du slider à la hauteur de la slide la plus haute */
        this.hasFixedHeight = false;
        /** Index de la slide active */
        this.activeIndex = 0;
        /** Nombre total de slides */
        this.totalSlides = 0;
        /** Hauteur actuelle du slider */
        this.currentHeight = 0;
        /** État du défilement automatique */
        this.isAutoplayActive = false;
        /** Position de départ du swipe/drag */
        this.startX = 0;
        this.startY = 0;
        /** Position actuelle du swipe/drag */
        this.currentX = 0;
        /** Est en train de swiper/dragger */
        this.isDragging = false;
        /** Tableau des slides */
        this.slides = [];
        this.handleSlotChange = () => {
            this.updateSlides();
            this.scheduleHeightUpdate(50);
        };
        this.handleResize = () => {
            this.scheduleHeightUpdate(50);
        };
        this.handlePrevious = () => {
            if (this.activeIndex > 0) {
                this.goToSlide(this.activeIndex - 1, 'previous');
            }
        };
        this.handleNext = () => {
            if (this.activeIndex < this.totalSlides - 1) {
                this.goToSlide(this.activeIndex + 1, 'next');
            }
        };
        this.handleDotClick = (index) => {
            this.goToSlide(index);
        };
        this.startAutoplay = () => {
            this.stopAutoplay();
            this.autoplayTimer = window.setInterval(() => {
                const nextIndex = this.activeIndex < this.totalSlides - 1 ? this.activeIndex + 1 : 0;
                this.goToSlide(nextIndex, 'next');
            }, this.autoplayInterval);
        };
        this.stopAutoplay = () => {
            if (this.autoplayTimer) {
                clearInterval(this.autoplayTimer);
                this.autoplayTimer = null;
            }
        };
        this.handleAutoplayToggle = (event) => {
            this.isAutoplayActive = event.detail;
            if (this.isAutoplayActive) {
                this.startAutoplay();
            }
            else {
                this.stopAutoplay();
            }
        };
    }
    componentDidLoad() {
        this.initializeSlider();
        const slotElement = this.el.shadowRoot.querySelector('slot');
        if (slotElement) {
            slotElement.addEventListener('slotchange', this.handleSlotChange);
        }
        window.addEventListener('resize', this.handleResize);
        this.setupResizeObserver();
        this.isAutoplayActive = this.autoplayEnabled;
        if (this.isAutoplayActive) {
            this.startAutoplay();
        }
    }
    disconnectedCallback() {
        var _a;
        window.removeEventListener('resize', this.handleResize);
        const slotElement = (_a = this.el.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('slot');
        if (slotElement) {
            slotElement.removeEventListener('slotchange', this.handleSlotChange);
        }
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
        }
        if (this.heightUpdateTimeout) {
            clearTimeout(this.heightUpdateTimeout);
        }
        this.stopAutoplay();
    }
    initializeSlider() {
        this.updateSlides();
        this.scheduleHeightUpdate(200);
        this.scheduleHeightUpdate(500);
    }
    setupResizeObserver() {
        if (typeof ResizeObserver !== 'undefined') {
            this.resizeObserver = new ResizeObserver(() => {
                this.scheduleHeightUpdate(50);
            });
            this.slides.forEach(slide => {
                var _a, _b;
                this.resizeObserver.observe(slide);
                const slotContent = (_b = (_a = slide.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('slot')) === null || _b === void 0 ? void 0 : _b.assignedElements()[0];
                if (slotContent) {
                    this.resizeObserver.observe(slotContent);
                    if (slotContent.shadowRoot) {
                        const shadowContent = slotContent.shadowRoot.firstElementChild;
                        if (shadowContent) {
                            this.resizeObserver.observe(shadowContent);
                        }
                    }
                }
            });
        }
    }
    scheduleHeightUpdate(delay = 0) {
        if (this.heightUpdateTimeout) {
            clearTimeout(this.heightUpdateTimeout);
        }
        this.heightUpdateTimeout = window.setTimeout(() => {
            this.updateHeight();
        }, delay);
    }
    updateSlides() {
        const slotElement = this.el.shadowRoot.querySelector('slot');
        if (slotElement) {
            const newSlides = slotElement.assignedElements();
            if (this.resizeObserver) {
                this.slides.forEach(slide => {
                    this.resizeObserver.unobserve(slide);
                });
            }
            this.slides = newSlides;
            this.totalSlides = this.slides.length;
            this.slides.forEach((slide, index) => {
                slide.style.transform = `translateX(${index * 100}%)`;
                if (index === this.activeIndex) {
                    slide.removeAttribute('inert');
                }
                else {
                    slide.setAttribute('inert', '');
                }
            });
            if (this.resizeObserver) {
                this.slides.forEach(slide => {
                    this.resizeObserver.observe(slide);
                });
            }
        }
    }
    async updateHeight() {
        if (this.hasFixedHeight) {
            await this.updateFixedHeight();
        }
        else {
            await this.updateActiveSlideHeight();
        }
    }
    async updateFixedHeight() {
        let maxHeight = 0;
        for (const slide of this.slides) {
            const slideHeight = await this.getSlideHeight(slide);
            if (slideHeight > maxHeight) {
                maxHeight = slideHeight;
            }
        }
        if (maxHeight > 0) {
            this.currentHeight = maxHeight;
            this.applyFixedHeightToHeroes(maxHeight);
        }
    }
    applyFixedHeightToHeroes(height) {
        var _a, _b, _c;
        for (const slide of this.slides) {
            const slotContent = (_b = (_a = slide.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('slot')) === null || _b === void 0 ? void 0 : _b.assignedElements()[0];
            if ((slotContent === null || slotContent === void 0 ? void 0 : slotContent.tagName.toLowerCase()) === 'spw-hero') {
                const heroElement = (_c = slotContent.shadowRoot) === null || _c === void 0 ? void 0 : _c.querySelector('.spw-hero');
                if (heroElement) {
                    heroElement.style.height = `${height}px`;
                }
            }
        }
    }
    async updateActiveSlideHeight() {
        if (this.slides[this.activeIndex]) {
            const activeSlide = this.slides[this.activeIndex];
            const slideHeight = await this.getSlideHeight(activeSlide);
            if (slideHeight > 50) {
                this.currentHeight = slideHeight;
            }
            else {
                this.retryHeightCalculation(0);
            }
        }
    }
    async getSlideHeight(slide) {
        var _a, _b;
        const slotContent = (_b = (_a = slide.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('slot')) === null || _b === void 0 ? void 0 : _b.assignedElements()[0];
        if (slotContent) {
            const tagName = slotContent.tagName.toLowerCase();
            if (tagName.includes('-')) {
                try {
                    await customElements.whenDefined(tagName);
                    await new Promise(resolve => setTimeout(resolve, 50));
                }
                catch (e) { }
            }
            const contentElement = slotContent;
            let slideHeight = contentElement.offsetHeight || contentElement.scrollHeight;
            if (contentElement.shadowRoot) {
                const shadowContent = contentElement.shadowRoot.firstElementChild;
                if (shadowContent) {
                    slideHeight = shadowContent.offsetHeight || shadowContent.scrollHeight;
                }
            }
            if (slideHeight > 0) {
                return slideHeight;
            }
        }
        return slide.offsetHeight || slide.scrollHeight;
    }
    retryHeightCalculation(attempt) {
        if (attempt >= 15)
            return;
        setTimeout(() => {
            var _a, _b;
            const activeSlide = this.slides[this.activeIndex];
            if (!activeSlide)
                return;
            const slotContent = (_b = (_a = activeSlide.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelector('slot')) === null || _b === void 0 ? void 0 : _b.assignedElements()[0];
            if (slotContent) {
                let retryHeight = slotContent.offsetHeight || slotContent.scrollHeight;
                if (slotContent.shadowRoot) {
                    const shadowContent = slotContent.shadowRoot.firstElementChild;
                    if (shadowContent) {
                        retryHeight = shadowContent.offsetHeight || shadowContent.scrollHeight;
                    }
                }
                if (retryHeight > 50) {
                    this.currentHeight = retryHeight;
                    return;
                }
            }
            const retryHeight = activeSlide.offsetHeight || activeSlide.scrollHeight;
            if (retryHeight > 50) {
                this.currentHeight = retryHeight;
            }
            else {
                this.retryHeightCalculation(attempt + 1);
            }
        }, 100 * (attempt + 1));
    }
    goToSlide(index, direction) {
        if (index < 0 || index >= this.totalSlides)
            return;
        const previousIndex = this.activeIndex;
        this.activeIndex = index;
        this.spwSliderChange.emit({ index, previousIndex });
        if (direction === 'next')
            this.spwSliderNext.emit({ index });
        if (direction === 'previous')
            this.spwSliderPrevious.emit({ index });
        this.slides.forEach((slide, i) => {
            const offset = (i - this.activeIndex) * 100;
            slide.style.transition = 'transform 0.3s ease-in-out';
            slide.style.transform = `translateX(${offset}%)`;
            if (i === this.activeIndex) {
                slide.removeAttribute('inert');
            }
            else {
                slide.setAttribute('inert', '');
            }
        });
        this.scheduleHeightUpdate(0);
        this.scheduleHeightUpdate(320);
        if (this.isAutoplayActive) {
            this.stopAutoplay();
            this.startAutoplay();
        }
    }
    handleTouchStart(event) {
        this.startX = event.touches[0].clientX;
        this.startY = event.touches[0].clientY;
        this.currentX = this.startX;
        this.isDragging = true;
        if (this.isAutoplayActive) {
            this.stopAutoplay();
        }
    }
    handleMouseDown(event) {
        this.startX = event.clientX;
        this.currentX = this.startX;
        this.isDragging = true;
        event.preventDefault();
        if (this.isAutoplayActive) {
            this.stopAutoplay();
        }
    }
    handleTouchMove(event) {
        if (!this.isDragging)
            return;
        const dx = event.touches[0].clientX - this.startX;
        const dy = event.touches[0].clientY - this.startY;
        if (Math.abs(dx) > Math.abs(dy)) {
            event.preventDefault();
        }
        this.currentX = event.touches[0].clientX;
    }
    handleMouseMove(event) {
        if (!this.isDragging)
            return;
        this.currentX = event.clientX;
    }
    handleTouchEnd() {
        this.handleDragEnd();
    }
    handleMouseUp() {
        this.handleDragEnd();
    }
    handleMouseLeave() {
        if (this.isDragging) {
            this.handleDragEnd();
        }
    }
    handleKeyDown(event) {
        if (event.key === 'ArrowLeft') {
            event.preventDefault();
            this.handlePrevious();
        }
        else if (event.key === 'ArrowRight') {
            event.preventDefault();
            this.handleNext();
        }
    }
    handleDragEnd() {
        if (!this.isDragging)
            return;
        const diff = this.startX - this.currentX;
        const threshold = 50;
        if (Math.abs(diff) > threshold) {
            if (diff > 0) {
                this.handleNext();
            }
            else {
                this.handlePrevious();
            }
        }
        this.isDragging = false;
        this.startX = 0;
        this.currentX = 0;
        if (this.isAutoplayActive) {
            this.startAutoplay();
        }
    }
    get elementClass() {
        return {
            'spw-slider': true,
            [`spw-slider--arrows-${this.arrowsPosition}`]: true,
            [`spw-slider--dots-${this.dotsPosition}`]: true,
        };
    }
    renderDots() {
        if (!this.showDots || this.totalSlides <= 1)
            return null;
        return (h("div", { class: { 'spw-slider__dots': true, 'spw-slider__dots--outside': this.dotsPosition === 'outside' } }, Array.from({ length: this.totalSlides }, (_, i) => (h("button", { class: {
                'spw-slider__dot': true,
                'spw-slider__dot--active': i === this.activeIndex,
            }, onClick: () => this.handleDotClick(i), "aria-label": `Slide ${i + 1}`, "aria-current": i === this.activeIndex ? 'true' : 'false' })))));
    }
    render() {
        return (h(Host, { key: '67c85fed7cc665da3cfa60082b5ac76b1f679c0d' }, h("div", { key: '1090245b2710939eb572d26c1ed23ade12c416e9', class: this.elementClass, style: { height: `${this.currentHeight}px` }, tabindex: "0", role: "region", "aria-label": this.accAriaLabel }, h("div", { key: 'e810a8fe4154b2f793041cae72f889a001988b84', class: "spw-slider__track" }, h("slot", { key: '440367be7154291d1d18465fab6dedbd79271792' })), this.showArrows && (h("div", { key: '7e8da39ecafddd9e3967d7a15e9d1838bbb51074', class: "spw-slider__navigation" }, h("button", { key: '48a77dde510252161146311dbd7ee8d75f39abfa', class: "spw-slider__arrow spw-slider__arrow--prev", onClick: this.handlePrevious, disabled: this.activeIndex === 0, "aria-label": this.previousSlideText }, h("spw-icon", { key: 'e8d9234727245e28a6d12d1914420cac33689edf', icon: "fa-chevron-left" })), h("button", { key: '66dd413bb8817caba03b3ca6af41c896459a91cf', class: "spw-slider__arrow spw-slider__arrow--next", onClick: this.handleNext, disabled: this.activeIndex === this.totalSlides - 1, "aria-label": this.nextSlideText }, h("spw-icon", { key: '8f545069639f403f8b4ef7843bf10d9d102609a1', icon: "fa-chevron-right" })))), this.dotsPosition === 'inside' && this.renderDots()), this.dotsPosition === 'outside' && (h("div", { key: '95bc58b0e2de1dc60a1e8f5036b8aec4eaebf9b6', class: "spw-slider__dots-container" }, this.renderDots())), this.showAutoplayToggle && (h("div", { key: 'e6e919ce3bbad911c74914bd19b3e920c028c4f9', class: "spw-slider__autoplay-toggle" }, h("spw-checkbox", { key: 'c8583e3b3a2b47e9ce67c7d6aa448b54dea0a3ec', variant: "toggle", checked: this.isAutoplayActive, onSpwChange: this.handleAutoplayToggle }, this.autoplayText)))));
    }
    static get is() { return "spw-slider"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["spw-slider.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["spw-slider.css"]
        };
    }
    static get properties() {
        return {
            "showArrows": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Affiche les fl\u00E8ches de navigation"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "show-arrows",
                "defaultValue": "true"
            },
            "showDots": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Affiche les dots de navigation"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "show-dots",
                "defaultValue": "true"
            },
            "showAutoplayToggle": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Affiche le toggle de d\u00E9filement automatique"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "show-autoplay-toggle",
                "defaultValue": "false"
            },
            "autoplayInterval": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Intervalle de d\u00E9filement automatique en millisecondes"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "autoplay-interval",
                "defaultValue": "5000"
            },
            "autoplayEnabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Active le d\u00E9filement automatique par d\u00E9faut"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "autoplay-enabled",
                "defaultValue": "false"
            },
            "autoplayText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Label du toggle de d\u00E9filement automatique"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "autoplay-text",
                "defaultValue": "'D\u00E9filement automatique'"
            },
            "arrowsPosition": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'outside' | 'inside'",
                    "resolved": "\"inside\" | \"outside\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Position des fl\u00E8ches gauche/droite"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "arrows-position",
                "defaultValue": "'inside'"
            },
            "dotsPosition": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "'inside' | 'outside'",
                    "resolved": "\"inside\" | \"outside\"",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Position des dots de navigation"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "dots-position",
                "defaultValue": "'inside'"
            },
            "nextSlideText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Texte aria-label pour la slide suivante"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "next-slide-text",
                "defaultValue": "'Slide suivante'"
            },
            "accAriaLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Texte aria-label du slider"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "acc-aria-label",
                "defaultValue": "'Slider de contenu'"
            },
            "previousSlideText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Texte aria-label pour la slide pr\u00E9c\u00E9dente"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "previous-slide-text",
                "defaultValue": "'Slide pr\u00E9c\u00E9dente'"
            },
            "hasFixedHeight": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Fixe la hauteur du slider \u00E0 la hauteur de la slide la plus haute"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "has-fixed-height",
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "activeIndex": {},
            "totalSlides": {},
            "currentHeight": {},
            "isAutoplayActive": {}
        };
    }
    static get events() {
        return [{
                "method": "spwSliderChange",
                "name": "spwSliderChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "\u00C9mis lors du changement de slide (index pr\u00E9c\u00E9dent et nouvel index)"
                },
                "complexType": {
                    "original": "{ index: number; previousIndex: number }",
                    "resolved": "{ index: number; previousIndex: number; }",
                    "references": {}
                }
            }, {
                "method": "spwSliderNext",
                "name": "spwSliderNext",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "\u00C9mis lors du passage \u00E0 la slide suivante"
                },
                "complexType": {
                    "original": "{ index: number }",
                    "resolved": "{ index: number; }",
                    "references": {}
                }
            }, {
                "method": "spwSliderPrevious",
                "name": "spwSliderPrevious",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "\u00C9mis lors du passage \u00E0 la slide pr\u00E9c\u00E9dente"
                },
                "complexType": {
                    "original": "{ index: number }",
                    "resolved": "{ index: number; }",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get listeners() {
        return [{
                "name": "touchstart",
                "method": "handleTouchStart",
                "target": undefined,
                "capture": false,
                "passive": true
            }, {
                "name": "mousedown",
                "method": "handleMouseDown",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "touchmove",
                "method": "handleTouchMove",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "mousemove",
                "method": "handleMouseMove",
                "target": undefined,
                "capture": false,
                "passive": true
            }, {
                "name": "touchend",
                "method": "handleTouchEnd",
                "target": undefined,
                "capture": false,
                "passive": true
            }, {
                "name": "mouseup",
                "method": "handleMouseUp",
                "target": undefined,
                "capture": false,
                "passive": true
            }, {
                "name": "mouseleave",
                "method": "handleMouseLeave",
                "target": undefined,
                "capture": false,
                "passive": true
            }, {
                "name": "keydown",
                "method": "handleKeyDown",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
