import { r as registerInstance, c as createEvent, g as getElement, h, d as Host } from './index-c0a4d8bd.js';
import { d as debounce } from './index-1190bec4.js';

const pnDropdownChoiceAddsRowCss = "pn-button-dropdown .pn-button-dropdown>pn-button>.pn-button{min-height:initial}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}@media screen and (max-width: 767px){.sr-only-mobile{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}}pn-dropdown-choice-adds-row{display:block;width:80rem}pn-dropdown-choice-adds-row .pn-row-select-dropdown{width:50%;margin-bottom:1rem}@media only screen and (max-width: 640px){pn-dropdown-choice-adds-row .pn-row-select-dropdown{width:100%}}pn-dropdown-choice-adds-row .pn-dropdown-choice-table{width:100%;border-spacing:0rem;border:none !important}pn-dropdown-choice-adds-row .pn-dropdown-choice-table thead th{text-align:left;padding:1rem 0.5rem}pn-dropdown-choice-adds-row .pn-dropdown-choice-table thead th label{color:#5e554a;font-size:1.4rem;font-weight:400}pn-dropdown-choice-adds-row .pn-dropdown-choice-table .generated-table-row{display:flex;margin-bottom:2rem}pn-dropdown-choice-adds-row .pn-dropdown-choice-table .table-header{display:flex;margin:2rem 0 3rem 0;font-weight:500}pn-dropdown-choice-adds-row .pn-dropdown-choice-table .table-header-dropdown,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .table-header-column,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .table-header-name,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .tr-dropdown,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .tr-column,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .tr-name{padding-right:0.5rem;width:35%}pn-dropdown-choice-adds-row .pn-dropdown-choice-table .table-header-dropdown pn-select,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .table-header-column pn-select,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .table-header-name pn-select,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .tr-dropdown pn-select,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .tr-column pn-select,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .tr-name pn-select{width:95%}pn-dropdown-choice-adds-row .pn-dropdown-choice-table .table-header-input,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .tr-input{width:15%}pn-dropdown-choice-adds-row .pn-dropdown-choice-table .table-header-input pn-input,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .tr-input pn-input{width:100%}pn-dropdown-choice-adds-row .pn-dropdown-choice-table .table-header-delete,pn-dropdown-choice-adds-row .pn-dropdown-choice-table .tr-delete{margin:1rem;width:15%}pn-dropdown-choice-adds-row .pn-dropdown-choice-table tbody td{padding:0.5rem}pn-dropdown-choice-adds-row .pn-dropdown-choice-table tbody tr:nth-child(even){background-color:#effbff}pn-dropdown-choice-adds-row .pn-dropdown-choice-table tbody .tr-delete{text-align:center}pn-dropdown-choice-adds-row .pn-dropdown-choice-table tfoot td small{color:#a70707;vertical-align:middle}pn-dropdown-choice-adds-row .pn-dropdown-choice-table tfoot td pn-icon{margin-right:0.25em;vertical-align:middle}";
const PnDropdownChoiceAddsRowStyle0 = pnDropdownChoiceAddsRowCss;

const pnDropdownChoiceAddsRow = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.rowvalues = createEvent(this, "rowvalues", 7);
        this.dropdownData = null;
        this.languageCode = null;
        this.addRowDropdownName = '';
        this.addRowDropdownPlaceholder = '';
        this.addRowDropdownLabel = '';
        this.rowNameLabel = '';
        this.rowHasDropdown = true;
        this.rowDropdownLabel = '';
        this.rowDropdownPlaceholder = '';
        this.rowInputLabel = '';
        this.rowDeleteButtonText = '';
        this.totalInputLimit = 0;
        this.minimumInputLimit = 0;
        this.inputLimitWarning = null;
        this.inputEmptyWarning = null;
        this.inputLowError = null;
        this.dropdownEmptyWarning = null;
        this.nextRowIndex = null;
        this.rowSelectDropdownArr = null;
        this.formValue = null;
    }
    get hostElement() { return getElement(this); }
    pnRowSelectDropdown = null;
    tableHead = null;
    tableBody = null;
    _dropdownData;
    rowvalues;
    dropdownDataWatcher() {
        if (typeof this.dropdownData === 'string') {
            this._dropdownData = JSON.parse(this.dropdownData);
        }
        else {
            this._dropdownData = this.dropdownData;
        }
    }
    componentWillLoad() {
        this.dropdownDataWatcher();
    }
    componentDidLoad() {
        this.setInitialValues();
        this.addEventHandlers();
    }
    addEventHandlers() {
        this.pnRowSelectDropdown.addEventListener('change', debounce(this.addRowElement.bind(this), 500));
    }
    setInitialValues() {
        this.nextRowIndex = 0;
        this.setRowSelectDropdownArr();
    }
    setRowSelectDropdownArr() {
        this.rowSelectDropdownArr = [];
        this._dropdownData.forEach(element => {
            this.rowSelectDropdownArr.push(element.label);
        });
    }
    formRowEvent = e => {
        const debouncedAddValue = debounce(this.updateHiddenFieldValue.bind(this), 500);
        if (e.target.matches('input')) {
            ['change', 'keyup'].forEach(eventName => {
                e.target.addEventListener(eventName, debouncedAddValue);
            });
        }
        else {
            const rowDropdown = e.target.closest('.generated-table-row')?.querySelector('pn-select');
            if (rowDropdown) {
                rowDropdown.addEventListener('change', debouncedAddValue);
            }
        }
    };
    updateHiddenFieldValue() {
        try {
            const allRows = [...this.tableBody.querySelectorAll('.generated-table-row')];
            const mainDropdown = this.hostElement.querySelector('.pn-row-select-dropdown');
            if (!mainDropdown) {
                return;
            }
            if (!allRows.length) {
                mainDropdown.setAttribute('error', `${this.dropdownEmptyWarning || "This field cannot be empty"}`);
                this.formValue = '';
                this.rowvalues.emit('');
                return;
            }
            let allRowsValid = true;
            const formValues = allRows.map(row => {
                const nameElm = row.querySelector('.tr-name');
                const dropdownElm = row.querySelector('.tr-dropdown');
                const inputElm = row.querySelector('.tr-input');
                if (!nameElm || !inputElm) {
                    allRowsValid = false;
                    return null;
                }
                const rowData = {
                    row: [
                        {
                            name: this.rowNameLabel,
                            value: nameElm.innerHTML
                        }
                    ]
                };
                if (dropdownElm && dropdownElm.querySelector('pn-select')) {
                    const pnSelect = dropdownElm.querySelector('pn-select');
                    const nativeSelect = pnSelect?.querySelector('select');
                    const dropdownSelection = nativeSelect?.value || '';
                    if (!dropdownSelection) {
                        allRowsValid = false;
                    }
                    else {
                        rowData.row.push({
                            name: this.rowDropdownLabel,
                            value: dropdownSelection
                        });
                    }
                }
                const input = inputElm.querySelector('input');
                const inputValue = parseInt(input?.value || '0', 10);
                if (inputValue > 0) {
                    rowData.row.push({
                        name: this.rowInputLabel,
                        value: inputValue.toString()
                    });
                }
                else {
                    allRowsValid = false;
                }
                return rowData;
            });
            if (!allRowsValid || !formValues.length || formValues.includes(null)) {
                this.formValue = '';
                this.rowvalues.emit('');
                return;
            }
            this.formValue = `PN-JSON|${JSON.stringify(formValues)}`;
            if (this.validateInputs()) {
                this.rowvalues.emit(this.formValue);
            }
            else {
                this.rowvalues.emit('');
            }
        }
        catch (error) {
            console.error('Error updating field value: ', error);
            this.formValue = '';
        }
    }
    addRowElement(e) {
        const selectedElement = e.target;
        const selectedValue = selectedElement?.value;
        if (!selectedValue) {
            return;
        }
        const mainDropdown = this.hostElement.querySelector('.pn-row-select-dropdown');
        mainDropdown?.removeAttribute('error');
        if (!this.tableBody) {
            console.error('tableBody is not defined.');
            return;
        }
        const newRow = document.createElement('div');
        newRow.setAttribute('index', `${this.nextRowIndex}`);
        newRow.className = 'generated-table-row';
        newRow.onclick = e => this.formRowEvent(e);
        const rowNameColumn = document.createElement('div');
        rowNameColumn.className = 'tr-name';
        rowNameColumn.innerHTML = selectedValue;
        rowNameColumn.dataset.name = selectedValue;
        newRow.appendChild(rowNameColumn);
        const selectedR = this._dropdownData?.find(item => item.label === selectedValue);
        if (selectedR?.values?.length) {
            this.rowHasDropdown = true;
            const dropdownCol = this.createDropdownColumn(selectedValue);
            newRow.appendChild(dropdownCol);
        }
        else {
            this.rowHasDropdown = false;
            const emptyDropdownCol = document.createElement('div');
            emptyDropdownCol.className = 'tr-column';
            newRow.appendChild(emptyDropdownCol);
        }
        const rowInputColumn = this.createInputColumn(selectedValue);
        newRow.appendChild(rowInputColumn);
        const deleteButton = this.createDeleteButtonColumn();
        newRow.appendChild(deleteButton);
        this.tableBody.appendChild(newRow);
        this.updateRowSelectDropdown();
        this.nextRowIndex++;
        selectedElement.value = '';
    }
    getCurrentRow(selectedValue) {
        return this.hostElement.querySelectorAll(`.tr-name[data-name='${selectedValue}'`);
    }
    createDropdownColumn(selectedValue) {
        const dropdownColumn = document.createElement('div');
        dropdownColumn.setAttribute('class', 'tr-dropdown');
        const selectedItem = this._dropdownData.find(arr => arr.label === selectedValue);
        const selectedOptionValues = [];
        const currentRow = this.getCurrentRow(selectedValue);
        currentRow.forEach(row => {
            selectedOptionValues.push(row.parentElement?.querySelector('.tr-dropdown [aria-selected=true]')?.textContent);
        });
        if (selectedItem.values.length) {
            const dropdown = document.createElement('pn-select');
            dropdown.setAttribute('name', `${selectedValue}-dropdown`);
            dropdown.setAttribute('placeholder', this.rowDropdownPlaceholder);
            dropdown.setAttribute('required', 'true');
            dropdown.setAttribute('error', '');
            const placeholder = document.createElement('option');
            placeholder.setAttribute("value", "");
            placeholder.textContent = this.rowDropdownPlaceholder;
            placeholder.selected = true;
            placeholder.disabled = true;
            dropdown.appendChild(placeholder);
            selectedItem.values.forEach(childItem => {
                const childOption = document.createElement('option');
                childOption.setAttribute("label", childItem.label);
                childOption.setAttribute("value", childItem.label);
                childOption.textContent = childItem.label;
                dropdown.appendChild(childOption);
            });
            dropdownColumn.appendChild(dropdown);
        }
        return dropdownColumn;
    }
    createInputColumn(selectedValue) {
        const inputColumn = document.createElement('div');
        inputColumn.setAttribute('class', 'tr-input');
        const inputElm = document.createElement('pn-input');
        inputElm.setAttribute('type', 'number');
        inputElm.setAttribute('name', `${selectedValue}-input`);
        if (this.totalInputLimit > 0) {
            inputElm.setAttribute('max', `${this.totalInputLimit}`);
        }
        inputElm.setAttribute('min', `${this.minimumInputLimit}`);
        inputElm.setAttribute('placeholder', `${this.minimumInputLimit}`);
        inputElm.setAttribute('error', '');
        inputColumn.appendChild(inputElm);
        return inputColumn;
    }
    createDeleteButtonColumn() {
        const buttonColumn = document.createElement('div');
        buttonColumn.setAttribute('class', 'tr-delete');
        const buttonElm = document.createElement('pn-button');
        buttonElm.onclick = e => this.deleteRow(e);
        buttonElm.setAttribute('appearance', 'warning');
        buttonElm.setAttribute('small', 'true');
        buttonElm.appendChild(document.createTextNode(this.rowDeleteButtonText));
        buttonColumn.appendChild(buttonElm);
        return buttonColumn;
    }
    updateRowSelectDropdown() {
        [].map.call(this.tableBody.querySelectorAll('.tr-name'), el => {
            const dropdownColumn = el?.parentElement?.querySelector('.tr-dropdown');
            const dropdownPlaceholder = dropdownColumn?.querySelector('.pn-select-content span')?.textContent;
            const row = {
                rowName: el?.innerHTML,
                selectedValue: dropdownColumn?.querySelector('[aria-selected=true]')?.textContent,
                placeholder: dropdownPlaceholder,
            };
            return row;
        });
        const selectOptions = this.pnRowSelectDropdown.querySelectorAll('option');
        selectOptions.forEach(elm => {
            elm.removeAttribute('selected');
        });
    }
    deleteRow(e) {
        e.preventDefault();
        this.nextRowIndex--;
        const targetElm = e.currentTarget;
        const targetRow = targetElm.closest('.generated-table-row');
        targetRow.remove();
        const allRows = [...this.tableBody.querySelectorAll('.generated-table-row')];
        allRows.map((elm, index) => {
            elm.setAttribute('index', `${index}`);
        });
        this.updateHiddenFieldValue();
        this.updateRowSelectDropdown();
    }
    validateInputs() {
        const dropdownSelections = this.tableBody.querySelectorAll('pn-select');
        const numberInputs = this.tableBody.querySelectorAll('pn-input');
        let selectionEmpty = false;
        let showWarning = false;
        if (dropdownSelections) {
            dropdownSelections.forEach(dropdownElem => {
                if (!dropdownElem) {
                    return;
                }
                const selection = dropdownElem.querySelector('select');
                const dropdownVal = selection?.value || '';
                if (dropdownVal === null || dropdownVal === "") {
                    dropdownElem.setAttribute('error', `${this.dropdownEmptyWarning || "This field cannot be empty"}`);
                    selectionEmpty = true;
                }
                else {
                    dropdownElem.setAttribute('error', '');
                }
            });
        }
        if (numberInputs) {
            numberInputs.forEach(inputElem => {
                if (inputElem) {
                    const currentNumber = inputElem.querySelector("input");
                    let currentValue = parseInt(currentNumber.value);
                    if (this.totalInputLimit < currentValue && inputElem.hasAttribute('max')) {
                        inputElem.setAttribute('error', `${this.inputLimitWarning || "Amount too high"}`);
                        showWarning = true;
                    }
                    else if (currentValue <= 0 || isNaN(currentValue)) {
                        inputElem.setAttribute('error', `${this.inputEmptyWarning || "This field cannot be empty"}`);
                        showWarning = true;
                    }
                    else {
                        inputElem.setAttribute('error', '');
                        showWarning = false;
                    }
                    if (this.minimumInputLimit > currentValue && inputElem.hasAttribute('min')) {
                        inputElem.setAttribute('error', `${this.inputLowError || "Amount too low"}`);
                        showWarning = true;
                    }
                    else if (currentValue <= 0 || isNaN(currentValue)) {
                        inputElem.setAttribute('error', `${this.inputEmptyWarning || "This field cannot be empty"}`);
                        showWarning = true;
                    }
                    else {
                        inputElem.setAttribute('error', '');
                        showWarning = false;
                    }
                }
            });
        }
        if (selectionEmpty || showWarning) {
            return false;
        }
        return true;
    }
    render() {
        return (h(Host, { key: '5a70a7d4f1f6a105a287df79562de1e00b276b15' }, h("div", { key: '47d5b7bd549f8e472e131221c9d4fc9ca0308ddc', class: "dropdown-choice-form-row" }, h("pn-select", { key: '7216476d425fb3a07544d2ea95fd71e1452094e3', ref: el => (this.pnRowSelectDropdown = el), name: this.addRowDropdownName, label: this.addRowDropdownLabel, class: "pn-row-select-dropdown", language: this.languageCode }, h("option", { key: 'a974d00186fbf37995a8580abcf1f78052bf5ea0', value: "", selected: true, disabled: true }, this.addRowDropdownPlaceholder), this.rowSelectDropdownArr?.map((value) => h("option", { label: value, value: value }, value)))), h("div", { key: 'dd06952618e12452caf8ad397166b6e60e76666d', class: "dropdown-choice-form-row" }, h("div", { key: '1663d80435cd4fa841d695a13778a8c4ed234e66', class: "pn-dropdown-choice-table" }, h("div", { key: 'c7417986ac520adf4b4ffd9ef0e4961a1aa33bb2', ref: el => (this.tableHead = el) }, this.nextRowIndex === 0 ? null : (h("div", { class: "table-header" }, h("div", { class: "table-header-name" }, h("label", null, this.rowNameLabel)), h("div", { class: "table-header-dropdown" }, h("label", null, this.rowDropdownLabel)), h("div", { class: "table-header-input" }, h("label", null, this.rowInputLabel)), h("div", { class: "table-header-delete" })))), h("div", { key: 'db9da456d23c77da5b26adf12b738b673f80c65b', ref: el => (this.tableBody = el), class: "pn-dropdown-choice-table-slot" }, h("slot", { key: 'd98c88973072f92b95f28a89b24b87ea2028fc69' }))))));
    }
    static get watchers() { return {
        "dropdownData": ["dropdownDataWatcher"]
    }; }
};
pnDropdownChoiceAddsRow.style = PnDropdownChoiceAddsRowStyle0;

export { pnDropdownChoiceAddsRow as pn_dropdown_choice_adds_row };

//# sourceMappingURL=pn-dropdown-choice-adds-row.entry.js.map