<script>
const scriptUrl = "https://script.google.com/macros/s/AKfycby62R2xhdB30mn0a5BisCNmtaF5RfFmqVB5dOS3gvwTvppXXNuj4T6onevc7L5PG2yjFQ/exec";

// Xử lý form kiểm tra dữ liệu
const checkDataForm = document.getElementById("checkDataForm");
const checkResponse = document.getElementById("checkResponse");
const loader = document.getElementById("loader");

checkDataForm.addEventListener("submit", async (event) => {
  event.preventDefault();
  const id = document.getElementById("id").value;

  // Show the loader before starting the request
  loader.style.display = "block";
  
  try {
    const response = await fetch(`${scriptUrl}?action=get&id=${encodeURIComponent(id)}`);
    const result = await response.json();

    // Hide the loader once the response is received
    loader.style.display = "none";

    if (result.error) {
      checkResponse.textContent = `Lỗi: ${result.error}`;
      checkResponse.classList.add("error");
      checkResponse.classList.remove("success");
    } else {
      let additionalRow = "";
      if (result.trangThai === "Đã duyệt" || result.trangThai === "Không đủ điều kiện") {
        additionalRow = ` 
          <div class="maChinh-container">
            <input type="text" id="maChinh" value="${result.maChinh || 'N/A'}" readonly>
          </div>
        `;
      }

      const availableTags = [
        "Hành Động", "Phiêu Lưu", "Hài Hước", "Kinh Dị", "Lãng Mạn", 
        "Lịch Sử", "Trinh Thám", "Tâm Lý", "Huyền Bí", "Viễn Tưởng", 
        "NamxNam", "NữxNữ", "Cổ Trang"
      ];

      const selectedTags = result.theLoai ? result.theLoai.split(',').map(tag => tag.trim()) : [];

      let tagsHTML = '';
      availableTags.forEach(tag => {
        const isSelected = selectedTags.includes(tag) ? 'selected' : '';
        tagsHTML += `
          <span class="tag ${isSelected}" data-value="${tag}" onclick="toggleTagSelection(this)">
            ${tag}
          </span>
        `;
      });

      const output = `
  <div class="row">
    <div><strong>ID:</strong> ${result.id}</div>
    <div><strong>Trạng thái:</strong> 
      <span class="${result.trangThai === "Không đủ điều kiện" ? "error" : ""}">
        ${result.trangThai}
      </span>
      ${result.trangThai === "Đã duyệt" ? `
        <svg viewBox="-296.96 -296.96 1617.92 1617.92" class="icon" version="1.1" xmlns="http://www.w3.org/2000/svg" fill="#000000">
          <g id="SVGRepo_bgCarrier" stroke-width="0"></g>
          <g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g>
          <g id="SVGRepo_iconCarrier">
            <path d="M512 64l100.266667 76.8 123.733333-17.066667 46.933333 117.333334 117.333334 46.933333-17.066667 123.733333L960 512l-76.8 100.266667 17.066667 123.733333-117.333334 46.933333-46.933333 117.333334-123.733333-17.066667L512 960l-100.266667-76.8-123.733333 17.066667-46.933333-117.333334-117.333334-46.933333 17.066667-123.733333L64 512l76.8-100.266667-17.066667-123.733333 117.333334-46.933333 46.933333-117.333334 123.733333 17.066667z" fill="#8BC34A"></path>
            <path d="M738.133333 311.466667L448 601.6l-119.466667-119.466667-59.733333 59.733334 179.2 179.2 349.866667-349.866667z" fill="#CCFF90"></path>
          </g>
        </svg>
            ` : ''}
          </div>
        </div>
        ${additionalRow}
        <div class="form-group">
          <label for="updateTacPham">Tác phẩm:</label>
          <input type="text" id="updateTacPham" value="${result.tacPham}">
        </div>
        <div class="form-group">
          <label for="updateTacGia">Tác giả:</label>
          <input type="text" id="updateTacGia" value="${result.tacGia}">
        </div>
        <div class="form-group">
          <label for="updateTheLoai">Thể loại:</label>
          <div class="tags-container" id="tagsContainer">
            ${tagsHTML}
          </div>
        </div>
        <div class="form-group">
          <label for="updateUrlBia">URL Bìa:</label>
          <input type="url" id="updateUrlBia" value="${result.urlBia}">
        </div>
        <div class="form-group">
          <label for="updateTrichDoan">Trích đoạn:</label>
          <textarea id="updateTrichDoan" rows="4">${result.trichDoan}</textarea>
        </div>
        <div class="form-group">
          <label for="updateProgress">Tiến độ:</label>
          <select id="updateProgress" name="progress" required>
            <option value="Đang viết" ${result.progress === 'Đang viết' ? 'selected' : ''}>Đang viết</option>
            <option value="Hoàn thành" ${result.progress === 'Hoàn thành' ? 'selected' : ''}>Hoàn thành</option>
            <option value="Tạm ngừng" ${result.progress === 'Tạm ngừng' ? 'selected' : ''}>Tạm ngừng</option>
          </select>
        </div>
        <button class="submit-btn" id="submitUpdateButton">Cập Nhật</button>
      `;

      checkResponse.innerHTML = output;
      checkResponse.classList.add("success");
      checkResponse.classList.remove("error");

      document.getElementById("submitUpdateButton").addEventListener("click", async () => {
        const updatedData = {
          id: result.id,
          tacPham: document.getElementById("updateTacPham").value,
          tacGia: document.getElementById("updateTacGia").value,
          theLoai: getSelectedTags().join(','),
          urlBia: document.getElementById("updateUrlBia").value,
          trichDoan: document.getElementById("updateTrichDoan").value,
          progress: document.getElementById("updateProgress").value,
          maChinh: result.trangThai === "Đã duyệt" || result.trangThai === "Không đủ điều kiện" ? document.getElementById("maChinh").value : ''
        };

        try {
          const updateResponse = await fetch(`${scriptUrl}?action=update&` + new URLSearchParams(updatedData));
          const updateResult = await updateResponse.json();

          if (updateResult.success) {
            checkResponse.textContent = "Cập nhật dữ liệu thành công!";
            checkResponse.classList.add("success");
            checkResponse.classList.remove("error");
          } else {
            checkResponse.textContent = `Lỗi: ${updateResult.error}`;
            checkResponse.classList.add("error");
            checkResponse.classList.remove("success");
          }
        } catch (error) {
          checkResponse.textContent = `Lỗi: ${error.message}`;
          checkResponse.classList.add("error");
          checkResponse.classList.remove("success");
        }
      });
    }
  } catch (error) {
    loader.style.display = "none";
    checkResponse.textContent = `Lỗi: ${error.message}`;
    checkResponse.classList.add("error");
    checkResponse.classList.remove("success");
  }
});



  // Function to toggle tag selection (for updating selected tags)
  function toggleTagSelection(tagElement) {
    const tag = tagElement.dataset.value;
    const tagsContainer = document.getElementById("tagsContainer");
    const selectedTags = getSelectedTags();

    if (selectedTags.includes(tag)) {
      // If already selected, remove it
      tagElement.classList.remove("selected");
    } else {
      // If not selected, add it
      tagElement.classList.add("selected");
    }

    // Update the list of selected tags
    updateSelectedTags();
  }

  // Function to get selected tags
  function getSelectedTags() {
    const tagsContainer = document.getElementById("tagsContainer");
    return Array.from(tagsContainer.getElementsByClassName("selected")).map(tag => tag.dataset.value);
  }

  // Function to update the list of selected tags (stored in a hidden field or variable)
  function updateSelectedTags() {
    const selectedTags = getSelectedTags();
    console.log("Selected Tags:", selectedTags); // For debugging, can be used to check the selected tags
    // Optionally, update a hidden field or variable to store the selected tags if needed
  }
</script>
