/* Minimal admin product list loader for Bizmart */
(function($){
    'use strict';

    function debounce(fn, wait) {
        var t;
        return function() { var ctx = this, args = arguments; clearTimeout(t); t = setTimeout(function(){ fn.apply(ctx, args); }, wait); };
    }

    function renderPagination(total, page, per) {
        per = per || 25;
        var pages = Math.max(1, Math.ceil((total||0)/per));
        var $wrap = $('#biz-products-pagination');
        $wrap.empty();
        
        // Simple pagination bounds
        var start = Math.max(1, page - 2);
        var end = Math.min(pages, page + 2);
        if (start > 1) start = Math.max(1, end - 4); 
        if (end < pages) end = Math.min(pages, start + 4);

        if (pages > 1) {
            var $prev = $('<button type="button" class="biz-btn biz-btn-secondary" style="margin-right:8px;padding:6px 12px;font-size:13px;" data-page="'+(page-1)+'">«</button>');
            if (page <= 1) $prev.prop('disabled', true).css('opacity', 0.5);
            $wrap.append($prev);
        }

        for (var i=start; i<=end; i++) {
            var isAct = (i === page);
            var style = isAct ? 'background:#4f46e5;color:white;border-color:#4f46e5;' : 'background:white;';
            var $a = $('<button type="button" class="biz-btn biz-btn-secondary" style="margin-right:4px;padding:6px 12px;font-size:13px;min-width:32px;'+style+'" data-page="'+i+'">'+i+'</button>');
            if (isAct) $a.prop('disabled', true).css('cursor', 'default');
            $wrap.append($a);
        }
        
        if (pages > 1) {
             var $next = $('<button type="button" class="biz-btn biz-btn-secondary" style="margin-left:4px;padding:6px 12px;font-size:13px;" data-page="'+(page+1)+'">»</button>');
             if (page >= pages) $next.prop('disabled', true).css('opacity', 0.5);
             $wrap.append($next);
        }
        
        // Show total count
        if (total > 0) {
            $wrap.prepend('<span style="margin-right:auto;color:#6b7280;font-size:13px;line-height:32px;display:flex;align-items:center;gap:6px;">Total: <b style="color:#111827;">'+total+'</b> products</span>');
        }
    }

    function loadProductPage(page) {
        page = page || 1;
        var per = 25;
        // Check local search input first, else global
        var s = ($('#biz-prod-search').val()||'').toString();
        
        var spinner = '<span class="biz-loading" style="vertical-align:middle;margin-right:8px;"></span>';
        $('#biz-products-table tbody').html('<tr><td colspan="6" style="padding:40px;text-align:center;color:#6b7280;font-size:15px;">'+spinner+' Loading products...</td></tr>');
        
        if (typeof BizmartProductsListData === 'undefined') return;

        $.post(BizmartProductsListData.ajaxUrl, { 
            action: 'bizmart_get_products_list', 
            nonce: BizmartProductsListData.nonce, 
            page: page, 
            per: per, 
            s: s 
        }, function(r){
            if (!r || !r.success) {
                $('#biz-products-table tbody').html('<tr><td colspan="6" style="padding:40px;text-align:center;color:#6b7280;">No products found</td></tr>');
                $('#biz-products-pagination').empty();
                return;
            }
            if (!r.data.html) {
                 $('#biz-products-table tbody').html('<tr><td colspan="6" style="padding:40px;text-align:center;color:#6b7280;">No products found</td></tr>');
                 $('#biz-products-pagination').empty();
                 return;
            }
            $('#biz-products-table tbody').html(r.data.html);
            renderPagination(r.data.total || 0, page, per);
        }).fail(function(){ 
            $('#biz-products-table tbody').html('<tr><td colspan="6" style="padding:40px;text-align:center;color:#ef4444;">Error loading products. Please try again or check console.</td></tr>'); 
        });
    }

    // Expose reload function
    window.BizProducts = window.BizProducts || {};
    window.BizProducts.reloadList = function() {
        loadProductPage(1);
    };

    $(document).ready(function(){
        if ($('#biz-products-table').length) {
            // Attach handlers with debounce
            $('#biz-prod-search').on('input', debounce(function(){ loadProductPage(1); }, 400));
            // Use delegation for pagination
            $(document).on('click', '#biz-products-pagination button', function(e){ 
                e.preventDefault();
                var p = parseInt($(this).data('page')||1, 10); 
                if (!isNaN(p)) loadProductPage(p); 
            });

            // Initial load
            loadProductPage(1);
        }
    });

})(jQuery);