<script>
    $(document).ready(() => {
        $.fn.editable.defaults.mode = 'inline';
        $.fn.editable.defaults.showbuttons = false;
        $.fn.editable.defaults.highlight = "rgb(170, 255, 128)";

        const systemOptions = {
            {% for id,name in dsystems %}
            "{{ id }}": "{{ name }}",
            {% endfor %}
        };

        $('.editable-system').editable({
            source: systemOptions,
            display: function(value, response) {
                $(this).text(response.newValueDisplay);
            },
            success: function(response, newValue) {
                $(this).attr('data-sort', response.newValueDisplay);
                showToast('Delivery system updated successfully');
            },
            validate: function(value) {
                if (value === null || value === '') {
                    return 'Delivery system is required';
                }
            }
        });

        const statusOptions = {
            {% for code,name in status %}
            "{{ code }}": "{{ name }}",
            {% endfor %}
        };

        $('.editable-status').editable({
            source: statusOptions,
            display: function(value, sourceData) {
                $(this).text(statusOptions[value]);
            },
            success: function(response, newValue) {
                $(this).attr('data-sort', newValue);
                $(this).text(statusOptions[newValue]);
                showToast('Status updated successfully');
            },
            validate: function(value) {
                if (value === null || value === '') {
                    return 'Status is required';
                }
            }
        });

        $('.editable-paid').editable({
            display: function(value, response) {
                const formatted = parseFloat(value).toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
                const row = $(this).closest('tr');
                const paidCell = row.find('.editable-paid');
                const totalCost = parseFloat(paidCell.data('totalcost') || '0');
                const deposit = parseFloat(paidCell.data('deposit') || '0');

                const formattedTotalCost = totalCost.toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });

                const boldElement = document.createElement('b');
                boldElement.textContent = formatted + ' / ' + formattedTotalCost + ' ISK';

                const fragment = document.createDocumentFragment();
                fragment.appendChild(boldElement);

                if (deposit > parseFloat(value)) {
                    const brElement = document.createElement('br');
                    const smallElement = document.createElement('small');
                    smallElement.className = 'text-warning';
                    smallElement.textContent = '(Deposit: ' + deposit.toLocaleString(undefined, {
                        minimumFractionDigits: 2,
                        maximumFractionDigits: 2
                    }) + ' ISK)';
                    fragment.appendChild(brElement);
                    fragment.appendChild(smallElement);
                }

                paidCell.empty();
                paidCell[0].appendChild(fragment);
            },
            success: function(response, newValue) {
                $(this).attr('data-sort', newValue);
                showToast('Payment updated successfully');
            },
            validate: function(value) {
                if (value === null || value === '' || isNaN(parseFloat(value))) {
                    return 'Valid payment amount is required';
                }
                if (parseFloat(value) < 0) {
                    return 'Negative payment not allowed';
                }
            }
        });

        $('.editable-estimated-date').editable({
            placeholder: '',
            display: function(value, response) {
                if (value && value.trim() !== '') {
                    $(this).text(value);
                    $(this).attr('data-sort', value);
                } else {
                    const span = document.createElement('span');
                    span.className = 'text-muted';
                    span.textContent = '-';
                    $(this).empty();
                    this.appendChild(span);
                    $(this).attr('data-sort', '');
                }
            },
            success: function(response, newValue) {
                if (response && response.newValue) {
                    $(this).text(response.newValue);
                    $(this).attr('data-sort', response.newValue);
                }
                showToast('Estimated delivery date updated successfully');
            }
        });
    });
</script>
