/**
 * DiveWP Filter Bar JavaScript
 *
 * Reusable filter bar component: handles filter button toggling, search input
 * with clear button, and emits custom events for consumers to react to.
 *
 * Events emitted on the .divewp-filter-bar element:
 *   - 'divewp:filter-changed' with detail: { filterBarId, filterValue, searchQuery }
 *
 * @package DiveWP
 * @version 1.0.0
 */

jQuery(document).ready(function($) {
    'use strict';

    /**
     * Emit the filter-changed event on the filter bar container
     *
     * @param {jQuery} $bar The .divewp-filter-bar element
     */
    function emitFilterChanged($bar) {
        var filterValue = $bar.find('.divewp-filter-bar__btn--active').data('filter') || 'all';
        var searchQuery = $bar.find('.divewp-filter-bar__search').val() || '';
        var filterBarId = $bar.attr('id') || '';

        $bar.trigger('divewp:filter-changed', {
            filterBarId: filterBarId,
            filterValue: filterValue,
            searchQuery: searchQuery.toLowerCase().trim()
        });
    }

    // =========================================================================
    // Filter Buttons
    // =========================================================================

    $(document).on('click', '.divewp-filter-bar__btn', function(e) {
        e.preventDefault();
        var $btn = $(this);
        var $bar = $btn.closest('.divewp-filter-bar');

        // Update active button state within this bar only
        $bar.find('.divewp-filter-bar__btn').removeClass('divewp-filter-bar__btn--active');
        $btn.addClass('divewp-filter-bar__btn--active');

        emitFilterChanged($bar);
    });

    // =========================================================================
    // Search with clear button
    // =========================================================================

    $(document).on('keyup input', '.divewp-filter-bar__search', function() {
        var $input = $(this);
        var $wrapper = $input.closest('.divewp-filter-bar__search-wrapper');
        var $bar = $input.closest('.divewp-filter-bar');

        // Toggle clear button visibility
        if ($input.val().length > 0) {
            $wrapper.addClass('has-value');
        } else {
            $wrapper.removeClass('has-value');
        }

        emitFilterChanged($bar);
    });

    $(document).on('click', '.divewp-filter-bar__search-clear', function(e) {
        e.preventDefault();
        var $wrapper = $(this).closest('.divewp-filter-bar__search-wrapper');
        var $input = $wrapper.find('.divewp-filter-bar__search');
        var $bar = $(this).closest('.divewp-filter-bar');

        $input.val('').focus();
        $wrapper.removeClass('has-value');

        emitFilterChanged($bar);
    });
});
