// Fetch Wilayah dari API Database
fetch("/api/layanan/wilayah")
    .then((response) => response.json())
    .then((data) => populateFilters(data))
    .catch((error) =>
        console.error("Gagal load wilayah dari database:", error)
    );

function populateFilters(data) {
    populateSelect("kabkota", data.kabkota);
    populateSelect("kecamatan", data.kecamatan);
    populateSelect("kelurahan", data.kelurahan);
}

function populateSelect(id, options) {
    const select = document.getElementById(id);
    if (!select) return;

    // Add default option
    let defaultOption =
        '<option value="">Semua ' +
        (id === "kabkota"
            ? "Kabupaten"
            : id === "kecamatan"
            ? "Kecamatan"
            : "Kelurahan") +
        "</option>";

    select.innerHTML =
        defaultOption +
        options
            .map(
                (opt) => `
    <option value="${opt.value}">${opt.label}</option>
  `
            )
            .join("");
}

// Fetch Layanan dari API Database
document.addEventListener("DOMContentLoaded", function () {
    fetch("/api/layanan/data")
        .then((response) => response.json())
        .then((data) => {
            initializeLayanan(data);
            setupUIHandlers();
        })
        .catch((error) =>
            console.error("Gagal load layanan dari database:", error)
        );
});

function initializeLayanan(data) {
    renderHeader(data.header);
    renderTabs(data.tabs);
    renderContents(data.contents);
    changeTab("amdal");
}

// Data Header
function renderHeader(header) {
    const headerContainer = document.querySelector("#layanan-header");
    if (!headerContainer) return;

    headerContainer.innerHTML = `
      <h1 class="text-2xl sm:text-4xl font-bold text-blue-900">${header.title}</h1>
      <p class="text-gray-700 mt-1 text-sm sm:text-base">${header.subtitle}</p>
    `;
}

// Data Tabs
function renderTabs(tabs) {
    const tabsContainer = document.querySelector("#layanan-tabs");
    if (!tabsContainer) return;

    tabsContainer.innerHTML = tabs
        .map(
            (tab) => `
      <button id="tab-${tab.id}"
              class="tab-btn bg-white border border-gray-300 px-3 sm:px-6 py-2 rounded text-sm sm:text-base"
              onclick="handleTabClick('${tab.id}')">
        ${tab.label}
      </button>
    `
        )
        .join("");
}

// Data Contents
function renderContents(contents) {
    const contentsContainer = document.querySelector("#layanan-contents");
    if (!contentsContainer) return;

    contentsContainer.innerHTML = Object.entries(contents)
        .map(([key, items]) => {
            if (key === "audit") {
                return `
          <div id="content-${key}" class="tab-content hidden bg-white rounded overflow-hidden shadow">
            ${renderAuditTable(items)}
          </div>
        `;
            } else {
                return `
          <div id="content-${key}" class="tab-content hidden bg-blue-900 rounded overflow-hidden">
            ${items
                .map((item, index) => renderStandardItem(item, index))
                .join("")}
          </div>
        `;
            }
        })
        .join("");
}

function renderStandardItem(item, index) {
    return `
      <div class="border-b border-blue-800 p-4 sm:p-6 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div class="flex gap-3 sm:gap-4 w-full">
          <div class="flex-shrink-0">
            <div class="bg-blue-500 p-2 rounded">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 sm:h-8 sm:w-8 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </div>
          </div>
          <div>
            <div class="text-blue-200 text-xs mt-1">
              <span class="bg-blue-700 px-2 py-1 rounded text-xs">${item.no_registrasi}</span>
              <span class="ml-2">${item.pemrakarsa}</span>
            </div>
            <h2 class="text-white font-bold text-sm sm:text-base mt-1 sm:mt-2 ">${item.title}</h2>
            <p class="text-blue-200 text-xs sm:text-sm">${item.description}</p>

          </div>
        </div>
        <div class="flex flex-row sm:flex-col items-center sm:items-end justify-between sm:justify-end gap-2 w-full sm:w-auto mt-2 sm:mt-0">
          <div class="text-white text-xs sm:text-sm text-right">${item.periode}</div>
          <button class="berikan-tanggapan-btn bg-green-500 text-white px-3 sm:px-6 py-1.5 sm:py-2 rounded text-xs sm:text-sm whitespace-nowrap"
                  data-item-id="${item.id}"
                  data-item-index="${index}"
                  data-item-title="${item.title}"
                  data-item-description="${item.description}"
                  data-item-periode="${item.periode}">
            Berikan Tanggapan
          </button>
        </div>
      </div>
    `;
}

function renderAuditTable(items) {
    return `
      <div class="overflow-x-auto">
        <table class="w-full text-xs sm:text-base">
          <thead>
            <tr class="bg-blue-800 text-white">
              <th class="py-2 sm:py-3 px-2 sm:px-4 text-left w-12 sm:w-16">No</th>
              <th class="py-2 sm:py-3 px-2 sm:px-4 text-left">Nama PT</th>
              <th class="py-2 sm:py-3 px-2 sm:px-4 text-left">Judul</th>
              <th class="py-2 sm:py-3 px-2 sm:px-4 text-left hidden md:table-cell">Deskripsi</th>
              <th class="py-2 sm:py-3 px-2 sm:px-4 text-center w-20 sm:w-32">Aksi</th>
            </tr>
          </thead>
          <tbody>
            ${items
                .map(
                    (item) => `
              <tr class="border-b border-gray-200">
                <td class="py-3 sm:py-4 px-2 sm:px-4 align-top">${item.no}</td>
                <td class="py-3 sm:py-4 px-2 sm:px-4 align-top">${item.company}</td>
                <td class="py-3 sm:py-4 px-2 sm:px-4 align-top">${item.title}</td>
                <td class="py-3 sm:py-4 px-2 sm:px-4 align-top hidden md:table-cell">
                  <div class="max-h-24 sm:max-h-32 overflow-y-auto pr-2">${item.description}</div>
                </td>
                <td class="py-3 sm:py-4 px-2 sm:px-4 align-top">
                  <button class="bg-green-500 text-white px-2 sm:px-4 py-1.5 sm:py-2 rounded w-full text-xs sm:text-sm">Download</button>
                </td>
              </tr>
            `
                )
                .join("")}
          </tbody>
        </table>
      </div>
    `;
}

function setupUIHandlers() {
    // Toggle filter section
    const filterButton = document.getElementById("filter-button");
    if (filterButton) {
        filterButton.addEventListener("click", function () {
            const filterSection = document.getElementById("filter-section");
            if (filterSection) filterSection.classList.toggle("hidden");
        });
    }

    // Clear filter inputs
    const clearButton = document.getElementById("clear-filter");
    if (clearButton) {
        clearButton.addEventListener("click", function () {
            document.getElementById("kabkota").value = "";
            document.getElementById("kecamatan").value = "";
            document.getElementById("kelurahan").value = "";

            const searchInput = document.querySelector(
                'input[placeholder="Search"]'
            );
            if (searchInput) searchInput.value = "";

            // Reload original data
            loadOriginalData();
        });
    }

    // Apply filter
    const applyFilterButton = document.querySelector(".bg-blue-600");
    if (applyFilterButton) {
        applyFilterButton.addEventListener("click", function () {
            applyFilters();
        });
    }

    // Search input
    const searchInput = document.querySelector('input[placeholder="Search"]');
    if (searchInput) {
        let searchTimeout;
        searchInput.addEventListener("input", function () {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                applyFilters();
            }, 500); // Debounce 500ms
        });
    }

    // Handle "Berikan Tanggapan" button clicks
    document.addEventListener("click", function (e) {
        if (e.target && e.target.classList.contains("berikan-tanggapan-btn")) {
            const itemId = e.target.getAttribute("data-item-id");
            const itemTitle = e.target.getAttribute("data-item-title");
            const itemDescription = e.target.getAttribute(
                "data-item-description"
            );
            const itemPeriode = e.target.getAttribute("data-item-periode");

            if (itemId) {
                // Fetch detail from API
                fetch(`/api/layanan/detail/${itemId}`)
                    .then((response) => response.json())
                    .then((data) => {
                        showFeedbackForm(data);
                    })
                    .catch((error) => {
                        console.error("Error fetching detail:", error);
                        // Fallback to basic data
                        showFeedbackForm({
                            nama_kegiatan: itemTitle,
                            deskripsi_kegiatan: itemDescription,
                            periode: itemPeriode,
                        });
                    });
            } else {
                // Fallback for old data structure
                showFeedbackForm({
                    nama_kegiatan: itemTitle,
                    deskripsi_kegiatan: itemDescription,
                    periode: itemPeriode,
                });
            }
        }
    });
}

// Function to show the feedback form
function showFeedbackForm(detailData) {
    const contentsContainer = document.querySelector("#layanan-contents");
    if (!contentsContainer) return;

    // Keep tabs visible, just reset their state
    const tabButtons = document.querySelectorAll(".tab-btn");
    tabButtons.forEach((button) => {
        button.classList.remove("bg-blue-900", "text-white");
        button.classList.add("bg-white", "border", "border-gray-300");
    });

    // Render the feedback form
    contentsContainer.innerHTML = `
        <div class="bg-white rounded overflow-hidden shadow">
            ${renderInformasiRencanaKegiatan(detailData)}
            ${renderSaranPendapatForm()}
        </div>
    `;
}

// Function to render "Informasi Rencana Kegiatan" section
function renderInformasiRencanaKegiatan(data) {
    return `
        <div class="border border-green-600 rounded-lg mb-6">
            <div class="bg-green-50 p-4 border-b border-green-200">
                <h2 class="text-lg font-semibold text-green-800">Informasi Rencana Kegiatan</h2>
            </div>
            <div class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="space-y-4">
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">No. Registrasi</label>
                                <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium">${
                                    data.no_registrasi || "-"
                                }</div>
                            </div>
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-gray-700 mb-2">Jenis Dokumen</label>
                                <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium">${
                                    data.jenis_dokumen || "-"
                                }</div>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Nama Kegiatan</label>
                            <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium leading-relaxed">
                                ${data.nama_kegiatan || "-"}
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Bidang Usaha/Kegiatan</label>
                                <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium">${
                                    data.bidang_usaha || "-"
                                }</div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Skala/Besaran</label>
                                <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium">${
                                    data.skala_besaran || "-"
                                }</div>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Lokasi Kegiatan</label>
                                <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium">${
                                    data.lokasi_kegiatan || "-"
                                }</div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Kewenangan</label>
                                <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium">${
                                    data.kewenangan || "-"
                                }</div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Pemrakarsa</label>
                                <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium">${
                                    data.pemrakarsa || "-"
                                }</div>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Provinsi/Kota</label>
                            <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium">${
                                data.provinsi_kota || "-"
                            }</div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Deskripsi Kegiatan</label>
                            <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium leading-relaxed">
                                ${data.deskripsi_kegiatan || "-"}
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Dampak Potensial</label>
                            <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium leading-relaxed">
                                ${data.dampak_potensial || "-"}
                            </div>
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Lokasi</label>
                        <div class="bg-blue-500 rounded-lg h-64 flex items-center justify-center text-white">
                            <div class="text-center">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 mx-auto mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                                </svg>
                                <p class="text-sm">Peta Lokasi Kegiatan</p>
                                ${
                                    data.latitude && data.longitude
                                        ? `<p class="text-xs mt-1">${data.latitude}, ${data.longitude}</p>`
                                        : ""
                                }
                            </div>
                        </div>
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Deskripsi Lokasi</label>
                            <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium leading-relaxed">
                                ${data.deskripsi_lokasi || "-"}
                            </div>
                        </div>
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Periode</label>
                            <div class="bg-green-100 text-green-800 px-3 py-2 rounded text-sm font-medium">
                                ${data.periode || "-"}
                            </div>
                        </div>
                        <div class="mt-6">
                            <button onclick="goBackToList()" class="bg-red-500 hover:bg-red-600 text-white px-6 py-2 rounded-md text-sm font-medium transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2">
                                Kembali
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// Function to render "Saran, Pendapat dan Tanggapan Kegiatan" form
function renderSaranPendapatForm() {
    return `
        <div class="border border-green-600 rounded-lg">
            <div class="bg-green-50 p-4 border-b border-green-200">
                <h2 class="text-lg font-semibold text-green-800 text-center">Saran, Pendapat, dan Tanggapan untuk Kegiatan</h2>
            </div>
            <div class="p-6">
                <form class="space-y-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="nama" class="block text-sm font-medium text-gray-700 mb-1">Nama</label>
                            <input type="text" id="nama" name="nama" placeholder="Nama"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-green-500 focus:border-green-500">
                        </div>
                        <div>
                            <label for="peran" class="block text-sm font-medium text-gray-700 mb-1">Peran</label>
                            <select id="peran" name="peran"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-green-500 focus:border-green-500">
                                <option value="">Pilih Peran</option>
                                <option value="masyarakat">Masyarakat</option>
                                <option value="lsm">LSM</option>
                                <option value="akademisi">Akademisi</option>
                                <option value="pemerintah">Pemerintah</option>
                            </select>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="nik" class="block text-sm font-medium text-gray-700 mb-1">NIK</label>
                            <input type="text" id="nik" name="nik" placeholder="NIK"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-green-500 focus:border-green-500">
                        </div>
                        <div>
                            <label for="telepon" class="block text-sm font-medium text-gray-700 mb-1">No. Telepon/Handphone</label>
                            <div class="flex">
                                <select class="px-3 py-2 border border-gray-300 border-r-0 rounded-l-md bg-gray-50">
                                    <option value="+62">+62</option>
                                </select>
                                <input type="text" id="telepon" name="telepon" placeholder="No. Telepon/Handphone"
                                       class="flex-1 px-3 py-2 border border-gray-300 rounded-r-md focus:outline-none focus:ring-green-500 focus:border-green-500">
                            </div>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                            <input type="email" id="email" name="email" placeholder="Email"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-green-500 focus:border-green-500">
                        </div>
                        <div>
                            <label for="gender" class="block text-sm font-medium text-gray-700 mb-1">Gender</label>
                            <select id="gender" name="gender"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-green-500 focus:border-green-500">
                                <option value="">Pilih Gender</option>
                                <option value="laki-laki">Laki-laki</option>
                                <option value="perempuan">Perempuan</option>
                            </select>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div class="md:col-span-2">
                            <div class="space-y-4">
                                <div>
                                    <label for="kondisi_lingkungan" class="block text-sm font-medium text-gray-700 mb-1">
                                        Kondisi Lingkungan di Dalam dan Sekitar Lokasi Tapak Proyek
                                    </label>
                                    <span class="text-xs text-red-500">Data wajib diisi</span>
                                    <textarea id="kondisi_lingkungan" name="kondisi_lingkungan" rows="3"
                                              placeholder="Kondisi Lingkungan di Dalam dan Sekitar Lokasi Tapak Proyek"
                                              class="w-full px-3 py-2 border border-red-300 rounded-md focus:outline-none focus:ring-green-500 focus:border-green-500"></textarea>
                                </div>

                                <div>
                                    <label for="nilai_lokal" class="block text-sm font-medium text-gray-700 mb-1">
                                        Nilai Lokal yang Berpotensi akan Terkena Dampak
                                    </label>
                                    <span class="text-xs text-red-500">Data wajib diisi</span>
                                    <textarea id="nilai_lokal" name="nilai_lokal" rows="3"
                                              placeholder="Nilai Lokal yang Berpotensi akan Terkena Dampak"
                                              class="w-full px-3 py-2 border border-red-300 rounded-md focus:outline-none focus:ring-green-500 focus:border-green-500"></textarea>
                                </div>

                                <div>
                                    <label for="kekhawatiran" class="block text-sm font-medium text-gray-700 mb-1">Kekhawatiran</label>
                                    <span class="text-xs text-red-500">Data wajib diisi</span>
                                    <textarea id="kekhawatiran" name="kekhawatiran" rows="3"
                                              placeholder="Kekhawatiran"
                                              class="w-full px-3 py-2 border border-red-300 rounded-md focus:outline-none focus:ring-green-500 focus:border-green-500"></textarea>
                                </div>

                                <div>
                                    <label for="harapan" class="block text-sm font-medium text-gray-700 mb-1">Harapan</label>
                                    <span class="text-xs text-red-500">Data wajib diisi</span>
                                    <textarea id="harapan" name="harapan" rows="3"
                                              placeholder="Harapan"
                                              class="w-full px-3 py-2 border border-red-300 rounded-md focus:outline-none focus:ring-green-500 focus:border-green-500"></textarea>
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">
                                        Tingkat Kekhawatiran atau Harapan terhadap Kegiatan Ini
                                    </label>
                                    <div class="flex items-center justify-between">
                                        <span class="text-sm text-gray-600">Khawatir</span>
                                        <div class="flex space-x-1">
                                            <button type="button" class="rating-star text-gray-300 hover:text-yellow-400 text-2xl" data-rating="1">★</button>
                                            <button type="button" class="rating-star text-gray-300 hover:text-yellow-400 text-2xl" data-rating="2">★</button>
                                            <button type="button" class="rating-star text-gray-300 hover:text-yellow-400 text-2xl" data-rating="3">★</button>
                                            <button type="button" class="rating-star text-gray-300 hover:text-yellow-400 text-2xl" data-rating="4">★</button>
                                            <button type="button" class="rating-star text-gray-300 hover:text-yellow-400 text-2xl" data-rating="5">★</button>
                                        </div>
                                        <span class="text-sm text-gray-600">Harapan</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                Unggah Foto Selfie
                            </label>
                            <span class="text-xs text-gray-500">(Ukuran Maks 1 MB)</span>
                            <div class="mt-2 flex flex-col items-center">
                                <div class="bg-gray-200 rounded-full w-24 h-24 flex items-center justify-center mb-3">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                    </svg>
                                </div>
                                <input type="file" id="foto_selfie" name="foto_selfie" accept="image/*"
                                       class="text-xs text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded file:border-0 file:text-xs file:font-semibold file:bg-green-50 file:text-green-700 hover:file:bg-green-100">
                            </div>
                        </div>
                    </div>

                    <div class="flex justify-end space-x-4 pt-6">
                        <button type="button" onclick="goBackToList()"
                                class="bg-red-500 text-white px-6 py-2 rounded hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500">
                            Batal
                        </button>
                        <button type="submit"
                                class="bg-green-500 text-white px-6 py-2 rounded hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500">
                            Kirim
                        </button>
                    </div>
                </form>
            </div>
        </div>
    `;
}

// Function to go back to the main list
function goBackToList() {
    // Re-render the original content from database
    fetch("/api/layanan/data")
        .then((response) => response.json())
        .then((data) => {
            renderContents(data.contents);
            changeTab("amdal"); // Default to AMDAL tab
        })
        .catch((error) =>
            console.error("Gagal load layanan dari database:", error)
        );
}

// Tab switching function
function changeTab(tabName) {
    const contentSections = document.querySelectorAll(".tab-content");
    contentSections.forEach((section) => {
        section.classList.add("hidden");
    });

    const tabButtons = document.querySelectorAll(".tab-btn");
    tabButtons.forEach((button) => {
        button.classList.remove("bg-blue-900", "text-white");
        button.classList.add("bg-white", "border", "border-gray-300");
    });

    const selectedTab = document.getElementById("tab-" + tabName);
    if (selectedTab) {
        selectedTab.classList.remove("bg-white", "border", "border-gray-300");
        selectedTab.classList.add("bg-blue-900", "text-white");
    }

    const selectedContent = document.getElementById("content-" + tabName);
    if (selectedContent) {
        selectedContent.classList.remove("hidden");
    }
}

// Handle tab click - check if we need to return to table view first
function handleTabClick(tabName) {
    // Check if we're currently in feedback form view
    const contentsContainer = document.querySelector("#layanan-contents");
    const isFeedbackForm =
        contentsContainer && !contentsContainer.querySelector(".tab-content");

    if (isFeedbackForm) {
        // Return to table view first, then switch to the clicked tab
        fetch("/api/layanan/data")
            .then((response) => response.json())
            .then((data) => {
                renderContents(data.contents);
                changeTab(tabName);
            })
            .catch((error) =>
                console.error("Gagal load layanan dari database:", error)
            );
    } else {
        // Normal tab switching
        changeTab(tabName);
    }
}

// Star rating functionality
document.addEventListener("click", function (e) {
    if (e.target && e.target.classList.contains("rating-star")) {
        const rating = parseInt(e.target.getAttribute("data-rating"));
        const stars = document.querySelectorAll(".rating-star");

        stars.forEach((star, index) => {
            if (index < rating) {
                star.classList.remove("text-gray-300");
                star.classList.add("text-yellow-400");
            } else {
                star.classList.remove("text-yellow-400");
                star.classList.add("text-gray-300");
            }
        });
    }
});

// Map tab ID to document type
function mapTabToDocumentType(tabId) {
    const mapping = {
        amdal: "AMDAL",
        "ukl-upl": "UKL-UPL",
        addendum: "Addendum",
        audit: "AUDIT",
    };
    return mapping[tabId] || "AMDAL";
}

// Apply filters function
function applyFilters() {
    const searchValue =
        document.querySelector('input[placeholder="Search"]')?.value || "";
    const kabkotaValue = document.getElementById("kabkota")?.value || "";
    const kecamatanValue = document.getElementById("kecamatan")?.value || "";
    const kelurahanValue = document.getElementById("kelurahan")?.value || "";

    // Get current active tab
    const activeTab = document.querySelector(".tab-btn.bg-blue-900");
    const activeTabId = activeTab ? activeTab.id.replace("tab-", "") : "amdal";

    const params = new URLSearchParams({
        search: searchValue,
        kabkota: kabkotaValue,
        kecamatan: kecamatanValue,
        kelurahan: kelurahanValue,
        jenis_dokumen: mapTabToDocumentType(activeTabId),
    });

    fetch(`/api/layanan/filter?${params}`)
        .then((response) => response.json())
        .then((data) => {
            renderContents(data);
            changeTab(activeTabId);
        })
        .catch((error) => {
            console.error("Error applying filters:", error);
        });
}

// Load original data function
function loadOriginalData() {
    fetch("/api/layanan/data")
        .then((response) => response.json())
        .then((data) => {
            renderContents(data.contents);
            changeTab("amdal");
        })
        .catch((error) =>
            console.error("Gagal load layanan dari database:", error)
        );
}
