<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        .info-container {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }
.cover {
    flex: 1;
    max-width: 200px;
    height: auto;
    margin-right: 20px;
    text-align: center;
}

.cover img {
    width: 100%;
    height: auto;
    object-fit: cover;
    border-radius: 8px;
    aspect-ratio: 2 / 3; /* Đảm bảo tỷ lệ 2:3 */
}

        .details {
            flex: 2;
            border-radius: 8px;
        }
        .details h2 {
            margin-top: 0;
        }
        .details p {
            margin: 10px 0;
        }
        .link {
            text-align: center;
            margin-top: 10px;
        }
        .custom-button {
            border: none;
            color: #fff;
            background-color: #007BFF;
            font-family: inherit;
            font-size: 17px;
            padding: 0.6em 1.5em;
            box-shadow: 0 0 0 10px rgba(5, 186, 218, 0.3);
            animation: custom-pulse 1.5s infinite;
            cursor: pointer;
            border-radius: 8px;
        }
        @keyframes custom-pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(5, 186, 218, 0.3);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(5, 186, 218, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(5, 186, 218, 0);
            }
        }
        @media (max-width: 768px) {
            .custom-button {
                font-size: 12px;
                padding: 0.3em 0.8em;
                box-shadow: 0 0 0 3px rgba(5, 186, 218, 0.3);
            }
            .details h2 {
                font-size: 22px;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                overflow: hidden;
                text-overflow: ellipsis;
                margin: 0;
            }
            .details p {
                font-size: 14px;
                line-height: 1.2;
            }
        }
        @media (max-width: 768px) {
            .cover .link {
                display: block;
                margin-top: 10px;
            }
            .details .link {
                display: none;
            }
        }
        @media (min-width: 769px) {
            .cover .link {
                display: none;
            }
            .details .link {
                display: block;
                text-align: left;
                margin-top: 20px;
            }
        }

        /* Chapters Section */
.container {
  padding: 5px; /* Giảm khoảng cách padding */ 
  display: flex;
}

.chapters-wrapper {
  max-height: 300px;
  width: 100%; /* Đảm bảo phần tử chiếm toàn bộ chiều rộng */
  max-width: none; /* Loại bỏ giới hạn chiều rộng */
  overflow-y: auto; 
  overflow-x: auto;
  background: var(--themeBd);
  border: var(--contentBd-line) solid var(--contentBd-color);
  border-radius: var(--contentBd-radiusA);
}


/* Hiding the scrollbar for horizontal overflow */
.chapters-wrapper::-webkit-scrollbar {
  display: none;
}


.chapter {
  display: flex;
  align-items: center;
  margin-bottom: 1px; /* Giảm khoảng cách giữa các chương */
  padding: 4px;
  font-size: 15px;
  white-space: nowrap; /* Đảm bảo nội dung không xuống dòng */
}

.chapter svg {
  flex-shrink: 0; /* Giữ kích thước cố định của SVG */
  width: 14px; /* Kích thước SVG nhỏ hơn */
  height: 14px;
  var(--contentBd);
}

.chapter-status {
  margin-right: 5px; /* Khoảng cách giữa SVG và chữ */
}

.chapter-name {
  flex: 1;
  display: block;
  padding-left: 5px;
  cursor: pointer;
  text-decoration: none;
  color: var(--contentBd);
  overflow-x: auto; /* Kích hoạt cuộn ngang nếu nội dung dài hơn */
  text-overflow: ellipsis;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch; /* Tối ưu trải nghiệm cuộn trên thiết bị cảm ứng */
  user-select: none; /* Ngăn chọn văn bản */
}

.chapter-name:hover {
  color: var(--linkB);
}

/* Hiding the scrollbar for .chapter-name */
.chapter-name::-webkit-scrollbar {
  display: none; /* Ẩn thanh cuộn */
}
/* Màu sắc cho từ "Hoàn thành" */
.completed {
    color: var(--linkB); /* Màu chữ được gán từ biến CSS --linkB */
    font-weight: bold; /* Làm chữ đậm để nổi bật */
}

.loader {
  display: block;
  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 id="loader" class="loader"></div>
    <div class="info-container">
        <div class="cover" id="cover"></div>
        <div class="details" id="details"></div>
    </div>

    <div class="introduction-container" id="introduction">
        <blockquote class="s2">
            <p id="intro-text" style="text-align: justify;"></p>
            <span id="author-name"></span>
        </blockquote>
    </div>

    <div class="container">

        <div class="chapters-wrapper">
            <div id="total-chapters-title" class="total-chapters-title"></div>
            <div id="chapters"></div>
        </div>
    </div>

    <script>

document.addEventListener('DOMContentLoaded', function () {
    const apiUrl = `https://script.google.com/macros/s/AKfycbyGvZthyMDAq4fry2di-VoXh69gHQXDjqSAsHioGAfYDwtxtbPehfNvCvdRdWxV6ch7/exec?title=${tabName}`;
    const apiBase = 'https://script.google.com/macros/s/AKfycbziyUUyyrgxzaO8nAK-9-OdRtyRPGu6mRLgJnQpqKMCaDl-sK8hF-nqFcWb3NY_yfI/exec';
    
    // Show loader when starting data fetching
    document.getElementById('loader').style.display = 'block';

    // Check if story data is in sessionStorage
    const storedStoryData = sessionStorage.getItem('storyData');
    if (storedStoryData) {
        const data = JSON.parse(storedStoryData);
        displayStoryData(data);
        // Hide loader when cached data is used
        document.getElementById('loader').style.display = 'none';
    } else {
        fetch(apiUrl)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    document.getElementById("details").innerHTML = `<p>${data.error}</p>`;
                    document.getElementById('loader').style.display = 'none'; // Hide loader in case of error
                    return;
                }

                if (data.length === 0) {
                    document.getElementById("details").innerHTML = "<p>Không tìm thấy thông tin cho truyện này.</p>";
                    document.getElementById('loader').style.display = 'none'; // Hide loader if no data
                    return;
                }

                // Save story data to sessionStorage
                sessionStorage.setItem('storyData', JSON.stringify(data));
                displayStoryData(data);
                document.getElementById('loader').style.display = 'none'; // Hide loader after API call success
            })
            .catch(error => {
                console.error("Error fetching story data:", error);
                document.getElementById("details").innerHTML = "<p>Đã xảy ra lỗi khi tải dữ liệu.</p>";
                document.getElementById('loader').style.display = 'none'; // Hide loader in case of error
            });
    }

    // Fetch chapters
    const storedChaptersData = sessionStorage.getItem('chaptersData');
    if (storedChaptersData) {
        const chapters = JSON.parse(storedChaptersData);
        displayChaptersData(chapters);
        // Hide loader if chapters data is cached
        document.getElementById('loader').style.display = 'none';
    } else {
        fetchChapters();
    }

    // Function to display story data
    function displayStoryData(data) {
        const story = data[0];
        const formattedIntroduction = story['Giới thiệu'].replace(/\n\n/g, '<br>');

        const cmntElement = document.querySelector('.cmnt');
        const commentCount = cmntElement && cmntElement.hasAttribute('data-text') 
                             ? cmntElement.getAttribute('data-text') 
                             : '0'; // Gán giá trị 0 nếu không có phần tử hoặc data-text không tồn tại

        let statusText = story['Tình trạng'];
        if (statusText === 'Hoàn thành') {
            statusText = `<span class="completed">${statusText}</span>`; // Gán màu chỉ cho "Hoàn thành"
        }

        document.getElementById("cover").innerHTML = `
            <img src="${story['Url bìa']}" alt="${story['Tác phẩm']}">
            <div class="link">
                <a href="${story['Link tác phẩm']}" target="_self">
                    <button class="custom-button">Đọc ngay</button>
                </a>
            </div>
        `;

        document.getElementById("details").innerHTML = `
            <h2>${story['Tác phẩm']}</h2>
            <p>
                <strong><a>${story['Số chương']}</a> chương</strong> | 
                <strong><a>${story['Tổng số lượt xem']}</a> lượt xem</strong> | 
                <strong><a>${story['Tổng lượt mở khóa']}</a> mở khóa</strong> | 
                <strong><a>${commentCount}</a> bình luận</strong>
            </p>
            <p><strong>Tác giả:</strong> ${story['Tác giả']}</p>
            <p><strong>Thể loại:</strong> ${story['Thể loại']}</p>
            <p><strong>Tình trạng:</strong> ${statusText}</p>
            <div class="link">
                <a href="${story['Link tác phẩm']}" target="_self">
                    <button class="custom-button">Đọc ngay</button>
                </a>
            </div>
        `;

        document.getElementById("intro-text").innerHTML = formattedIntroduction;
        document.getElementById("author-name").innerHTML = story['Tác giả'];
    }

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

            if (chapters.error) {
                document.getElementById('chapters').innerHTML = `<p style="text-align: center; font-style: italic;">Tác giả chưa ra chương nào, khổ thân bạn rồi, lỡ dại va vào hố trường tăm tối thế?</p>`;
                document.getElementById('loader').style.display = 'none'; // Hide loader in case of error
                return;
            }

            // Save chapters data to sessionStorage
            sessionStorage.setItem('chaptersData', JSON.stringify(chapters));
            displayChaptersData(chapters);
            document.getElementById('loader').style.display = 'none'; // Hide loader after API call success
        } catch (error) {
            console.error('Error fetching chapters:', error);
            document.getElementById('loader').style.display = 'none'; // Hide loader in case of error
            document.getElementById('chapters').innerHTML = '<p>Unable to load chapters.</p>';
        }
    }

    // Function to display chapters data
    function displayChaptersData(chapters) {
        const chaptersContainer = document.getElementById('chapters');
        chaptersContainer.innerHTML = '';

        const validChapters = chapters.filter(chapter => /^[cC]hương \d+/.test(chapter.chapterName));

        const totalChaptersTitle = document.getElementById('total-chapters-title');
        totalChaptersTitle.innerHTML = `<b><a>Truyện hiện có: ${validChapters.length} chương</a></b>`;

        chapters.forEach(chapter => {
            const chapterDiv = document.createElement('div');
            chapterDiv.className = 'chapter';

            const lockIcon = chapter.status === 'Locked'
                ? `<svg class="c" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path class="line" d="M2 16C2 13.1716 2 11.7574 2.87868 10.8787C3.75736 10 5.17157 10 8 10H16C18.8284 10 20.2426 10 21.1213 10.8787C22 11.7574 22 13.1716 22 16C22 18.8284 22 20.2426 21.1213 21.1213C20.2426 22 18.8284 22 16 22H8C5.17157 22 3.75736 22 2.87868 21.1213C2 20.2426 2 18.8284 2 16Z" stroke="#1C274C" stroke-width="2.4"></path> <circle class="line" cx="12" cy="16" r="2" stroke="#1C274C" stroke-width="2.4"></circle> <path class="line" d="M6 10V8C6 4.68629 8.68629 2 12 2C15.3137 2 18 4.68629 18 8V10" stroke="#1C274C" stroke-width="2.4" stroke-linecap="round"></path> </g></svg>`
                : `<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"></svg>`;

            chapterDiv.innerHTML = `
                <div class="chapter-status">${lockIcon}</div>
                <div class="chapter-name" onclick="window.location.href = 'https://kunsnovel.blogspot.com/p/chapter.html?chapterName=${encodeURIComponent(chapter.chapterName)}&tabName=${encodeURIComponent(tabName)}'">
                    <div>${chapter.chapterName}</div>
                </div>
            `;

            chaptersContainer.appendChild(chapterDiv);
        });
    }
});

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