frappe.pages["pallet-list"].on_page_load = function(wrapper) {
    var page = frappe.ui.make_app_page({
        parent: wrapper,
        title: __("Pallet List"),
        single_column: true
    });
    
    var content = frappe.render_template("pallet-list", {});
    $(page.body).append(content);
    
    var currentPage = 1;
    var pageSize = 100;
    var currentSort = "pallet_number";
    var sortDir = "desc";
    var searchTerm = "";
    var statusFilter = "";
    
    function loadPallets() {
        frappe.call({
            method: "westech_r2.page.pallet_list.pallet_list.get_pallets",
            args: {
                page: currentPage,
                page_size: pageSize,
                sort_field: currentSort,
                sort_dir: sortDir,
                status_filter: statusFilter,
                search: searchTerm
            },
            callback: function(r) {
                if (r.message) {
                    renderPallets(r.message.pallets, r.message.total);
                }
            }
        });
    }
    
    function renderPallets(pallets, total) {
        var tbody = $("#pallet-tbody");
        tbody.empty();
        
        if (!pallets || pallets.length === 0) {
            tbody.append('<tr><td colspan="13" style="text-align:center;padding:40px;">No pallets found</td></tr>');
            return;
        }
        
        pallets.forEach(function(p) {
            var statusClass = "status-" + (p.status || "").toLowerCase().replace(/\s+/g, "-");
            var link = "/app/pallet/" + encodeURIComponent(p.name);
            var pn = (p.pallet_number || "").replace(/</g, "&lt;").replace(/>/g, "&gt;");
            
            var row = '<tr>' +
                '<td><a href="' + link + '" style="color:#3cc062;text-decoration:none;font-weight:600;">' + pn + '</a></td>' +
                '<td>' + fmtDate(p.date_reserved) + '</td>' +
                '<td>' + fmtDate(p.received_date) + '</td>' +
                '<td>' + (p.customer_number || "") + '</td>' +
                '<td>' + (p.company_name || "") + '</td>' +
                '<td>' + (p.inbound_weight || "") + '</td>' +
                '<td>' + (p.tester || "") + '</td>' +
                '<td>' + (p.description || "") + '</td>' +
                '<td>' + (p.qty_to_sales || "") + '</td>' +
                '<td>' + (p.weight_to_sales || "") + '</td>' +
                '<td>' + fmtDate(p.finish_date) + '</td>' +
                '<td class="' + statusClass + '">' + (p.status || "") + '</td>' +
                '<td>' + (p.notes || "").substring(0, 50) + '</td>' +
                '</tr>';
            tbody.append(row);
        });
        
        renderPagination(total);
    }
    
    function renderPagination(total) {
        var totalPages = Math.ceil(total / pageSize);
        var pagination = $("#pallet-pagination");
        pagination.empty();
        
        if (totalPages <= 1) return;
        
        var prevBtn = $('<button>&laquo; Prev</button>').attr("disabled", currentPage === 1)
            .css({padding: "5px 12px", border: "1px solid #ddd", background: "white", cursor: "pointer", marginRight: "5px"})
            .on("click", function() {
                if (currentPage > 1) { currentPage--; loadPallets(); }
            });
        pagination.append(prevBtn);
        
        var startPage = Math.max(1, currentPage - 2);
        var endPage = Math.min(totalPages, startPage + 4);
        
        for (var i = startPage; i <= endPage; i++) {
            var btn = $('<button>' + i + '</button>')
                .css({padding: "5px 12px", border: "1px solid #ddd", background: i === currentPage ? "#3cc062" : "white", 
                      color: i === currentPage ? "white" : "#333", cursor: "pointer", marginRight: "5px"})
                .on("click", function(page) {
                    return function() { currentPage = page; loadPallets(); };
                }(i));
            pagination.append(btn);
        }
        
        var nextBtn = $('<button>Next &raquo;</button>').attr("disabled", currentPage === totalPages)
            .css({padding: "5px 12px", border: "1px solid #ddd", background: "white", cursor: "pointer", marginRight: "5px"})
            .on("click", function() {
                if (currentPage < totalPages) { currentPage++; loadPallets(); }
            });
        pagination.append(nextBtn);
    }
    
    function fmtDate(v) {
        if (!v) return "";
        var s = String(v);
        if (s.indexOf("T") > -1) s = s.split("T")[0];
        if (s.indexOf(" ") > -1) s = s.split(" ")[0];
        return s;
    }
    
    $("#pallet-search").on("input", function() {
        searchTerm = $(this).val();
        currentPage = 1;
        loadPallets();
    });
    
    $("#status-filter").on("change", function() {
        statusFilter = $(this).val();
        currentPage = 1;
        loadPallets();
    });
    
    loadPallets();
};
