import { Host, h } from "@stencil/core";
import Masonry from "masonry-layout";
export class SpwMosaic {
    constructor() {
        /** Active le mode "masonry" pour une mise en page en grille ajustable */
        this.isMasonry = false;
        /** Nombre de colonnes à afficher en vue mobile */
        this.colsMobile = 1;
        /** Nombre de colonnes à afficher en vue tablette */
        this.colsTablet = 2;
        /** Nombre de colonnes à afficher en vue desktop */
        this.colsDesktop = 3;
        this.initialized = false;
    }
    itemsChanged(newValue, oldValue) {
        if (newValue !== oldValue && this.isMasonry) {
            this.refreshMasonryLayout();
        }
    }
    isMasonryChanged(newValue) {
        if (newValue) {
            this.initializeMasonry();
        }
        else {
            this.destroyMasonry();
        }
    }
    async waitForImages() {
        const images = this.el.shadowRoot.querySelectorAll('img');
        const loadPromises = Array.from(images).map(image => {
            return new Promise(resolve => {
                if (image.complete) {
                    resolve();
                }
                else {
                    image.addEventListener('load', () => resolve(), { once: true });
                }
            });
        });
        await Promise.all(loadPromises);
    }
    emitConfigurationChanged() {
        const event = new CustomEvent('mosaicConfigurationChanged', {
            detail: {
                colsMobile: this.colsMobile,
                colsTablet: this.colsTablet,
                colsDesktop: this.colsDesktop,
            },
            bubbles: true,
            composed: true,
        });
        this.el.dispatchEvent(event);
    }
    configurationChanged() {
        this.emitConfigurationChanged();
    }
    async refreshMasonryLayout() {
        if (!this.isMasonry)
            return;
        await this.waitForImages();
        this.initializeMasonry();
    }
    componentDidLoad() {
        if (this.isMasonry) {
            this.initializeMasonry();
        }
        this.observeSlotChanges();
        this.emitConfigurationChanged();
    }
    componentDidUpdate() {
        if (this.isMasonry) {
            this.refreshMasonryLayout();
        }
    }
    disconnectedCallback() {
        this.destroyMasonry();
        if (this.observer) {
            this.observer.disconnect();
        }
    }
    async initializeMasonry() {
        if (!this.isMasonry)
            return;
        requestAnimationFrame(() => {
            const slot = this.el.shadowRoot.querySelector('slot');
            const masonryItems = slot.assignedElements({ flatten: true });
            if (masonryItems.length > 0) {
                // Trouver un item sans colSpan pour calculer la largeur de base d'une colonne
                const baseItem = Array.from(masonryItems).find(item => !item.hasAttribute('col-span-desktop') && !item.hasAttribute('col-span-tablet') && !item.hasAttribute('col-span-mobile')) ||
                    masonryItems[0];
                this.masonry = new Masonry(this.el, {
                    itemSelector: 'spw-mosaic-item',
                    columnWidth: baseItem,
                    percentPosition: true,
                    gutter: 0,
                });
                this.initialized = true;
                masonryItems.forEach(item => {
                    const images = item.querySelectorAll('img');
                    images.forEach(image => {
                        if (!image.complete) {
                            image.addEventListener('load', this.updateMasonryLayout.bind(this), { once: true });
                        }
                    });
                });
            }
        });
    }
    updateMasonryLayout() {
        if (this.masonry && this.initialized && this.isMasonry) {
            this.masonry.layout();
        }
    }
    destroyMasonry() {
        if (this.masonry) {
            this.masonry.destroy();
            this.masonry = null;
            this.initialized = false;
        }
    }
    observeSlotChanges() {
        const slot = this.el.shadowRoot.querySelector('slot');
        this.observer = new MutationObserver(mutations => {
            for (const mutation of mutations) {
                if (mutation.type === 'childList' && this.initialized && this.isMasonry) {
                    this.initializeMasonry();
                }
            }
        });
        this.observer.observe(slot, { childList: true });
    }
    get elementClass() {
        return {
            'spw-mosaic': true,
            'spw-mosaic--no-masonry': !this.isMasonry,
        };
    }
    render() {
        return (h(Host, { key: 'a2878c9196d2cb6eb75ac2b406a951c2eafb8f17' }, h("div", { key: 'b57c237e408c7b6c8d1759886d695bee866f19e1', class: this.elementClass }, h("slot", { key: '4bcadc41dd9e4d4319f284f627e803dae17b62ab' }))));
    }
    static get is() { return "spw-mosaic"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["spw-mosaic.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["spw-mosaic.css"]
        };
    }
    static get properties() {
        return {
            "items": {
                "type": "any",
                "mutable": false,
                "complexType": {
                    "original": "any",
                    "resolved": "any",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Liste des \u00E9l\u00E9ments \u00E0 afficher dans la mosa\u00EFque"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "items"
            },
            "isMasonry": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Active le mode \"masonry\" pour une mise en page en grille ajustable"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "is-masonry",
                "defaultValue": "false"
            },
            "colsMobile": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Nombre de colonnes \u00E0 afficher en vue mobile"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "cols-mobile",
                "defaultValue": "1"
            },
            "colsTablet": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Nombre de colonnes \u00E0 afficher en vue tablette"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "cols-tablet",
                "defaultValue": "2"
            },
            "colsDesktop": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Nombre de colonnes \u00E0 afficher en vue desktop"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "cols-desktop",
                "defaultValue": "3"
            }
        };
    }
    static get states() {
        return {
            "initialized": {}
        };
    }
    static get methods() {
        return {
            "waitForImages": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "initializeMasonry": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "HTMLElement": {
                            "location": "global",
                            "id": "global::HTMLElement"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "items",
                "methodName": "itemsChanged"
            }, {
                "propName": "isMasonry",
                "methodName": "isMasonryChanged"
            }, {
                "propName": "colsMobile",
                "methodName": "configurationChanged"
            }, {
                "propName": "colsTablet",
                "methodName": "configurationChanged"
            }, {
                "propName": "colsDesktop",
                "methodName": "configurationChanged"
            }];
    }
}
