

<style>.brdCmb, .pTtl.aTtl.sml { display: none; } </style>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .form-group {
    margin-bottom: 15px;
    display: flex;
    flex-wrap: nowrap; /* Giữ các phần tử trên cùng một hàng */
    gap: 10px; /* Khoảng cách giữa các phần tử */
}

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

#button-kuns {
    background-color: var(--linkB);
    color: white;
    border: none;
}

.loader {
    display: none;
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-left-color: #007BFF;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    animation: loader 1s linear infinite;
    margin: 15px auto;
}

.error {
    color: red;
    font-weight: bold;
    text-align: center;
}

.content {
  margin-top: 20px;
  text-align: justify;
  line-height: 1.6;
}
#contentText::before {
    content: attr(data-content); /* Gán nội dung vào before */
    white-space: pre-wrap; /* Giữ nguyên các dòng mới (newline) */
    display: block; /* Đảm bảo nội dung hiển thị dưới dạng block */
}

.navigation {
  display: flex;
  justify-content: space-between; /* Tạo kh#contentText::before {
    content: attr(data-content); /* Gán nội dung vào before */
    white-space: pre-wrap; /* Giữ nguyên các dòng mới (newline) */
    display: block; /* Đảm bảo nội dung hiển thị dưới dạng block */
}

.navigation button {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
  padding: 12px 18px;
  font-size: 16px;
  background-color: var(--linkB);
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

h3 {
  text-align: center;
}

.password-dialog {
}

.password-dialog input {
}

.password-dialog button {
  background-color: var(--linkB); 
  color: white;
  border-radius: 5px;
  cursor: pointer;
}

.error-message {
  color: red;
  font-size: 14px;
  margin-top: 8px;
  text-align: center;
}

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

  </style>
</head>
<body>
<div class="container">
  <!-- Loader spinner initially visible -->
  <div id="loader" class="loader"></div>
  
<div id="chapterContent" class="content" style="display: none; margin: 0; padding: 0;">
  <h3 id="tabName" style="margin: 0.5px;"></h3>
<h3 id="contentTitle" style="margin: 0; padding: 0; font-weight: normal; color: var(--darkTa); font-size: 18px;"></h3><br>
  <div id="contentText"></div><br>
  <div class="navigation" style="display: flex; justify-content: center;">
<button id="prevChapter" onclick="scrollToTop(); navigateChapter(-1)">Chương trước</button>
<button id="nextChapter" onclick="scrollToTop(); navigateChapter(1)">Chương sau</button>

  </div>
</div>


<div id="passwordDialog" class="password-dialog" style="display: none;">
  <div class="form-group">
    <input type="password" id="passwordInput" placeholder="Vui lòng nhập mật khẩu..." style="flex: 2;">
    <button id="button-kuns" onclick="submitPassword()" style="flex: 1; margin-left: 10px; display: flex; justify-content: center; align-items: center;">Xác nhận</button>
  </div>
  <div id="passwordLoader" class="loader" style="display: none;"></div>
  <p id="errorMessage" class="error" style="display: none;">Mật khẩu không đúng. Vui lòng thử lại.</p>
</div>


<script>
const apiBase = 'https://script.google.com/macros/s/AKfycbziyUUyyrgxzaO8nAK-9-OdRtyRPGu6mRLgJnQpqKMCaDl-sK8hF-nqFcWb3NY_yfI/exec';

// Lấy tên tab từ URL
let urlTabName = new URLSearchParams(window.location.search).get('tabName');
let tabName = urlTabName; // Mặc định là 'defaultTab' nếu không tìm thấy

// Hiển thị tên tab trong giao diện
document.getElementById('tabName').innerHTML = `<strong>${tabName}</strong>`;

let chaptersList = []; // Dữ liệu chương được lưu trong bộ nhớ
let currentChapterIndex = -1;

let chapterContentCache = {}; // Bộ nhớ chứa dữ liệu nội dung chương đã tải

// Fetch chapters from the API based on the tabName
async function fetchChapters() {
    // Kiểm tra nếu dữ liệu đã được tải trước đó
    if (chaptersList.length > 0) {
        console.log('Chapters already loaded.');
        return; // Nếu đã có dữ liệu, không gọi API
    }

    try {
        const response = await fetch(`${apiBase}?action=getChapters&tabName=${tabName}`);
        const chapters = await response.json();

        if (chapters.error) {
            document.getElementById('chapters').innerHTML = `<p>Error: ${chapters.error}</p>`;
            return;
        }

        // Lưu dữ liệu vào bộ nhớ
        chaptersList = chapters.sort((a, b) => a.order - b.order); // Sắp xếp chương theo thứ tự
    } catch (error) {
        console.error('Error fetching chapters:', error);
        document.getElementById('chapters').innerHTML = '<p>Unable to load chapters.</p>';
    }
}

// Fetch chapter content
async function fetchChapterContent(chapterName) {
    let password = getCookie(`password_${chapterName}`) || ''; // Lấy mật khẩu từ cookie (nếu có)

    const chapter = chaptersList.find(ch => ch.chapterName === chapterName);
    if (!chapter) {
        alert('Chapter does not exist');
        return;
    }

    if (chapter.status === 'Locked') {
        if (password) {
            fetchChapterContentWithPassword(chapterName, password, true); // Kiểm tra mật khẩu từ cookie
        } else {
            showPasswordDialog(chapterName); // Hiển thị hộp thoại nhập mật khẩu
        }
        return;
    }

    // Nếu chương đã mở khóa, tiến hành tải nội dung
    fetchUnlockedChapterContent(chapterName);
}

// Fetch unlocked chapter content
async function fetchUnlockedChapterContent(chapterName) {
    // Kiểm tra nếu dữ liệu đã được tải trước đó, không gọi lại API
    if (chapterContentCache[chapterName]) {
        console.log('Chapter content already loaded.');
        displayChapterContent(chapterContentCache[chapterName]);
        return;
    }

    try {
        document.getElementById('loader').style.display = 'block';
        document.getElementById('chapterContent').style.display = 'none'; // Ẩn nội dung khi đang tải

        const response = await fetch(
            `${apiBase}?action=getChapterContent&tabName=${tabName}&chapterName=${encodeURIComponent(chapterName)}`
        );
        const content = await response.json();

        if (content.error) {
            alert(content.error);
            return;
        }

        // Lưu nội dung chương vào bộ nhớ
        chapterContentCache[chapterName] = content;

        displayChapterContent(content);
    } catch (error) {
        console.error('Error fetching chapter content:', error);
        alert('Unable to fetch chapter content.');
    }
}

function displayChapterContent(content) {
    document.getElementById('contentText').innerHTML = ''; // Xóa nội dung cũ
    document.getElementById('contentTitle').innerHTML = `<em>${content.chapterName}</em>`;

    // Tách nội dung thành các đoạn văn
    const paragraphs = content.content.split('\n').filter(p => p.trim().length > 0);

    // Xử lý từng đoạn văn
    let cssContent = '';

    paragraphs.forEach((paragraph, index) => {
        const formattedParagraph = paragraph.trim();

        const contentElement = document.createElement('div');
        contentElement.classList.add(`content-section${index + 1}`);
        contentElement.setAttribute(`data-content${index + 1}`, formattedParagraph);

        document.getElementById('contentText').appendChild(contentElement);

        cssContent += `
            .content-section${index + 1}::before {
                content: attr(data-content${index + 1});
                white-space: pre-wrap;
                display: block;
                margin-bottom: 12px;
                margin-top: 12px;
            }
        `;
    });

    const style = document.createElement('style');
    style.innerHTML = cssContent;
    document.head.appendChild(style);

    document.getElementById('loader').style.display = 'none';
    document.getElementById('chapterContent').style.display = 'block';
}

function showPasswordDialog(chapterName) {
    document.getElementById('passwordDialog').style.display = 'block';
    document.getElementById('passwordInput').dataset.chapterName = chapterName; // Gắn tên chương vào dữ liệu
    document.getElementById('passwordLoader').style.display = 'none';
    document.getElementById('errorMessage').style.display = 'none';

    document.getElementById('loader').style.display = 'none';
    document.getElementById('chapterContent').style.display = 'none';
    document.getElementById('prevChapter').style.display = 'none';
    document.getElementById('nextChapter').style.display = 'none';
}

function submitPassword() {
    const passwordInput = document.getElementById('passwordInput');
    const password = passwordInput.value;
    const chapterName = passwordInput.dataset.chapterName; // Lấy tên chương từ dữ liệu

    if (!password) {
        alert('Bạn cần nhập mật khẩu!');
        return;
    }

    document.getElementById('passwordLoader').style.display = 'block';
    document.getElementById('errorMessage').style.display = 'none'; // Ẩn thông báo lỗi

    fetchChapterContentWithPassword(chapterName, password, false); // false: mật khẩu nhập tay
}

async function fetchChapterContentWithPassword(chapterName, password, fromCookie) {
    try {
        if (fromCookie) {
            document.getElementById('passwordLoader').style.display = 'none';
            document.getElementById('loader').style.display = 'block'; // Hiển thị spinner tải nội dung
        } else {
            document.getElementById('passwordLoader').style.display = 'block'; // Hiển thị passwordLoader khi nhập mật khẩu
            document.getElementById('loader').style.display = 'none';  // Ẩn loader
        }

        // Ẩn các phần không cần thiết
        document.getElementById('passwordInput').dataset.chapterName = chapterName;
        document.getElementById('errorMessage').style.display = 'none'; // Ẩn thông báo lỗi
        document.getElementById('chapterContent').style.display = 'none'; // Ẩn nội dung chương
        document.getElementById('prevChapter').style.display = 'none'; // Ẩn nút trước
        document.getElementById('nextChapter').style.display = 'none'; // Ẩn nút tiếp theo

        const response = await fetch(
            `${apiBase}?action=getChapterContent&tabName=${tabName}&chapterName=${encodeURIComponent(chapterName)}&password=${encodeURIComponent(password)}`
        );

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }

        const content = await response.json();

        // Nếu có lỗi từ API thì hiển thị thông báo lỗi
        if (content.error) {
            document.getElementById('errorMessage').style.display = 'block';
            document.getElementById('errorMessage').innerHTML = content.error; // Hiển thị nội dung lỗi
            document.getElementById('passwordLoader').style.display = 'none';
            document.getElementById('loader').style.display = 'none';
            return;
        }

        // Nếu mật khẩu đúng, hiển thị nội dung chương
        if (!fromCookie) {
            setCookie(`password_${chapterName}`, password, 30); // Lưu mật khẩu vào cookie trong 30 ngày
        }

        document.getElementById('passwordDialog').style.display = 'none';
        document.getElementById('chapterContent').style.display = 'block'; // Hiển thị nội dung chương
        document.getElementById('loader').style.display = 'none'; // Ẩn spinner tải
        document.getElementById('contentText').innerHTML = ''; // Xóa nội dung cũ
        document.getElementById('contentTitle').innerHTML = `<em>${content.chapterName}</em>`;

        // Tách nội dung thành các đoạn từ ký tự xuống dòng (\n)
        const paragraphs = content.content.split('\n').filter(p => p.trim().length > 0);

        // Tạo CSS cho ::before
        let cssContent = '';

        // Duyệt qua các đoạn văn và tạo phần tử div với các data-content1, data-content2, ...
        paragraphs.forEach((paragraph, index) => {
            const formattedParagraph = paragraph.trim();

            // Tạo phần tử div mới với lớp content-section1, content-section2, v.v.
            const contentElement = document.createElement('div');
            contentElement.classList.add(`content-section${index + 1}`);

            // Gán nội dung vào thuộc tính data-content1, data-content2, v.v.
            contentElement.setAttribute(`data-content${index + 1}`, formattedParagraph);

            // Gán phần tử vào #contentText thay vì #chapterContent
            document.getElementById('contentText').appendChild(contentElement);

            // Tạo CSS cho ::before của mỗi content-sectionX
            cssContent += `
                .content-section${index + 1}::before {
                    content: attr(data-content${index + 1});
                    white-space: pre-wrap;  /* Giữ lại các ký tự xuống dòng */
                    display: block;
                    margin-bottom: 12px;
                    margin-top: 12px;
                }
            `;
        });

        // Thêm CSS vào head
        const style = document.createElement('style');
        style.innerHTML = cssContent;
        document.head.appendChild(style);

        document.getElementById('prevChapter').style.display = 'inline-block'; // Hiển thị nút trước
        document.getElementById('nextChapter').style.display = 'inline-block'; // Hiển thị nút tiếp theo
        updateNavigationButtons(); // Cập nhật các nút điều hướng

    } catch (error) {
        console.error('Error fetching chapter content:', error);
        alert('Unable to fetch chapter content.');
        document.getElementById('passwordLoader').style.display = 'none'; // Ẩn passwordLoader nếu có lỗi
        document.getElementById('loader').style.display = 'none'; // Ẩn loader nếu có lỗi
        document.getElementById('errorMessage').style.display = 'block'; // Hiển thị lỗi nếu không thành công
    }
}



function setCookie(name, value, days) {
    const expires = new Date(Date.now() + days * 86400000).toUTCString();
    document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; expires=${expires}; path=/; SameSite=Lax`;
}

function getCookie(name) {
    const match = document.cookie.match(new RegExp(`(?:^|; )${encodeURIComponent(name)}=([^;]*)`));
    return match ? decodeURIComponent(match[1]) : '';
}


function updateNavigationButtons() {
    // Update the visibility of navigation buttons based on the current chapter position
    const prevButton = document.getElementById('prevChapter');
    const nextButton = document.getElementById('nextChapter');
    
    // Hide previous button if this is the first chapter
    prevButton.style.display = currentChapterIndex > 0 ? 'inline-block' : 'none';

    // Hide next button if this is the last chapter
    nextButton.style.display = currentChapterIndex < chaptersList.length - 1 ? 'inline-block' : 'none';
}

function navigateChapter(direction) {
    const newIndex = currentChapterIndex + direction;

    if (newIndex < 0 || newIndex >= chaptersList.length) {
        alert('No more chapters!');
        return;
    }

    handleChapterClick(newIndex);
}

// Hàm xử lý sự kiện khi người dùng nhấn nút quay lại
window.onpopstate = function(event) {
    if (event.state && event.state.chapter) {
        // Nếu có state trong lịch sử, tìm và tải chương tương ứng
        const chapterName = event.state.chapter;
        const chapterIndex = chaptersList.findIndex(ch => ch.chapterName === chapterName);
        if (chapterIndex !== -1) {
            currentChapterIndex = chapterIndex;
            fetchChapterContent(chapterName);
        }
    } else {
        // Quay lại trang trước nếu không có state
        window.history.back();
    }
};

// Thêm lịch sử trạng thái khi tải nội dung chương
// Modify this to correctly update the URL with tabName and chapterName
function handleChapterClick(index) {
    currentChapterIndex = index;
    const chapterName = chaptersList[currentChapterIndex].chapterName;

    // Update the URL with tabName and chapterName
    window.history.pushState(
        { chapter: chapterName },
        '',
        `?tabName=${encodeURIComponent(tabName)}&chapterName=${encodeURIComponent(chapterName)}`
    );

    fetchChapterContent(chapterName);
}



const chapterName = new URLSearchParams(window.location.search).get('chapterName');
if (chapterName) {
    fetchChapters().then(() => {
        const chapterIndex = chaptersList.findIndex(ch => ch.chapterName === chapterName);
        if (chapterIndex !== -1) {
            currentChapterIndex = chapterIndex;
            fetchChapterContent(chapterName);
        } else {
            alert('Chương không tồn tại!');
        }
    });
}
  function scrollToTop() {
  window.scrollTo({
    top: 0, // Vị trí cuộn đến (đầu trang)
    behavior: 'smooth' // Hiệu ứng cuộn mượt
  });
}

</script>
</body>
</html>




