import { Host, h } from "@stencil/core";
import { animationTo } from "../../utils/animation";
const VARIANT_ICONS = {
    success: 'fa-check',
    info: 'fa-info',
    warning: 'fa-exclamation',
    alert: 'fa-close',
};
export class SpwToast {
    constructor() {
        /** Variante du toast */
        this.variant = 'info';
        /** Titre du toast (gras) */
        this.heading = '';
        /** Message / description du toast */
        this.message = '';
        /** Texte du lien optionnel */
        this.linkLabel = '';
        /** URL du lien optionnel */
        this.linkHref = '';
        /** Durée d'affichage automatique en ms (0 = pas d'auto-dismiss) */
        this.duration = 5000;
        /** Affiche le bouton de fermeture */
        this.dismissable = true;
        /** Texte du bouton de fermeture */
        this.dismissText = 'Fermer';
        this.visible = false;
        this.autoDismissTimer = null;
        this.timerStartedAt = null;
        this.timerRemaining = null;
        // Swipe
        this.swipeTouchStartX = 0;
        this.swipeTouchStartY = 0;
    }
    componentDidLoad() {
        this.show();
    }
    disconnectedCallback() {
        this.clearTimer();
    }
    clearTimer() {
        if (this.autoDismissTimer !== null) {
            clearTimeout(this.autoDismissTimer);
            this.autoDismissTimer = null;
        }
    }
    startAutoDismiss(remaining) {
        if (this.duration <= 0)
            return;
        const ms = remaining !== null && remaining !== void 0 ? remaining : this.duration;
        this.timerStartedAt = Date.now();
        this.timerRemaining = ms;
        this.autoDismissTimer = setTimeout(() => this.dismiss(), ms);
    }
    pauseTimer() {
        var _a;
        if (this.autoDismissTimer === null || this.timerStartedAt === null)
            return;
        this.clearTimer();
        const elapsed = Date.now() - this.timerStartedAt;
        this.timerRemaining = Math.max(0, ((_a = this.timerRemaining) !== null && _a !== void 0 ? _a : this.duration) - elapsed);
        this.timerStartedAt = null;
        // pause CSS animation
        if (this.progressEl) {
            this.progressEl.style.animationPlayState = 'paused';
        }
    }
    resumeTimer() {
        if (this.timerRemaining === null || this.timerRemaining <= 0)
            return;
        this.startAutoDismiss(this.timerRemaining);
        // resume CSS animation
        if (this.progressEl) {
            this.progressEl.style.animationPlayState = 'running';
        }
    }
    /** Affiche le toast avec animation */
    async show() {
        this.visible = true;
        await new Promise(r => requestAnimationFrame(r));
        if (this.containerEl) {
            animationTo(this.containerEl, SLIDE_IN_KEYFRAMES, { duration: 300 });
        }
        this.startAutoDismiss();
    }
    /** Ferme le toast avec animation */
    async dismiss() {
        this.clearTimer();
        if (this.containerEl) {
            const anim = animationTo(this.containerEl, SLIDE_OUT_KEYFRAMES, { duration: 200 });
            anim.addEventListener('finish', () => this.remove());
        }
        else {
            this.remove();
        }
    }
    remove() {
        this.visible = false;
        this.spwToastDismiss.emit();
        this.el.remove();
    }
    durationChanged() {
        this.clearTimer();
        this.timerRemaining = null;
        this.startAutoDismiss();
    }
    get resolvedIcon() {
        return this.icon || VARIANT_ICONS[this.variant];
    }
    render() {
        if (!this.visible)
            return null;
        const hasProgress = this.duration > 0;
        return (h(Host, null, h("div", { class: { 'spw-toast': true, [`spw-toast--${this.variant}`]: true }, role: "alert", "aria-live": "assertive", "aria-atomic": "true", ref: el => (this.containerEl = el), onMouseEnter: () => this.pauseTimer(), onMouseLeave: () => this.resumeTimer(), onTouchStart: (e) => {
                this.swipeTouchStartX = e.touches[0].clientX;
                this.swipeTouchStartY = e.touches[0].clientY;
            }, onTouchEnd: (e) => {
                const dx = e.changedTouches[0].clientX - this.swipeTouchStartX;
                const dy = e.changedTouches[0].clientY - this.swipeTouchStartY;
                if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > 50) {
                    this.dismiss();
                }
            } }, h("div", { class: "spw-toast__aside" }, h("div", { class: "spw-toast__icon-wrapper" }, h("spw-icon", { variant: "fa-regular", icon: this.resolvedIcon }))), h("div", { class: "spw-toast__body" }, h("div", { class: "spw-toast__top" }, this.heading && h("p", { class: "spw-toast__heading" }, this.heading), this.dismissable && (h("button", { class: "spw-toast__close", "aria-label": this.dismissText, onClick: () => this.dismiss() }, h("span", { class: "spw-toast__close-label" }, this.dismissText), h("spw-icon", { icon: "fa-xmark" })))), this.message && h("p", { class: "spw-toast__message" }, this.message), this.linkLabel && (h("a", { class: "spw-toast__link", href: this.linkHref || undefined, role: !this.linkHref ? 'button' : undefined, tabindex: !this.linkHref ? '0' : undefined, onClick: e => {
                if (!this.linkHref)
                    e.preventDefault();
                this.spwToastLinkClick.emit();
            }, onKeyDown: e => {
                if (!this.linkHref && (e.key === 'Enter' || e.key === ' ')) {
                    e.preventDefault();
                    this.spwToastLinkClick.emit();
                }
            } }, this.linkLabel))), hasProgress && h("div", { class: "spw-toast__progress", style: { animationDuration: `${this.duration}ms` }, ref: el => (this.progressEl = el) }))));
    }
    static get is() { return "spw-toast"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["spw-toast.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["spw-toast.css"]
        };
    }
    static get properties() {
        return {
            "variant": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "SpwToastVariant",
                    "resolved": "\"alert\" | \"info\" | \"success\" | \"warning\"",
                    "references": {
                        "SpwToastVariant": {
                            "location": "local",
                            "path": "/Users/pectonite/Desktop/SPW/spw-design-system/packages/spw-stencil-library/src/components/spw-toast/spw-toast.tsx",
                            "id": "src/components/spw-toast/spw-toast.tsx::SpwToastVariant"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Variante du toast"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "variant",
                "defaultValue": "'info'"
            },
            "heading": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Titre du toast (gras)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "heading",
                "defaultValue": "''"
            },
            "message": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Message / description du toast"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "message",
                "defaultValue": "''"
            },
            "linkLabel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Texte du lien optionnel"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "link-label",
                "defaultValue": "''"
            },
            "linkHref": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "URL du lien optionnel"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "link-href",
                "defaultValue": "''"
            },
            "duration": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Dur\u00E9e d'affichage automatique en ms (0 = pas d'auto-dismiss)"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "duration",
                "defaultValue": "5000"
            },
            "dismissable": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Affiche le bouton de fermeture"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "dismissable",
                "defaultValue": "true"
            },
            "dismissText": {
                "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": "dismiss-text",
                "defaultValue": "'Fermer'"
            },
            "icon": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "Ic\u00F4ne personnalis\u00E9e"
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "icon"
            }
        };
    }
    static get states() {
        return {
            "visible": {}
        };
    }
    static get events() {
        return [{
                "method": "spwToastDismiss",
                "name": "spwToastDismiss",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "\u00C9mis quand le toast est ferm\u00E9"
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }, {
                "method": "spwToastLinkClick",
                "name": "spwToastLinkClick",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "\u00C9mis lors du clic sur le lien (utile en Angular sans href)"
                },
                "complexType": {
                    "original": "void",
                    "resolved": "void",
                    "references": {}
                }
            }];
    }
    static get methods() {
        return {
            "show": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Affiche le toast avec animation",
                    "tags": []
                }
            },
            "dismiss": {
                "complexType": {
                    "signature": "() => Promise<void>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "Ferme le toast avec animation",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "duration",
                "methodName": "durationChanged"
            }];
    }
}
const SLIDE_IN_KEYFRAMES = [
    { offset: 0, opacity: '0', transform: 'translateY(20%)', easing: 'ease-out' },
    { offset: 1, opacity: '1', transform: 'translateY(0)', easing: 'ease-out' },
];
const SLIDE_OUT_KEYFRAMES = [
    { offset: 0, opacity: '1' },
    { offset: 1, opacity: '0' },
];
