<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Kiểm Tra ID</title>
  <style>

    h2 {
      text-align: center;
    }

.form-group {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  gap: 10px; /* Khoảng cách giữa input và button */
}


    .form-group label {
      font-weight: bold;
      width: 150px;
      font-size: 16px;
      text-align: center;
      color: var(--bodyC);
    }

    .form-group input, .form-group textarea, .form-group select {
      padding: 12px;
      font-size: 16px;
      border: 1px solid var(--contentL);
      background: var(--contentB);
      border-radius: 8px;
      width: 100%;
      box-sizing: border-box;
      transition: border-color .3s, background-color .3s;
      color: var(--bodyC);
    }


    .tags-container {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-top: 10px;
      justify-content: center;
    }

    .tag {
      background-color: #007bff;
      color: white;
      padding: 8px 16px;
      border-radius: 20px;
      cursor: pointer;
      font-size: 14px;
      user-select: none;
      transition: background-color .3s ease;
    }

    .tag.selected {
      background-color: #28a745;
    }

    .tag:hover {
      background-color: #0056b3;
    }

    .submit-btn {
      background-color: #007bff;
      color: white;
      padding: 12px 20px;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-size: 16px;
      width: auto;
      margin: 0 auto;
      display: block;
      transition: background-color .3s ease;
    }

    .submit-btn:hover {
      background-color: #0056b3;
    }

    .response {
      margin-top: 15px;
      text-align: center;
      font-weight: bold;
      margin-bottom: 20px;
    }

    .success {
      color: green;
    }

    .error {
      color: red;
    }

    .loader {
      display: none;
      border: 4px solid rgba(0, 0, 0, .1);
      border-left-color: #007bff;
      border-radius: 50%;
      width: 24px;
      height: 24px;
      animation: loader 1s linear infinite;
      margin: 0 auto;
      margin-bottom: 20px;
    }

    @keyframes loader {
      to {
        transform: rotate(360deg);
      }
    }

    @media (max-width: 768px) {
      .form-group {
        flex-direction: column;
        align-items: flex-start;
      }

      .form-group label {
        width: auto;
      }

      .tags-container {
        justify-content: flex-start;
      }

      button {
        width: auto;
      }
    }

 .row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px; /* Added space below the row */
}

.row div {
  width: 48%;
}

.response {
  margin-top: 15px;
  text-align: center;
  font-weight: bold;
  margin-bottom: 20px; /* Space added below the response */
}

    
    /* Center Mã chính field and add space below */
    .maChinh-container {
      display: flex;
      justify-content: center;
      margin-bottom: 20px;
    }

    .maChinh-container input {
      text-align: center;
      width: 100%;
      max-width: 300px;
      border: 1px solid var(--contentL);
      background: var(--contentB);
            padding: 12px;
      border-radius: 8px;
    
    }
    
  </style>
</head>
<body>
  <div class="container">
    <form id="checkDataForm">
      <div class="form-group">
        <input type="text" id="id" name="id" placeholder="Truy vấn ID..."  style="flex: 2;" required>
        <button type="submit" class="submit-btn" style="flex: 1; margin-left: 10px; display: flex; justify-content: center; align-items: center;">Xác nhận</button>
      </div>
      <p id="checkResponse" class="response"></p>
      <div class="loader" id="loader"></div>
    </form>
  </div>

<script>
const scriptUrl = "https://script.google.com/macros/s/AKfycbwlTwlxo5bHAbMOOE9ER6x7uN41scjx2XmKzPq7PLrIzl4QWvqvvsf8JxM2XEyUC_Q/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", "Giật Gân", "Phiêu Lưu", "Hài Hước", "Kinh Dị", "Lãng Mạn", "Hiện Thực",
        "Lịch Sử", "Trinh Thám", "Tâm Lý", "Bí Ẩn", "Viễn Tưởng", "Khoa Học Viễn Tưởng", "Tận Thế", "Tâm Linh",
        "NamxNam", "NữxNữ", "Cổ Trang", "18+"
      ];

      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> ${result.trangThai}</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">Giới thiệu:</label>
          <textarea id="updateTrichDoan" rows="4">${result.trichDoan}</textarea>
        </div>

      <div class="form-group">
          <label for="updateChuong1">Bản thảo chương 1:</label>
          <textarea id="updateChuong1" rows="4">${result.chuong1 || ''}</textarea>
        </div>
        <div class="form-group">
          <label for="updateChuong2">Bản thảo chương 2:</label>
          <textarea id="updateChuong2" rows="4">${result.chuong2 || ''}</textarea>
        </div>
        <div class="form-group">
          <label for="updateChuong3">Bản thảo chương 3:</label>
          <textarea id="updateChuong3" rows="4">${result.chuong3 || ''}</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,
                    chuong1: document.getElementById("updateChuong1").value,
          chuong2: document.getElementById("updateChuong2").value,
          chuong3: document.getElementById("updateChuong3").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>