function populateFormForEdit(tableRow) {
    const unitDataString = tableRow.dataset.unit;
    if (!unitDataString) {
        console.error("No unit data found on table row.");
        return;
    }

    try {
        const unit = JSON.parse(unitDataString);
        const form = document.getElementById('unit-form');

        form.querySelector('#form-action').value = 'edit_unit';
        form.querySelector('#unit_db_id').value = unit.id;

        // Populate all fields
        // Ensure IDs in the form match the keys in 'unit' object or map them accordingly
        for (const key in unit) {
            if (unit.hasOwnProperty(key)) {
                const inputElement = form.querySelector(`#${key}`);
                if (inputElement) {
                    if (inputElement.type === 'checkbox') { // If you had checkboxes
                        inputElement.checked = !!unit[key];
                    } else {
                        inputElement.value = unit[key] !== null ? unit[key] : '';
                    }
                }
            }
        }
        // Scroll to the form for better UX
        document.getElementById('add-edit-unit-section').scrollIntoView({ behavior: 'smooth' });
        form.querySelector('h2') ? form.querySelector('h2').textContent = 'Edit Unit' : null; // If h2 is inside form
        const sectionH2 = document.querySelector('#add-edit-unit-section h2');
        if (sectionH2) sectionH2.textContent = `Edit Unit: ${unit.unit_id_display}`;


    } catch (e) {
        console.error("Error parsing unit data for edit:", e);
        alert("Could not load unit data for editing.");
    }
}

function clearUnitForm() {
    const form = document.getElementById('unit-form');
    form.reset(); // Resets all form fields to their initial values

    form.querySelector('#form-action').value = 'add_unit';
    form.querySelector('#unit_db_id').value = '';

    const sectionH2 = document.querySelector('#add-edit-unit-section h2');
    if (sectionH2) sectionH2.textContent = 'Add New Unit / Edit Unit';

    // Remove any success/error messages specific to a previous operation if they are inside the form area
}

document.addEventListener('DOMContentLoaded', function() {
    // Add any other admin-specific JS enhancements here
    // For example, live validation, dynamic field changes, etc.
});