/*!
 * Custom elements for Nanopore-Digital Web applications
 */
import { getAssetPath, proxyCustomElement, HTMLElement, createEvent, Build, Host } from '@stencil/core/internal/client';
import { h } from './renderer.js';

let CACHED_MAP;
const getIconMap = () => {
    if (!CACHED_MAP) {
        const win = window;
        win.Nanoicons = win.Nanoicons || {};
        CACHED_MAP = win.Nanoicons.map = win.Nanoicons.map || new Map();
    }
    return CACHED_MAP;
};
const getUrl = (i) => {
    let url = getSrc(i.src);
    if (url)
        return url;
    url = getName(i.name, i.icon);
    if (url)
        return getNamedUrl(url);
    if (i.icon) {
        url = getSrc(i.icon);
        if (url)
            return url;
    }
    return null;
};
const getNamedUrl = (iconName) => {
    const url = getIconMap().get(iconName);
    if (url)
        return url;
    if (iconName.startsWith('device/') ||
        iconName.startsWith('pictogram/') ||
        iconName.startsWith('flag/')) {
        return getAssetPath(`../nano-assets/icon/${iconName}.svg`);
    }
    return getAssetPath(`../nano-assets/fontawesome-pro/svgs/${iconName}.svg`);
};
const getName = (iconName, icon) => {
    if (!iconName && icon && !isSrc(icon)) {
        iconName = icon;
    }
    if (isStr(iconName)) {
        iconName = toLower(iconName);
    }
    if (!isStr(iconName) || iconName.trim() === '') {
        return null;
    }
    // only allow alpha characters and dash
    const invalidChars = iconName.replace(/[a-z]|-|\/|\d/gi, '');
    if (invalidChars !== '') {
        console.warn('invalid characters in icon name ' + iconName);
        return null;
    }
    return iconName;
};
const getSrc = (src) => {
    if (isStr(src)) {
        src = src.trim();
        if (isSrc(src))
            return src;
    }
    return null;
};
const isSrc = (str) => str.length > 0 && /(\/|\.)/.test(str);
const isStr = (val) => typeof val === 'string';
const toLower = (val) => val.toLowerCase();

const validateContent = (svgContent) => {
    if (svgContent && document) {
        const div = document.createElement('div');
        div.innerHTML = svgContent;
        // setup this way to ensure it works on our buddy IE
        for (let i = div.childNodes.length - 1; i >= 0; i--) {
            if (div.childNodes[i].nodeName.toLowerCase() !== 'svg') {
                div.removeChild(div.childNodes[i]);
            }
        }
        // must only have 1 root element
        const svgElm = div.firstElementChild;
        if (svgElm && svgElm.nodeName.toLowerCase() === 'svg') {
            const svgClass = svgElm.getAttribute('class') || '';
            svgElm.setAttribute('class', (svgClass + ' sc-nano-icon s-nano-icon svg').trim());
            // root element must be an svg
            // lets double check we've got valid elements
            // do not allow scripts
            if (isValid(svgElm)) {
                return div.innerHTML;
            }
        }
    }
    return '';
};
const isValid = (elm) => {
    if (elm.nodeType === 1) {
        if (elm.nodeName.toLowerCase() === 'script') {
            return false;
        }
        for (let i = 0; i < elm.attributes.length; i++) {
            const val = elm.attributes[i].value;
            if (isStr(val) && val.toLowerCase().indexOf('on') === 0) {
                return false;
            }
        }
        for (let i = 0; i < elm.childNodes.length; i++) {
            if (!isValid(elm.childNodes[i])) {
                return false;
            }
        }
    }
    return true;
};

const iconContent = new Map();
const requests = new Map();
const getSvgContent = (url) => {
    // see if we already have a request for this url
    let req = requests.get(url);
    if (!req) {
        // we don't already have a request
        req = fetch(url).then((rsp) => {
            if (rsp.ok) {
                return rsp.text().then((svgContent) => {
                    iconContent.set(url, validateContent(svgContent));
                });
            }
            iconContent.set(url, '');
        });
        // cache for the same requests
        requests.set(url, req);
    }
    return req;
};

const iconCss = ":host,*,*::before,*::after{box-sizing:border-box}[hidden]{display:none !important}@media (prefers-reduced-motion: reduce){:host,*,*::before,*::after{animation-duration:0.01ms !important;animation-iteration-count:1 !important;transition-duration:0.01ms !important;scroll-behavior:auto !important}}:host,*,*::before,*::after{box-sizing:border-box}[hidden]{display:none !important}@media (prefers-reduced-motion: reduce){:host,*,*::before,*::after{animation-duration:0.01ms !important;animation-iteration-count:1 !important;transition-duration:0.01ms !important;scroll-behavior:auto !important}}:host{--icon-size:1em;--primary-color:currentcolor\n  --secondary-color: color-mix(in srgb, currentColor 50%, transparent);--primary-opacity:0.8;--secondary-opacity:1;display:inline-block;inline-size:var(--icon-size);block-size:var(--icon-size);min-inline-size:var(--icon-size);min-block-size:var(--icon-size);contain:strict;fill:currentcolor;box-sizing:content-box !important;transition:opacity 0.3s ease;color:currentcolor}:host .nanoicon{stroke:currentcolor}.nanoicon-fill-none{fill:none}.icon-inner,.nanoicon,svg,.svg{display:block;block-size:100%;inline-size:100%;overflow:visible}:host(.loading){opacity:0}.fa-primary{color:var(--primary-color);opacity:var(--primary-opacity, 1)}.fa-secondary{color:var(--secondary-color);opacity:var(--secondary-opacity) !important}:host(.flip-rtl) .icon-inner{transform:scaleX(-1)}:host([name^=pictogram]),:host([name^=device]){font-size:max(var(--nano-pictogram-size-medium), var(--icon-size))}:host([size=small][name^=pictogram]),:host([size=small][name^=device]){font-size:var(--nano-pictogram-size-small)}:host([size=regular]){font-size:var(--nano-icon-size-small)}:host([size=regular][name^=pictogram]),:host([size=regular][name^=device]){font-size:var(--nano-pictogram-size-medium)}:host([size=large]){font-size:var(--nano-icon-size-large)}:host([size=large][name^=pictogram]),:host([size=large][name^=device]){font-size:var(--nano-pictogram-size-large)}:host([size=xl][name^=pictogram]),:host([size=xl][name^=device]){font-size:var(--nano-pictogram-size-x-large)}:host([name^=pictogram]),:host([name^=device]),:host([color=primary]){color:var(--nano-color-primary-1100)}:host([color=neutral]){color:var(--nano-color-base-1000)}";

const Icon = /*@__PURE__*/ proxyCustomElement(class Icon extends HTMLElement {
    constructor() {
        super();
        this.__registerHost();
        this.__attachShadow();
        this.nanoLoad = createEvent(this, "nanoLoad", 7);
        this.nanoError = createEvent(this, "nanoError", 7);
    }
    io;
    get el() { return this; }
    svgContent;
    isVisible = false;
    isLoading = true;
    /**
     * Specifies the color of the icon. If not specified, the icon will inherit the color of the parent element.
     */
    color;
    /**
     * Specifies the role to use for accessibility. Defaults to 'presentation' (invisible to screen-readers)
     */
    role;
    setAriaLabel() {
        if (!this.ariaLabel && !this.el.ariaLabel) {
            if (!this.role || this.role !== 'presentation') {
                // if the role is not 'presentation' and the user did not explicitly set a role,
                // let's try and derive one from the icon name
                const label = getName(this.name, this.icon);
                // user did not provide a label
                // come up with the label based on the icon name
                if (label) {
                    this.ariaLabel = label.split('/').slice(-1)[0].replace(/-/g, ' ');
                }
            }
        }
        else if (this.role === 'presentation') {
            this.ariaLabel = undefined;
        }
    }
    /**
     * Specifies the label to use for accessibility. Defaults to the icon name.
     */
    ariaLabel;
    updateRole() {
        // force the role to be 'img' if the aria-label is explicitly set
        if (this.ariaLabel)
            this.role = 'img';
        else if (!this.ariaLabel)
            this.role = 'presentation';
    }
    /**
     * Specifies whether the icon should horizontally flip when `dir` is `"rtl"`.
     * By default, when an 'arrow' or 'chevron' icon is used, it will flip automatically when detecting `dir="rtl"` on the document or closest ancestor.
     */
    flipRtl;
    /**
     * Specifies which icon to use from the built-in set of icons.
     */
    name;
    /**
     * Specifies the exact `src` of an SVG file to use.
     */
    src;
    /**
     * A combination of both `name` and `src`. If a `src` url is detected
     * it will set the `src` property. Otherwise it assumes it's a built-in named
     * SVG and set the `name` property.
     */
    icon;
    /**
     * The size of the icon. `auto` automatically sizes according to the font-size of the parent element.
     * *Note*: size will be different on 'pictogram' and 'device' vs 'font awesome' icons.
     */
    size = 'auto';
    /**
     * If enabled, nano-icon will be loaded lazily when it's visible in the viewport.
     * Default, `true`.
     */
    lazy = true;
    loadIcon() {
        if (Build.isBrowser && this.isVisible) {
            const url = getUrl(this);
            if (url) {
                if (iconContent.has(url)) {
                    // sync if it's already loaded
                    this.svgContent = iconContent.get(url);
                    requestAnimationFrame(() => {
                        this.isLoading = false;
                        this.nanoLoad.emit();
                    });
                }
                else {
                    // async if it hasn't been loaded
                    getSvgContent(url).then(() => {
                        this.svgContent = iconContent.get(url);
                        requestAnimationFrame(() => {
                            this.isLoading = false;
                            this.nanoLoad.emit();
                        });
                        this.setAriaLabel();
                    }, () => {
                        // error loading icon
                        this.nanoError.emit();
                    });
                }
            }
        }
    }
    /** Emitted when the icon has finished loading. */
    nanoLoad;
    /** Emitted when the icon fails to load. */
    nanoError;
    waitUntilVisible(el, rootMargin, cb) {
        if (Build.isBrowser &&
            this.lazy &&
            typeof window !== 'undefined' &&
            window.IntersectionObserver) {
            const io = (this.io = new window.IntersectionObserver((data) => {
                if (data[0].isIntersecting || (data[1] && data[1].isIntersecting)) {
                    io.disconnect();
                    this.io = undefined;
                    cb();
                }
            }, { rootMargin }));
            io.observe(el);
        }
        else {
            // not a browser env (e.g. node)
            // or we're not loading lazily
            // or env doesn't support IntersectionObserver (testing?)
            // - immediately fetch icon
            cb();
        }
    }
    isRtl() {
        // doc is in rtl
        if (this.el.ownerDocument?.dir === 'rtl')
            return true;
        // html element is in rtl element
        if (this.el.closest('[dir="rtl"]'))
            return true;
        // nested in a shadow dom - see if that host element is contained in an rtl element
        const rootNode = this.el.getRootNode();
        const ownerHost = rootNode.host;
        if (ownerHost && ownerHost.closest('[dir="rtl"]'))
            return true;
        return false;
    }
    connectedCallback() {
        // purposely do not return the promise here because loading
        // the svg file should not hold up loading the app
        // only load the svg if it's visible
        this.waitUntilVisible(this.el, '50px', () => {
            this.isVisible = true;
            this.loadIcon();
        });
    }
    disconnectedCallback() {
        if (this.io) {
            this.io.disconnect();
            this.io = undefined;
        }
    }
    componentWillLoad() {
        this.updateRole();
        this.setAriaLabel();
    }
    render() {
        const flipRtl = this.flipRtl ||
            (this.name &&
                this.name.match(/right|left/) &&
                (this.name.indexOf('arrow') > -1 ||
                    this.name.indexOf('chevron') > -1) &&
                this.isRtl());
        return (h(Host, { key: '5c392d7707158df8b3c3d75f00824e597c3a87a9', class: {
                loading: this.isLoading,
                'flip-rtl': !!flipRtl,
                'nano-icon': true,
            } }, Build.isBrowser && this.svgContent ? (h("div", { class: "icon-inner", innerHTML: this.svgContent })) : (h("div", { class: "icon-inner" }))));
    }
    static get assetsDirs() { return ["device", "pictogram", "flag"]; }
    static get watchers() { return {
        "role": ["setAriaLabel"],
        "ariaLabel": ["updateRole"],
        "name": ["loadIcon"],
        "src": ["loadIcon"],
        "icon": ["loadIcon"]
    }; }
    static get style() { return iconCss; }
}, [257, "nano-icon", {
        "color": [1],
        "role": [1537],
        "ariaLabel": [1537, "aria-label"],
        "flipRtl": [4, "flip-rtl"],
        "name": [513],
        "src": [1],
        "icon": [8],
        "size": [513],
        "lazy": [4],
        "svgContent": [32],
        "isVisible": [32],
        "isLoading": [32]
    }, undefined, {
        "role": ["setAriaLabel"],
        "ariaLabel": ["updateRole"],
        "name": ["loadIcon"],
        "src": ["loadIcon"],
        "icon": ["loadIcon"]
    }]);
function defineCustomElement() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["nano-icon"];
    components.forEach(tagName => { switch (tagName) {
        case "nano-icon":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, Icon);
            }
            break;
    } });
}

export { Icon as I, defineCustomElement as d };
