(function( $ ) {
    'use strict';

    // Make sure ACF exists before running
    if (typeof acf === 'undefined') return;

    const MIN_ROWS = 5; 

    // Target the repeater by its actual NAME instead of its key
    acf.addAction('ready_field/name=apartment_fees', function(field) {
        var $field = field.$el;
        
        $field.find('.acf-input').first().prepend('<div class="acf-fee-filters-wrapper" style="margin: 0 0 15px 0;"></div>');
        var $wrapper = $field.find('.acf-fee-filters-wrapper');

        var labels = {
            'monthly': 'Monthly',
            'annual': 'Annual',
            'onetime': 'One Time'
        };

        function refreshFilters( enforceVisibility ) {
            var $rows = $field.find('.acf-row:not(.acf-clone)');
            var activeFilter = $wrapper.find('.acf-fee-btn.button-primary').data('filter') || 'all';
            
            // Tag rows and collect unique types
            var presentTypes = new Set();
            $rows.each(function() {
                // Target the sub-field by its data-name attribute
                var $select = $(this).find('.acf-field[data-name="frequency"] select');
                var val = $select.val();
                if(val) {
                    $(this).attr('data-fee-type', val);
                    presentTypes.add(val);
                }
            });

            // UX Check
            if ($rows.length < MIN_ROWS || presentTypes.size <= 1) {
                $wrapper.empty().hide();
                $rows.show(); 
                return;
            }

            if (activeFilter !== 'all' && !presentTypes.has(activeFilter)) {
                activeFilter = 'all';
            }

            // Build Dynamic Buttons
            var html = '<ul style="padding: 0; margin: 0; list-style: none; display: flex; gap: 8px;">';
            var allClass = (activeFilter === 'all') ? 'button-primary' : '';
            html += '<li><button type="button" class="button acf-fee-btn ' + allClass + '" data-filter="all">All (' + $rows.length + ')</button></li>';
            
            presentTypes.forEach(function(type) {
                var count = $rows.filter('[data-fee-type="' + type + '"]').length;
                var btnClass = (activeFilter === type) ? 'button-primary' : '';
                var label = labels[type] || type;
                html += '<li><button type="button" class="button acf-fee-btn ' + btnClass + '" data-filter="' + type + '">' + label + ' (' + count + ')</button></li>';
            });
            
            html += '</ul>';
            $wrapper.html(html).show();

            // Enforce Visibility ONLY if requested
            if ( enforceVisibility !== false ) {
                if (activeFilter === 'all') {
                    $rows.show();
                } else {
                    $rows.hide().filter('[data-fee-type="' + activeFilter + '"]').show();
                }
            }
        }

        // Initial load
        refreshFilters();

        // Handle Button Clicks
        $wrapper.on('click', '.acf-fee-btn', function(e) {
            e.preventDefault();
            $wrapper.find('.acf-fee-btn').removeClass('button-primary');
            $(this).addClass('button-primary');
            refreshFilters( true );
        });

        // Handle Dropdown Changes (Targeted by data-name)
        $field.on('change', '.acf-field[data-name="frequency"] select', function() {
            refreshFilters( false ); 
        });

        // Listen for row removal
        acf.addAction('remove', function($el) {
            if ($el.hasClass('acf-row') && $el.closest('.acf-field[data-name="apartment_fees"]').length) {
                setTimeout(function() { refreshFilters(true); }, 50); 
            }
        });
        
        // Listen for new rows
        acf.addAction('append', function($el) {
            if ($el.hasClass('acf-row') && $el.closest('.acf-field[data-name="apartment_fees"]').length) {
                var activeFilter = $wrapper.find('.acf-fee-btn.button-primary').data('filter');
                
                if (activeFilter && activeFilter !== 'all') {
                    var $select = $el.find('.acf-field[data-name="frequency"] select');
                    $select.val(activeFilter).trigger('change');
                }
                
                refreshFilters( false );
            }
        });
    });

})( jQuery );
