/*!
 * Built with Stencil
 * By PostNord.
 */
import { h, Host, forceUpdate } from "@stencil/core";
import { arrow_left, arrow_right } from "pn-design-assets/pn-assets/icons.js";
/**
 * The `pn-segmented-control` and `pn-segmented` is built with native `input[type="radio"]` in the background.
 * This means you can use native events to listen to the changes.
 *
 * @nativeChange Use the `change` event to listen when the segment state is being changed.
 */
export class PnSegmentedControl {
    mo;
    segmentContainer;
    segments = [];
    activeBg;
    hoverBg;
    scrollRegistered = false;
    hostElement;
    showScrollArrows = false;
    showLeftArrow = false;
    showRightArrow = false;
    /** This is the name of the radio buttons inside the controller. @deprecated Set the name in the nested `pn-segment` components. */
    name;
    /** Currently active segment value. */
    value;
    valueHandler() {
        this.setActiveSegment();
    }
    changeHandler(event) {
        const target = event.target;
        this.value = target.value;
        this.setActiveSegment();
    }
    handleResize() {
        this.rerender();
    }
    handleHover(event) {
        const { target } = event.detail;
        this.calcHighlight(target, true);
    }
    componentDidLoad() {
        if (this.mo)
            this.mo.disconnect();
        this.mo = new MutationObserver(() => {
            forceUpdate(this.hostElement);
            this.setSegments();
        });
        this.mo.observe(this.hostElement, { childList: true });
        this.setSegments();
    }
    setSegments() {
        this.segments = Array.from(this.hostElement.querySelectorAll('pn-segment'));
        this.setActiveSegment();
    }
    setActiveSegment() {
        this.segments.forEach(segmentEl => {
            if (this.value === segmentEl.value)
                segmentEl.setAttribute('selected', 'true');
            else
                segmentEl.removeAttribute('selected');
        });
        this.rerender();
    }
    rerender() {
        requestAnimationFrame(() => {
            this.calcHighlight();
            this.scrollArrowRender();
        });
    }
    /*---------------------------------------HIGHLIGHT LOGIC-------------------------------------------*/
    calcHighlight(element, hover) {
        const chip = hover ? this.hoverBg : this.activeBg;
        requestAnimationFrame(() => {
            const el = element || this.segments.find(({ value }) => value === this.value);
            const elSegment = el?.closest('pn-segment');
            if (!elSegment)
                return;
            const elRect = elSegment.getBoundingClientRect();
            const { left: hostLeft } = this.segmentContainer.getBoundingClientRect();
            const { left: segmentLeft, height: segmentHeight, width: segmentWidth } = elRect;
            const offset = segmentLeft - hostLeft + this.segmentContainer.scrollLeft;
            chip.style.setProperty('transform', `translate(${offset}px, -50%`);
            chip.style.setProperty('width', `${segmentWidth}px`);
            chip.style.setProperty('height', `${segmentHeight}px`);
            el.disabled ? (chip.dataset.disabled = '') : delete chip.dataset.disabled;
        });
    }
    /*---------------------------------------/HIGHLIGHT LOGIC-------------------------------------------*/
    /*---------------------------------------SCROLL ARROW LOGIC-------------------------------------------*/
    scrollArrowRender() {
        if (this.segmentContainer.scrollWidth > this.segmentContainer.clientWidth) {
            this.showScrollArrows = true;
            if (!this.scrollRegistered) {
                this.segmentContainer.addEventListener('scroll', this.scrollArrowRender.bind(this));
                this.scrollRegistered = true;
            }
            const amountScrolled = Math.round(this.segmentContainer.scrollWidth - this.segmentContainer.scrollLeft);
            const distanceToEnd = amountScrolled - this.segmentContainer.clientWidth;
            const distanceToStart = this.segmentContainer.scrollLeft;
            this.showLeftArrow = distanceToStart > 0;
            this.showRightArrow = distanceToEnd > 0;
            return;
        }
        this.showLeftArrow = false;
        this.showRightArrow = false;
        this.showScrollArrows = false;
    }
    scroll(val) {
        let amount = this.segmentContainer.scrollLeft + val;
        this.segmentContainer.scroll({
            left: amount,
            behavior: 'smooth',
        });
    }
    scrollArrowClasses() {
        const list = ['pn-sc-arrows'];
        if (this.showLeftArrow)
            list.push('pn-sc-left-visible');
        if (this.showRightArrow)
            list.push('pn-sc-right-visible');
        return list.join(' ');
    }
    /*---------------------------------------/SCROLL ARROW LOGIC-------------------------------------------*/
    render() {
        return (h(Host, { key: '4ff48c9a0556397894d55f7d3dc0a266349ef8fc' }, h("div", { key: '82ef8456eda4724b55705f9a662577eb172df89d', class: "pn-segmented-control", ref: el => (this.segmentContainer = el) }, h("slot", { key: '9b2949cf6e7976795543f6f8a67c126bee02e59d' }), h("div", { key: '42ab10791de502f48aac3a16766425b435c1c52e', class: "pn-sc-bg", "data-active": true, ref: el => (this.activeBg = el) }), h("div", { key: '24060bf183aabe485b7ff66bbad9b44a7704df12', class: "pn-sc-bg", "data-hover": true, ref: el => (this.hoverBg = el) })), h("div", { key: '31790d3f9fccd0c4242b5584ba2ff6ee32df4297', class: this.scrollArrowClasses(), hidden: !this.showScrollArrows }, h("button", { key: '8ffa7498550bc0f052b77f5297b349b84efbccb8', "aria-label": "Left", class: "pn-sc-arrow pn-sc-arrow-left", onClick: () => this.scroll(-120), tabindex: "-1" }, h("pn-icon", { key: '89d4ee843ade39e7264e08c31ad83c2dd32f7931', icon: arrow_left })), h("button", { key: '8f1707b0e2debb84451210d03187b51eba3f2897', "aria-label": "Right", class: "pn-sc-arrow pn-sc-arrow-right", onClick: () => this.scroll(120), tabindex: "-1" }, h("pn-icon", { key: '4fa0fcd57eb268e3c9cd9e42f5d4e84b433fafee', icon: arrow_right })))));
    }
    static get is() { return "pn-segmented-control"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-segmented-control.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-segmented-control.css"]
        };
    }
    static get properties() {
        return {
            "name": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": true,
                "optional": false,
                "docs": {
                    "tags": [{
                            "name": "deprecated",
                            "text": "Set the name in the nested `pn-segment` components."
                        }],
                    "text": "This is the name of the radio buttons inside the controller."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "name"
            },
            "value": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Currently active segment value."
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "attribute": "value"
            }
        };
    }
    static get states() {
        return {
            "showScrollArrows": {},
            "showLeftArrow": {},
            "showRightArrow": {}
        };
    }
    static get elementRef() { return "hostElement"; }
    static get watchers() {
        return [{
                "propName": "value",
                "methodName": "valueHandler"
            }];
    }
    static get listeners() {
        return [{
                "name": "change",
                "method": "changeHandler",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "resize",
                "method": "handleResize",
                "target": "window",
                "capture": false,
                "passive": true
            }, {
                "name": "segmentHover",
                "method": "handleHover",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
