<style>
    .material-selection-with-price {
        display: grid;
        grid-template-columns: minmax(0, 1fr) 180px;
        gap: 12px;
        align-items: end;
        width: 100%;
    }
    .material-order-price {
        display: flex;
        align-items: stretch;
        min-width: 0;
    }
    .material-order-price label {
        display: flex;
        align-items: center;
        margin: 0;
        padding: 0 9px;
        color: #607089;
        background: #f4f7fb;
        border: 1px solid #dce3ef;
        border-right: 0;
        border-radius: 4px 0 0 4px;
        font-size: 12px;
        font-weight: 600;
        line-height: 1.2;
        text-transform: none;
        white-space: nowrap;
    }
    .material-order-price .form-control {
        min-width: 0;
        min-height: 45px;
        border-radius: 0 4px 4px 0;
    }
    @media (max-width: 767px) {
        .material-selection-with-price { grid-template-columns: 1fr; }
    }
</style>
<script type="text/javascript">
(function () {
    'use strict';

    function numberValue(element) {
        return element ? (Number(element.value) || 0) : 0;
    }

    function normalizedText(value) {
        return (value || '').replace(/\s+/g, ' ').trim();
    }

    function nativeProductSelect(element) {
        if (!element) return null;
        if (element.tagName === 'SELECT') return element;
        return element.querySelector('select.curtain-product-select, select');
    }

    function unitPriceClass(select) {
        if (select.classList.contains('window-fabric-product')) return 'window-fabric-unit-price';
        if (select.classList.contains('window-netting-product')) return 'window-netting-unit-price';
        if (select.classList.contains('door-detail-product')) return 'door-unit-price';
        if (select.classList.contains('bedding-product')) return 'bedding-unit-price';
        if (select.classList.contains('under-cover-product')) return 'under-cover-unit-price';
        return '';
    }

    function installUnitPriceInput(select, occurrence) {
        if (!select || !select.name || select.closest('.material-selection-with-price')) return;
        var priceClass = unitPriceClass(select);
        if (!priceClass) return;

        var priceName = select.name.replace('_product_id[]', '_unit_price[]');
        var priceKey = priceName.replace('[]', '');
        var snapshots = window.tailoringOrderMaterialPrices || {};
        var snapshot = snapshots[priceKey]
            && snapshots[priceKey][occurrence] !== undefined
            && snapshots[priceKey][occurrence] !== null
            ? snapshots[priceKey][occurrence]
            : '';
        var picker = select.closest('.bootstrap-select');
        var visibleControl = picker || select;
        var parent = visibleControl.parentNode;
        var container = document.createElement('div');
        var priceField = document.createElement('div');
        var label = document.createElement('label');
        var input = document.createElement('input');

        container.className = 'material-selection-with-price';
        priceField.className = 'material-order-price';
        label.textContent = @json(trans('file.Order Price per Meter'));
        input.type = 'number';
        input.name = priceName;
        input.min = '0';
        input.step = '0.01';
        input.value = snapshot;
        input.className = 'form-control material-unit-price ' + priceClass;
        if (select.classList.contains('window-detail-input')) input.classList.add('window-detail-input');
        if (select.classList.contains('door-detail-input')) input.classList.add('door-detail-input');
        if (select.classList.contains('bedding-detail-input')) input.classList.add('bedding-detail-input');
        if (select.classList.contains('under-cover-input')) input.classList.add('under-cover-input');

        parent.insertBefore(container, visibleControl);
        container.appendChild(visibleControl);
        priceField.appendChild(label);
        priceField.appendChild(input);
        container.appendChild(priceField);
    }

    var priceOccurrences = {};
    document.querySelectorAll('select.curtain-product-select').forEach(function (select) {
        var key = select.name || '';
        var occurrence = priceOccurrences[key] || 0;
        installUnitPriceInput(select, occurrence);
        priceOccurrences[key] = occurrence + 1;
    });

    function restorePickerSelection(element) {
        var select = nativeProductSelect(element);
        if (!select || !select.options) return null;

        if (select.selectedIndex >= 0 && select.value) {
            return select.options[select.selectedIndex];
        }

        var picker = select.closest('.bootstrap-select');
        var display = picker ? picker.querySelector('.filter-option-inner-inner, .filter-option') : null;
        var displayedText = normalizedText(display ? display.textContent : '');
        if (!displayedText) return null;

        var displayedCode = normalizedText(displayedText.split('—')[0]);
        for (var index = 0; index < select.options.length; index += 1) {
            var option = select.options[index];
            if (!option.value) continue;

            var optionText = normalizedText(option.textContent);
            var optionCode = normalizedText(optionText.split('—')[0]);
            if (optionText === displayedText || (displayedCode && optionCode === displayedCode)) {
                option.selected = true;
                select.selectedIndex = index;
                return option;
            }
        }

        return null;
    }

    function productListPrice(element) {
        var option = restorePickerSelection(element);
        return option ? (Number(option.getAttribute('data-price')) || 0) : 0;
    }

    function rowUnitPrice(row, priceSelector, productSelector) {
        var priceInput = row.querySelector(priceSelector);
        if (priceInput && priceInput.value !== '') {
            return numberValue(priceInput);
        }
        return productListPrice(row.querySelector(productSelector));
    }

    function priceInputForProduct(select) {
        var row = select ? select.closest('tr') : null;
        if (!row) return null;
        if (select.classList.contains('window-fabric-product')) return row.querySelector('.window-fabric-unit-price');
        if (select.classList.contains('window-netting-product')) return row.querySelector('.window-netting-unit-price');
        if (select.classList.contains('door-detail-product')) return row.querySelector('.door-unit-price');
        if (select.classList.contains('bedding-product')) return row.querySelector('.bedding-unit-price');
        if (select.classList.contains('under-cover-product')) return row.querySelector('.under-cover-unit-price');
        return null;
    }

    function fillPriceFromProduct(element, overwrite) {
        var select = nativeProductSelect(element);
        if (!select) return;
        var priceInput = priceInputForProduct(select);
        if (!priceInput || (!overwrite && priceInput.value !== '')) return;
        priceInput.value = select.value ? productListPrice(select).toFixed(2) : '';
    }

    function setMoneyValue(selector, value) {
        var element = document.querySelector(selector);
        if (element) element.value = value.toFixed(2);
    }

    function selectedTailorRates() {
        var select = document.querySelector('select#curtain_tailor');
        var option = select && select.selectedIndex >= 0 ? select.options[select.selectedIndex] : null;
        if (!option || !option.value) return null;
        return {
            fabric: Number(option.getAttribute('data-fabric-meter-fee')) || 0,
            netting: Number(option.getAttribute('data-netting-meter-fee')) || 0,
            mattress: Number(option.getAttribute('data-mattress-fee')) || 0,
            pillow: Number(option.getAttribute('data-pillow-fee')) || 0,
            bolster: Number(option.getAttribute('data-bolster-fee')) || 0,
            method: option.getAttribute('data-under-cover-fee-method') || 'corresponding',
            mattressUnderCover: Number(option.getAttribute('data-mattress-under-cover-fee')) || 0,
            pillowUnderCover: Number(option.getAttribute('data-pillow-under-cover-fee')) || 0,
            bolsterUnderCover: Number(option.getAttribute('data-bolster-under-cover-fee')) || 0
        };
    }

    function refreshTailorCost() {
        var rates = selectedTailorRates();
        if (!rates) {
            setMoneyValue('#tailor_cost', 0);
            return;
        }

        var fabricMeters = 0;
        var nettingMeters = 0;
        var cost = 0;
        document.querySelectorAll('#window-detail-table tbody tr').forEach(function (row) {
            var windowCount = numberValue(row.querySelector('.window-detail-count'));
            fabricMeters += windowCount * numberValue(row.querySelector('.window-detail-panel-count')) * numberValue(row.querySelector('.window-detail-panel-meter'));
            nettingMeters += windowCount * numberValue(row.querySelector('.window-detail-middle-netting'));
        });
        document.querySelectorAll('#door-detail-table tbody tr').forEach(function (row) {
            var meterage = numberValue(row.querySelector('.door-detail-meterage'));
            var materialType = row.querySelector('[name="door_detail_material_type[]"]');
            if (materialType && materialType.value === 'netting') nettingMeters += meterage;
            else fabricMeters += meterage;
        });

        cost += fabricMeters * rates.fabric;
        cost += nettingMeters * rates.netting;
        document.querySelectorAll('.bedding-detail-row').forEach(function (row) {
            var table = row.closest('.bedding-detail-table');
            var type = table ? table.getAttribute('data-type') : '';
            if (!type || rates[type] === undefined) return;
            cost += numberValue(row.querySelector('.bedding-detail-count')) * rates[type];

            var underCover = row.querySelector('.toggle-under-cover');
            if (underCover && underCover.checked && rates.method === 'separate') {
                var separateKey = type + 'UnderCover';
                var underCoverRate = rates[separateKey];
                cost += numberValue(row.querySelector('.under-cover-count')) * underCoverRate;
            }
        });

        setMoneyValue('#tailor_cost', cost);
    }

    function refreshTailoringOrderTotals() {
        var materialTotal = 0;

        document.querySelectorAll('#window-detail-table tbody tr').forEach(function (row) {
            var windowCount = numberValue(row.querySelector('.window-detail-count'));
            var panelCount = numberValue(row.querySelector('.window-detail-panel-count'));
            var panelMeter = numberValue(row.querySelector('.window-detail-panel-meter'));
            var middleNetting = numberValue(row.querySelector('.window-detail-middle-netting'));

            materialTotal += windowCount * panelCount * panelMeter * rowUnitPrice(row, '.window-fabric-unit-price', '.window-fabric-product');
            materialTotal += windowCount * middleNetting * rowUnitPrice(row, '.window-netting-unit-price', '.window-netting-product');
        });

        document.querySelectorAll('#door-detail-table tbody tr').forEach(function (row) {
            materialTotal += numberValue(row.querySelector('.door-detail-meterage')) * rowUnitPrice(row, '.door-unit-price', '.door-detail-product');
        });

        document.querySelectorAll('.bedding-detail-row').forEach(function (row) {
            materialTotal += numberValue(row.querySelector('.bedding-detail-meterage')) * rowUnitPrice(row, '.bedding-unit-price', '.bedding-product');
            var underCover = row.querySelector('.toggle-under-cover');
            if (underCover && underCover.checked) {
                materialTotal += numberValue(row.querySelector('.under-cover-meterage')) * rowUnitPrice(row, '.under-cover-unit-price', '.under-cover-product');
            }
        });

        var totalPrice = materialTotal + numberValue(document.querySelector('#service_charge'));
        var paidAmount = numberValue(document.querySelector('#paid_amount'));

        setMoneyValue('#material_total', materialTotal);
        setMoneyValue('#total_price', totalPrice);
        setMoneyValue('#due', Math.max(totalPrice - paidAmount, 0));
        refreshTailorCost();
    }

    function isCalculatorInput(target) {
        return target && target.matches('.curtain-product-select, #curtain_tailor, #service_charge, #paid_amount, .window-detail-input, .door-detail-input, .bedding-detail-input, .under-cover-input, .toggle-under-cover');
    }

    document.addEventListener('input', function (event) {
        if (isCalculatorInput(event.target)) refreshTailoringOrderTotals();
    });
    document.addEventListener('change', function (event) {
        var changedSelect = nativeProductSelect(event.target);
        if (changedSelect && changedSelect.classList.contains('curtain-product-select')) {
            fillPriceFromProduct(changedSelect, true);
        }
        if (isCalculatorInput(event.target)) refreshTailoringOrderTotals();
    });

    window.refreshTailoringOrderTotals = refreshTailoringOrderTotals;
    window.refreshTailorCost = refreshTailorCost;
    document.querySelectorAll('select.curtain-product-select').forEach(function (select) {
        fillPriceFromProduct(select, false);
    });
    refreshTailoringOrderTotals();
}());
</script>
