document.addEventListener('DOMContentLoaded', function() {
    // Initialize Select2
    $('.select2').select2({
        width: '100%',
        placeholder: 'Select an option',
        allowClear: true
    });

    // Add event listeners
    const propertySelect = document.getElementById('property_id');
    const blockSelect = document.getElementById('block_id');
    const unitSelect = document.getElementById('unit_id');
    
    // When property changes
    if (propertySelect) {
        $(propertySelect).on('change', function() {
            const propertyId = $(this).val();
            
            // Reset and disable dependent selects
            $(blockSelect).val('').trigger('change').prop('disabled', !propertyId);
            $(unitSelect).val('').trigger('change').prop('disabled', true);
            
            if (!propertyId) {
                return;
            }
            
            // Filter blocks for the selected property
            const blocks = blockSelect.querySelectorAll('option');
            blocks.forEach(option => {
                if (option.value === '') {
                    option.style.display = '';
                } else {
                    const blockPropertyId = option.getAttribute('data-property');
                    option.style.display = (blockPropertyId === propertyId) ? '' : 'none';
                }
            });
            
            // Enable block select
            $(blockSelect).prop('disabled', false);
            
            // Trigger change on block select to update units
            if ($(blockSelect).val()) {
                $(blockSelect).trigger('change');
            }
        });
    }
    
    // When block changes
    if (blockSelect) {
        $(blockSelect).on('change', function() {
            const blockId = $(this).val();
            const unitSelect = document.getElementById('unit_id');
            
            if (!blockId) {
                $(unitSelect).val('').trigger('change').prop('disabled', true);
                return;
            }
            
            // Filter units for the selected block
            const units = unitSelect.querySelectorAll('option');
            units.forEach(option => {
                if (option.value === '') {
                    option.style.display = '';
                } else {
                    const unitBlockId = option.getAttribute('data-block');
                    option.style.display = (unitBlockId === blockId) ? '' : 'none';
                }
            });
            
            // Enable unit select
            $(unitSelect).prop('disabled', false);
        });
    }
    
    // Trigger change on property select if it has a value (edit mode)
    if (propertySelect && $(propertySelect).val()) {
        $(propertySelect).trigger('change');
    }
    
    // Trigger change on block select if it has a value (edit mode)
    if (blockSelect && $(blockSelect).val()) {
        $(blockSelect).trigger('change');
    }
});
