<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chapter Viewer</title>
<style>#contentTitle{font-weight:700;margin-bottom:12px;font-family:var(--custom-font-family)!important;font-size:var(--custom-font-size);text-align:var(--custom-text-align);color:var(--custom-text-color);line-height:var(--custom-line-height)}#loader{text-align:center}#chapterContent{display:none;white-space:pre-wrap}.content-block{display:none}.content-block[data-content]::before{content:attr(data-content);display:block;margin-bottom:12px}.nav-buttons{display:flex;justify-content:space-between;gap:10px;margin-top:20px;margin-bottom:0}.nav-buttons button{display:flex;align-items:center;justify-content:center;padding:10px 20px;font-size:16px;cursor:pointer;border:none;border-radius:25px;background-color:var(--linkB);color:#fff;flex-grow:1;width:auto}.password-input{text-align:center;margin-top:20px}.password-input label{font-weight:700}.password-input input{padding:12px;font-size:16px;border:1px solid var(--contentL);background:var(--contentB);border-radius:8px;width:80%;box-sizing:border-box;transition:border-color 0.3s,background-color 0.3s;color:var(--bodyC)}.password-input button{padding:8px 16px;margin-top:10px;background-color:var(--linkB);color:#fff;border:none;border-radius:5px}#error-message{color:var(--custom-text-color);margin-top:10px;display:none}</style>
</head>
<body>
<div id="loader">
 Đang tải...
</div>
    <div id="contentTitle"></div>
    <div id="chapterContent"></div>
  
  
    <div class="password-input" id="passwordDiv" style="display: none;">
        <input type="text" id="password" placeholder="Nhập mật khẩu..."/>
        <button id="unlockBtn">Xác nhận</button>
        <div id="error-message"></div>
    </div>

<div class="nav-buttons" style="display: none;">
    <button id="prevBtn">Trước</button>
    <button id="nextBtn">Tiếp</button>
</div>



<script>const apiBase='https://script.google.com/macros/s/AKfycbzaRD1EDPEcBctBHRJUSF3a3Sh3skJJOBwjE7oFU-FtZHsTk1bWcrCauJkXdnBDNyY0/exec';const urlParams=new URLSearchParams(window.location.search);const id=urlParams.get('id');let currentChapter=urlParams.get('chap');let currentPass=urlParams.get('pass');let chapters=[];if(!id){alert('Đường dẫn không chính xác, vui lòng quay về trang chủ.')}else{const storedChapters=sessionStorage.getItem(`chapters_${id}`);document.getElementById('loader').style.display='block';if(storedChapters){chapters=JSON.parse(storedChapters);initializeNavigation();fetchChapterContent(id,currentChapter,currentPass).finally(()=>{document.getElementById('loader').style.display='none'})}else{const chapterListUrl=`${apiBase}?id=${id}`;const chapterContentUrl=`${apiBase}?action=getChapterContent&id=${encodeURIComponent(id)}&chap=${encodeURIComponent(currentChapter)}&pass=${encodeURIComponent(currentPass)}`;Promise.all([fetch(chapterListUrl).then(response=>response.json()),fetch(chapterContentUrl).then(response=>response.text())]).then(([chapterList,encodedContent])=>{chapters=chapterList;sessionStorage.setItem(`chapters_${id}`,JSON.stringify(chapters));initializeNavigation();if(!encodedContent){showPasswordFieldWithError("An error occurred. Please try again.");return}
const decodedContent=decode(encodedContent);let parsedContent;try{parsedContent=JSON.parse(decodedContent)}catch(e){showPasswordFieldWithError("Failed to load chapter content. Please try again.");return}
const chapterData=parsedContent[0];if(!chapterData){showPasswordFieldWithError("No data available for this chapter.");return}
if(chapterData.status==='Locked'){if(chapterData.error){showPasswordFieldWithError("Incorrect password. Please try again.")}else{displayChapterContent({title:chapterData.chapter,content:chapterData.data})}}else{displayChapterContent({title:chapterData.chapter,content:chapterData.data})}}).catch(()=>{showPasswordFieldWithError("Chương này bị khóa, vui lòng nhập mật khẩu.")}).finally(()=>{document.getElementById('loader').style.display='none'})}}
function decodeBase64(str){return atob(str)}
function decodeUnicode(str){return str.replace(/\\u[\dA-F]{4}/gi,match=>String.fromCharCode(parseInt(match.replace(/\\u/g,''),16)))}
function reverseString(str){return str.split('').reverse().join('')}
function shiftCharactersBack(str){return[...str].map(char=>String.fromCharCode(char.charCodeAt(0)-3)).join('')}
function decode(input){const base64Decoded=decodeBase64(input);const unicodeDecoded=decodeUnicode(base64Decoded);const reversed=reverseString(unicodeDecoded);const finalDecoded=shiftCharactersBack(reversed);return finalDecoded}
function fetchChapterContent(id,chap,pass){try{document.getElementById('loader').style.display='block';document.getElementById('chapterContent').style.display='none';document.querySelector('.nav-buttons').style.display='none';document.getElementById('contentTitle').style.display='none';document.getElementById('passwordDiv').style.display='none';document.getElementById('error-message').style.display='none';const url=`${apiBase}?action=getChapterContent&id=${encodeURIComponent(id)}&chap=${encodeURIComponent(chap)}&pass=${encodeURIComponent(pass)}`;urlParams.delete('pass');const newUrl=window.location.origin+window.location.pathname+'?'+urlParams.toString();history.replaceState(null,'',newUrl);fetch(url).then(response=>response.text()).then(encodedContent=>{if(!encodedContent){showPasswordFieldWithError("An error occurred. Please try again.");return}
const decodedContent=decode(encodedContent);let parsedContent;try{parsedContent=JSON.parse(decodedContent)}catch(e){showPasswordFieldWithError("Failed to load chapter content. Please try again.");return}
const chapterData=parsedContent[0];if(!chapterData){showPasswordFieldWithError("No data available for this chapter.");return}
if(chapterData.status==='Locked'){if(chapterData.error){showPasswordFieldWithError("Incorrect password. Please try again.")}else{displayChapterContent({title:chapterData.chapter,content:chapterData.data});document.getElementById('error-message').style.display='none'}}else{displayChapterContent({title:chapterData.chapter,content:chapterData.data})}}).catch(()=>{showPasswordFieldWithError("Mật khẩu không được nhập đúng, vui lòng cung cấp chính xác!")}).finally(()=>{document.getElementById('loader').style.display='none'})}catch(error){document.getElementById('loader').style.display='none'}}
function showPasswordFieldWithError(errorMessage){document.getElementById('passwordDiv').style.display='block';document.getElementById('chapterContent').style.display='none';document.querySelector('.nav-buttons').style.display='none';document.getElementById('contentTitle').style.display='none';document.getElementById('error-message').textContent=errorMessage;document.getElementById('error-message').style.display='block'}
function displayChapterContent(chapterData){const titleElement=document.getElementById('contentTitle');const contentElement=document.getElementById('chapterContent');titleElement.textContent=chapterData.title;const contentParts=chapterData.content.split('\n');contentElement.innerHTML='';contentParts.forEach((part)=>{const contentBlock=document.createElement('div');contentBlock.classList.add('content-block');contentBlock.setAttribute('data-content',part);contentElement.appendChild(contentBlock)});document.getElementById('chapterContent').style.display='block';document.querySelector('.nav-buttons').style.display='';const contentBlocks=document.querySelectorAll('.content-block');contentBlocks.forEach(block=>{block.style.display='block'});document.getElementById('contentTitle').style.display=''}
function initializeNavigation(){let currentIndex=chapters.findIndex(chapter=>chapter.chapter===currentChapter);function navigateToChapter(chapterName){currentChapter=chapterName;urlParams.set('chap',chapterName);urlParams.set('pass',currentPass||'');const newUrl=window.location.origin+window.location.pathname+'?'+urlParams.toString();history.replaceState(null,'',newUrl);currentIndex=chapters.findIndex(chapter=>chapter.chapter===currentChapter);fetchChapterContent(id,currentChapter,currentPass)}
document.getElementById('prevBtn').onclick=function(){if(currentIndex>0){const prevChapter=chapters[currentIndex-1];if(prevChapter.status==='Locked'){const deduction=Math.floor(prevChapter.wordCount*0.1);const userPass=prompt(`Chương trước đã bị khóa! Nếu sử dụng mật khẩu VIP, bạn sẽ bị trừ ${deduction} đồng. Mật khẩu hiện tại bạn đang sử dụng là: ${currentPass || 'không có'}:`,currentPass||'');if(userPass!==null){if(userPass===''){alert('Hành động bị hủy vì chưa nhập mật khẩu.')}else{currentPass=userPass;navigateToChapter(prevChapter.chapter)}}}else{navigateToChapter(prevChapter.chapter)}}else{alert('Đây đã là chương đầu tiên rồi, bạn còn muốn văng đi đâu nữa!')}};document.getElementById('nextBtn').onclick=function(){if(currentIndex<chapters.length-1){const nextChapter=chapters[currentIndex+1];if(nextChapter.status==='Locked'){const deduction=Math.floor(nextChapter.wordCount*0.1);const userPass=prompt(`Chương sau vẫn bị khóa! Nếu sử dụng mật khẩu VIP, bạn sẽ bị trừ ${deduction} đồng. Mật khẩu hiện tại bạn đang sử dụng là: ${currentPass || 'Không có'}:`,currentPass||'');if(userPass!==null){if(userPass===''){alert('Hành động bị hủy vì chưa nhập mật khẩu.')}else{currentPass=userPass;navigateToChapter(nextChapter.chapter)}}}else{navigateToChapter(nextChapter.chapter)}}else{alert('Chúc mừng bạn đã kiên trì đọc đến chương cuối cùng...')}}}
document.getElementById('unlockBtn').onclick=function(){const password=document.getElementById('password').value;if(password){currentPass=password;document.getElementById('loader').style.display='block';urlParams.set('pass',currentPass);const newUrl=window.location.origin+window.location.pathname+'?'+urlParams.toString();history.replaceState(null,'',newUrl);fetchChapterContent(id,currentChapter,currentPass).finally(()=>{document.getElementById('loader').style.display='none'})}else{document.getElementById('error-message').innerText='Vui lòng nhập mật khẩu!'}};window.addEventListener('load',function(){if(!currentChapter){document.getElementById('passwordDiv').style.display='none'}});window.addEventListener('beforeunload',function(){sessionStorage.removeItem(`chapters_${id}`)});function trackReadingHistory(){const urlParams=new URLSearchParams(window.location.search);const id=urlParams.get('id');const chap=urlParams.get('chap');if(id&&chap){const url=window.location.href;let readingHistory=JSON.parse(localStorage.getItem('readingHistory'))||{};readingHistory[id]={chapter:chap,url:url};localStorage.setItem('readingHistory',JSON.stringify(readingHistory))}}
trackReadingHistory();window.addEventListener('popstate',trackReadingHistory);window.addEventListener('hashchange',trackReadingHistory);(function(){const originalPushState=history.pushState;const originalReplaceState=history.replaceState;history.pushState=function(...args){originalPushState.apply(history,args);trackReadingHistory()};history.replaceState=function(...args){originalReplaceState.apply(history,args);trackReadingHistory()}})();</script>
</body>
</html>