<!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 = {
    "Dung lượng": [
      "Truyện dài", "Truyện ngắn", "Tản văn"
    ],

    "Thể loại": [
      "Bí Ẩn", "Cổ Trang", "Hành động", "Hài Hước", "Hiện thực", "Hư Cấu", "Kì Ảo",
      "Khoa Học Viễn Tưởng", "Kinh Dị", "Lãng Mạn", "Lịch sử", "NamxNam", "NữxNữ",
      "Phiêu Lưu", "Tâm Linh", "Tâm Lí", "Tiên Hiệp", "Trinh Thám", "Viễn Tưởng"
    ],

	"Chủ đề": [
	  "Âm nhạc", "Đào tạo", "E-sport", "Khoa học công nghệ", "Ma pháp", "Nấu ăn", "Quan trường",
 	 "Sinh tồn", "Thể thao", "Thi đấu", "Thương trường", "Quân đội", "Tu tiên", "Võ hiệp", "Y học"
	],

    "Phong cách truyện": [
      "Chữa lành", "Điền văn", "Hoài niệm", "Kịch tính", "Ngọt sủng", "Sủng ngược đan xen",
      "Tăm tối", "Truyện buồn", "Truyện dài", "Truyện ngược", "Truyện vui", "Thực tế"
    ],

    "Bối cảnh": [
      "Cận đại", "Cổ đại", "Hiện đại", "Tương lai"
    ],

    "Thời không": [
      "Dị giới", "Giới giải trí", "Hậu tận thế", "Thế giới cao võ", "Thế giới dị năng",
      "Thế giới song song", "Tận thế", "Vương triều tranh bá", "Xã hội đen"
    ],

    "Nhân vật chính": [
      "Bàn tay vàng", "Con nhà nghèo", "Con nhà giàu", "Kẻ săn tiền thưởng", "Linh mục",
      "Người thường", "Nhân vật phụ", "Phản diện", "Phù thủy", "Phế tài", "Sát thủ",
      "Tổng tài", "Xuyên không", "Bác học", "Nội gián", "Thăng cấp"
    ],

    "Chủng tộc": [
      "Con người", "Kỹ thuật sinh học", "Linh hồn/ma quỷ", "Người ngoài hành tinh", "Yêu quái"
    ],

    "Tính cách": [
      "Ái kỷ", "Ám ảnh tâm lý", "Cứng đầu", "Điềm đạm", "Dễ nóng giận", "Điên loạn",
      "Giảo hoạt", "Lạnh lùng", "Kiêu ngạo", "Mơ mộng", "Ngây thơ", "Ngu ngốc", "Nhiệt huyết",
      "Thông minh", "Vô sỉ", "Yêu động vật", "Đa nhân cách"
    ],

    "Mối quan hệ": [
      "Ân nhân", "Cường cường", "Cường nhược", "Đồng nghiệp", "Hôn nhân hợp đồng", "Kẻ thù đến tình nhân",
      "Người yêu cũ", "Người lạ", "Oan gia ngõ hẹp", "Sư đồ luyến", "Thanh mai trúc mã",
      "Tình một đêm", "Tình tay ba", "Thần phàm", "Thế thân", "Trả thù", "Yêu thầm", "Cưới trước yêu sau"
    ]
  };


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

function toggleTagSelection(tagElement) {
  // Định nghĩa giới hạn số lượng thẻ tối đa có thể chọn cho mỗi nhóm
const maxTagsPerGroup = {
  "Dung lượng": 1,         // Giới hạn 3 thẻ cho nhóm "Dung lượng"
  "Thể loại": 3,           // Giới hạn 5 thẻ cho nhóm "Thể loại"
  "Chủ đề": 2,             // Giới hạn 4 thẻ cho nhóm "Chủ Đề"
  "Phong cách truyện": 1,  // Giới hạn 4 thẻ cho nhóm "Phong cách truyện"
  "Bối cảnh": 1,           // Giới hạn 2 thẻ cho nhóm "Bối cảnh"
  "Thời không": 1,         // Giới hạn 3 thẻ cho nhóm "Thời không"
  "Nhân vật chính": 1,     // Giới hạn 5 thẻ cho nhóm "Nhân vật chính"
  "Chủng tộc": 1,          // Giới hạn 3 thẻ cho nhóm "Chủng tộc"
  "Tính cách": 1,          // Giới hạn 4 thẻ cho nhóm "Tính cách"
  "Mối quan hệ": 1         // Giới hạn 4 thẻ cho nhóm "Mối quan hệ"
};


  // Lấy nhóm thẻ hiện tại
  const tagGroup = tagElement.closest('.tag-group');
  const groupTitle = tagGroup.querySelector('div').textContent.trim().replace(':', ''); // Lấy tiêu đề nhóm
  const groupLimit = maxTagsPerGroup[groupTitle]; // Lấy giới hạn cho nhóm đó

  if (!groupLimit) {
    return; // Nếu không tìm thấy giới hạn, không thực hiện gì
  }

  const selectedTagsInGroup = tagGroup.querySelectorAll('.tag.selected'); // Lấy các thẻ đã chọn trong nhóm

  // Nếu thẻ đang được chọn, bỏ chọn thẻ
  if (tagElement.classList.contains('selected')) {
    tagElement.classList.remove('selected');
  } else if (selectedTagsInGroup.length < groupLimit) {
    // Nếu chưa đạt giới hạn, cho phép chọn thẻ
    tagElement.classList.add('selected');
  } else {
    // Nếu đã đạt giới hạn, hiển thị thông báo hoặc không cho phép chọn thêm
    alert(`Bạn chỉ có thể chọn tối đa ${groupLimit} thẻ trong nhóm "${groupTitle}".`);
  }
}


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