/**
 * Client-side search for the admin dishes list.
 */
(function ($) {
    'use strict';

    var storageKey = 'maca_menulist_dish_list_search';

    function normalizeQuery(value) {
        return String(value || '')
            .toLowerCase()
            .replace(/\s+/g, ' ')
            .trim();
    }

    function tokenizeQuery(value) {
        var query = normalizeQuery(value);
        if (!query) {
            return [];
        }

        return query.split(' ').filter(function (token) {
            return token.length > 0;
        });
    }

    function rowMatches(rowHaystack, tokens) {
        if (!tokens.length) {
            return true;
        }

        var haystack = normalizeQuery(rowHaystack);
        var index;

        for (index = 0; index < tokens.length; index += 1) {
            if (haystack.indexOf(tokens[index]) === -1) {
                return false;
            }
        }

        return true;
    }

    function formatCountLabel(visible, total, template) {
        if (!template) {
            return '';
        }

        return template
            .replace('%1$d', String(visible))
            .replace('%2$d', String(total))
            .replace('%d', String(visible));
    }

    function applySearch($input) {
        var $table = $('#maca-dishes-list-table');
        var $rows = $table.find('.maca-dish-list-row');
        var $noResults = $('#maca-dish-list-no-results');
        var $meta = $('#maca-dishes-list-search-meta');
        var cfg = window.macaMenulistDishListSearch || {};
        var tokens = tokenizeQuery($input.val());
        var visible = 0;
        var total = $rows.length;

        $rows.each(function () {
            var $row = $(this);
            var matches = rowMatches($row.attr('data-search') || '', tokens);

            $row.toggleClass('is-hidden-by-search', !matches);

            if (matches) {
                visible += 1;
            }
        });

        if ($noResults.length) {
            if (tokens.length && visible === 0) {
                $noResults.prop('hidden', false);
            } else {
                $noResults.prop('hidden', true);
            }
        }

        if ($meta.length) {
            if (!tokens.length) {
                $meta.text('');
            } else {
                $meta.text(formatCountLabel(visible, total, cfg.countLabel));
            }
        }

        try {
            if ($input.val()) {
                window.sessionStorage.setItem(storageKey, $input.val());
            } else {
                window.sessionStorage.removeItem(storageKey);
            }
        } catch (error) {
            // Ignore storage errors.
        }
    }

    $(function () {
        var $input = $('#maca-dishes-list-search-input');

        if (!$input.length) {
            return;
        }

        try {
            var saved = window.sessionStorage.getItem(storageKey);
            if (saved) {
                $input.val(saved);
            }
        } catch (error) {
            // Ignore storage errors.
        }

        $input.on('input search', function () {
            applySearch($input);
        });

        applySearch($input);

        $input.on('keydown', function (event) {
            if (event.key === 'Escape') {
                $input.val('');
                applySearch($input);
                $input.blur();
            }
        });
    });
})(jQuery);
