<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>.tab{display:none}.tab.active{display:block}.form-group{margin-bottom:15px;display:flex;flex-wrap:wrap;gap:10px}
label-kuns{font-weight:bold;font-size:16px;margin-bottom:3px;width:100%}
input,select,textarea{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 0.3s,background-color 0.3s;color:var(--bodyC)}
textarea{height:350px;resize:vertical}.button-container{display:flex;flex-wrap:wrap;justify-content:space-between;gap:5px}
button{padding:12px 20px;font-size:16px;border-radius:5px;cursor:pointer;transition:background-color 0.3s ease;flex-grow:1}
#button-kuns{background-color:var(--linkB);color:white;border:none}
#addRowBtn{background-color:var(--linkB);color:white;border:none}
#addRowBtn.hidden{display:none}.error,.success,.info{text-align:center;font-weight:bold;margin-top:16px;margin-bottom:0px;font-size:16px}.error{color:red}.success{color:green}.info{color:var(--bodyC)}
#dataTable{margin-top:20px;list-style-type:none;padding:0}
#dataTable li{border:1px solid var(--contentL);background:var(--contentB);border-radius:5px;padding:12px;margin:8px 0;cursor:pointer;transition:background-color 0.3s}
#dataTable li:hover{color:var(--bodyC)}
#dataTable div{margin-top:10px;display:table;width:100%}
#dataTable div div{display:table-cell;padding:5px}
#dataTable div div:first-child{width:20px}.status-password-container{display:flex;gap:10px;margin-top:20px;flex-wrap:nowrap}.status-password-container select,.status-password-container input{flex:1 1 48%}.status-password-container{display:flex;align-items:center;justify-content:center;width:100%;margin-top:15px;text-align:center}.status-password-container select,.status-password-container input{margin-right:0;margin-bottom:10px;display:block;margin-left:auto;margin-right:auto}.password-container{display:flex;flex-direction:column}.loader{display:none;border:4px solid rgba(0,0,0,0.1);border-left-color:var(--linkB);border-radius:50%;width:24px;height:24px;animation:loader 1s linear infinite;margin:0 auto}
@keyframes loader{to{transform:rotate(360deg)}}
@media(max-width:768px){.form-group{margin-bottom:10px}
input,select,textarea{font-size:14px}
@media(max-width:480px){h2,h3{font-size:18px}
#dataTable li{padding:10px;font-size:14px}}</style>

<title>Danh sách Chương</title>
</head>
<body>

<!-- Spinner element -->
<div class="loader"></div>

<div id="tab1" class="tab active">
<h4 id="listHeading" style="display: none; background-color: var(--linkB); text-align: center; margin-bottom: 25px; margin-top: 0px; color: white;">≡ DANH SÁCH CHƯƠNG</h4>
    <ul id="dataTable"></ul>
    <button id="addRowBtn" class="hidden" onclick="addRow()">✑ Thêm chương mới</button>
</div>

<div id="tab2" class="tab">
    <h4 style="background-color: var(--linkB); text-align: center; margin-bottom: 25px; margin-top: 0px; color: white;">⟳ CẬP NHẬT CHƯƠNG</h4>
    <div class="form-group">
        <label for="chapterName"><b>Tên chương</b></label>
        <input type="text" id="chapterName">
    </div>

    <div class="form-group">
        <label for="content"><b>Nội dung</b></label>
        <textarea id="content" rows="6" cols="50"></textarea>
    </div>

    <div class="form-group status-password-container">
        <div>
            <label for="status"></label>
            <select id="status" onchange="togglePasswordField()">
                <option value="Open">Miễn phí</option>
                <option value="Locked">Khóa chương</option>
            </select>
        </div>
        <div class="password-container" id="passwordField">
            <label for="rowPassword"></label>
            <input type="text" id="rowPassword" style="text-align: center;">
        </div>
    </div>

    <div class="button-container">
<button id="button-kuns" onclick="goBackToTab1()" style="flex: 1; display: flex; justify-content: center; align-items: center;">Về</button>
<button id="button-kuns" onclick="deleteRow()" style="flex: 1; display: flex; justify-content: center; align-items: center;">Xóa</button>
<button id="button-kuns" onclick="saveData()" style="flex: 1; display: flex; justify-content: center; align-items: center;">Lưu</button>
    </div>
</div>

  <div id="message"></div>


<script>const apiUrl='https://script.google.com/macros/s/AKfycbwmelD7CkQB2Y_lbhxTmgA3MOCsYAuM1rdK41-hM3WejpXBsxL_LwpFFnBZczCpLlKZ/exec';let currentPassword=null;let currentRowIndex=null;let data=[];function getQueryParam(param){const urlParams=new URLSearchParams(window.location.search);return urlParams.get(param)}
function decodeBase64(base64String){try{return atob(base64String)}catch(e){console.error('Lỗi:',e);return null}}
function validatePassword(password){const messageDiv=document.getElementById('message');const loader=document.querySelector('.loader');const listHeading=document.getElementById('listHeading');if(!password){showMessage('error','ID không hợp lệ!');return}
loader.style.display='block';messageDiv.textContent='';fetch(`${apiUrl}?action=getData&password=${password}`).then(response=>response.json()).then(fetchedData=>{loader.style.display='none';if(fetchedData&&Array.isArray(fetchedData)){currentPassword=password;data=fetchedData;loadData();document.getElementById('addRowBtn').classList.remove('hidden');listHeading.style.display='block'}else{showMessage('error','ID của bạn không tồn tại!');document.getElementById('addRowBtn').classList.add('hidden');listHeading.style.display='none'}}).catch(error=>{loader.style.display='none';showMessage('error','Đã xảy ra lỗi khi xác minh!');console.error('Error:',error)})}
function showMessage(type,message){const messageDiv=document.getElementById('message');messageDiv.className=type;messageDiv.textContent=message;setTimeout(()=>{messageDiv.textContent=''},5000)}
window.onload=function(){const idFromUrl=getQueryParam('id');if(!idFromUrl){showMessage('info','Vui lòng nhấp vào Viết từ trang quản lí tác phẩm.')}else{const decodedId=decodeBase64(idFromUrl);if(decodedId){validatePassword(decodedId)}else{showMessage('error','Dữ liệu ID không hợp lệ!')}
const url=new URL(window.location);url.searchParams.delete('id');window.history.replaceState({},'',url.toString())}};function loadData(){const listContainer=document.getElementById('listContainer');listContainer.innerHTML='';if(data.length===0){listContainer.textContent='Không có dữ liệu để hiển thị!';return}
const ul=document.createElement('ul');data.forEach(item=>{const li=document.createElement('li');li.textContent=item;ul.appendChild(li)});listContainer.appendChild(ul)}
function loadData(){const list=document.getElementById('dataTable');list.innerHTML='';data.forEach((row,index)=>{const wordCount=row.content?row.content.split(/\s+/).filter(Boolean).length:0;const li=document.createElement('li');li.innerHTML=`
            <span>${row.chapter}</span>
        `;li.onclick=()=>editRow(index,row);list.appendChild(li);const table=document.createElement('table');table.style.width='100%';table.style.marginTop='0px';table.style.borderCollapse='collapse';table.style.marginBottom='0px';const tableRow=document.createElement('tr');const leftCell=document.createElement('td');leftCell.style.padding='5px';leftCell.style.fontSize='12px';leftCell.style.color='var(--darkTa)';leftCell.style.textAlign='left';const iconTextWrapper=document.createElement('span');iconTextWrapper.style.display='flex';iconTextWrapper.style.alignItems='center';const checkmarkSVG=`
  <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 512 512" xml:space="preserve" fill="#000000" style="transform: scale(0.6) translateY(5px); margin-right: 2px;">
    <g id="SVGRepo_bgCarrier" stroke-width="0"></g>
    <g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g>
    <g id="SVGRepo_iconCarrier"> 
      <path style="fill:#003C61;" d="M437.02,74.98C388.667,26.628,324.25,0,255.87,0S123.333,26.628,74.98,74.98 C26.628,123.333,0,187.62,0,256s26.628,132.667,74.98,181.02C123.333,485.372,187.49,512,255.87,512s132.797-26.628,181.15-74.98 C485.372,388.667,512,324.38,512,256S485.372,123.333,437.02,74.98z"></path> 
      <path style="fill:#0066A6;" d="M255.87,0.003C187.58,0.067,123.275,26.686,74.98,74.98C26.628,123.333,0,187.62,0,256 s26.628,132.667,74.98,181.02c48.295,48.294,112.6,74.915,180.89,74.978V0.003z"></path> 
      <path style="fill:#005A95;" d="M398.454,113.546c-38.051-38.052-88.772-59.007-142.584-59.007s-104.273,20.955-142.325,59.007 C75.494,151.597,54.539,202.188,54.539,256s20.955,104.403,59.007,142.454c38.05,38.052,88.511,59.007,142.324,59.007 s104.534-20.955,142.584-59.007c38.052-38.051,59.007-88.642,59.007-142.454S436.506,151.597,398.454,113.546z"></path> 
      <path style="fill:#31AAEF;" d="M255.87,54.542c-53.721,0.063-104.331,21.01-142.325,59.004 C75.494,151.597,54.539,202.188,54.539,256s20.955,104.403,59.006,142.454c37.994,37.993,88.603,58.94,142.325,59.004V54.542z"></path> 
      <path style="fill:#79C6BF;" d="M225.38,368.767c-10.332,0-20.241-4.105-27.547-11.41l-68.094-68.094 c-15.213-15.213-15.213-39.879,0-55.093c15.214-15.212,39.88-15.213,55.093,0l40.547,40.547l101.936-101.936 c15.214-15.213,39.879-15.213,55.093,0c15.213,15.213,15.213,39.879,0,55.092L252.926,357.357 C245.621,364.663,235.711,368.767,225.38,368.767z"></path> 
      <path style="fill:#E4F3F6;" d="M255.87,244.227l-30.491,30.491l-40.547-40.547c-15.213-15.213-39.879-15.213-55.093,0 c-15.213,15.213-15.213,39.879,0,55.093l68.094,68.094c7.306,7.306,17.214,11.41,27.547,11.41c10.331,0,20.241-4.105,27.547-11.41 l2.944-2.944L255.87,244.227L255.87,244.227z"></path> 
    </g>
  </svg>
        `;const svgContainer=document.createElement('span');svgContainer.innerHTML=checkmarkSVG;const column7Value=row.timestamp?new Date(row.timestamp).toLocaleString('vi-VN',{timeZone:'Asia/Ho_Chi_Minh'}):'';const textNode=document.createTextNode(`Đã đăng | ${column7Value}`);iconTextWrapper.appendChild(svgContainer);iconTextWrapper.appendChild(textNode);leftCell.appendChild(iconTextWrapper);tableRow.appendChild(leftCell);table.appendChild(tableRow);li.appendChild(table);const svgAndWordCountCell=document.createElement('td');svgAndWordCountCell.style.padding='5px';svgAndWordCountCell.style.textAlign='right';svgAndWordCountCell.style.fontSize='12px';svgAndWordCountCell.style.color='var(--darkTa)';if(row.status==='Locked'){svgAndWordCountCell.innerHTML=`
<svg viewBox="0 0 64 64" id="Layer_1" version="1.1" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#000000" style="transform: scale(0.8) translateY(7px);"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <style type="text/css"> .st0{fill:#B4E6DD;} .st1{fill:#80D4C4;} .st2{fill:#D2F0EA;} .st3{fill:#FFFFFF;} .st4{fill:#FBD872;} .st5{fill:#DB7767;} .st6{fill:#F38E7A;} .st7{fill:#F6AF62;} .st8{fill:#32A48E;} .st9{fill:#A38FD8;} .st10{fill:#7C64BD;} .st11{fill:#EAA157;} .st12{fill:#9681CF;} .st13{fill:#F9C46A;} .st14{fill:#CE6B61;} </style> <g> <g> <path class="st2" d="M46.44,36.38H17.56V22.44C17.56,14.48,24.04,8,32,8s14.44,6.48,14.44,14.44V36.38z M23.32,28.7h17.37v-6.26 c0-4.79-3.9-8.68-8.68-8.68c-4.79,0-8.68,3.9-8.68,8.68V28.7z"></path> </g> <path class="st4" d="M32,56L32,56c-9.8,0-17.74-7.94-17.74-17.74V27.74h35.48v10.52C49.74,48.06,41.8,56,32,56z"></path> <path class="st7" d="M36,37.73c0-2.21-1.79-4-4-4c-2.21,0-4,1.79-4,4c0,1.39,0.71,2.62,1.79,3.33v4.74c0,1.22,0.99,2.21,2.21,2.21 c1.22,0,2.21-0.99,2.21-2.21v-4.74C35.29,40.35,36,39.12,36,37.73z"></path> </g> </g></svg>
                |&nbsp; ${wordCount} từ
            `}else{svgAndWordCountCell.innerHTML=`${wordCount} từ`}
tableRow.appendChild(svgAndWordCountCell);table.appendChild(tableRow);list.appendChild(table)})}
function editRow(index,row){currentRowIndex=index;document.getElementById('tab1').classList.remove('active');document.getElementById('tab2').classList.add('active');document.getElementById('chapterName').value=row.chapter;document.getElementById('content').value=row.content.replace(/\{\{NEWLINE\}\}/g,'\n');document.getElementById('status').value=row.status||'Open';document.getElementById('rowPassword').value=row.password||'';togglePasswordField()}
function goBackToTab1(){document.getElementById('tab2').classList.remove('active');document.getElementById('tab1').classList.add('active')}
function togglePasswordField(){const status=document.getElementById('status').value;const passwordField=document.getElementById('passwordField');if(status==='Open'){passwordField.style.display='none'}else{passwordField.style.display='block'}}
document.addEventListener('DOMContentLoaded',function(){const statusSelect=document.getElementById('status');const passwordField=document.getElementById('passwordField');togglePasswordField();statusSelect.addEventListener('change',function(){togglePasswordField()});function togglePasswordField(){const status=statusSelect.value;if(status==='Open'){passwordField.style.display='none'}else{passwordField.style.display='block'}}});function saveData(){const updatedChapter=document.getElementById('chapterName').value.trim();const updatedContent=document.getElementById('content').value.trim();const updatedStatus=document.getElementById('status').value;const updatedPassword=document.getElementById('rowPassword').value.trim();if(!updatedChapter||!updatedContent){showMessage('error','Không được để trống tên & nội dung của chương!');return}
const currentTime=new Date().toLocaleString('vi-VN',{timeZone:'Asia/Ho_Chi_Minh'});if(updatedStatus==='Miễn phí'){document.getElementById('rowPassword').style.display='none'}else if(updatedStatus==='Khóa chương'){document.getElementById('rowPassword').style.display='block'}
showMessage('info','Đang cập nhật dữ liệu...');const params=new URLSearchParams();params.append('password',currentPassword);params.append('chapter',updatedChapter);params.append('content',updatedContent);params.append('status',updatedStatus);params.append('rowPassword',updatedPassword);if(currentRowIndex===null){const newRow={chapter:updatedChapter,content:updatedContent,status:updatedStatus,password:updatedPassword,timestamp:currentTime};data.push(newRow);loadData();params.append('action','addRow');params.append('row',data.length)}else{data[currentRowIndex]={chapter:updatedChapter,content:updatedContent,status:updatedStatus,password:updatedPassword,timestamp:currentTime};loadData();params.append('action','updateData');params.append('row',currentRowIndex+2)}
fetch(apiUrl,{method:'POST',body:params}).then(response=>response.json()).then(result=>{if(result.status==='success'){const successMessage=currentRowIndex===null?'Đã đăng chương mới thành công, tác phẩm +1 chương mới, quả thật là hạnh phúc.':'Chương đã được cập nhật thành công, tác giả +1 sự chăm chỉ, quả nhiên là tác giả của Kunsnovel.';showMessage('success',successMessage)}else{showMessage('error','Lỗi khi lưu dữ liệu! Vui lòng thử lại.')}
goBackToTab1()}).catch(error=>{console.error('Error:',error);showMessage('error','Có lỗi xảy ra khi gửi dữ liệu.');goBackToTab1()})}
function deleteRow(){if(currentRowIndex===null){showMessage('error','Không có chương nào để xóa!');return}
const modalStyles=` /* Modal styles */ .modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0, 0, 0, 0.5); padding-top: 100px; } .modal-content { background-color: var(--contentB); color: var(--bodyC); border: 1px solid var(--contentL); border-radius: 8px; margin: auto; padding: 20px; width: 80%; max-width: 400px; text-align: center; } .modal-buttons { display: flex; justify-content: space-between; margin-top: 20px; gap: 5px;  } .modal-buttons button { padding: 10px 20px; font-size: 14px; background-color: #f44336; color: white; border: none; border-radius: 5px; cursor: pointer; } #cancelDeleteBtn { background-color: #4CAF50; } #cancelDeleteBtn:hover { background-color: #45a049; }`;const styleSheet=document.createElement("style");styleSheet.type="text/css";styleSheet.innerText=modalStyles;document.head.appendChild(styleSheet);const modalHtml=`
        <div id="confirmModal" class="modal">
            <div class="modal-content">
                <h3><a>Xác nhận lần cuối!</a></h3>
                <p>Bạn chắc chắn muốn xóa chương này sao, gan ruột của bạn tạo nên đấy, không chắc thì căng mắt ra nhìn đi!</p>
                <div class="modal-buttons">
                    <button id="confirmDeleteBtn">Xóa</button>
                    <button id="cancelDeleteBtn">Hủy</button>
                </div>
            </div>
        </div>
    `;document.body.insertAdjacentHTML('beforeend',modalHtml);const modal=document.getElementById('confirmModal');const confirmDeleteBtn=document.getElementById('confirmDeleteBtn');const cancelDeleteBtn=document.getElementById('cancelDeleteBtn');modal.style.display='block';confirmDeleteBtn.onclick=function(){modal.style.display='none';showMessage('info','Đang xóa dữ liệu...');data.splice(currentRowIndex,1);loadData();const params=new URLSearchParams();params.append('action','deleteRow');params.append('password',currentPassword);params.append('row',currentRowIndex+2);fetch(apiUrl,{method:'POST',body:params}).then(response=>response.json()).then(result=>{if(result.status==='success'){showMessage('success','Chương đã xóa thành công, tác giả bị -1 uy tín, quả nhiên là lòng người.')}else{showMessage('error','Lỗi khi xóa dữ liệu! Vui lòng thử lại.')}
goBackToTab1()}).catch(error=>{console.error('Error:',error);showMessage('error','Có lỗi xảy ra khi xóa dữ liệu.');goBackToTab1()})};cancelDeleteBtn.onclick=function(){modal.style.display='none'}}
function showMessage(type,message){const messageDiv=document.getElementById('message');messageDiv.textContent=message;messageDiv.className=type;messageDiv.style.display='block';if(type!=='info'){setTimeout(function(){messageDiv.style.display='none'},3000)}}
function addRow(){if(!currentPassword){showMessage('error','Vui lòng xác nhận mật khẩu trước');return}
document.getElementById('tab1').classList.remove('active');document.getElementById('tab2').classList.add('active');document.getElementById('chapterName').value='';document.getElementById('content').value='';document.getElementById('status').value='Open';document.getElementById('rowPassword').value='';currentRowIndex=null}</script>
</body>
</html>
