import { Host, h } from "@stencil/core";
import { animationTo, KEYFRAMES } from "../../utils/animation";
export class SpwLightbox {
    constructor() {
        /** Texte du bouton de fermeture */
        this.closeButtonText = 'Fermer';
        /** Indique si la fermeture est possible en cliquant sur le backdrop */
        this.closeOnBackdropClick = true;
        /** Affiche ou masque la galerie de miniatures sous l'image principale */
        this.showThumbnails = true;
        // Textes customisables
        /** Label aria de la dialog */
        this.textDialogLabel = "Galerie d'images";
        /** Label aria du bouton image précédente */
        this.textPrevious = 'Image précédente';
        /** Label aria du bouton image suivante */
        this.textNext = 'Image suivante';
        /** Label aria de la liste de miniatures */
        this.textThumbnailsLabel = 'Miniatures';
        /** Label aria d'une miniature (utiliser {index} comme placeholder) */
        this.textThumbnailItem = 'Image {index}';
        this.opened = false;
        this.activeIndex = 0;
        this.items = [];
        this.previouslyFocusedElement = null;
        this.currentAnimation = null;
        this.swipeStartX = 0;
        this.swipeStartY = 0;
        this.isSwiping = false;
        this.SWIPE_THRESHOLD = 50;
        this.handleItemClick = (event) => {
            var _a;
            this.collectItems();
            this.activeIndex = (_a = event.detail.index) !== null && _a !== void 0 ? _a : 0;
            this.opened = true;
        };
        this.handleKeydown = (event) => {
            if (!this.opened)
                return;
            switch (event.key) {
                case 'Escape':
                    this.doClose();
                    break;
                case 'ArrowRight':
                case 'ArrowDown':
                    event.preventDefault();
                    this.navigate(1);
                    break;
                case 'ArrowLeft':
                case 'ArrowUp':
                    event.preventDefault();
                    this.navigate(-1);
                    break;
            }
        };
        this.handleTouchStart = (event) => {
            this.swipeStartX = event.touches[0].clientX;
            this.swipeStartY = event.touches[0].clientY;
            this.isSwiping = true;
        };
        this.handleTouchMove = (event) => {
            if (!this.isSwiping)
                return;
            const dx = event.touches[0].clientX - this.swipeStartX;
            const dy = event.touches[0].clientY - this.swipeStartY;
            if (Math.abs(dx) > Math.abs(dy)) {
                event.preventDefault();
            }
        };
        this.handleTouchEnd = (event) => {
            if (!this.isSwiping)
                return;
            const dx = this.swipeStartX - event.changedTouches[0].clientX;
            if (Math.abs(dx) >= this.SWIPE_THRESHOLD) {
                this.navigate(dx > 0 ? 1 : -1);
            }
            this.isSwiping = false;
        };
    }
    componentDidLoad() {
        window.addEventListener('keydown', this.handleKeydown);
        this.hostElement.addEventListener('spwLightboxItemClick', this.handleItemClick);
        this.imageWrapperEl.addEventListener('touchstart', this.handleTouchStart, { passive: true });
        this.imageWrapperEl.addEventListener('touchmove', this.handleTouchMove, { passive: false });
        this.imageWrapperEl.addEventListener('touchend', this.handleTouchEnd);
    }
    disconnectedCallback() {
        var _a, _b, _c;
        window.removeEventListener('keydown', this.handleKeydown);
        this.hostElement.removeEventListener('spwLightboxItemClick', this.handleItemClick);
        (_a = this.imageWrapperEl) === null || _a === void 0 ? void 0 : _a.removeEventListener('touchstart', this.handleTouchStart);
        (_b = this.imageWrapperEl) === null || _b === void 0 ? void 0 : _b.removeEventListener('touchmove', this.handleTouchMove);
        (_c = this.imageWrapperEl) === null || _c === void 0 ? void 0 : _c.removeEventListener('touchend', this.handleTouchEnd);
        document.body.style.overflow = '';
    }
    async open(index = 0) {
        this.collectItems();
        this.activeIndex = index;
        this.opened = true;
    }
    async close() {
        this.doClose();
    }
    onOpenedChange(newValue) {
        if (newValue) {
            this.onOpen();
        }
        else {
            this.onClose();
        }
    }
    collectItems() {
        const lightboxItems = this.hostElement.querySelectorAll(`spw-lightbox-item`);
        this.items = Array.from(lightboxItems).map(el => ({
            src: el.getAttribute('src') || '',
            alt: el.getAttribute('alt') || '',
            captionTitle: el.getAttribute('caption-title') || '',
            captionText: el.getAttribute('caption-text') || '',
            copyrightText: el.getAttribute('copyright-text') || '',
            copyrightIcon: el.getAttribute('copyright-icon') || 'fa-copyright',
            copyrightIconVariant: el.getAttribute('copyright-icon-variant') || 'fa-light',
            copyrightHref: el.getAttribute('copyright-href') || '',
            copyrightTarget: el.getAttribute('copyright-target') || '_blank',
        }));
    }
    cancelCurrentAnimation() {
        if (this.currentAnimation) {
            this.currentAnimation.cancel();
            this.currentAnimation = null;
        }
    }
    scrollToActiveThumbnail() {
        if (!this.thumbnailsEl)
            return;
        const thumb = this.thumbnailsEl.querySelectorAll('.spw-lightbox__thumb')[this.activeIndex];
        thumb === null || thumb === void 0 ? void 0 : thumb.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
    }
    onOpen() {
        var _a;
        this.cancelCurrentAnimation();
        this.previouslyFocusedElement = document.activeElement;
        document.body.style.overflow = 'hidden';
        try {
            this.currentAnimation = animationTo(this.lightboxContainer, KEYFRAMES.fadeIn, { duration: 200 });
            this.currentAnimation.addEventListener('finish', () => {
                var _a;
                this.currentAnimation = null;
                (_a = this.closeButtonEl) === null || _a === void 0 ? void 0 : _a.focus();
                this.scrollToActiveThumbnail();
                this.spwLightboxOpen.emit({ index: this.activeIndex });
            });
        }
        catch (_b) {
            this.currentAnimation = null;
            (_a = this.closeButtonEl) === null || _a === void 0 ? void 0 : _a.focus();
            this.scrollToActiveThumbnail();
            this.spwLightboxOpen.emit({ index: this.activeIndex });
        }
    }
    onClose() {
        var _a;
        this.cancelCurrentAnimation();
        document.body.style.overflow = '';
        try {
            this.currentAnimation = animationTo(this.lightboxContainer, KEYFRAMES.fadeOut, { duration: 200 });
            this.currentAnimation.addEventListener('finish', () => {
                var _a;
                this.currentAnimation = null;
                (_a = this.previouslyFocusedElement) === null || _a === void 0 ? void 0 : _a.focus();
                this.spwLightboxClose.emit();
            });
        }
        catch (_b) {
            this.currentAnimation = null;
            (_a = this.previouslyFocusedElement) === null || _a === void 0 ? void 0 : _a.focus();
            this.spwLightboxClose.emit();
        }
    }
    doClose() {
        this.opened = false;
    }
    handleFocusTrap(event) {
        var _a, _b;
        if (!this.opened || event.key !== 'Tab')
            return;
        const focusable = (_a = this.hostElement.shadowRoot) === null || _a === void 0 ? void 0 : _a.querySelectorAll('button:not([disabled]), [tabindex]:not([tabindex="-1"])');
        if (!focusable || focusable.length === 0)
            return;
        const first = focusable[0];
        const last = focusable[focusable.length - 1];
        const active = (_b = this.hostElement.shadowRoot) === null || _b === void 0 ? void 0 : _b.activeElement;
        if (event.shiftKey) {
            if (active === first) {
                event.preventDefault();
                last === null || last === void 0 ? void 0 : last.focus();
            }
        }
        else {
            if (active === last) {
                event.preventDefault();
                first === null || first === void 0 ? void 0 : first.focus();
            }
        }
    }
    navigate(direction) {
        if (this.items.length <= 1)
            return;
        this.activeIndex = (this.activeIndex + direction + this.items.length) % this.items.length;
    }
    onActiveIndexChange() {
        this.scrollToActiveThumbnail();
    }
    handleBackdropClick() {
        if (this.closeOnBackdropClick) {
            this.doClose();
        }
    }
    get activeItem() {
        var _a;
        return (_a = this.items[this.activeIndex]) !== null && _a !== void 0 ? _a : null;
    }
    render() {
        const { opened, activeItem, items, activeIndex } = this;
        return (h(Host, { key: 'abc234b600e09d3d5e37779d35f23343df01c918' }, h("div", { key: '6657c6faae953f97c09e999f7a6036bfa0dbb0fd', inert: opened || undefined }, h("slot", { key: '061101ace7cecc154e617ab50a7d44a240436cc4' })), h("div", { key: '433ef70c4eb86951d0b3907d1cde807594acf40b', ref: el => (this.lightboxContainer = el), class: { 'spw-lightbox': true, 'spw-lightbox--opened': opened }, role: "dialog", "aria-modal": "true", "aria-label": this.textDialogLabel }, h("div", { key: '154248164e28fd9c726aa3a6582d0726f390aa62', class: "spw-lightbox__backdrop", onClick: () => this.handleBackdropClick(), "aria-hidden": "true" }), h("div", { key: '4f70b9589c5e78685b667dbdda1d4581fd8dad11', class: "spw-lightbox__container" }, h("div", { key: 'ec59ccae09faaa9845ab65ad184645018442c215', class: "spw-lightbox__toolbar" }, h("span", { key: 'f0f135ef2c553256e741ad32b11da0257a5436a6', class: "spw-lightbox__counter", "aria-live": "polite" }, items.length > 0 ? `${activeIndex + 1} / ${items.length}` : ''), h("div", { key: '4e6d451fb01b36c5ae5b9efb6516dd856311c888', ref: el => (this.closeButtonEl = el), class: "spw-lightbox__close", tabIndex: 0, role: "button", onClick: () => this.doClose(), onKeyDown: (e) => {
                if (e.key === 'Enter' || e.key === ' ')
                    this.doClose();
            } }, h("spw-link", { key: '4817278c8bdade56a340bb4c18b60d194b2c99d7', "icon-position": "right", icon: "fa-xmark" }, this.closeButtonText))), h("div", { key: '613c3cb8e491e0112e2e9ac6bbf867c5f5d9c4b9', class: "spw-lightbox__stage" }, items.length > 1 && (h("spw-button", { key: '1a9765fa1c715f8aba10f23fd5c175e5c367db44', class: "spw-lightbox__nav spw-lightbox__nav--prev", "is-icon-only": true, icon: "fa-chevron-left", "acc-aria-label": this.textPrevious, variant: "secondary", onClick: () => this.navigate(-1) })), h("div", { key: 'ade43ad0a877fb87e089e7cb824c52a517833eb3', class: "spw-lightbox__image-wrapper", ref: el => (this.imageWrapperEl = el) }, activeItem && (h("div", { key: '2e6e36b4eded34277c368d587226e031e4c87ec5', class: "spw-lightbox__image-frame" }, h("img", { class: "spw-lightbox__image", src: activeItem.src, alt: activeItem.alt || '', key: activeItem.src }), ((activeItem === null || activeItem === void 0 ? void 0 : activeItem.captionTitle) || (activeItem === null || activeItem === void 0 ? void 0 : activeItem.captionText) || (activeItem === null || activeItem === void 0 ? void 0 : activeItem.copyrightText)) && (h("div", { key: 'b9a6e7249e8fe88233e48c7af83e0779911fca43', class: "spw-lightbox__caption", "aria-live": "polite" }, h("div", { key: '419860cb7b290233496aef849a783b673d87a7df', class: "spw-lightbox__caption-content" }, activeItem.captionTitle && h("strong", { key: 'f862d8a5a98a8da511fbaf7b1fe4b30283df2ee1', class: "spw-lightbox__caption-title" }, activeItem.captionTitle), activeItem.captionText && h("span", { key: '7b5adb2375e9fe815fcf50a854b71f7f214f52d6', class: "spw-lightbox__caption-text" }, activeItem.captionText)), activeItem.copyrightText && (h("spw-tag", { key: 'f5206abefcaf73d1483f9cef173d8ee01c6b3ab5', size: "small", "icon-variant": activeItem.copyrightIconVariant, class: "spw-lightbox__copyright", icon: activeItem.copyrightIcon, href: activeItem.copyrightHref || undefined, target: activeItem.copyrightHref ? activeItem.copyrightTarget : undefined }, activeItem.copyrightText))))))), items.length > 1 && (h("spw-button", { key: 'f9bf7db26386b749281b21c95af273ad210cada4', class: "spw-lightbox__nav spw-lightbox__nav--next", "is-icon-only": true, icon: "fa-chevron-right", "acc-aria-label": this.textNext, variant: "secondary", onClick: () => this.navigate(1) }))), this.showThumbnails && items.length > 1 && (h("div", { key: '1ea2bb1c95e66f37bc53460823aece1fe8c7cfe0', class: "spw-lightbox__thumbnails", role: "tablist", "aria-label": this.textThumbnailsLabel, ref: el => (this.thumbnailsEl = el) }, items.map((item, index) => (h("button", { key: item.src, role: "tab", class: { 'spw-lightbox__thumb': true, 'spw-lightbox__thumb--active': index === activeIndex }, onClick: () => (this.activeIndex = index), "aria-selected": String(index === activeIndex), "aria-label": item.alt || this.textThumbnailItem.replace('{index}', String(index + 1)) }, h("img", { src: item.src, alt: item.alt || '', loading: "lazy" }))))))))));
    }
    static get is() { return "spw-lightbox"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["spw-lightbox.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["spw-lightbox.css"]
        };
    }
    static get properties() {
        return {
            "gallery": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Identifiant de la galerie (partag\u00E9 avec spw-lightbox-item pour grouper les items)"
                },
                "getter": false,
                "setter": false,
                "reflect": true,
                "attribute": "gallery"
            },
            "closeButtonText": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Texte du bouton de fermeture"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "close-button-text",
                "defaultValue": "'Fermer'"
            },
            "closeOnBackdropClick": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Indique si la fermeture est possible en cliquant sur le backdrop"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "close-on-backdrop-click",
                "defaultValue": "true"
            },
            "showThumbnails": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Affiche ou masque la galerie de miniatures sous l'image principale"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "show-thumbnails",
                "defaultValue": "true"
            },
            "textDialogLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Label aria de la dialog"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "text-dialog-label",
                "defaultValue": "\"Galerie d'images\""
            },
            "textPrevious": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Label aria du bouton image pr\u00E9c\u00E9dente"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "text-previous",
                "defaultValue": "'Image pr\u00E9c\u00E9dente'"
            },
            "textNext": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Label aria du bouton image suivante"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "text-next",
                "defaultValue": "'Image suivante'"
            },
            "textThumbnailsLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Label aria de la liste de miniatures"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "text-thumbnails-label",
                "defaultValue": "'Miniatures'"
            },
            "textThumbnailItem": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Label aria d'une miniature (utiliser {index} comme placeholder)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "text-thumbnail-item",
                "defaultValue": "'Image {index}'"
            }
        };
    }
    static get states() {
        return {
            "opened": {},
            "activeIndex": {},
            "items": {}
        };
    }
    static get events() {
        return [{
                "method": "spwLightboxOpen",
                "name": "spwLightboxOpen",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "{ index: number }",
                    "resolved": "{ index: number; }",
                    "references": {}
                }
            }, {
                "method": "spwLightboxClose",
                "name": "spwLightboxClose",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "open": {
                "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": []
                }
            },
            "close": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "hostElement"; }
    static get watchers() {
        return [{
                "propName": "opened",
                "methodName": "onOpenedChange"
            }, {
                "propName": "activeIndex",
                "methodName": "onActiveIndexChange"
            }];
    }
    static get listeners() {
        return [{
                "name": "keydown",
                "method": "handleFocusTrap",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
