jQuery(function($){
    function performSearch() {
        var keyword   = $('#isbk-keyword').val();
        var category  = $('#isbk-category').val();
        var tag       = $('#isbk-tag').val();

        // Mostra loading
        $('#isbk-loading').show();
        $('#isbk-results').hide();
        $('#isbk-no-results').hide();

        $.post(isbk_ajax.ajax_url, {
            action: 'isbk_search',
            nonce: isbk_ajax.nonce,
            keyword: keyword,
            category: category,
            tag: tag
        }, function(response) {
            $('#isbk-loading').hide();
            
            if (response.success && response.data) {
                $('#isbk-results').html(response.data).fadeIn(300);
                initLightbox();
            } else {
                $('#isbk-no-results').fadeIn(300);
            }
        }).fail(function() {
            $('#isbk-loading').hide();
            alert('Errore nella ricerca. Riprova.');
        });
    }

    function initLightbox() {
        $("#isbk-results .gallery a").fancybox({
            loop: true,
            buttons: ["zoom", "slideShow", "thumbs", "close"],
            caption: function(instance, item) {
                var caption = $(this).next("figcaption").find(".isbk-caption").html() || "";
                return caption;
            },
            afterLoad: function(instance, current) {
                current.$content.css("max-height", "90vh");
            }
        });
    }

    // Submit form
    $('#isbk-search-form').on('submit', function(e){
        e.preventDefault();
        performSearch();
    });

    // Reset filtri
    $('#isbk-reset').on('click', function(){
        $('#isbk-keyword').val('');
        $('#isbk-category').val('');
        $('#isbk-tag').val('');
        $('#isbk-results').html('').hide();
        $('#isbk-no-results').hide();
    });

    // Inizializza lightbox al caricamento
    initLightbox();
});