<!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;
}

h2, h3 {
    text-align: center;
}

.form-group {
    margin-bottom: 15px;
    display: flex;
    flex-wrap: wrap; /* Cho phép các phần tử nằm trong 1 hàng nếu cần */
    gap: 10px; /* Khoảng cách giữa các phần tử */
}

label-kuns {
    font-weight: bold;
    font-size: 16px;
    margin-bottom: 5px; /* Khoảng cách giữa label và input */
    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: 450px; /* Đặt chiều cao cho textarea */
    resize: vertical; /* Cho phép người dùng thay đổi chiều cao */
}

/* Container chứa các nút */
.button-container {
    display: flex;
    flex-wrap: wrap;  /* Cho phép các nút bọc lại khi không đủ không gian */
    gap: 10px;        /* Khoảng cách giữa các nút */
    justify-content: space-between; /* Căn giữa các nút */
}

/* Styling cho các nút */
button {
    padding: 12px 20px;
    font-size: 16px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
    flex-grow: 1;  /* Nút sẽ tự động mở rộng để chiếm hết không gian */
    min-width: 120px;  /* Đảm bảo mỗi nút có độ rộng tối thiểu */
    margin: 5px;  /* Khoảng cách giữa các nút khi chúng bọc lại */
}

#button-kuns {
    background-color: #007BFF;
    color: white;
    border: none;
}

#button-kuns:hover {
    background-color: #0056b3;
}


#addRowBtn {
    background-color: #008CBA;
    color: white;
    border: none;
}

#addRowBtn:hover {
    background-color: #007B8C;
}

#addRowBtn.hidden {
    display: none;
}

/* Error and Success Messages */
.error, .success {
    text-align: center;
    font-weight: bold;
}

.error {
    color: red;
}

.success {
    color: green;
}

/* Data Table Styles */
#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);
}

/* Table-like Structure for SVG and Word Count */
#dataTable div {
    margin-top: 10px;
    display: table;
    width: 100%;
}

#dataTable div div {
    display: table-cell;
    padding: 5px;
}

#dataTable div div:first-child {
    width: 20px; /* Adjust width of the SVG column */
}

/* Password Status Container */
.status-password-container {
    display: flex;
    gap: 10px;
    margin-top: 20px;
    flex-wrap: nowrap; /* Đảm bảo các phần tử luôn nằm trên một hàng */
}


.status-password-container select,
.status-password-container input {
    flex: 1 1 48%; /* Các input sẽ chiếm 48% chiều rộng của phần chứa */
}
.status-password-container {
    display: flex;
    align-items: center;
    justify-content: center; /* Căn giữa các phần tử con theo chiều ngang */
    width: 100%;
    margin-top: 15px;
    text-align: center; /* Căn giữa nội dung trong container */
}

.status-password-container select,
.status-password-container input {
    margin-right: 0;
    margin-bottom: 10px;
    display: block; /* Đảm bảo các phần tử input và select chiếm toàn bộ chiều ngang */
    margin-left: auto;
    margin-right: auto; /* Căn giữa phần tử input và select */
}

.password-container {
    display: flex;
    flex-direction: column;
}

.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: 0 auto;
}

@keyframes loader {
    to { transform: rotate(360deg); }
}

/* Responsive Design */
@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>
<div class="form-group">
    <input type="text" id="password" placeholder="ID tác phẩm..." style="flex: 2;"> <!-- Left side for input -->
    <button id="button-kuns" onclick="validatePassword()" style="flex: 1; margin-left: 10px; display: flex; justify-content: center; align-items: center;">Xác nhận</button>

</div>

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

<div id="tab1" class="tab active">
    <h3 id="listHeading" style="display: none;">Danh sách chương</h3>
    <ul id="dataTable"></ul>
    <button id="addRowBtn" class="hidden" onclick="addRow()">Thêm chương mới</button>
</div>

<div id="tab2" class="tab">
    <h3>Cập nhật chương</h3>
    <div class="form-group">
        <label for="chapterName">Tên chương</label>
        <input type="text" id="chapterName">
    </div>

    <div class="form-group">
        <label for="content">Nội dung chương</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="deleteRow()" style="flex: 1; margin-left: 10px; display: flex; justify-content: center; align-items: center;">Xóa chương</button>
<button id="button-kuns" onclick="saveData()" style="flex: 1; margin-left: 10px; display: flex; justify-content: center; align-items: center;">Lưu chương</button>
<button id="button-kuns" onclick="goBackToTab1()" style="flex: 1; margin-left: 10px; display: flex; justify-content: center; align-items: center;">Quay lại</button>

    </div>
</div>



    <script>
        const apiUrl = 'https://script.google.com/macros/s/AKfycbwlTwlxo5bHAbMOOE9ER6x7uN41scjx2XmKzPq7PLrIzl4QWvqvvsf8JxM2XEyUC_Q/exec';
        let currentPassword = null;
        let currentRowIndex = null;
        let data = [];

function validatePassword() {
    const password = document.getElementById('password').value;
    const messageDiv = document.getElementById('message');
    const loader = document.querySelector('.loader');  // Chọn spinner
    const listHeading = document.getElementById('listHeading');  // Lấy phần tử tiêu đề danh sách

    if (!password) {
        showMessage('error', 'Bạn chưa nhập ID để xác minh, trong trường hợp quên ID, vui lòng liên hệ đến QTV!');
        return;
    }

    // Hiển thị spinner khi bắt đầu xác thực mật khẩu
    loader.style.display = 'block';
    messageDiv.textContent = '';

    fetch(`${apiUrl}?action=getData&password=${password}`)
        .then(response => response.json())
        .then(fetchedData => {
            // Ẩn spinner khi nhận phản hồi từ API
            loader.style.display = 'none';

            if (fetchedData && Array.isArray(fetchedData)) {
                currentPassword = password;
                data = fetchedData;
                showMessage('success', 'Chào mừng bạn quay trở lại, sáng tác thật hay nhé.');
                loadData();
                document.getElementById('addRowBtn').classList.remove('hidden');  // Hiển thị nút thêm

                // Hiển thị tiêu đề danh sách chương
                listHeading.style.display = 'block'; 
            } else {
                showMessage('error', 'ID của bạn không tồn tại, trong trường hợp quên ID, vui lòng liên hệ đến QTV!');
                document.getElementById('addRowBtn').classList.add('hidden');  // Ẩn nút thêm

                // Ẩn tiêu đề danh sách chương nếu mật khẩu không đúng
                listHeading.style.display = 'none';
            }
        })
        .catch(error => {
            // Ẩn spinner nếu có lỗi
            loader.style.display = 'none';
            showMessage('error', 'ID của bạn không tồn tại, trong trường hợp quên ID, vui lòng liên hệ đến QTV!');
            console.error('Error:', error);
        });
}

function loadData() {
    const list = document.getElementById('dataTable');
    list.innerHTML = ''; // Clear existing data

    data.forEach((row, index) => {
        const wordCount = row.content ? row.content.split(/\s+/).filter(Boolean).length : 0; // Đếm số từ
        const li = document.createElement('li');
        
        // Add chapter name in the list item without word count
        li.innerHTML = `
            <span>${row.chapter}</span>
        `;
        
        li.onclick = () => editRow(index, row);
        list.appendChild(li);

        // Create a new table to hold the SVG, word count, and the text on the left
        const table = document.createElement('table');
        table.style.width = '100%';
        table.style.marginTop = '0px'; // Remove top margin to make the table flush with the list item
        table.style.borderCollapse = 'collapse'; // Ensures no extra space between table cells
        table.style.marginBottom = '0px'; // Optionally remove any bottom margin

        // Create a table row
        const tableRow = document.createElement('tr');

// Add "Đã đăng" text with SVG checkmark in the first cell (left side)
const leftCell = document.createElement('td');
leftCell.style.padding = '5px';
leftCell.style.fontSize = '12px'; // Smaller text size
leftCell.style.color = 'var(--darkTa)'; // Set text color
leftCell.style.textAlign = 'left'; // Align to the left

// Create a span to hold the SVG icon and text
const iconTextWrapper = document.createElement('span');
iconTextWrapper.style.display = 'flex';
iconTextWrapper.style.alignItems = 'center'; // Align icon and text vertically

// Add the SVG checkmark icon with scale adjustment
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>
`;

// Create a span container for the SVG
const svgContainer = document.createElement('span');
svgContainer.innerHTML = checkmarkSVG;

// Add the text "Đã đăng"
const textNode = document.createTextNode('Đã đăng');

// Append the SVG icon and text to the wrapper
iconTextWrapper.appendChild(svgContainer);
iconTextWrapper.appendChild(textNode);

// Append the wrapper to the table cell
leftCell.appendChild(iconTextWrapper);
tableRow.appendChild(leftCell);



        // Add both SVG and word count in the second cell (right side)
        const svgAndWordCountCell = document.createElement('td');
        svgAndWordCountCell.style.padding = '5px';
        svgAndWordCountCell.style.textAlign = 'right'; // Align content to the right
        svgAndWordCountCell.style.fontSize = '12px'; // Smaller text size
        svgAndWordCountCell.style.color = 'var(--darkTa)'; // Set text color

        // Add SVG and word count separated by |
        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);

        // Append the table row to the table
        table.appendChild(tableRow);

        // Append the table to the list item
        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(); // Điều chỉnh trường mật khẩu
        }

        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';
            }
        }

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

    if (!apiUrl) {
        showMessage('error', 'Không thể lưu dữ liệu: API URL chưa được cấu hình.');
        return;
    }

    if (currentRowIndex !== null && (typeof currentRowIndex !== 'number' || currentRowIndex < 0)) {
        showMessage('error', 'Không thể cập nhật: Dữ liệu dòng hiện tại không hợp lệ.');
        return;
    }

    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) {
        // Thêm dòng mới
        params.append('action', 'addRow');
        params.append('row', data.length);

        fetch(apiUrl, { method: 'POST', body: params })
            .then(response => {
                if (!response.ok) throw new Error(`API error: ${response.status}`);
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    showMessage('success', 'Chương mới đã được thêm!');
                    data.push({
                        chapter: updatedChapter,
                        content: updatedContent,
                        status: updatedStatus,
                        password: updatedPassword
                    });
                    loadData(); // Cập nhật giao diện
                } else {
                    throw new Error(result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('error', `Không thể thêm dữ liệu: ${error.message}`);
            });
    } else {
        // Cập nhật dòng hiện có
        params.append('action', 'updateData');
        params.append('row', currentRowIndex + 2);

        fetch(apiUrl, { method: 'POST', body: params })
            .then(response => {
                if (!response.ok) throw new Error(`API error: ${response.status}`);
                return response.json();
            })
            .then(result => {
                if (result.success) {
                    showMessage('success', 'Dữ liệu chương đã được cập nhật!');
                    data[currentRowIndex] = {
                        chapter: updatedChapter,
                        content: updatedContent,
                        status: updatedStatus,
                        password: updatedPassword
                    };
                    loadData(); // Cập nhật giao diện
                } else {
                    throw new Error(result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('error', `Không thể cập nhật dữ liệu: ${error.message}`);
            });
    }

    goBackToTab1(); // Quay lại tab1
}


function deleteRow() {
    if (currentRowIndex === null) {
        showMessage('error', 'Không có chương nào để xóa!');
        return;
    }

    // CSS styles for the confirmation modal
    const modalStyles = `
        /* Modal styles */
        .modal {
            display: none; /* Hidden by default */
            position: fixed;
            z-index: 1; /* Sit on top */
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto; /* Enable scrolling if needed */
            padding-top: 100px;
        }

        .modal-content {
    background-color: var(--contentB);
    color: var(--bodyC);
        border: 1px solid var(--contentL); 
        border-radius: 8px;
            margin: auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 400px;
            text-align: center;
        }

        .modal-buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }

        .modal-buttons button {
            padding: 10px 20px;
            font-size: 14px;
            background-color: #f44336; /* Red color for delete button */
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .modal-buttons button:hover {
            background-color: #d32f2f;
        }

        #cancelDeleteBtn {
            background-color: #4CAF50; /* Green color for cancel button */
        }

        #cancelDeleteBtn:hover {
            background-color: #45a049;
        }
    `;

    // Injecting the styles dynamically into the head section
    const styleSheet = document.createElement("style");
    styleSheet.type = "text/css";
    styleSheet.innerText = modalStyles;
    document.head.appendChild(styleSheet);

    // Create the confirmation modal HTML dynamically
    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ì bình tĩnh né nút đỏ ngay còn kịp!</p>
                <div class="modal-buttons">
                    <button id="confirmDeleteBtn">Xóa</button>
                    <button id="cancelDeleteBtn">Hủy</button>
                </div>
            </div>
        </div>
    `;

    // Insert the modal HTML into the body
    document.body.insertAdjacentHTML('beforeend', modalHtml);

    // Show the confirmation modal
    const modal = document.getElementById('confirmModal');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');

    modal.style.display = 'block';

    // Handle the "Xóa" button click (confirm deletion)
    confirmDeleteBtn.onclick = function() {
        // Proceed with deletion
        data.splice(currentRowIndex, 1);  // Remove the chapter from the data
        loadData();  // Update the list immediately

        // Call the API to delete the data from Google Sheets (don't wait for a response)
        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())
            .catch(error => console.error('Error:', error));

        showMessage('success', 'Chương đã bị xóa rồi, buồn thế!');
        goBackToTab1();  // Return to the first tab after deletion
        modal.style.display = 'none';  // Close the modal
    };

    // Handle the "Hủy" button click (cancel deletion)
    cancelDeleteBtn.onclick = function() {
        modal.style.display = 'none';  // Close the modal without deletion
    };
}

      

        function showMessage(type, message) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = message;
            messageDiv.className = type;
        }

function addRow() {
    if (!currentPassword) {
        showMessage('error', 'Vui lòng xác nhận mật khẩu trước');
        return;
    }

    // Chuyển sang Tab 2 với giá trị rỗng
    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 = '';

    // Đặt currentRowIndex là null, vì là một dòng mới
    currentRowIndex = null;
}

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


