let currentPage = 1;
const rowsPerPage = 10; // Menampilkan 10 data per halaman
let dataRows = [];

fetch("hasil_pelabelan.csv")
    .then(res => res.text())
    .then(data => {
        let result = data.split(/\r?\n|\r/).map(row => row.split(","));

        let headers = result[0].map(h => h.replace(/\ufeff/g, "").trim());
        let ulasanIndex = headers.indexOf("final_text");
        let sentimenIndex = headers.indexOf("sentimen");

        if (ulasanIndex === -1 || sentimenIndex === -1) {
            console.error("Kolom 'Text_bersih' atau 'label' tidak ditemukan dalam CSV.");
            return;
        }

        // Simpan data dalam array
        dataRows = result.slice(1).map(row => ({
            ulasan: row[ulasanIndex] || "Data Hilang",
            sentimen: row[sentimenIndex] || "Data Hilang"
        }));

        showPage(currentPage);
    })
    .catch(error => console.error("Error membaca file CSV:", error));

function showPage(page) {
    let tbody = document.querySelector("#dataTable tbody");
    tbody.innerHTML = ""; // Kosongkan tabel sebelum menampilkan data baru

    let start = (page - 1) * rowsPerPage;
    let end = start + rowsPerPage;
    let paginatedItems = dataRows.slice(start, end);

    paginatedItems.forEach(row => {
        let tr = document.createElement("tr");
        tr.innerHTML = `<th>${row.ulasan}</th><th>${row.sentimen}</th>`;
        tbody.appendChild(tr);
    });

    document.querySelector("#pageInfo").textContent = `Page ${page} of ${Math.ceil(dataRows.length / rowsPerPage)}`;

    // Nonaktifkan tombol jika sudah di halaman pertama/terakhir
    document.querySelector("#prevPage").disabled = page === 1;
    document.querySelector("#nextPage").disabled = page === Math.ceil(dataRows.length / rowsPerPage);
}

// Event listener tombol pagination
document.querySelector("#prevPage").addEventListener("click", () => {
    if (currentPage > 1) {
        currentPage--;
        showPage(currentPage);
    }
});
document.querySelector("#nextPage").addEventListener("click", () => {
    if (currentPage < Math.ceil(dataRows.length / rowsPerPage)) {
        currentPage++;
        showPage(currentPage);
    }
});
