<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Tạo và sửa tác phẩm</title>
<style>.form-group{display:flex;align-items:center;justify-content:space-between;margin-bottom:15px;gap:10px}.form-group label{font-weight:700;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:#fff}.submit-btn{background-color:var(--linkB);color:#fff;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:700;margin-bottom:20px}.success{color:green}.error{color:red}.loader{display:none;border:4px solid rgb(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}.row div{width:48%}.response{margin-top:15px;text-align:center;font-weight:700;margin-bottom:20px}.tag-group{margin-bottom:20px;color:var(--darkTa);text-align:left}.tags-container{display:flex;flex-wrap:wrap;gap:10px}.tag{display:inline-block;margin-bottom:5px;padding:5px;cursor:pointer;flex-grow:1;min-width:100px;text-align:center}button:disabled{cursor:not-allowed;background-color:#fff;color:gray}.word-count{display:flex;justify-content:flex-end;font-size:12px;color:var(--darkTa);margin-bottom:6px;margin-top:0;font-style:italic}input[readonly],textarea[readonly]{background-color:gray;color:#fff;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/AKfycbwMqSA4DryXn8o2cIhPenwhRdutcGaZabrQwQ5qxXiylIEeyAEpYX_gw1L1Jx5EQkB2CQ/exec";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");function decodeBase64(encodedStr){try{return atob(encodedStr)}catch(e){return null}}
function getURLParameter(param){const urlParams=new URLSearchParams(window.location.search);return urlParams.get(param)}
async function fetchDataById(id){loader.style.display="block";try{const response=await fetch(scriptUrl,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded',},body:new URLSearchParams({action:'get',id:encodeURIComponent(id)})});const result=await response.json();loader.style.display="none";if(result.error){checkResponse.textContent=`Lỗi: ${result.error}`;checkResponse.classList.add("error");checkResponse.classList.remove("success")}else{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={"Hình thức":["Cổ tích","Hồi kí","Kịch","Phóng sự","Sử thi","Thơ","Tản văn","Truyền thuyết","Truyện ngắn","Tự truyện"],"Thể loại":["Bí ẩn","Chiến tranh","Cổ trang","Hài hước","Hành động","Hiện thực","Học đường","Hư cấu","Khoa học viễn tưởng","Khoa học","Kì ảo","Kinh dị","Lãng mạn","Lịch sử","Namxnam","Nữxnữ","Phiêu lưu","Tâm linh","Tâm lí","Thần bí","Tiên hiệp","Tình cảm","Trinh thám","Viễn tưởng"],"Chủ đề":["Âm nhạc","Báo thù","Cuộc chiến gia tộc","Cuộc sống nông thôn","Cuộc sống thành thị","Đào tạo","Đế chế","E-sport","Hậu tận thế","Học đường","Khoa học","Kinh doanh","Ma pháp","Nền văn minh","Nấu ăn","Quan trường","Quân đội","Quyền lực","Siêu anh hùng","Sinh tồn","Thám hiểm","Thần thoại","Thể thao","Thi đấu","Thương trường","Thần thoại","Tu tiên","Võ hiệp","Vũ trụ","Y học","Ác quỷ"],"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","Thực tế","Truyện buồn","Truyện hài","Truyện ngược","Truyện vui"],"Bối cảnh":["Cận đại","Cổ đại","Hiện đại","Tương lai"],"Thời không":["Chiều không gian khác","Dị giới","Giới giải trí","Hậu tận thế","Thế giới cao võ","Thế giới động vật","Thế giới dị năng","Thế giới phép thuật","Thế giới song song","Thời đại băng hà","Thời đại nguyên thủy","Tận thế","Vương triều","Viễn tây","Xã hội đen"],"Nhân vật chính":["Phi nhân loại","Bác học","Bàn tay vàng","Chiến thần","Con nhà giàu","Con nhà nghèo","Gián điệp","Kẻ săn tiền thưởng","Linh mục","Người thường","Nhân vật phụ","Nội gián","Phản diện","Phế tài","Phù thủy","Sát thủ","Thăng cấp","Tổng tài","Xuyên không"],"Tính cách":["Ái kỷ","Ám ảnh tâm lý","Cứng đầu","Dễ nóng giận","Điên loạn","Điềm đạm","Đa nhân cách","Giảo hoạt","Kiêu ngạo","Lạnh lùng","Mơ mộng","Ngây thơ","Ngu ngốc","Nhiệt huyết","Thông minh","Vô sỉ","Yêu động vật","Hội chứng"],"Mối quan hệ":["Ân nhân","Bạn bè","Gia đình","Cưới trước yêu sau","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 lạ","Người yêu cũ","Oan gia ngõ hẹp","Sư đồ luyến","Thanh mai trúc mã","Thần phàm","Robot","Thế thân","Tình một đêm","Tình tay ba","Yêu thầm"]};const selectedTags=result.theLoai?result.theLoai.split(',').map(tag=>tag.trim()):[];let tagsHTML='';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="word-count">
      <span class="word-count">* Nhận mọi số nguyên nhưng không bắt đầu bằng số 0!</span>
    </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="word-count">
      <span class="word-count">* Nhận mọi số nguyên nhưng không bắt đầu bằng số 0!</span>
    </div>
    <div class="form-group">
      <label for="updateTheLoai"></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="Lấy link bìa phía trên...">
    </div>
            <div class="word-count">
      <span class="word-count">Kích cỡ bìa truyện chuẩn là 2:3.</span>
    </div>
    <div class="form-group">
      <label for="updateTrichDoan">Giới thiệu:</label>
      <textarea id="updateTrichDoan" rows="4" style="height: 300px;" placeholder="Điền giới thiệu tác phẩm...">${result.trichDoan || ''}</textarea>
    </div>
            <div class="word-count">
      <span class="word-count">* Không khuyến khích viết quá dài.</span>
    </div>
    <div class="form-group">
      <label for="updateChuong3">Bản thảo</label>
      <textarea id="updateChuong3" rows="4" style="height: 400px;" placeholder="Bản thảo tối thiểu 400 từ, tối đa 40.000 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">Lời nhắn:</label>
  <input type="text" id="updateProgress" name="progress" value="${result.progress || 'Không có'}" required>
</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=`400 < ${wordCount} từ < 40000`});const initialWordCount=textarea.value.trim().split(/\s+/).filter(word=>word).length;wordCountSpan.textContent=`400 < ${initialWordCount} từ < 40000`}})}
updateWordCount();if(id){submitUpdateButton.style.display="block";submitSendButton.style.display="none";document.getElementById("updateTacGia").readOnly=!0;if(result.trangThai==="Đã duyệt"){document.getElementById("updateTacPham").readOnly=!0;document.getElementById("updateChuong3").readOnly=!0}else{document.getElementById("updateTacPham").readOnly=!1;document.getElementById("updateChuong3").readOnly=!1}}else{submitSendButton.style.display="block";submitUpdateButton.style.display="none";document.getElementById("updateTacPham").readOnly=!1;document.getElementById("updateTacGia").readOnly=!1;document.getElementById("updateChuong3").readOnly=!1}
submitUpdateButton.addEventListener("click",async()=>{loader.style.display="block";submitUpdateButton.disabled=!0;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,chuong3:document.getElementById("updateChuong3").value,};try{const updateResponse=await fetch(scriptUrl,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded',},body:new URLSearchParams({action:'update',...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");fetchDataById(id)}else{checkResponse.textContent=`${updateResult.error}`;checkResponse.classList.add("error");checkResponse.classList.remove("success")}}catch(error){checkResponse.textContent=`${error.message}`;checkResponse.classList.add("error");checkResponse.classList.remove("success")}finally{loader.style.display="none";submitUpdateButton.disabled=!1;submitUpdateButton.style.display='none'}});submitSendButton.addEventListener("click",async()=>{loader.style.display="block";submitSendButton.disabled=!0;function countWords(text){return text.trim().split(/\s+/).length}
function isValidUrl(url){const pattern=/^(https?:\/\/)/;return pattern.test(url)}
function validateFields(){const tacPham=document.getElementById("updateTacPham").value.trim();const tacGia=document.getElementById("updateTacGia").value.trim();const urlBia=document.getElementById("updateUrlBia").value.trim();const trichDoan=document.getElementById("updateTrichDoan").value.trim();const progress=document.getElementById("updateProgress").value.trim();const chuong3=document.getElementById("updateChuong3").value.trim();const wordCount3=countWords(chuong3);const isUrlValid=isValidUrl(urlBia);const isWordCountValid=wordCount3>=400&&wordCount3<=40000;const areFieldsFilled=tacPham&&tacGia&&urlBia&&trichDoan&&progress&&chuong3;const isValid=isUrlValid&&isWordCountValid&&areFieldsFilled;const submitButton=document.getElementById("submitSendButton");submitButton.disabled=!isValid;submitButton.style.backgroundColor=isValid?"":"gray";submitButton.style.color=isValid?"":"white"}["updateTacPham","updateTacGia","updateUrlBia","updateTrichDoan","updateProgress","updateChuong3"].forEach(fieldId=>{document.getElementById(fieldId).addEventListener("input",validateFields)});validateFields();const newData={tacPham:document.getElementById("updateTacPham").value,tacGia:document.getElementById("updateTacGia").value,theLoai:["Oneshot",...getSelectedTags()].join(','),urlBia:document.getElementById("updateUrlBia").value,trichDoan:document.getElementById("updateTrichDoan").value,progress:document.getElementById("updateProgress").value,chuong3:document.getElementById("updateChuong3").value,};try{const sendResponse=await fetch(scriptUrl,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded',},body:new URLSearchParams({action:'add',...newData,}),});const sendResult=await sendResponse.json();if(sendResult.success){const[part1,part2]=sendResult.id.split("-");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");document.getElementById("submitSendButton").style.display="none";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!";note.style.color="var(--darkTa)";note.style.display="block";checkResponse.appendChild(note)}else{checkResponse.textContent=`${sendResult.error}`;checkResponse.classList.add("error");checkResponse.classList.remove("success")}}catch(error){checkResponse.textContent=`${error.message}`;checkResponse.classList.add("error");checkResponse.classList.remove("success")}finally{loader.style.display="none";submitSendButton.disabled=!1;submitSendButton.style.display='none'}})}
if(performance.navigation.type===1){console.log("Trang đã được tải lại. Giữ lại sessionStorage.")}else{sessionStorage.removeItem('currentId');console.log("Trang đã chuyển đi. Xóa sessionStorage.")}
const urlEncodedId=getURLParameter("id");if(urlEncodedId){const decodedId=decodeBase64(urlEncodedId);if(decodedId){fetchDataById(decodedId);sessionStorage.setItem('currentId',decodedId);const url=new URL(window.location);url.searchParams.delete("id");window.history.pushState({},"",url)}else{checkResponse.textContent="Có lỗi xảy ra, vui lòng thử lại.";checkResponse.classList.add("error");checkResponse.classList.remove("success")}}else if(sessionStorage.getItem('currentId')){const decodedId=sessionStorage.getItem('currentId');fetchDataById(decodedId)}else{renderResult({},null)}
function toggleTagSelection(tagElement){const maxTagsPerGroup={"Hình thức":1,"Thể loại":3,"Chủ đề":3,"Phong cách truyện":1,"Bối cảnh":1,"Thời không":1,"Nhân vật chính":1,"Tính cách":1,"Mối quan hệ":1};const tagGroup=tagElement.closest('.tag-group');const groupTitle=tagGroup.querySelector('div').textContent.trim().replace(':','');const groupLimit=maxTagsPerGroup[groupTitle];if(!groupLimit){return}
const selectedTagsInGroup=tagGroup.querySelectorAll('.tag.selected');if(tagElement.classList.contains('selected')){tagElement.classList.remove('selected')}else if(selectedTagsInGroup.length<groupLimit){tagElement.classList.add('selected')}else{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>






