(function () {
    'use strict';

    const config = window.KARVI_INVOICE_FORM || {};
    const vatRate = Number(config.vatRate || 19);
    const hasOptionalPrinter = Boolean(config.hasOptionalPrinter);
    const form = document.getElementById('invoiceContractForm');
    const tbody = document.getElementById('invoiceLineItemsBody');
    const optionalCheckbox = document.getElementById('optional_printer');
    const optionalPriceInput = document.getElementById('optional_printer_price');
    const discountInput = document.getElementById('invoiceDiscount');
    const addLineBtn = document.getElementById('invoiceAddLineBtn');
    const selectServicesBtn = document.getElementById('invoiceSelectServicesBtn');
    const servicesModal = document.getElementById('invoiceServicesModal');
    const displaysToggle = document.getElementById('invoiceDisplaysToggle');
    const displaysList = document.getElementById('invoiceDisplaysList');

    if (!form || !tbody) {
        return;
    }

    function parseMoney(value) {
        const normalized = String(value ?? '')
            .replace(/\s/g, '')
            .replace(/€/g, '')
            .replace(/EUR/gi, '')
            .trim();

        if (!normalized) {
            return 0;
        }

        if (normalized.includes(',')) {
            return Number(normalized.replace(/\./g, '').replace(',', '.')) || 0;
        }

        return Number(normalized) || 0;
    }

    function formatMoney(amount) {
        return new Intl.NumberFormat('de-DE', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
        }).format(amount) + ' €';
    }

    function rowTemplate(description, price) {
        const row = document.createElement('tr');
        row.className = 'invoice-line-row';
        row.innerHTML = ''
            + '<td><input type="text" name="line_description[]" class="form-input invoice-line-description" required></td>'
            + '<td><input type="number" name="line_quantity[]" class="form-input invoice-line-qty" min="1" value="1" required></td>'
            + '<td><input type="text" name="line_unit_price[]" class="form-input invoice-line-price" required></td>'
            + '<td class="invoice-line-total-cell"><span class="invoice-line-total">0,00 €</span></td>'
            + '<td><button type="button" class="invoice-line-remove btn-ghost" title="' + (config.labels?.remove_line || 'Remove') + '">'
            + '<span class="material-symbols-rounded">close</span></button></td>';

        const descriptionInput = row.querySelector('.invoice-line-description');
        const priceInput = row.querySelector('.invoice-line-price');
        if (descriptionInput) {
            descriptionInput.value = description || '';
        }
        if (priceInput) {
            priceInput.value = price || '0,00 €';
        }

        return row;
    }

    function getEmptyRow() {
        return document.getElementById('invoiceEmptyRow');
    }

    function removeEmptyRow() {
        const emptyRow = getEmptyRow();
        if (emptyRow) {
            emptyRow.remove();
        }
    }

    function ensureEmptyRow() {
        if (tbody.querySelector('.invoice-line-row')) {
            return;
        }

        if (getEmptyRow()) {
            return;
        }

        const row = document.createElement('tr');
        row.id = 'invoiceEmptyRow';
        row.className = 'invoice-empty-row';
        row.innerHTML = '<td colspan="5" class="text-center text-sm text-karvi-500 py-6">'
            + (config.labels?.no_line_items || 'No line items yet.')
            + '</td>';
        tbody.appendChild(row);
    }

    function updateRemoveButtons() {
        const rows = tbody.querySelectorAll('.invoice-line-row');
        rows.forEach(function (row) {
            const removeBtn = row.querySelector('.invoice-line-remove');
            if (!removeBtn) {
                return;
            }
            removeBtn.hidden = rows.length <= 1;
        });
    }

    function getOptionalPrice() {
        if (!optionalPriceInput) {
            return Number(config.optionalPrice || 0);
        }

        return parseMoney(optionalPriceInput.value || config.optionalPrice || 0);
    }

    function recalculate() {
        let subtotal = 0;

        tbody.querySelectorAll('.invoice-line-row').forEach(function (row) {
            const qty = Math.max(1, Number(row.querySelector('.invoice-line-qty')?.value || 1));
            const unitPrice = parseMoney(row.querySelector('.invoice-line-price')?.value || 0);
            const lineTotal = qty * unitPrice;
            subtotal += lineTotal;

            const totalEl = row.querySelector('.invoice-line-total');
            if (totalEl) {
                totalEl.textContent = formatMoney(lineTotal);
            }
        });

        if (hasOptionalPrinter && optionalCheckbox && optionalCheckbox.checked) {
            subtotal += getOptionalPrice();
        }

        const discount = Math.max(0, parseMoney(discountInput?.value || 0));
        const net = Math.max(0, subtotal - discount);
        const vat = net * (vatRate / 100);
        const total = net + vat;

        const subtotalEl = document.getElementById('invoiceSubtotal');
        const vatEl = document.getElementById('invoiceVat');
        const netEl = document.getElementById('invoiceNet');
        const totalEl = document.getElementById('invoiceTotal');

        if (subtotalEl) subtotalEl.textContent = formatMoney(subtotal);
        if (vatEl) vatEl.textContent = formatMoney(vat);
        if (netEl) netEl.textContent = formatMoney(net);
        if (totalEl) totalEl.textContent = formatMoney(total);
    }

    function bindRow(row) {
        row.querySelectorAll('input').forEach(function (input) {
            input.addEventListener('input', recalculate);
            input.addEventListener('change', recalculate);
        });

        const removeBtn = row.querySelector('.invoice-line-remove');
        if (removeBtn) {
            removeBtn.addEventListener('click', function () {
                row.remove();
                if (!tbody.querySelector('.invoice-line-row')) {
                    ensureEmptyRow();
                }
                updateRemoveButtons();
                recalculate();
            });
        }
    }

    function addLine(description, price) {
        removeEmptyRow();
        const row = rowTemplate(description || '', price || '0,00 €');
        tbody.appendChild(row);
        bindRow(row);
        updateRemoveButtons();
        recalculate();
        return row;
    }

    function openServicesModal() {
        if (!servicesModal) {
            return;
        }
        servicesModal.classList.remove('hidden');
        document.body.classList.add('admin-modal-open');
    }

    function closeServicesModal() {
        if (!servicesModal) {
            return;
        }
        servicesModal.classList.add('hidden');
        document.body.classList.remove('admin-modal-open');
    }

    tbody.querySelectorAll('.invoice-line-row').forEach(bindRow);
    updateRemoveButtons();

    if (optionalCheckbox) {
        optionalCheckbox.addEventListener('change', recalculate);
    }

    if (optionalPriceInput) {
        optionalPriceInput.addEventListener('input', recalculate);
        optionalPriceInput.addEventListener('change', recalculate);
        optionalPriceInput.addEventListener('click', function (event) {
            event.stopPropagation();
        });
    }

    if (discountInput) {
        discountInput.addEventListener('input', recalculate);
        discountInput.addEventListener('change', recalculate);
    }

    if (addLineBtn) {
        addLineBtn.addEventListener('click', function () {
            const row = addLine('', '0,00 €');
            row.querySelector('.invoice-line-description')?.focus();
        });
    }

    if (selectServicesBtn) {
        selectServicesBtn.addEventListener('click', openServicesModal);
    }

    if (servicesModal) {
        servicesModal.querySelectorAll('[data-services-modal-close]').forEach(function (el) {
            el.addEventListener('click', closeServicesModal);
        });

        servicesModal.querySelectorAll('.invoice-service-add-btn').forEach(function (button) {
            button.addEventListener('click', function () {
                const title = button.getAttribute('data-service-title') || '';
                const price = button.getAttribute('data-service-price') || '0,00 €';
                addLine(title, price);
            });
        });

        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape' && !servicesModal.classList.contains('hidden')) {
                closeServicesModal();
            }
        });
    }

    if (displaysToggle && displaysList) {
        displaysToggle.addEventListener('click', function () {
            const collapsed = displaysList.classList.toggle('is-collapsed');
            displaysToggle.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
            const icon = displaysToggle.querySelector('.invoice-service-group-icon');
            if (icon) {
                icon.textContent = collapsed ? 'expand_more' : 'expand_less';
            }
        });
    }

    function resetLineItemsToDefaults(lineItems) {
        tbody.querySelectorAll('.invoice-line-row').forEach(function (row) {
            row.remove();
        });
        removeEmptyRow();

        if (!Array.isArray(lineItems) || lineItems.length === 0) {
            ensureEmptyRow();
            recalculate();
            return;
        }

        lineItems.forEach(function (item) {
            addLine(item.description || '', item.price || '0,00 €');
        });
    }

    const posTypeInputs = form.querySelectorAll('input[name="pos_contract_type"]');
    posTypeInputs.forEach(function (input) {
        input.addEventListener('change', function () {
            const typeDefaults = config.posTypeDefaults?.[input.value];
            if (typeDefaults?.line_items) {
                resetLineItemsToDefaults(typeDefaults.line_items);
            }
        });
    });

    form.addEventListener('submit', function () {
        tbody.querySelectorAll('.invoice-line-row').forEach(function (row) {
            const description = row.querySelector('.invoice-line-description');
            const priceInput = row.querySelector('.invoice-line-price');
            if (description && description.value.trim() === '') {
                row.remove();
                return;
            }
            if (priceInput) {
                priceInput.value = formatMoney(parseMoney(priceInput.value));
            }
        });

        if (optionalPriceInput) {
            optionalPriceInput.value = formatMoney(parseMoney(optionalPriceInput.value));
        }
    });

    recalculate();
})();
