<!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>

.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;
    }

    .tag {
	  border: 1px solid var(--contentL); 
      background:var(--contentBs);
      color: var(--bodyC);
      padding: 3px 6px;
      cursor: pointer;
      font-size: 14px;
      user-select: none;
      transition: background-color .3s ease;
    }

    .tag.selected {
      background-color: var(--linkB);
      color: white;
    }

    .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;
    }

    .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 */
}
.tag-group {
  margin-bottom: 20px;
  color: var(--darkTa);
  text-align: left; /* Căn trái nội dung trong tag-group */
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* Khoảng cách giữa các tag */
}

.tag {
  display: inline-block;  /* Đảm bảo mỗi tag là một khối inline */
  margin-bottom: 5px;  /* Khoảng cách giữa các tag */
  padding: 5px;

  cursor: pointer;
  flex-grow: 1;  /* Các tag sẽ giãn ra để lấp đầy không gian */
  min-width: 100px;  /* Đặt một chiều rộng tối thiểu cho tag */
  text-align: center;  
}

    /* Định dạng chung cho nút */
button:disabled {
  cursor: not-allowed; /* Đổi con trỏ khi rê chuột vào nút disabled */
  background-color: #f0f0f0; /* Màu nền mờ cho nút disabled */
  color: #999; /* Màu chữ mờ cho nút disabled */
}
.word-count {
  display: flex;
  justify-content: flex-end; /* Căn phải */
  font-size: 12px; /* Tăng kích thước chữ cho dễ đọc */
  color: var(--darkTa); /* Sử dụng màu nổi bật */
  margin-bottom: 6px; /* Tạo khoảng cách phía trên */
  margin-top: 0;
  font-style: italic; /* Thêm kiểu chữ nghiêng */
}
input[readonly], textarea[readonly] {
  background-color: #f0f0f0;
  color: #999;
  cursor: not-allowed;
}

    
  </style>
</head>
<body>
<div class="container">
  <form id="checkDataForm">
    <div class="form-group">
      <!-- Các trường dữ liệu sẽ được tạo tự động -->
    </div>
    <p id="checkResponse" class="response"></p>
    <div class="loader" id="loader" style="display: none;"></div>
    <!-- Nút Cập Nhật và Spinner -->
    <div class="form-group" style="display: flex; flex-direction: column; align-items: center;">
      <button type="button" class="submit-btn" id="submitUpdateButton" style="display: none;">Cập nhật</button>
      <button type="button" class="submit-btn" id="submitSendButton" style="display: none;">Gửi duyệt</button>
    </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");
const submitUpdateButton = document.getElementById("submitUpdateButton");
const submitSendButton = document.getElementById("submitSendButton");

// Hàm giải mã Base64
function decodeBase64(encodedStr) {
  try {
    return atob(encodedStr);
  } catch (e) {
    return null;
  }
}

// Lấy tham số từ URL
function getURLParameter(param) {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(param);
}

// Gửi yêu cầu API
async function fetchDataById(id) {
  loader.style.display = "block"; // Hiển thị loader
  try {
    const response = await fetch(`${scriptUrl}?action=get&id=${encodeURIComponent(id)}`);
    const result = await response.json();
    loader.style.display = "none"; // Ẩn loader sau khi nhận phản hồi

    if (result.error) {
      checkResponse.textContent = `Lỗi: ${result.error}`;
      checkResponse.classList.add("error");
      checkResponse.classList.remove("success");
    } else {
      // Giao diện hiển thị kết quả
      renderResult(result, id);
    }
  } catch (error) {
    loader.style.display = "none";
    checkResponse.textContent = `Lỗi: ${error.message}`;
    checkResponse.classList.add("error");
    checkResponse.classList.remove("success");
  }
}

function renderResult(result, id) {
  const availableTags = {
    "Thể loại chính": [
      "Hành Động", "Giật Gân", "Phiêu Lưu", "Kinh Dị", "Lãng Mạn", "Hiện Thực", "Lịch Sử", "Trinh Thám", "Tâm Lý"
    ],
    "Thể loại phụ": [
      "Bí Ẩn", "Hư Cấu", "Kì Ảo", "Tiên Hiệp", "Viễn Tưởng", "Khoa Học Viễn Tưởng", "Tận Thế", "Tâm Linh"
    ],
    "Tình cảm": [
      "NamxNam", "NữxNữ", "Cổ Trang", "18+"
    ]
  };

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

  // Lặp qua các nhóm tag và thêm tiêu đề
  Object.keys(availableTags).forEach(group => {
    tagsHTML += `
      <div class="tag-group">
        <div>${group}:</div>
        <div class="tags-container">
          ${availableTags[group].map(tag => {
            const isSelected = selectedTags.includes(tag) ? 'selected' : '';
            return `
              <span class="tag ${isSelected}" data-value="${tag}" onclick="toggleTagSelection(this)">
                ${tag}
              </span>
            `;
          }).join('')}
        </div>
      </div>
    `;
  });

const output = `
  <div class="form-group">
    <label for="updateTacPham">Tác phẩm:</label>
    <input type="text" id="updateTacPham" value="${result.tacPham || ''}" placeholder="Điền tên tác phẩm...">
  </div>
  <div class="form-group">
    <label for="updateTacGia">Tác giả:</label>
    <input type="text" id="updateTacGia" value="${result.tacGia || ''}" placeholder="Điền tên tác giả...">
  </div>
  <div class="form-group">
    <label for="updateTheLoai">Thể loại:</label>
    <div id="tagsContainer">
      ${tagsHTML}
    </div>
  </div>
  <div class="form-group">
    <label for="updateUrlBia">URL bìa:</label>
    <input type="url" id="updateUrlBia" value="${result.urlBia || ''}" placeholder="Có thể lấy link từ mục hỗ trợ trong menu...">
  </div>
  <div class="form-group">
    <label for="updateTrichDoan">Giới thiệu:</label>
    <textarea id="updateTrichDoan" rows="4" placeholder="Điền giới thiệu tác phẩm...">${result.trichDoan || ''}</textarea>
  </div>
  <div class="form-group">
    <label for="updateChuong1">Bản thảo chương 1:</label>
    <textarea id="updateChuong1" rows="4" placeholder="Bản thảo tối thiểu 800 từ, tối đa 8000 từ...">${result.chuong1 || ''}</textarea>
    </div>
    <div class="word-count">
    <span id="wordCountChuong1" class="word-count">0 từ</span>
  </div>
  <div class="form-group">
    <label for="updateChuong2">Bản thảo chương 2:</label>
    <textarea id="updateChuong2" rows="4" placeholder="Bản thảo tối thiểu 800 từ, tối đa 8000 từ...">${result.chuong2 || ''}</textarea>
    </div>
    <div class="word-count">
    <span id="wordCountChuong2" class="word-count">0 từ</span>
  </div>
  <div class="form-group">
    <label for="updateChuong3">Bản thảo chương 3:</label>
    <textarea id="updateChuong3" rows="4" placeholder="Bản thảo tối thiểu 800 từ, tối đa 8000 từ...">${result.chuong3 || ''}</textarea>
    </div>
    <div class="word-count">
    <span id="wordCountChuong3" class="word-count">0 từ</span>
  </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>
`;


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

  function updateWordCount() {
  ["updateChuong1", "updateChuong2", "updateChuong3"].forEach((id, index) => {
    const textarea = document.getElementById(id);
    const wordCountSpan = document.getElementById(`wordCountChuong${index + 1}`);
    if (textarea && wordCountSpan) {
      textarea.addEventListener('input', () => {
        const wordCount = textarea.value.trim().split(/\s+/).filter(word => word).length;
        wordCountSpan.textContent = `${wordCount} từ`;
      });

      // Gọi ngay để hiển thị số từ ban đầu
      const initialWordCount = textarea.value.trim().split(/\s+/).filter(word => word).length;
      wordCountSpan.textContent = `${initialWordCount} từ`;
    }
  });
}

// Gọi hàm sau khi render
updateWordCount();

  // Kiểm tra các trường dữ liệu và vô hiệu hóa nút "Gửi duyệt" nếu có trường rỗng
function validateFields() {
  const fields = [
    "updateTacPham",
    "updateTacGia",
    "updateUrlBia",
    "updateTrichDoan"
  ]; // Các trường cơ bản (không bao gồm chương)

  let isValid = true;

  // Kiểm tra các trường cơ bản
  fields.forEach(field => {
    const fieldElement = document.getElementById(field);
    if (!fieldElement || !fieldElement.value.trim()) {
      isValid = false;
    }
  });

  // Kiểm tra số từ của các trường chương
  ["updateChuong1", "updateChuong2", "updateChuong3"].forEach(chapterField => {
    const chapterElement = document.getElementById(chapterField);
    if (chapterElement) {
      const wordCount = chapterElement.value.trim().split(/\s+/).length; // Đếm số từ
      if (wordCount < 800) {
        isValid = false;
      }
    } else {
      isValid = false; // Nếu không tìm thấy trường
    }
  });

  // Kiểm tra ít nhất một thẻ tag được chọn
  const activeTags = document.querySelectorAll('.tag.selected');
  if (activeTags.length === 0) {
    isValid = false;
  }

  // Cập nhật trạng thái của nút gửi
  const submitSendButton = document.getElementById("submitSendButton");
  if (submitSendButton) {
    submitSendButton.disabled = !isValid; // Disable nếu bất kỳ điều kiện nào không hợp lệ
  }
}

  // Gọi hàm validateFields sau khi render dữ liệu
  validateFields();

  // Lắng nghe sự kiện input trên tất cả các trường và gọi validateFields mỗi khi có thay đổi
  document.querySelectorAll('input, textarea, select').forEach(input => {
    input.addEventListener('input', validateFields);
  });

// Hiển thị nút "Cập Nhật" nếu có ID, nút "Gửi duyệt" nếu không có ID
if (id) {
  submitUpdateButton.style.display = "block";
  submitSendButton.style.display = "none";

  // Không cho phép chỉnh sửa trường Tác giả
  document.getElementById("updateTacGia").readOnly = true;

  // Kiểm tra tình trạng
  if (result.trangThai === "Đã duyệt") {
    // Không cho phép chỉnh sửa trường Tác phẩm nếu tình trạng là "Đã duyệt"
    document.getElementById("updateTacPham").readOnly = true;

    // Không cho phép chỉnh sửa các trường Bản thảo chương 1, 2, 3
    document.getElementById("updateChuong1").readOnly = true;
    document.getElementById("updateChuong2").readOnly = true;
    document.getElementById("updateChuong3").readOnly = true;
  } else {
    // Cho phép chỉnh sửa trường Tác phẩm nếu không phải "Đã duyệt"
    document.getElementById("updateTacPham").readOnly = false;

    // Cho phép chỉnh sửa các trường Bản thảo chương 1, 2, 3 nếu không phải "Đã duyệt"
    document.getElementById("updateChuong1").readOnly = false;
    document.getElementById("updateChuong2").readOnly = false;
    document.getElementById("updateChuong3").readOnly = false;
  }
} else {
  submitSendButton.style.display = "block";
  submitUpdateButton.style.display = "none";

  // Đảm bảo tất cả các trường có thể chỉnh sửa khi không có ID
  document.getElementById("updateTacPham").readOnly = false;
  document.getElementById("updateTacGia").readOnly = false;
  document.getElementById("updateChuong1").readOnly = false;
  document.getElementById("updateChuong2").readOnly = false;
  document.getElementById("updateChuong3").readOnly = false;
}



  // Sự kiện cập nhật dữ liệu
  submitUpdateButton.addEventListener("click", async () => {
    loader.style.display = "block"; 
    submitUpdateButton.disabled = true; 

    const updatedData = {
      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,
    };

    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");

        // Reload the data after update
        fetchDataById(id);
      } 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");
    } finally {
      loader.style.display = "none"; // Ẩn spinner
      submitUpdateButton.disabled = false; // Enable the button after update
    }
  });

  // Sự kiện gửi duyệt dữ liệu
  submitSendButton.addEventListener("click", async () => {
    loader.style.display = "block"; 
    submitSendButton.disabled = true; 

    const newData = {
      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,
    };

    try {
      const sendResponse = await fetch(`${scriptUrl}?action=add&` + new URLSearchParams(newData));
      const sendResult = await sendResponse.json();

      if (sendResult.success) {
        // Tách phần XXX và YYY từ ID
        const [part1, part2] = sendResult.id.split("-");

        // Tạo nội dung phản hồi với phần XXX in đỏ
        checkResponse.innerHTML = `
          Tác phẩm đã được nhận và đang đợi kiểm duyệt với ID là: 
          <span style="color: red;">${part1}</span>-${part2}
        `;
        checkResponse.classList.add("success");
        checkResponse.classList.remove("error");

        // Ẩn nút "Gửi duyệt"
        document.getElementById("submitSendButton").style.display = "none";
        
        // Thêm chú thích nhỏ
        const note = document.createElement("span");
        note.textContent = "Tuyệt đối không được để lộ dãy ID trên, trước khi thoát khỏi trang, vui lòng lưu giữ phần ID được đánh dấu đỏ một cách cẩn thận! Nếu bạn thấy phần ID được đánh dấu đỏ bị khuyết, bút danh bạn sử dụng đã tồn tại trên hệ thống!";
        note.style.color = "var(--darkTa)";
        note.style.display = "block"; // Hiển thị theo block để xuống dòng
        checkResponse.appendChild(note);
      } else {
        checkResponse.textContent = `Lỗi: ${sendResult.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");
    } finally {
      loader.style.display = "none"; // Ẩn spinner
      submitSendButton.disabled = false; // Enable the button after sending
    }
  });
}


// Tự động xử lý khi tham số ID tồn tại trong URL
const urlEncodedId = getURLParameter("id");
if (urlEncodedId) {
  const decodedId = decodeBase64(urlEncodedId);
  if (decodedId) {
    fetchDataById(decodedId); // Gửi truy vấn ngay khi giải mã thành công
  } else {
    checkResponse.textContent = "Lỗi: ID không hợp lệ (Base64)";
    checkResponse.classList.add("error");
    checkResponse.classList.remove("success");
  }
} else {
  // Nếu không có ID, hiển thị các trường rỗng
  renderResult({}, null);
}

// Các hàm hỗ trợ xử lý thẻ
function toggleTagSelection(tagElement) {
  const tag = tagElement.dataset.value;
  tagElement.classList.toggle("selected");
}

function getSelectedTags() {
  return Array.from(document.querySelectorAll(".tag.selected")).map(tag => tag.dataset.value);
}
</script>



