// retoor <retoor@molodetz.nl>

import { Component } from "./Component.js";

export class AppToast extends Component {
    connectedCallback() {
        this.classList.add("dp-toast-host");
    }

    show(message, options = {}) {
        const type = options.type || "info";
        const ms = options.ms || 3000;
        const toast = document.createElement("div");
        toast.className = `dp-toast dp-toast-${type}`;
        const assertive = type === "error" || type === "warning";
        toast.setAttribute("role", assertive ? "alert" : "status");
        toast.setAttribute("aria-live", assertive ? "assertive" : "polite");
        toast.setAttribute("aria-atomic", "true");
        toast.textContent = message;
        const action = this._action(options);
        if (action) {
            toast.classList.add("dp-toast-link");
            toast.addEventListener("click", action);
        }
        this.appendChild(toast);
        requestAnimationFrame(() => toast.classList.add("visible"));
        setTimeout(() => {
            toast.classList.remove("visible");
            setTimeout(() => toast.remove(), 200);
        }, ms);
        return toast;
    }

    _action(options) {
        if (typeof options.onClick === "function") return options.onClick;
        if (options.url) {
            return () => {
                window.location.href = options.url;
            };
        }
        return null;
    }
}

customElements.define("dp-toast", AppToast);
