(function() {
    function addNoteRow(container, widgetName, timestamp, content) {
        var row = document.createElement('div');
        row.className = 'task-note-row row mb-2 align-items-start';
        row.innerHTML =
            '<div class="col-md-3">' +
                '<input type="hidden" name="' + widgetName + '_timestamps" value="' + timestamp + '">' +
            '</div>' +
            '<div class="col-md-7">' +
                '<textarea name="' + widgetName + '_contents" class="form-control" rows="2">' + (content || '') + '</textarea>' +
            '</div>' +
            '<div class="col-md-2">' +
                '<button type="button" class="btn btn-sm btn-outline-danger remove-note">&times;</button>' +
            '</div>';
        container.appendChild(row);
    }

    document.addEventListener('click', function(e) {
        var addBtn = e.target.closest('.add-note');
        if (addBtn) {
            e.preventDefault();
            var container = document.getElementById('task-notes-container');
            var now = Math.floor(Date.now() / 1000);
            var widgetName = addBtn.getAttribute('data-widget-name');
            addNoteRow(container, widgetName, String(now), '');
        }
    });

    document.addEventListener('click', function(e) {
        var removeBtn = e.target.closest('.remove-note');
        if (removeBtn) {
            e.preventDefault();
            removeBtn.closest('.task-note-row').remove();
        }
    });
})();
