jQuery(document).ready(function($) {
    function updateTotals() {
        var totalDebit = 0, totalCredit = 0;
        $('#od-lines-tbody .od-line-row').each(function() {
            totalDebit += parseFloat($(this).find('.line-debit').val()) || 0;
            totalCredit += parseFloat($(this).find('.line-credit').val()) || 0;
        });
        $('#total-debit').text(totalDebit.toFixed(2));
        $('#total-credit').text(totalCredit.toFixed(2));
        var diff = Math.abs(totalDebit - totalCredit);
        $('#difference').text(diff.toFixed(2)).css('color', diff < 0.01 ? '#00a32a' : '#d63638');
    }

    function serializeLines() {
        var lines = [];
        $('#od-lines-tbody .od-line-row').each(function() {
            var compte = $(this).find('.line-compte').val().trim();
            var debit = parseFloat($(this).find('.line-debit').val()) || 0;
            var credit = parseFloat($(this).find('.line-credit').val()) || 0;
            if (compte && (debit > 0 || credit > 0)) {
                lines.push({
                    compte: compte,
                    libelle: $(this).find('.line-libelle').val().trim(),
                    debit: debit,
                    credit: credit
                });
            }
        });
        $('#lines_json').val(JSON.stringify(lines));
    }

    $('#add-line').on('click', function() {
        var newRow = $('#od-lines-tbody .od-line-row:first').clone();
        newRow.find('input').val('');
        newRow.find('.line-debit, .line-credit').val('0');
        $('#od-lines-tbody').append(newRow);
    });

    $(document).on('click', '.remove-line', function() {
        if ($('#od-lines-tbody .od-line-row').length > 1) {
            $(this).closest('.od-line-row').remove();
            updateTotals();
        }
    });

    $(document).on('input', '.line-debit, .line-credit', function() {
        updateTotals();
    });

    $('#comptaflow-uk-manual-od-form').on('submit', function() {
        serializeLines();
    });
});